code stringlengths 4 1.01M |
|---|
# Store
A store holds the whole [state tree](../Glossary.md#state) of your application.
The only way to change the state inside it is to dispatch an [action](../Glossary.md#action) on it.
A store is not a class. It’s just an object with a few methods on it.
To create it, pass your root [reducing function](../Glossary.md#reducer) to [`createStore`](createStore.md).
>##### A Note for Flux Users
>If you’re coming from Flux, there is a single important difference you need to understand. Redux doesn’t have a Dispatcher or support many stores. **Instead, there is just a single store with a single root [reducing function](../Glossary.md#reducer).** As your app grows, instead of adding stores, you split the root reducer into smaller reducers independently operating on the different parts of the state tree. You can use a helper like [`combineReducers`](combineReducers.md) to combine them. This is similar to how there is just one root component in a React app, but it is composed out of many small components.
### Store Methods
- [`getState()`](#getState)
- [`dispatch(action)`](#dispatch)
- [`subscribe(listener)`](#subscribe)
- [`replaceReducer(nextReducer)`](#replaceReducer)
## Store Methods
### <a id='getState'></a>[`getState()`](#getState)
Returns the current state tree of your application.
It is equal to the last value returned by the store’s reducer.
#### Returns
*(any)*: The current state tree of your application.
<hr>
### <a id='dispatch'></a>[`dispatch(action)`](#dispatch)
Dispatches an action. This is the only way to trigger a state change.
The store’s reducing function will be called with the current [`getState()`](#getState) result and the given `action` synchronously. Its return value will be considered the next state. It will be returned from [`getState()`](#getState) from now on, and the change listeners will immediately be notified.
>##### A Note for Flux Users
>If you attempt to call `dispatch` from inside the [reducer](../Glossary.md#reducer), it will throw with an error saying “Reducers may not dispatch actions.” This is similar to “Cannot dispatch in a middle of dispatch” error in Flux, but doesn’t cause the problems associated with it. In Flux, a dispatch is forbidden while Stores are handling the action and emitting updates. This is unfortunate because it makes it impossible to dispatch actions from component lifecycle hooks or other benign places.
>In Redux, subscriptions are called after the root reducer has returned the new state, so you *may* dispatch in the subscription listeners. You are only disallowed to dispatch inside the reducers because they must have no side effects. If you want to cause a side effect in response to an action, the right place to do this is in the potentially async [action creator](../Glossary.md#action-creator).
#### Arguments
1. `action` (*Object*<sup>†</sup>): A plain object describing the change that makes sense for your application. Actions are the only way to get data into the store, so any data, whether from the UI events, network callbacks, or other sources such as WebSockets needs to eventually be dispatched as actions. By convention, actions should have a `type` field that indicates the type of action being performed. Types can be defined as constants and imported from another module. It’s better to use strings for `type` than [Symbols](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Symbol) because strings are serializable. Other than `type`, the structure of an action object is really up to you. If you’re interested, check out [Flux Standard Action](https://github.com/acdlite/flux-standard-action) for recommendations on how actions should be constructed.
#### Returns
(Object<sup>†</sup>): The dispatched action.
#### Notes
<sup>†</sup> The “vanilla” store implementation you get by calling [`createStore`](createStore.md) only supports plain object actions and hands them immediately to the reducer.
However, if you wrap [`createStore`](createStore.md) with [`applyMiddleware`](applyMiddleware.md), the middleware can interpret actions differently, and provide support for dispatching [intents](../Glossary.md#intent). Intents are usually asynchronous primitives like Promises, Observables, or thunks.
Middleware is created by the community and does not ship with Redux by default. You need to explicitly install packages like [redux-thunk](https://github.com/gaearon/redux-thunk) or [redux-promise](https://github.com/acdlite/redux-promise) to use it. You may also create your own middleware.
To learn how to describe asynchronous API calls, read the current state inside action creators, perform side effects, or chain them to execute in a sequence, see the examples for [`applyMiddleware`](applyMiddleware.md).
#### Example
```js
import { createStore } from 'redux';
let store = createStore(todos, ['Use Redux']);
function addTodo(text) {
return {
type: 'ADD_TODO',
text
};
}
store.dispatch(addTodo('Read the docs'));
store.dispatch(addTodo('Read about the middleware'));
```
<hr>
### <a id='subscribe'></a>[`subscribe(listener)`](#subscribe)
Adds a change listener. It will be called any time an action is dispatched, and some part of the state tree may potentially have changed. You may then call [`getState()`](#getState) to read the current state tree inside the callback.
It is a low-level API. Most likely, instead of using it directly, you’ll use React (or other) bindings. If you feel that the callback needs to be invoked with the current state, you might want to [convert the store to an Observable or write a custom `observeStore` utility instead](https://github.com/rackt/redux/issues/303#issuecomment-125184409).
To unsubscribe the change listener, invoke the function returned by `subscribe`.
#### Arguments
1. `listener` (*Function*): The callback to be invoked any time an action has been dispatched, and the state tree might have changed. You may call [`getState()`](#getState) inside this callback to read the current state tree. It is reasonable to expect that the store’s reducer is a pure function, so you may compare references to some deep path in the state tree to learn whether its value has changed.
##### Returns
(*Function*): A function that unsubscribes the change listener.
##### Example
```js
function select(state) {
return state.some.deep.property;
}
let currentValue;
function handleChange() {
let previousValue = currentValue;
currentValue = select(store.getState());
if (previousValue !== currentValue) {
console.log('Some deep nested property changed from', previousValue, 'to', currentValue);
}
}
let unsubscribe = store.subscribe(handleChange);
handleChange();
```
<hr>
### <a id='replaceReducer'></a>[`replaceReducer(nextReducer)`](#replaceReducer)
>##### Deprecated
>This API has been [deprecated](https://github.com/rackt/redux/issues/350).
>It will be removed when we find a better solution for this problem.
Replaces the reducer currently used by the store to calculate the state.
It is an advanced API. You might need this if your app implements code splitting, and you want to load some of the reducers dynamically. You might also need this if you implement a hot reloading mechanism for Redux.
#### Arguments
1. `reducer` (*Function*) The next reducer for the store to use.
|
# coding: utf-8
# Copyright (c) Pymatgen Development Team.
# Distributed under the terms of the MIT License.
"""
This package contains various command line wrappers to programs used in
pymatgen that do not have Python equivalents.
"""
|
package main
import (
"fmt"
"log"
"net/http"
"gopkg.in/jcelliott/turnpike.v1"
)
func main() {
s := turnpike.NewServer()
http.Handle("/ws", s.Handler)
http.Handle("/", http.FileServer(http.Dir("web")))
fmt.Println("Listening on port 8080")
if err := http.ListenAndServe(":8080", nil); err != nil {
log.Fatal("ListenAndServe:", err)
}
}
|
/*
Brown Paper style from goldblog.com.ua (c) Zaripov Yura <yur4ik7@ukr.net>
*/
.hljs {
display: block;
padding: .5em;
overflow-x: auto;
-webkit-text-size-adjust: none;
background: #b7a68e url(./brown_papersq.png);
}
.hljs-keyword,
.hljs-literal,
.hljs-change,
.hljs-winutils,
.hljs-flow,
.nginx .hljs-title,
.tex .hljs-special,
.hljs-request,
.hljs-status {
font-weight: bold;
color: #059;
}
.hljs,
.hljs-subst,
.hljs-tag .hljs-keyword {
color: #363c69;
}
.hljs-string,
.hljs-title,
.hljs-type,
.hljs-tag .hljs-value,
.css .hljs-rule .hljs-value,
.hljs-preprocessor,
.hljs-pragma,
.ruby .hljs-symbol,
.ruby .hljs-symbol .hljs-string,
.ruby .hljs-class .hljs-parent,
.hljs-built_in,
.django .hljs-template_tag,
.django .hljs-variable,
.smalltalk .hljs-class,
.ruby .hljs-string,
.django .hljs-filter .hljs-argument,
.smalltalk .hljs-localvars,
.smalltalk .hljs-array,
.hljs-attr_selector,
.hljs-pseudo,
.hljs-addition,
.hljs-stream,
.hljs-envvar,
.apache .hljs-tag,
.apache .hljs-cbracket,
.tex .hljs-number,
.hljs-name {
color: #2c009f;
}
.hljs-comment,
.hljs-annotation,
.hljs-decorator,
.hljs-pi,
.hljs-doctype,
.hljs-deletion,
.hljs-shebang,
.apache .hljs-sqbracket,
.nginx .hljs-built_in,
.tex .hljs-formula {
color: #802022;
}
.hljs-keyword,
.hljs-literal,
.css .hljs-id,
.hljs-doctag,
.hljs-title,
.hljs-type,
.vbscript .hljs-built_in,
.rsl .hljs-built_in,
.smalltalk .hljs-class,
.diff .hljs-header,
.hljs-chunk,
.hljs-winutils,
.bash .hljs-variable,
.apache .hljs-tag,
.tex .hljs-command {
font-weight: bold;
}
.coffeescript .javascript,
.javascript .xml,
.tex .hljs-formula,
.xml .javascript,
.xml .vbscript,
.xml .css,
.xml .hljs-cdata {
opacity: .8;
}
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="robots" content="index, follow, all" />
<title>Thelia\Controller\Admin\CouponController | </title>
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css">
</head>
<body id="class">
<div class="header">
<ul>
<li><a href="../../../classes.html">Classes</a></li>
<li><a href="../../../namespaces.html">Namespaces</a></li>
<li><a href="../../../interfaces.html">Interfaces</a></li>
<li><a href="../../../traits.html">Traits</a></li>
<li><a href="../../../doc-index.html">Index</a></li>
</ul>
<div id="title"></div>
<div class="type">Class</div>
<h1><a href="../../../Thelia/Controller/Admin.html">Thelia\Controller\Admin</a>\CouponController</h1>
</div>
<div class="content">
<p> class
<strong>CouponController</strong> extends <a href="../../../Thelia/Controller/Admin/BaseAdminController.html"><abbr title="Thelia\Controller\Admin\BaseAdminController">BaseAdminController</abbr></a></p>
<div class="description">
<p>Control View and Action (Model) via Events</p>
<p>
</p>
</div>
<h2>Constants</h2>
<table>
<tr>
<td>TEMPLATE_404</td>
<td class="last">
<p><em>
</em></p>
<p>
</p>
</td>
</tr>
</table>
<h2>Methods</h2>
<table>
<tr>
<td class="type">
</td>
<td class="last">
<a href="#method_adminLogAppend">adminLogAppend</a>(string $resource, string $action, string $message)
<p>Helper to append a message to the admin log.</p>
</td>
<td><small>from <a href="../../../Thelia/Controller/Admin/BaseAdminController.html#method_adminLogAppend"><abbr title="Thelia\Controller\Admin\BaseAdminController">BaseAdminController</abbr></a></small></td>
</tr>
<tr>
<td class="type">
<a href="../../../Thelia/Core/HttpFoundation/Response.html"><abbr title="Thelia\Core\HttpFoundation\Response">Response</abbr></a>
</td>
<td class="last">
<a href="#method_processTemplateAction">processTemplateAction</a>(string $template)
<p>This method process the rendering of view called from an admin page</p>
</td>
<td><small>from <a href="../../../Thelia/Controller/Admin/BaseAdminController.html#method_processTemplateAction"><abbr title="Thelia\Controller\Admin\BaseAdminController">BaseAdminController</abbr></a></small></td>
</tr>
<tr>
<td class="type">
<a href="../../../Thelia/Core/HttpFoundation/Response.html"><abbr title="Thelia\Core\HttpFoundation\Response">Response</abbr></a>
</td>
<td class="last">
<a href="#method_browseAction">browseAction</a>()
<p>Manage Coupons list display</p>
</td>
<td></td>
</tr>
<tr>
<td class="type">
<a href="../../../Thelia/Core/HttpFoundation/Response.html"><abbr title="Thelia\Core\HttpFoundation\Response">Response</abbr></a>
</td>
<td class="last">
<a href="#method_createAction">createAction</a>()
<p>Manage Coupons creation display</p>
</td>
<td></td>
</tr>
<tr>
<td class="type">
<a href="../../../Thelia/Core/HttpFoundation/Response.html"><abbr title="Thelia\Core\HttpFoundation\Response">Response</abbr></a>
</td>
<td class="last">
<a href="#method_updateAction">updateAction</a>(int $couponId)
<p>Manage Coupons edition display</p>
</td>
<td></td>
</tr>
<tr>
<td class="type">
<a href="../../../Thelia/Core/HttpFoundation/Response.html"><abbr title="Thelia\Core\HttpFoundation\Response">Response</abbr></a>
</td>
<td class="last">
<a href="#method_getConditionEmptyInputAjaxAction">getConditionEmptyInputAjaxAction</a>(string $conditionId)
<p>Manage Coupons read display</p>
</td>
<td></td>
</tr>
<tr>
<td class="type">
<a href="../../../Thelia/Core/HttpFoundation/Response.html"><abbr title="Thelia\Core\HttpFoundation\Response">Response</abbr></a>
</td>
<td class="last">
<a href="#method_getConditionToUpdateInputAjaxAction">getConditionToUpdateInputAjaxAction</a>(int $couponId, int $conditionIndex)
<p>Manage Coupons read display</p>
</td>
<td></td>
</tr>
<tr>
<td class="type">
<a href="../../../Thelia/Core/HttpFoundation/Response.html"><abbr title="Thelia\Core\HttpFoundation\Response">Response</abbr></a>
</td>
<td class="last">
<a href="#method_saveConditionsAction">saveConditionsAction</a>(int $couponId)
<p>Manage Coupons read display</p>
</td>
<td></td>
</tr>
<tr>
<td class="type">
<a href="../../../Thelia/Core/HttpFoundation/Response.html"><abbr title="Thelia\Core\HttpFoundation\Response">Response</abbr></a>
</td>
<td class="last">
<a href="#method_deleteConditionsAction">deleteConditionsAction</a>(int $couponId, int $conditionIndex)
<p>Manage Coupons condition deleteion</p>
</td>
<td></td>
</tr>
<tr>
<td class="type">
<a href="../../../Thelia/Tools/Rest/ResponseRest.html"><abbr title="Thelia\Tools\Rest\ResponseRest">ResponseRest</abbr></a>
</td>
<td class="last">
<a href="#method_getBackOfficeInputsAjaxAction">getBackOfficeInputsAjaxAction</a>(string $couponServiceId)
<p>Draw the input displayed in the BackOffice allowing Admin to set its Coupon effect</p>
</td>
<td></td>
</tr>
<tr>
<td class="type">
<a href="../../../Thelia/Tools/Rest/ResponseRest.html"><abbr title="Thelia\Tools\Rest\ResponseRest">ResponseRest</abbr></a>
</td>
<td class="last">
<a href="#method_getBackOfficeConditionSummariesAjaxAction">getBackOfficeConditionSummariesAjaxAction</a>(int $couponId)
<p>Draw the input displayed in the BackOffice allowing Admin to set its Coupon effect</p>
</td>
<td></td>
</tr>
</table>
<h2>Details</h2>
<h3 id="method_adminLogAppend">
<div class="location">in <a href="../../../Thelia/Controller/Admin/BaseAdminController.html#method_adminLogAppend"><abbr title="Thelia\Controller\Admin\BaseAdminController">BaseAdminController</abbr></a> at line 51</div>
<code> public
<strong>adminLogAppend</strong>(string $resource, string $action, string $message)</code>
</h3>
<div class="details">
<p>Helper to append a message to the admin log.</p>
<p>
</p>
<div class="tags">
<h4>Parameters</h4>
<table>
<tr>
<td>string</td>
<td>$resource</td>
<td>
</td>
</tr>
<tr>
<td>string</td>
<td>$action</td>
<td>
</td>
</tr>
<tr>
<td>string</td>
<td>$message</td>
<td>
</td>
</tr>
</table>
</div>
</div>
<h3 id="method_processTemplateAction">
<div class="location">in <a href="../../../Thelia/Controller/Admin/BaseAdminController.html#method_processTemplateAction"><abbr title="Thelia\Controller\Admin\BaseAdminController">BaseAdminController</abbr></a> at line 62</div>
<code> public <a href="../../../Thelia/Core/HttpFoundation/Response.html"><abbr title="Thelia\Core\HttpFoundation\Response">Response</abbr></a>
<strong>processTemplateAction</strong>(string $template)</code>
</h3>
<div class="details">
<p>This method process the rendering of view called from an admin page</p>
<p>
</p>
<div class="tags">
<h4>Parameters</h4>
<table>
<tr>
<td>string</td>
<td>$template</td>
<td>the template name</td>
</tr>
</table>
<h4>Return Value</h4>
<table>
<tr>
<td><a href="../../../Thelia/Core/HttpFoundation/Response.html"><abbr title="Thelia\Core\HttpFoundation\Response">Response</abbr></a></td>
<td>the response which contains the rendered view</td>
</tr>
</table>
</div>
</div>
<h3 id="method_browseAction">
<div class="location">at line 54</div>
<code> public <a href="../../../Thelia/Core/HttpFoundation/Response.html"><abbr title="Thelia\Core\HttpFoundation\Response">Response</abbr></a>
<strong>browseAction</strong>()</code>
</h3>
<div class="details">
<p>Manage Coupons list display</p>
<p>
</p>
<div class="tags">
<h4>Return Value</h4>
<table>
<tr>
<td><a href="../../../Thelia/Core/HttpFoundation/Response.html"><abbr title="Thelia\Core\HttpFoundation\Response">Response</abbr></a></td>
<td>
</td>
</tr>
</table>
</div>
</div>
<h3 id="method_createAction">
<div class="location">at line 70</div>
<code> public <a href="../../../Thelia/Core/HttpFoundation/Response.html"><abbr title="Thelia\Core\HttpFoundation\Response">Response</abbr></a>
<strong>createAction</strong>()</code>
</h3>
<div class="details">
<p>Manage Coupons creation display</p>
<p>
</p>
<div class="tags">
<h4>Return Value</h4>
<table>
<tr>
<td><a href="../../../Thelia/Core/HttpFoundation/Response.html"><abbr title="Thelia\Core\HttpFoundation\Response">Response</abbr></a></td>
<td>
</td>
</tr>
</table>
</div>
</div>
<h3 id="method_updateAction">
<div class="location">at line 117</div>
<code> public <a href="../../../Thelia/Core/HttpFoundation/Response.html"><abbr title="Thelia\Core\HttpFoundation\Response">Response</abbr></a>
<strong>updateAction</strong>(int $couponId)</code>
</h3>
<div class="details">
<p>Manage Coupons edition display</p>
<p>
</p>
<div class="tags">
<h4>Parameters</h4>
<table>
<tr>
<td>int</td>
<td>$couponId</td>
<td>Coupon id</td>
</tr>
</table>
<h4>Return Value</h4>
<table>
<tr>
<td><a href="../../../Thelia/Core/HttpFoundation/Response.html"><abbr title="Thelia\Core\HttpFoundation\Response">Response</abbr></a></td>
<td>
</td>
</tr>
</table>
</div>
</div>
<h3 id="method_getConditionEmptyInputAjaxAction">
<div class="location">at line 264</div>
<code> public <a href="../../../Thelia/Core/HttpFoundation/Response.html"><abbr title="Thelia\Core\HttpFoundation\Response">Response</abbr></a>
<strong>getConditionEmptyInputAjaxAction</strong>(string $conditionId)</code>
</h3>
<div class="details">
<p>Manage Coupons read display</p>
<p>
</p>
<div class="tags">
<h4>Parameters</h4>
<table>
<tr>
<td>string</td>
<td>$conditionId</td>
<td>Condition service id</td>
</tr>
</table>
<h4>Return Value</h4>
<table>
<tr>
<td><a href="../../../Thelia/Core/HttpFoundation/Response.html"><abbr title="Thelia\Core\HttpFoundation\Response">Response</abbr></a></td>
<td>
</td>
</tr>
</table>
</div>
</div>
<h3 id="method_getConditionToUpdateInputAjaxAction">
<div class="location">at line 313</div>
<code> public <a href="../../../Thelia/Core/HttpFoundation/Response.html"><abbr title="Thelia\Core\HttpFoundation\Response">Response</abbr></a>
<strong>getConditionToUpdateInputAjaxAction</strong>(int $couponId, int $conditionIndex)</code>
</h3>
<div class="details">
<p>Manage Coupons read display</p>
<p>
</p>
<div class="tags">
<h4>Parameters</h4>
<table>
<tr>
<td>int</td>
<td>$couponId</td>
<td>Coupon id being updated</td>
</tr>
<tr>
<td>int</td>
<td>$conditionIndex</td>
<td>Coupon Condition position in the collection</td>
</tr>
</table>
<h4>Return Value</h4>
<table>
<tr>
<td><a href="../../../Thelia/Core/HttpFoundation/Response.html"><abbr title="Thelia\Core\HttpFoundation\Response">Response</abbr></a></td>
<td>
</td>
</tr>
</table>
</div>
</div>
<h3 id="method_saveConditionsAction">
<div class="location">at line 368</div>
<code> public <a href="../../../Thelia/Core/HttpFoundation/Response.html"><abbr title="Thelia\Core\HttpFoundation\Response">Response</abbr></a>
<strong>saveConditionsAction</strong>(int $couponId)</code>
</h3>
<div class="details">
<p>Manage Coupons read display</p>
<p>
</p>
<div class="tags">
<h4>Parameters</h4>
<table>
<tr>
<td>int</td>
<td>$couponId</td>
<td>Coupon id</td>
</tr>
</table>
<h4>Return Value</h4>
<table>
<tr>
<td><a href="../../../Thelia/Core/HttpFoundation/Response.html"><abbr title="Thelia\Core\HttpFoundation\Response">Response</abbr></a></td>
<td>
</td>
</tr>
</table>
</div>
</div>
<h3 id="method_deleteConditionsAction">
<div class="location">at line 417</div>
<code> public <a href="../../../Thelia/Core/HttpFoundation/Response.html"><abbr title="Thelia\Core\HttpFoundation\Response">Response</abbr></a>
<strong>deleteConditionsAction</strong>(int $couponId, int $conditionIndex)</code>
</h3>
<div class="details">
<p>Manage Coupons condition deleteion</p>
<p>
</p>
<div class="tags">
<h4>Parameters</h4>
<table>
<tr>
<td>int</td>
<td>$couponId</td>
<td>Coupon id</td>
</tr>
<tr>
<td>int</td>
<td>$conditionIndex</td>
<td>Coupon condition index in the collection</td>
</tr>
</table>
<h4>Return Value</h4>
<table>
<tr>
<td><a href="../../../Thelia/Core/HttpFoundation/Response.html"><abbr title="Thelia\Core\HttpFoundation\Response">Response</abbr></a></td>
<td>
</td>
</tr>
</table>
</div>
</div>
<h3 id="method_getBackOfficeInputsAjaxAction">
<div class="location">at line 625</div>
<code> public <a href="../../../Thelia/Tools/Rest/ResponseRest.html"><abbr title="Thelia\Tools\Rest\ResponseRest">ResponseRest</abbr></a>
<strong>getBackOfficeInputsAjaxAction</strong>(string $couponServiceId)</code>
</h3>
<div class="details">
<p>Draw the input displayed in the BackOffice allowing Admin to set its Coupon effect</p>
<p>
</p>
<div class="tags">
<h4>Parameters</h4>
<table>
<tr>
<td>string</td>
<td>$couponServiceId</td>
<td>Coupon service id</td>
</tr>
</table>
<h4>Return Value</h4>
<table>
<tr>
<td><a href="../../../Thelia/Tools/Rest/ResponseRest.html"><abbr title="Thelia\Tools\Rest\ResponseRest">ResponseRest</abbr></a></td>
<td>
</td>
</tr>
</table>
</div>
</div>
<h3 id="method_getBackOfficeConditionSummariesAjaxAction">
<div class="location">at line 659</div>
<code> public <a href="../../../Thelia/Tools/Rest/ResponseRest.html"><abbr title="Thelia\Tools\Rest\ResponseRest">ResponseRest</abbr></a>
<strong>getBackOfficeConditionSummariesAjaxAction</strong>(int $couponId)</code>
</h3>
<div class="details">
<p>Draw the input displayed in the BackOffice allowing Admin to set its Coupon effect</p>
<p>
</p>
<div class="tags">
<h4>Parameters</h4>
<table>
<tr>
<td>int</td>
<td>$couponId</td>
<td>Coupon id</td>
</tr>
</table>
<h4>Return Value</h4>
<table>
<tr>
<td><a href="../../../Thelia/Tools/Rest/ResponseRest.html"><abbr title="Thelia\Tools\Rest\ResponseRest">ResponseRest</abbr></a></td>
<td>
</td>
</tr>
</table>
</div>
</div>
</div>
<div id="footer">
Generated by <a href="http://sami.sensiolabs.org/" target="_top">Sami, the API Documentation Generator</a>.
</div>
</body>
</html>
|
<!doctype html>
<html lang="en" ng-app="docsApp" ng-strict-di ng-controller="DocsController">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="Description"
content="AngularJS is what HTML would have been, had it been designed for building web-apps.
Declarative templates with data-binding, MVC, dependency injection and great
testability story all implemented with pure client-side JavaScript!">
<meta name="fragment" content="!">
<title ng-bind-template="AngularJS: {{ currentArea.name }}: {{ currentPage.name || 'Error: Page not found'}}">AngularJS</title>
<script type="text/javascript">
// dynamically add base tag as well as css and javascript files.
// we can't add css/js the usual way, because some browsers (FF) eagerly prefetch resources
// before the base attribute is added, causing 404 and terribly slow loading of the docs app.
(function() {
var indexFile = (location.pathname.match(/\/(index[^\.]*\.html)/) || ['', ''])[1],
rUrl = /(#!\/|api|guide|misc|tutorial|error|index[^\.]*\.html).*$/,
baseUrl = location.href.replace(rUrl, indexFile),
production = location.hostname === 'docs.angularjs.org',
headEl = document.getElementsByTagName('head')[0],
sync = true;
addTag('base', {href: baseUrl});
addTag('link', {rel: 'stylesheet', href: 'components/bootstrap-3.1.1/css/bootstrap.min.css', type: 'text/css'});
addTag('link', {rel: 'stylesheet', href: 'components/open-sans-fontface-1.0.4/open-sans.css', type: 'text/css'});
addTag('link', {rel: 'stylesheet', href: 'css/prettify-theme.css', type: 'text/css'});
addTag('link', {rel: 'stylesheet', href: 'css/docs.css', type: 'text/css'});
addTag('link', {rel: 'stylesheet', href: 'css/animations.css', type: 'text/css'});
addTag('script', {src: 'components/jquery-2.1.1/jquery.js' }, sync);
addTag('script', {src: '../angular.min.js' }, sync);
addTag('script', {src: '../angular-resource.min.js' }, sync);
addTag('script', {src: '../angular-route.min.js' }, sync);
addTag('script', {src: '../angular-cookies.min.js' }, sync);
addTag('script', {src: '../angular-sanitize.min.js' }, sync);
addTag('script', {src: '../angular-touch.min.js' }, sync);
addTag('script', {src: '../angular-animate.min.js' }, sync);
addTag('script', {src: 'components/marked-0.3.3/lib/marked.js' }, sync);
addTag('script', {src: 'js/angular-bootstrap/bootstrap.min.js' }, sync);
addTag('script', {src: 'js/angular-bootstrap/dropdown-toggle.min.js' }, sync);
addTag('script', {src: 'components/lunr.js-0.4.2/lunr.min.js' }, sync);
addTag('script', {src: 'components/google-code-prettify-1.0.1/src/prettify.js' }, sync);
addTag('script', {src: 'components/google-code-prettify-1.0.1/src/lang-css.js' }, sync);
addTag('script', {src: 'js/versions-data.js' }, sync);
addTag('script', {src: 'js/pages-data.js' }, sync);
addTag('script', {src: 'js/nav-data.js' }, sync);
addTag('script', {src: 'js/docs.min.js' }, sync);
function addTag(name, attributes, sync) {
var el = document.createElement(name),
attrName;
for (attrName in attributes) {
el.setAttribute(attrName, attributes[attrName]);
}
sync ? document.write(outerHTML(el)) : headEl.appendChild(el);
}
function outerHTML(node){
// if IE, Chrome take the internal method otherwise build one
return node.outerHTML || (
function(n){
var div = document.createElement('div'), h;
div.appendChild(n);
h = div.innerHTML;
div = null;
return h;
})(node);
}
})();
// GA asynchronous tracker
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-8594346-3']);
_gaq.push(['_setDomainName', '.angularjs.org']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
</head>
<body>
<div id="wrapper">
<header scroll-y-offset-element class="header header-fixed">
<section class="navbar navbar-inverse docs-navbar-primary" ng-controller="DocsSearchCtrl">
<div class="container">
<div class="row">
<div class="col-md-9 header-branding">
<a class="brand navbar-brand" href="http://angularjs.org">
<img width="117" height="30" class="logo" ng-src="img/angularjs-for-header-only.svg">
</a>
<ul class="nav navbar-nav">
<li class="divider-vertical"></li>
<li><a href="http://angularjs.org"><i class="icon-home icon-white"></i> Home</a></li>
<li class="divider-vertical"></li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
<i class="icon-eye-open icon-white"></i> Learn <b class="caret"></b>
</a>
<ul class="dropdown-menu">
<li class="disabled"><a href="http://angularjs.org/">Why AngularJS?</a></li>
<li><a href="http://www.youtube.com/user/angularjs">Watch</a></li>
<li><a href="tutorial">Tutorial</a></li>
<li><a href="http://builtwith.angularjs.org/">Case Studies</a></li>
<li><a href="https://github.com/angular/angular-seed">Seed App project template</a></li>
<li><a href="misc/faq">FAQ</a></li>
</ul>
</li>
<li class="divider-vertical"></li>
<li class="dropdown active">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
<i class="icon-book icon-white"></i> Develop <b class="caret"></b>
</a>
<ul class="dropdown-menu">
<li><a href="tutorial">Tutorial</a></li>
<li><a href="guide">Developer Guide</a></li>
<li><a href="api">API Reference</a></li>
<li><a href="error">Error Reference</a></li>
<li><a href="misc/contribute">Contribute</a></li>
<li><a href="http://code.angularjs.org/">Download</a></li>
</ul>
</li>
<li class="divider-vertical"></li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
<i class="icon-comment icon-white"></i> Discuss <b class="caret"></b>
</a>
<ul class="dropdown-menu">
<li><a href="http://blog.angularjs.org">Blog</a></li>
<li><a href="http://groups.google.com/group/angular">Mailing List</a></li>
<li><a href="http://webchat.freenode.net/?channels=angularjs&uio=d4">Chat Room</a></li>
<li class="divider"></li>
<li><a href="https://twitter.com/#!/angularjs">Twitter</a></li>
<li><a href="https://plus.google.com/110323587230527980117">Google+</a></li>
<li class="divider"></li>
<li><a href="https://github.com/angular/angular.js">GitHub</a></li>
<li><a href="https://github.com/angular/angular.js/issues">Issue Tracker</a></li>
</ul>
</li>
<li class="divider-vertical"></li>
</ul>
</div>
<form ng-class="{focus:focus}" class="navbar-search col-md-3 docs-search" ng-submit="submit()">
<span class="glyphicon glyphicon-search search-icon"></span>
<input type="text"
name="as_q"
class="search-query"
placeholder="Click or press / to search"
ng-focus="focus=true"
ng-blur="focus=false"
ng-change="search(q)"
ng-model="q"
docs-search-input
autocomplete="off" />
</form>
</div>
</div>
<div class="search-results-container" ng-show="hasResults">
<div class="container">
<div class="search-results-frame">
<div ng-repeat="(key, value) in results" class="search-results-group" ng-class="colClassName + ' col-group-' + key">
<h4 class="search-results-group-heading">{{ key }}</h4>
<div class="search-results">
<div ng-repeat="item in value" class="search-result">
- <a ng-click="hideResults()" ng-href="{{ item.path }}">{{ item.name }}</a>
</div>
</div>
</div>
</div>
<a href="" ng-click="hideResults()" class="search-close">
<span class="glyphicon glyphicon-remove search-close-icon"></span> Close
</a>
</div>
</div>
</section>
<section class="sup-header">
<div class="container main-grid main-header-grid">
<div class="grid-left">
<div ng-controller="DocsVersionsCtrl" class="picker version-picker">
<select ng-options="v as ('v' + v.version + (v.isSnapshot ? ' (snapshot)' : '')) group by getGroupName(v) for v in docs_versions"
ng-model="docs_version"
ng-change="jumpToDocsVersion(docs_version)"
class="docs-version-jump">
</select>
</div>
</div>
<div class="grid-right">
<ul class="nav-breadcrumb">
<li ng-repeat="crumb in breadcrumb" class="nav-breadcrumb-entry naked-list">
<span class="divider"> /</span>
<a ng-href="{{crumb.url}}">{{crumb.name}}</a>
</li>
</ul>
</div>
</div>
</section>
</header>
<section role="main" class="container main-body">
<div class="main-grid main-body-grid">
<div class="grid-left">
<a class="btn toc-toggle visible-xs" ng-click="toc=!toc">Show / Hide Table of Contents</a>
<div class="side-navigation" ng-show="toc==true">
<ul class="nav-list naked-list">
<li ng-repeat="navGroup in currentArea.navGroups track by navGroup.name" class="nav-index-group">
<a href="{{ navGroup.href }}" ng-class="navClass(navGroup)" class="nav-index-group-heading">{{ navGroup.name }}</a>
<ul class="aside-nav">
<li ng-repeat="navItem in navGroup.navItems" ng-class="navClass(navItem)" class="nav-index-listing">
<a ng-if="navItem.extra.href" ng-class="navClass(navItem.extra)" href="{{navItem.extra.href}}">
{{navItem.extra.text}}<i ng-if="navItem.extra.icon" class="icon-{{navItem.extra.icon}}"></i>
</a>
<a tabindex="2" ng-class="linkClass(navItem)" href="{{navItem.href}}">{{navItem.name}}</a>
</li>
</ul>
</li>
</ul>
<a href="" ng-click="toc=false" class="toc-close visible-xs">
<span class="glyphicon glyphicon-remove toc-close-icon"></span> Close
</a>
</div>
</div>
<div class="grid-right">
<div id="loading" ng-show="loading">Loading...</div>
<div ng-hide="loading" ng-include="partialPath" autoscroll></div>
</div>
</div>
</section>
<footer class="footer">
<div class="container">
<p class="pull-right"><a back-to-top>Back to top</a></p>
<p>
Super-powered by Google ©2010-2015
( <a id="version"
ng-href="https://github.com/angular/angular.js/blob/master/CHANGELOG.md#{{versionNumber}}"
ng-bind-template="v{{version}}">
</a>
)
</p>
<p>
Code licensed under the
<a href="https://github.com/angular/angular.js/blob/master/LICENSE" target="_blank">The
MIT License</a>. Documentation licensed under <a
href="http://creativecommons.org/licenses/by/3.0/">CC BY 3.0</a>.
</p>
</div>
</footer>
</div>
</body>
</html>
|
@charset "UTF-8";
/*!
* reveal.js
* http://lab.hakim.se/reveal-js
* MIT licensed
*
* Copyright (C) 2011-2012 Hakim El Hattab, http://hakim.se
*/
/*********************************************
* RESET STYLES
*********************************************/
html, body, .reveal div, .reveal span, .reveal applet, .reveal object, .reveal iframe,
.reveal h1, .reveal h2, .reveal h3, .reveal h4, .reveal h5, .reveal h6, .reveal p, .reveal blockquote, .reveal pre,
.reveal a, .reveal abbr, .reveal acronym, .reveal address, .reveal big, .reveal cite, .reveal code,
.reveal del, .reveal dfn, .reveal em, .reveal img, .reveal ins, .reveal kbd, .reveal q, .reveal s, .reveal samp,
.reveal small, .reveal strike, .reveal strong, .reveal sub, .reveal sup, .reveal tt, .reveal var,
.reveal b, .reveal u, .reveal i, .reveal center,
.reveal dl, .reveal dt, .reveal dd, .reveal ol, .reveal ul, .reveal li,
.reveal fieldset, .reveal form, .reveal label, .reveal legend,
.reveal table, .reveal caption, .reveal tbody, .reveal tfoot, .reveal thead, .reveal tr, .reveal th, .reveal td,
.reveal article, .reveal aside, .reveal canvas, .reveal details, .reveal embed,
.reveal figure, .reveal figcaption, .reveal footer, .reveal header, .reveal hgroup,
.reveal menu, .reveal nav, .reveal output, .reveal ruby, .reveal section, .reveal summary,
.reveal time, .reveal mark, .reveal audio, video {
margin: 0;
padding: 0;
border: 0;
font-size: 100%;
font: inherit;
vertical-align: baseline;
}
.reveal article, .reveal aside, .reveal details, .reveal figcaption, .reveal figure,
.reveal footer, .reveal header, .reveal hgroup, .reveal menu, .reveal nav, .reveal section {
display: block;
}
/*********************************************
* GLOBAL STYLES
*********************************************/
html,
body {
width: 100%;
height: 100%;
min-height: 600px;
overflow: hidden;
}
body {
position: relative;
line-height: 1;
}
::selection {
background:#FF5E99;
color:#fff;
text-shadow: none;
}
@media screen and (max-width: 900px) {
.reveal {
font-size: 30px;
}
}
.reveal footer{
position: fixed;
height: 40px;
width: 100%;
bottom: 3px;
left: 0;
z-index: 10;
font-size: 35%;
text-align:right;
background-image: url(../css/images/pink-logo.png);
background-repeat: no-repeat;
background-size: auto 100%;
}
.reveal footer .copyright{
margin:15px 5px 0 100px;
font-style: italic;
}
.reveal footer .copyright a img{
vertical-align: middle;
}
/*********************************************
* OVERRIDES
**********************************************/
.left-align{text-align:left}
.right-align{ text-align:right}
.left{float:left}
.right{float:right}
.clear{clear:both}
.blue{color:#01A9B4 }
.green{color:#92BB44}
.yellow{color:#EDAB23}
.pink{color:#F05B62}
.red{color:#8B0036}
/*********************************************
* HEADERS
*********************************************/
.reveal h1 { font-size: 3.77em; }
.reveal h2 { font-size: 2.11em; }
.reveal h3 { font-size: 1.55em; }
.reveal h4 { font-size: 1em; }
/*********************************************
* VIEW FRAGMENTS
*********************************************/
.reveal .slides section .fragment {
opacity: 0;
-webkit-transition: all .2s ease;
-moz-transition: all .2s ease;
-ms-transition: all .2s ease;
-o-transition: all .2s ease;
transition: all .2s ease;
}
.reveal .slides section .fragment.visible {
opacity: 1;
}
.reveal .slides section .fragment.grow {
opacity: 1;
}
.reveal .slides section .fragment.grow.visible {
-webkit-transform: scale( 1.3 );
-moz-transform: scale( 1.3 );
-ms-transform: scale( 1.3 );
-o-transform: scale( 1.3 );
transform: scale( 1.3 );
}
.reveal .slides section .fragment.shrink {
opacity: 1;
}
.reveal .slides section .fragment.shrink.visible {
-webkit-transform: scale( 0.7 );
-moz-transform: scale( 0.7 );
-ms-transform: scale( 0.7 );
-o-transform: scale( 0.7 );
transform: scale( 0.7 );
}
.reveal .slides section .fragment.roll-in {
opacity: 0;
-webkit-transform: rotateX( 90deg );
-moz-transform: rotateX( 90deg );
-ms-transform: rotateX( 90deg );
-o-transform: rotateX( 90deg );
transform: rotateX( 90deg );
}
.reveal .slides section .fragment.roll-in.visible {
opacity: 1;
-webkit-transform: rotateX( 0 );
-moz-transform: rotateX( 0 );
-ms-transform: rotateX( 0 );
-o-transform: rotateX( 0 );
transform: rotateX( 0 );
}
.reveal .slides section .fragment.fade-out {
opacity: 1;
}
.reveal .slides section .fragment.fade-out.visible {
opacity: 0;
}
.reveal .slides section .fragment.highlight-red,
.reveal .slides section .fragment.highlight-green,
.reveal .slides section .fragment.highlight-blue {
opacity: 1;
}
.reveal .slides section .fragment.highlight-red.visible {
color: #ff2c2d
}
.reveal .slides section .fragment.highlight-green.visible {
color: #17ff2e;
}
.reveal .slides section .fragment.highlight-blue.visible {
color: #1b91ff;
}
/*********************************************
* DEFAULT ELEMENT STYLES
*********************************************/
.reveal .slides section {
line-height: 1.2em;
font-weight: normal;
}
.reveal img {
/* preserve aspect ratio and scale image so it's bound within the section */
max-width: 100%;
max-height: 100%;
}
.reveal strong,
.reveal b {
font-weight: bold;
}
.reveal em,
.reveal i {
font-style: italic;
}
.reveal ol,
.reveal ul {
display: inline-block;
text-align: left;
margin: 0 0 0 1em;
}
.reveal ol {
list-style-type: decimal;
}
.reveal ul {
list-style-type: disc;
}
.reveal ul ul {
list-style-type: square;
}
.reveal ul ul ul {
list-style-type: circle;
}
.reveal ul ul,
.reveal ul ol,
.reveal ol ol,
.reveal ol ul {
display: block;
margin-left: 40px;
}
.reveal p {
margin-bottom: 10px;
line-height: 1.2em;
}
.reveal q,
.reveal blockquote {
quotes: none;
}
.reveal blockquote {
display: block;
position: relative;
width: 70%;
margin: 5px auto;
padding: 5px;
font-style: italic;
background: rgba(255, 255, 255, 0.05);
box-shadow: 0px 0px 2px rgba(0,0,0,0.2);
}
.reveal blockquote:before {
content: '\201C';
}
.reveal blockquote:after {
content: '\201D';
}
.reveal q {
font-style: italic;
}
.reveal q:before {
content: '\201C';
}
.reveal q:after {
content: '\201D';
}
.reveal pre {
display: block;
position: relative;
width: 90%;
margin: 15px auto;
text-align: left;
font-size: 0.55em;
font-family: monospace;
line-height: 1.2em;
word-wrap: break-word;
}
.reveal pre code {
box-shadow: 0px 0px 6px rgba(0,0,0,0.3);
padding: 5px;
}
.reveal code {
font-family: monospace;
overflow: auto;
max-height: 400px;
}
.reveal table th,
.reveal table td {
text-align: left;
padding-right: .3em;
}
.reveal table th {
text-shadow: rgb(255,255,255) 1px 1px 2px;
}
.reveal sup {
vertical-align: super;
}
.reveal sub {
vertical-align: sub;
}
.reveal small {
display: inline-block;
font-size: 0.6em;
line-height: 1.2em;
vertical-align: top;
}
.reveal small * {
vertical-align: top;
}
/*********************************************
* CONTROLS
*********************************************/
.reveal .controls {
display: none;
position: fixed;
width: 110px;
height: 110px;
z-index: 30;
right: 10px;
bottom: 10px;
}
.reveal .controls div {
position: absolute;
opacity: 0.1;
width: 0;
height: 0;
border: 12px solid transparent;
-webkit-transition: opacity 0.2s ease;
-moz-transition: opacity 0.2s ease;
-ms-transition: opacity 0.2s ease;
-o-transition: opacity 0.2s ease;
transition: opacity 0.2s ease;
}
.reveal .controls div.enabled {
opacity: 0.6;
cursor: pointer;
}
.reveal .controls div.enabled:active {
margin-top: 1px;
}
.reveal .controls div.left {
top: 42px;
border-right-width: 22px;
border-right-color: #eee;
}
.reveal .controls div.right {
left: 74px;
top: 42px;
border-left-width: 22px;
border-left-color: #eee;
}
.reveal .controls div.up {
left: 42px;
border-bottom-width: 22px;
border-bottom-color: #eee;
}
.reveal .controls div.down {
left: 42px;
top: 74px;
border-top-width: 22px;
border-top-color: #eee;
}
/*********************************************
* PROGRESS BAR
*********************************************/
.reveal .progress {
position: fixed;
display: none;
height: 3px;
width: 100%;
bottom: 0;
left: 0;
z-index: 10;
}
.reveal .progress:after {
content: '';
display: 'block';
position: absolute;
height: 20px;
width: 100%;
top: -20px;
}
.reveal .progress span {
display: block;
height: 100%;
width: 0px;
-webkit-transition: width 800ms cubic-bezier(0.260, 0.860, 0.440, 0.985);
-moz-transition: width 800ms cubic-bezier(0.260, 0.860, 0.440, 0.985);
-ms-transition: width 800ms cubic-bezier(0.260, 0.860, 0.440, 0.985);
-o-transition: width 800ms cubic-bezier(0.260, 0.860, 0.440, 0.985);
transition: width 800ms cubic-bezier(0.260, 0.860, 0.440, 0.985);
}
/*********************************************
* SLIDES
*********************************************/
.reveal .slides {
position: absolute;
max-width: 900px;
width: 80%;
height: 60%;
left: 50%;
top: 50%;
margin-top: -320px;
padding: 20px 0px;
overflow: visible;
z-index: 1;
text-align: center;
-webkit-transition: -webkit-perspective .4s ease;
-moz-transition: -moz-perspective .4s ease;
-ms-transition: -ms-perspective .4s ease;
-o-transition: -o-perspective .4s ease;
transition: perspective .4s ease;
-webkit-perspective: 600px;
-moz-perspective: 600px;
-ms-perspective: 600px;
perspective: 600px;
-webkit-perspective-origin: 0% 25%;
-moz-perspective-origin: 0% 25%;
-ms-perspective-origin: 0% 25%;
perspective-origin: 0% 25%;
}
.reveal .slides>section,
.reveal .slides>section>section {
display: none;
position: absolute;
width: 100%;
min-height: 600px;
z-index: 10;
-webkit-transform-style: preserve-3d;
-moz-transform-style: preserve-3d;
-ms-transform-style: preserve-3d;
transform-style: preserve-3d;
-webkit-transition: all 800ms cubic-bezier(0.260, 0.860, 0.440, 0.985);
-moz-transition: all 800ms cubic-bezier(0.260, 0.860, 0.440, 0.985);
-ms-transition: all 800ms cubic-bezier(0.260, 0.860, 0.440, 0.985);
-o-transition: all 800ms cubic-bezier(0.260, 0.860, 0.440, 0.985);
transition: all 800ms cubic-bezier(0.260, 0.860, 0.440, 0.985);
}
.reveal .slides>section.present {
display: block;
z-index: 11;
opacity: 1;
}
.reveal .slides>section {
margin-left: -50%;
}
/*********************************************
* DEFAULT TRANSITION
*********************************************/
.reveal .slides>section.past {
display: block;
opacity: 0;
-webkit-transform: translate3d(-100%, 0, 0) rotateY(-90deg) translate3d(-100%, 0, 0);
-moz-transform: translate3d(-100%, 0, 0) rotateY(-90deg) translate3d(-100%, 0, 0);
-ms-transform: translate3d(-100%, 0, 0) rotateY(-90deg) translate3d(-100%, 0, 0);
transform: translate3d(-100%, 0, 0) rotateY(-90deg) translate3d(-100%, 0, 0);
}
.reveal .slides>section.future {
display: block;
opacity: 0;
-webkit-transform: translate3d(100%, 0, 0) rotateY(90deg) translate3d(100%, 0, 0);
-moz-transform: translate3d(100%, 0, 0) rotateY(90deg) translate3d(100%, 0, 0);
-ms-transform: translate3d(100%, 0, 0) rotateY(90deg) translate3d(100%, 0, 0);
transform: translate3d(100%, 0, 0) rotateY(90deg) translate3d(100%, 0, 0);
}
.reveal .slides>section>section.past {
display: block;
opacity: 0;
-webkit-transform: translate3d(0, -50%, 0) rotateX(70deg) translate3d(0, -50%, 0);
-moz-transform: translate3d(0, -50%, 0) rotateX(70deg) translate3d(0, -50%, 0);
-ms-transform: translate3d(0, -50%, 0) rotateX(70deg) translate3d(0, -50%, 0);
transform: translate3d(0, -50%, 0) rotateX(70deg) translate3d(0, -50%, 0);
}
.reveal .slides>section>section.future {
display: block;
opacity: 0;
-webkit-transform: translate3d(0, 50%, 0) rotateX(-70deg) translate3d(0, 50%, 0);
-moz-transform: translate3d(0, 50%, 0) rotateX(-70deg) translate3d(0, 50%, 0);
-ms-transform: translate3d(0, 50%, 0) rotateX(-70deg) translate3d(0, 50%, 0);
transform: translate3d(0, 50%, 0) rotateX(-70deg) translate3d(0, 50%, 0);
}
/*********************************************
* CONCAVE TRANSITION
*********************************************/
.reveal.concave .slides>section.past {
-webkit-transform: translate3d(-100%, 0, 0) rotateY(90deg) translate3d(-100%, 0, 0);
-moz-transform: translate3d(-100%, 0, 0) rotateY(90deg) translate3d(-100%, 0, 0);
-ms-transform: translate3d(-100%, 0, 0) rotateY(90deg) translate3d(-100%, 0, 0);
transform: translate3d(-100%, 0, 0) rotateY(90deg) translate3d(-100%, 0, 0);
}
.reveal.concave .slides>section.future {
-webkit-transform: translate3d(100%, 0, 0) rotateY(-90deg) translate3d(100%, 0, 0);
-moz-transform: translate3d(100%, 0, 0) rotateY(-90deg) translate3d(100%, 0, 0);
-ms-transform: translate3d(100%, 0, 0) rotateY(-90deg) translate3d(100%, 0, 0);
transform: translate3d(100%, 0, 0) rotateY(-90deg) translate3d(100%, 0, 0);
}
.reveal.concave .slides>section>section.past {
-webkit-transform: translate3d(0, -80%, 0) rotateX(-70deg) translate3d(0, -80%, 0);
-moz-transform: translate3d(0, -80%, 0) rotateX(-70deg) translate3d(0, -80%, 0);
-ms-transform: translate3d(0, -80%, 0) rotateX(-70deg) translate3d(0, -80%, 0);
transform: translate3d(0, -80%, 0) rotateX(-70deg) translate3d(0, -80%, 0);
}
.reveal.concave .slides>section>section.future {
-webkit-transform: translate3d(0, 80%, 0) rotateX(70deg) translate3d(0, 80%, 0);
-moz-transform: translate3d(0, 80%, 0) rotateX(70deg) translate3d(0, 80%, 0);
-ms-transform: translate3d(0, 80%, 0) rotateX(70deg) translate3d(0, 80%, 0);
transform: translate3d(0, 80%, 0) rotateX(70deg) translate3d(0, 80%, 0);
}
/*********************************************
* ZOOM TRANSITION
*********************************************/
.reveal.zoom .slides>section,
.reveal.zoom .slides>section>section {
-webkit-transition: all 600ms cubic-bezier(0.260, 0.860, 0.440, 0.985);
-moz-transition: all 600ms cubic-bezier(0.260, 0.860, 0.440, 0.985);
-ms-transition: all 600ms cubic-bezier(0.260, 0.860, 0.440, 0.985);
-o-transition: all 600ms cubic-bezier(0.260, 0.860, 0.440, 0.985);
transition: all 600ms cubic-bezier(0.260, 0.860, 0.440, 0.985);
}
.reveal.zoom .slides>section.past {
opacity: 0;
visibility: hidden;
-webkit-transform: scale(16);
-moz-transform: scale(16);
-ms-transform: scale(16);
-o-transform: scale(16);
transform: scale(16);
}
.reveal.zoom .slides>section.future {
opacity: 0;
visibility: hidden;
-webkit-transform: scale(0.2);
-moz-transform: scale(0.2);
-ms-transform: scale(0.2);
-o-transform: scale(0.2);
transform: scale(0.2);
}
.reveal.zoom .slides>section>section.past {
-webkit-transform: translate(0, -150%);
-moz-transform: translate(0, -150%);
-ms-transform: translate(0, -150%);
-o-transform: translate(0, -150%);
transform: translate(0, -150%);
}
.reveal.zoom .slides>section>section.future {
-webkit-transform: translate(0, 150%);
-moz-transform: translate(0, 150%);
-ms-transform: translate(0, 150%);
-o-transform: translate(0, 150%);
transform: translate(0, 150%);
}
/*********************************************
* LINEAR TRANSITION
*********************************************/
.reveal.linear .slides>section.past {
-webkit-transform: translate(-150%, 0);
-moz-transform: translate(-150%, 0);
-ms-transform: translate(-150%, 0);
-o-transform: translate(-150%, 0);
transform: translate(-150%, 0);
}
.reveal.linear .slides>section.future {
-webkit-transform: translate(150%, 0);
-moz-transform: translate(150%, 0);
-ms-transform: translate(150%, 0);
-o-transform: translate(150%, 0);
transform: translate(150%, 0);
}
.reveal.linear .slides>section>section.past {
-webkit-transform: translate(0, -150%);
-moz-transform: translate(0, -150%);
-ms-transform: translate(0, -150%);
-o-transform: translate(0, -150%);
transform: translate(0, -150%);
}
.reveal.linear .slides>section>section.future {
-webkit-transform: translate(0, 150%);
-moz-transform: translate(0, 150%);
-ms-transform: translate(0, 150%);
-o-transform: translate(0, 150%);
transform: translate(0, 150%);
}
/*********************************************
* CUBE TRANSITION
*********************************************/
.reveal.cube .slides {
-webkit-perspective-origin: 0% 25%;
-moz-perspective-origin: 0% 25%;
-ms-perspective-origin: 0% 25%;
perspective-origin: 0% 25%;
-webkit-perspective: 1300px;
-moz-perspective: 1300px;
-ms-perspective: 1300px;
perspective: 1300px;
}
.reveal.cube .slides section {
padding: 30px;
-webkit-backface-visibility: hidden;
-moz-backface-visibility: hidden;
-ms-backface-visibility: hidden;
backface-visibility: hidden;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
.reveal.cube .slides section:not(.stack):before {
content: '';
position: absolute;
display: block;
width: 100%;
height: 100%;
left: 0;
top: 0;
background: rgba(0,0,0,0.1);
border-radius: 4px;
-webkit-transform: translateZ( -20px );
-moz-transform: translateZ( -20px );
-ms-transform: translateZ( -20px );
-o-transform: translateZ( -20px );
transform: translateZ( -20px );
}
.reveal.cube .slides section:not(.stack):after {
content: '';
position: absolute;
display: block;
width: 90%;
height: 30px;
left: 5%;
bottom: 0;
background: none;
z-index: 1;
border-radius: 4px;
box-shadow: 0px 95px 25px rgba(0,0,0,0.2);
-webkit-transform: translateZ(-90px) rotateX( 65deg );
-moz-transform: translateZ(-90px) rotateX( 65deg );
-ms-transform: translateZ(-90px) rotateX( 65deg );
-o-transform: translateZ(-90px) rotateX( 65deg );
transform: translateZ(-90px) rotateX( 65deg );
}
.reveal.cube .slides>section.stack {
padding: 0;
background: none;
}
.reveal.cube .slides>section.past {
-webkit-transform-origin: 100% 0%;
-moz-transform-origin: 100% 0%;
-ms-transform-origin: 100% 0%;
transform-origin: 100% 0%;
-webkit-transform: translate3d(-100%, 0, 0) rotateY(-90deg);
-moz-transform: translate3d(-100%, 0, 0) rotateY(-90deg);
-ms-transform: translate3d(-100%, 0, 0) rotateY(-90deg);
transform: translate3d(-100%, 0, 0) rotateY(-90deg);
}
.reveal.cube .slides>section.future {
-webkit-transform-origin: 0% 0%;
-moz-transform-origin: 0% 0%;
-ms-transform-origin: 0% 0%;
transform-origin: 0% 0%;
-webkit-transform: translate3d(100%, 0, 0) rotateY(90deg);
-moz-transform: translate3d(100%, 0, 0) rotateY(90deg);
-ms-transform: translate3d(100%, 0, 0) rotateY(90deg);
transform: translate3d(100%, 0, 0) rotateY(90deg);
}
.reveal.cube .slides>section>section.past {
-webkit-transform-origin: 0% 100%;
-moz-transform-origin: 0% 100%;
-ms-transform-origin: 0% 100%;
transform-origin: 0% 100%;
-webkit-transform: translate3d(0, -100%, 0) rotateX(90deg);
-moz-transform: translate3d(0, -100%, 0) rotateX(90deg);
-ms-transform: translate3d(0, -100%, 0) rotateX(90deg);
transform: translate3d(0, -100%, 0) rotateX(90deg);
}
.reveal.cube .slides>section>section.future {
-webkit-transform-origin: 0% 0%;
-moz-transform-origin: 0% 0%;
-ms-transform-origin: 0% 0%;
transform-origin: 0% 0%;
-webkit-transform: translate3d(0, 100%, 0) rotateX(-90deg);
-moz-transform: translate3d(0, 100%, 0) rotateX(-90deg);
-ms-transform: translate3d(0, 100%, 0) rotateX(-90deg);
transform: translate3d(0, 100%, 0) rotateX(-90deg);
}
/*********************************************
* PAGE TRANSITION
*********************************************/
.reveal.page .slides {
-webkit-perspective-origin: 0% 50%;
-moz-perspective-origin: 0% 50%;
-ms-perspective-origin: 0% 50%;
perspective-origin: 0% 50%;
-webkit-perspective: 3000px;
-moz-perspective: 3000px;
-ms-perspective: 3000px;
perspective: 3000px;
}
.reveal.page .slides section {
padding: 30px;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
.reveal.page .slides section.past {
z-index: 12;
}
.reveal.page .slides section:not(.stack):before {
content: '';
position: absolute;
display: block;
width: 100%;
height: 100%;
left: 0;
top: 0;
background: rgba(0,0,0,0.1);
-webkit-transform: translateZ( -20px );
-moz-transform: translateZ( -20px );
-ms-transform: translateZ( -20px );
-o-transform: translateZ( -20px );
transform: translateZ( -20px );
}
.reveal.page .slides section:not(.stack):after {
content: '';
position: absolute;
display: block;
width: 90%;
height: 30px;
left: 5%;
bottom: 0;
background: none;
z-index: 1;
border-radius: 4px;
box-shadow: 0px 95px 25px rgba(0,0,0,0.2);
-webkit-transform: translateZ(-90px) rotateX( 65deg );
}
.reveal.page .slides>section.stack {
padding: 0;
background: none;
}
.reveal.page .slides>section.past {
-webkit-transform-origin: 0% 0%;
-moz-transform-origin: 0% 0%;
-ms-transform-origin: 0% 0%;
transform-origin: 0% 0%;
-webkit-transform: translate3d(-40%, 0, 0) rotateY(-80deg);
-moz-transform: translate3d(-40%, 0, 0) rotateY(-80deg);
-ms-transform: translate3d(-40%, 0, 0) rotateY(-80deg);
transform: translate3d(-40%, 0, 0) rotateY(-80deg);
}
.reveal.page .slides>section.future {
-webkit-transform-origin: 100% 0%;
-moz-transform-origin: 100% 0%;
-ms-transform-origin: 100% 0%;
transform-origin: 100% 0%;
-webkit-transform: translate3d(0, 0, 0);
-moz-transform: translate3d(0, 0, 0);
-ms-transform: translate3d(0, 0, 0);
transform: translate3d(0, 0, 0);
}
.reveal.page .slides>section>section.past {
-webkit-transform-origin: 0% 0%;
-moz-transform-origin: 0% 0%;
-ms-transform-origin: 0% 0%;
transform-origin: 0% 0%;
-webkit-transform: translate3d(0, -40%, 0) rotateX(80deg);
-moz-transform: translate3d(0, -40%, 0) rotateX(80deg);
-ms-transform: translate3d(0, -40%, 0) rotateX(80deg);
transform: translate3d(0, -40%, 0) rotateX(80deg);
}
.reveal.page .slides>section>section.future {
-webkit-transform-origin: 0% 100%;
-moz-transform-origin: 0% 100%;
-ms-transform-origin: 0% 100%;
transform-origin: 0% 100%;
-webkit-transform: translate3d(0, 0, 0);
-moz-transform: translate3d(0, 0, 0);
-ms-transform: translate3d(0, 0, 0);
transform: translate3d(0, 0, 0);
}
/*********************************************
* TILE-FLIP TRANSITION (CSS shader)
*********************************************/
.reveal.tileflip .slides section.present {
-webkit-transform: none;
-webkit-transition-duration: 800ms;
-webkit-filter: custom( url(shaders/tile-flip.vs) mix(url(shaders/tile-flip.fs) multiply source-atop), 10 10 border-box detached, transform perspective(1000) scale(1) rotateX(0deg) rotateY(0deg) rotateZ(0deg),
amount 0, randomness 0, flipAxis 0 1 0, tileOutline 1
);
}
.reveal.tileflip .slides section.past {
-webkit-transform: none;
-webkit-transition-duration: 800ms;
-webkit-filter: custom( url(shaders/tile-flip.vs) mix(url(shaders/tile-flip.fs) multiply source-atop), 10 10 border-box detached, transform perspective(1000) scale(1) rotateX(0deg) rotateY(0deg) rotateZ(0deg),
amount 1, randomness 0, flipAxis 0 1 0, tileOutline 1
);
}
.reveal.tileflip .slides section.future {
-webkit-transform: none;
-webkit-transition-duration: 800ms;
-webkit-filter: custom( url(shaders/tile-flip.vs) mix(url(shaders/tile-flip.fs) multiply source-atop), 10 10 border-box detached, transform perspective(1000) scale(1) rotateX(0deg) rotateY(0deg) rotateZ(0deg),
amount 1, randomness 0, flipAxis 0 1 0, tileOutline 1
);
}
.reveal.tileflip .slides>section>section.present {
-webkit-filter: custom( url(shaders/tile-flip.vs) mix(url(shaders/tile-flip.fs) multiply source-atop), 10 10 border-box detached, transform perspective(1000) scale(1) rotateX(0deg) rotateY(0deg) rotateZ(0deg),
amount 0, randomness 2, flipAxis 1 0 0, tileOutline 1
);
}
.reveal.tileflip .slides>section>section.past {
-webkit-filter: custom( url(shaders/tile-flip.vs) mix(url(shaders/tile-flip.fs) multiply source-atop), 10 10 border-box detached, transform perspective(1000) scale(1) rotateX(0deg) rotateY(0deg) rotateZ(0deg),
amount 1, randomness 2, flipAxis 1 0 0, tileOutline 1
);
}
.reveal.tileflip .slides>section>section.future {
-webkit-filter: custom( url(shaders/tile-flip.vs) mix(url(shaders/tile-flip.fs) multiply source-atop), 10 10 border-box detached, transform perspective(1000) scale(1) rotateX(0deg) rotateY(0deg) rotateZ(0deg),
amount 1, randomness 2, flipAxis 1 0 0, tileOutline 1
);
}
/*********************************************
* NO TRANSITION
*********************************************/
.reveal.none .slides section {
-webkit-transform: none;
-moz-transform: none;
-ms-transform: none;
-o-transform: none;
transform: none;
-webkit-transition: none;
-moz-transition: none;
-ms-transition: none;
-o-transition: none;
transition: none;
}
/*********************************************
* OVERVIEW
*********************************************/
.reveal.overview .slides {
-webkit-perspective: 700px;
-moz-perspective: 700px;
-ms-perspective: 700px;
perspective: 700px;
}
.reveal.overview .slides section {
padding: 20px 0;
max-height: 600px;
overflow: hidden;
opacity: 1!important;
visibility: visible!important;
cursor: pointer;
background: rgba(0,0,0,0.1);
}
.reveal.overview .slides section .fragment {
opacity: 1;
}
.reveal.overview .slides section:after,
.reveal.overview .slides section:before {
display: none !important;
}
.reveal.overview .slides section>section {
opacity: 1;
cursor: pointer;
}
.reveal.overview .slides section:hover {
background: rgba(0,0,0,0.3);
}
.reveal.overview .slides section.present {
background: rgba(0,0,0,0.3);
}
.reveal.overview .slides>section.stack {
background: none;
padding: 0;
overflow: visible;
}
/*********************************************
* PAUSED MODE
*********************************************/
.reveal .pause-overlay {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: black;
visibility: hidden;
opacity: 0;
z-index: 100;
-webkit-transition: all 1s ease;
-moz-transition: all 1s ease;
-ms-transition: all 1s ease;
-o-transition: all 1s ease;
transition: all 1s ease;
}
.reveal.paused .pause-overlay {
visibility: visible;
opacity: 1;
}
/*********************************************
* FALLBACK
*********************************************/
.no-transforms {
overflow-y: auto;
}
.no-transforms .slides section {
display: block!important;
opacity: 1!important;
position: relative!important;
height: auto;
min-height: auto;
margin-bottom: 100px;
-webkit-transform: none;
-moz-transform: none;
-ms-transform: none;
transform: none;
}
/*********************************************
* BACKGROUND STATES
*********************************************/
.reveal .state-background {
position: absolute;
width: 100%;
height: 100%;
background: rgba( 0, 0, 0, 0 );
-webkit-transition: background 800ms ease;
-moz-transition: background 800ms ease;
-ms-transition: background 800ms ease;
-o-transition: background 800ms ease;
transition: background 800ms ease;
}
.alert .reveal .state-background {
background: rgba( 200, 50, 30, 0.6 );
}
.soothe .reveal .state-background {
background: rgba( 50, 200, 90, 0.4 );
}
.blackout .reveal .state-background {
background: rgba( 0, 0, 0, 0.6 );
}
/*********************************************
* SPEAKER NOTES
*********************************************/
.reveal aside.notes {
display: none;
}
/*********************************************
* ZOOM PLUGIN
*********************************************/
.zoomed .reveal *,
.zoomed .reveal *:before,
.zoomed .reveal *:after {
-webkit-transform: none !important;
-moz-transform: none !important;
-ms-transform: none !important;
transform: none !important;
-webkit-backface-visibility: visible !important;
-moz-backface-visibility: visible !important;
-ms-backface-visibility: visible !important;
backface-visibility: visible !important;
}
.zoomed .reveal .progress,
.zoomed .reveal .controls {
opacity: 0;
}
.zoomed .reveal .roll span {
background: none;
}
.zoomed .reveal .roll span:after {
visibility: hidden;
}
|
# Fact: lsbdistid
#
# Purpose: Return Linux Standard Base information for the host.
#
# Resolution:
# Uses the lsbdistid key of the os structured fact, which itself
# uses the `lsb_release` system command.
#
# Caveats:
# Only works on Linux (and the kfreebsd derivative) systems.
# Requires the `lsb_release` program, which may not be installed by default.
# Also is as only as accurate as that program outputs.
Facter.add(:lsbdistid) do
confine do
!Facter.value(:os)["lsb"].nil?
end
setcode { Facter.value("os")["lsb"]["distid"] }
end
|
"""Tests for distutils.command.build_scripts."""
import os
import unittest
from distutils.command.build_scripts import build_scripts
from distutils.core import Distribution
import sysconfig
from distutils.tests import support
from test.test_support import run_unittest
class BuildScriptsTestCase(support.TempdirManager,
support.LoggingSilencer,
unittest.TestCase):
def test_default_settings(self):
cmd = self.get_build_scripts_cmd("/foo/bar", [])
self.assertTrue(not cmd.force)
self.assertTrue(cmd.build_dir is None)
cmd.finalize_options()
self.assertTrue(cmd.force)
self.assertEqual(cmd.build_dir, "/foo/bar")
def test_build(self):
source = self.mkdtemp()
target = self.mkdtemp()
expected = self.write_sample_scripts(source)
cmd = self.get_build_scripts_cmd(target,
[os.path.join(source, fn)
for fn in expected])
cmd.finalize_options()
cmd.run()
built = os.listdir(target)
for name in expected:
self.assertTrue(name in built)
def get_build_scripts_cmd(self, target, scripts):
import sys
dist = Distribution()
dist.scripts = scripts
dist.command_obj["build"] = support.DummyCommand(
build_scripts=target,
force=1,
executable=sys.executable
)
return build_scripts(dist)
def write_sample_scripts(self, dir):
expected = []
expected.append("script1.py")
self.write_script(dir, "script1.py",
("#! /usr/bin/env python2.3\n"
"# bogus script w/ Python sh-bang\n"
"pass\n"))
expected.append("script2.py")
self.write_script(dir, "script2.py",
("#!/usr/bin/python\n"
"# bogus script w/ Python sh-bang\n"
"pass\n"))
expected.append("shell.sh")
self.write_script(dir, "shell.sh",
("#!/bin/sh\n"
"# bogus shell script w/ sh-bang\n"
"exit 0\n"))
return expected
def write_script(self, dir, name, text):
f = open(os.path.join(dir, name), "w")
try:
f.write(text)
finally:
f.close()
def test_version_int(self):
source = self.mkdtemp()
target = self.mkdtemp()
expected = self.write_sample_scripts(source)
cmd = self.get_build_scripts_cmd(target,
[os.path.join(source, fn)
for fn in expected])
cmd.finalize_options()
# http://bugs.python.org/issue4524
#
# On linux-g++-32 with command line `./configure --enable-ipv6
# --with-suffix=3`, python is compiled okay but the build scripts
# failed when writing the name of the executable
old = sysconfig.get_config_vars().get('VERSION')
sysconfig._CONFIG_VARS['VERSION'] = 4
try:
cmd.run()
finally:
if old is not None:
sysconfig._CONFIG_VARS['VERSION'] = old
built = os.listdir(target)
for name in expected:
self.assertTrue(name in built)
def test_suite():
return unittest.makeSuite(BuildScriptsTestCase)
if __name__ == "__main__":
run_unittest(test_suite())
|
import { sendMail } from '../functions/sendMail';
import { unsubscribe } from '../functions/unsubscribe';
export const Mailer = {
sendMail,
unsubscribe,
};
|
/*
* The MIT License
*
* Copyright 2018 Victor Martinez.
*
* 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.
*/
package hudson.cli;
import hudson.matrix.Axis;
import hudson.matrix.AxisList;
import hudson.matrix.MatrixProject;
import hudson.maven.MavenModuleSet;
import hudson.model.DirectlyModifiableView;
import hudson.model.FreeStyleProject;
import hudson.model.Label;
import hudson.model.ListView;
import hudson.model.labels.LabelExpression;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.jvnet.hudson.test.Issue;
import org.jvnet.hudson.test.JenkinsRule;
import org.jvnet.hudson.test.MockFolder;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.isEmptyString;
import static org.hamcrest.Matchers.not;
public class ListJobsCommandTest {
@Rule public JenkinsRule j = new JenkinsRule();
private CLICommand listJobsCommand;
private CLICommandInvoker command;
@Before public void setUp() {
listJobsCommand = new ListJobsCommand();
command = new CLICommandInvoker(j, listJobsCommand);
}
@Test public void getAllJobsFromView() throws Exception {
MockFolder folder = j.createFolder("Folder");
MockFolder nestedFolder = folder.createProject(MockFolder.class, "NestedFolder");
FreeStyleProject job = folder.createProject(FreeStyleProject.class, "job");
FreeStyleProject nestedJob = nestedFolder.createProject(FreeStyleProject.class, "nestedJob");
ListView view = new ListView("OuterFolder");
view.setRecurse(true);
j.jenkins.addView(view);
((DirectlyModifiableView) j.jenkins.getView("OuterFolder")).add(folder);
((DirectlyModifiableView) j.jenkins.getView("OuterFolder")).add(job);
CLICommandInvoker.Result result = command.invokeWithArgs("OuterFolder");
assertThat(result, CLICommandInvoker.Matcher.succeeded());
assertThat(result.stdout(), containsString("Folder"));
assertThat(result.stdout(), containsString("job"));
assertThat(result.stdout(), not(containsString("nestedJob")));
}
@Issue("JENKINS-48220")
@Test public void getAllJobsFromFolder() throws Exception {
MockFolder folder = j.createFolder("Folder");
MockFolder nestedFolder = folder.createProject(MockFolder.class, "NestedFolder");
FreeStyleProject job = folder.createProject(FreeStyleProject.class, "job");
FreeStyleProject nestedJob = nestedFolder.createProject(FreeStyleProject.class, "nestedJob");
CLICommandInvoker.Result result = command.invokeWithArgs("Folder");
assertThat(result, CLICommandInvoker.Matcher.succeeded());
assertThat(result.stdout(), containsString("job"));
assertThat(result.stdout(), containsString("NestedFolder"));
assertThat(result.stdout(), not(containsString("nestedJob")));
}
@Issue("JENKINS-18393")
@Test public void getAllJobsFromFolderWithMatrixProject() throws Exception {
MockFolder folder = j.createFolder("Folder");
FreeStyleProject job1 = folder.createProject(FreeStyleProject.class, "job1");
FreeStyleProject job2 = folder.createProject(FreeStyleProject.class, "job2");
MatrixProject matrixProject = folder.createProject(MatrixProject.class, "mp");
matrixProject.setDisplayName("downstream");
matrixProject.setAxes(new AxisList(
new Axis("axis", "a", "b")
));
Label label = LabelExpression.get("aws-linux-dummy");
matrixProject.setAssignedLabel(label);
CLICommandInvoker.Result result = command.invokeWithArgs("Folder");
assertThat(result, CLICommandInvoker.Matcher.succeeded());
assertThat(result.stdout(), containsString("job1"));
assertThat(result.stdout(), containsString("job2"));
assertThat(result.stdout(), containsString("mp"));
}
@Issue("JENKINS-18393")
@Test public void getAllJobsFromFolderWithMavenModuleSet() throws Exception {
MockFolder folder = j.createFolder("Folder");
FreeStyleProject job1 = folder.createProject(FreeStyleProject.class, "job1");
FreeStyleProject job2 = folder.createProject(FreeStyleProject.class, "job2");
MavenModuleSet mavenProject = folder.createProject(MavenModuleSet.class, "mvn");
CLICommandInvoker.Result result = command.invokeWithArgs("Folder");
assertThat(result, CLICommandInvoker.Matcher.succeeded());
assertThat(result.stdout(), containsString("job1"));
assertThat(result.stdout(), containsString("job2"));
assertThat(result.stdout(), containsString("mvn"));
}
@Issue("JENKINS-18393")
@Test public void failForMatrixProject() throws Exception {
MatrixProject matrixProject = j.createProject(MatrixProject.class, "mp");
CLICommandInvoker.Result result = command.invokeWithArgs("MatrixJob");
assertThat(result, CLICommandInvoker.Matcher.failedWith(3));
assertThat(result.stdout(), isEmptyString());
assertThat(result.stderr(), containsString("No view or item group with the given name 'MatrixJob' found."));
}
}
|
/* flatpickr v4.2.1, @license MIT */
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
typeof define === 'function' && define.amd ? define(['exports'], factory) :
(factory((global.sv = {})));
}(this, (function (exports) { 'use strict';
var fp = typeof window !== "undefined" && window.flatpickr !== undefined
? window.flatpickr
: {
l10ns: {},
};
var Swedish = {
firstDayOfWeek: 1,
weekAbbreviation: "v",
weekdays: {
shorthand: ["Sön", "Mån", "Tis", "Ons", "Tor", "Fre", "Lör"],
longhand: [
"Söndag",
"Måndag",
"Tisdag",
"Onsdag",
"Torsdag",
"Fredag",
"Lördag",
],
},
months: {
shorthand: [
"Jan",
"Feb",
"Mar",
"Apr",
"Maj",
"Jun",
"Jul",
"Aug",
"Sep",
"Okt",
"Nov",
"Dec",
],
longhand: [
"Januari",
"Februari",
"Mars",
"April",
"Maj",
"Juni",
"Juli",
"Augusti",
"September",
"Oktober",
"November",
"December",
],
},
ordinal: function () {
return ".";
},
};
fp.l10ns.sv = Swedish;
var sv = fp.l10ns;
exports.Swedish = Swedish;
exports['default'] = sv;
Object.defineProperty(exports, '__esModule', { value: true });
})));
|
require 'spec_helper'
require 'command_helper'
require 'shellwords'
describe "Invoking the 'mina' command in a project" do
before :each do
Dir.chdir root('test_env')
end
it 'should echo commands in verbose mode' do
mina 'deploy', '--verbose', '--simulate'
expect(stdout).to include %[echo #{Shellwords.escape('$ git')}]
end
it 'should not echo commands when not in verbose mode' do
mina 'deploy', '--simulate'
expect(stdout).not_to include %[echo #{Shellwords.escape('$ git')}]
end
end
|
##
# This file is part of WhatWeb and may be subject to
# redistribution and commercial restrictions. Please see the WhatWeb
# web site for more information on licensing and terms of use.
# http://www.morningstarsecurity.com/research/whatweb
##
Plugin.define "Citrix-NetScaler" do
author "Aung Khant <http://yehg.net/>" # 2011-02-04
version "0.1"
description "Citrix NetScaler - http://www.citrix.com/netscaler"
def passive
m = []
m << {:name=>"http via" } if @headers["via"] =~ /NS\-CACHE/i
if @headers["via"] =~ /NS\-CACHE\-(\d{1,4}\.\d{1,4}):/i
version = @headers["via"].scan(/NS\-CACHE\-(\d{1,4}\.\d{1,4})/i)
m << {:version=>version.to_s}
end
m
end
end
|
/* 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 "glk/glulx/glulx.h"
namespace Glk {
namespace Glulx {
#define IFFID(c1, c2, c3, c4) MKTAG(c1, c2, c3, c4)
bool Glulx::init_serial() {
undo_chain_num = 0;
undo_chain_size = max_undo_level;
undo_chain = (unsigned char **)glulx_malloc(sizeof(unsigned char *) * undo_chain_size);
if (!undo_chain)
return false;
#ifdef SERIALIZE_CACHE_RAM
{
uint len = (endmem - ramstart);
uint res;
ramcache = (unsigned char *)glulx_malloc(sizeof(unsigned char *) * len);
if (!ramcache)
return false;
_gameFile.seek(gamefile_start + ramstart);
res = _gameFile.read(ramcache, len);
if (res != len)
return false;
}
#endif /* SERIALIZE_CACHE_RAM */
return true;
}
void Glulx::final_serial() {
if (undo_chain) {
int ix;
for (ix = 0; ix < undo_chain_num; ix++) {
glulx_free(undo_chain[ix]);
}
glulx_free(undo_chain);
}
undo_chain = nullptr;
undo_chain_size = 0;
undo_chain_num = 0;
#ifdef SERIALIZE_CACHE_RAM
if (ramcache) {
glulx_free(ramcache);
ramcache = nullptr;
}
#endif /* SERIALIZE_CACHE_RAM */
}
uint Glulx::perform_saveundo() {
dest_t dest;
uint res;
uint memstart = 0, memlen = 0, heapstart = 0, heaplen = 0;
uint stackstart = 0, stacklen = 0;
/* The format for undo-saves is simpler than for saves on disk. We
just have a memory chunk, a heap chunk, and a stack chunk, in
that order. We skip the IFF chunk headers (although the size
fields are still there.) We also don't bother with IFF's 16-bit
alignment. */
if (undo_chain_size == 0)
return 1;
dest._isMem = true;
res = 0;
if (res == 0) {
res = write_long(&dest, 0); /* space for chunk length */
}
if (res == 0) {
memstart = dest._pos;
res = write_memstate(&dest);
memlen = dest._pos - memstart;
}
if (res == 0) {
res = write_long(&dest, 0); /* space for chunk length */
}
if (res == 0) {
heapstart = dest._pos;
res = write_heapstate(&dest, false);
heaplen = dest._pos - heapstart;
}
if (res == 0) {
res = write_long(&dest, 0); /* space for chunk length */
}
if (res == 0) {
stackstart = dest._pos;
res = write_stackstate(&dest, false);
stacklen = dest._pos - stackstart;
}
if (res == 0) {
/* Trim it down to the perfect size. */
dest._ptr = (byte *)glulx_realloc(dest._ptr, dest._pos);
if (!dest._ptr)
res = 1;
}
if (res == 0) {
res = reposition_write(&dest, memstart - 4);
}
if (res == 0) {
res = write_long(&dest, memlen);
}
if (res == 0) {
res = reposition_write(&dest, heapstart - 4);
}
if (res == 0) {
res = write_long(&dest, heaplen);
}
if (res == 0) {
res = reposition_write(&dest, stackstart - 4);
}
if (res == 0) {
res = write_long(&dest, stacklen);
}
if (res == 0) {
/* It worked. */
if (undo_chain_num >= undo_chain_size) {
glulx_free(undo_chain[undo_chain_num - 1]);
undo_chain[undo_chain_num - 1] = nullptr;
}
if (undo_chain_size > 1)
memmove(undo_chain + 1, undo_chain,
(undo_chain_size - 1) * sizeof(unsigned char *));
undo_chain[0] = dest._ptr;
if (undo_chain_num < undo_chain_size)
undo_chain_num += 1;
dest._ptr = nullptr;
} else {
/* It didn't work. */
if (dest._ptr) {
glulx_free(dest._ptr);
dest._ptr = nullptr;
}
}
return res;
}
uint Glulx::perform_restoreundo() {
dest_t dest;
uint res, val = 0;
uint heapsumlen = 0;
uint *heapsumarr = nullptr;
/* If profiling is enabled and active then fail. */
#if VM_PROFILING
if (profile_profiling_active())
return 1;
#endif /* VM_PROFILING */
if (undo_chain_size == 0 || undo_chain_num == 0)
return 1;
dest._isMem = true;
dest._ptr = undo_chain[0];
res = 0;
if (res == 0) {
res = read_long(&dest, &val);
}
if (res == 0) {
res = read_memstate(&dest, val);
}
if (res == 0) {
res = read_long(&dest, &val);
}
if (res == 0) {
res = read_heapstate(&dest, val, false, &heapsumlen, &heapsumarr);
}
if (res == 0) {
res = read_long(&dest, &val);
}
if (res == 0) {
res = read_stackstate(&dest, val, false);
}
/* ### really, many of the failure modes of those calls ought to
cause fatal errors. The stack or main memory may be damaged now. */
if (res == 0) {
if (heapsumarr)
res = heap_apply_summary(heapsumlen, heapsumarr);
}
if (res == 0) {
/* It worked. */
if (undo_chain_size > 1)
memmove(undo_chain, undo_chain + 1,
(undo_chain_size - 1) * sizeof(unsigned char *));
undo_chain_num -= 1;
glulx_free(dest._ptr);
dest._ptr = nullptr;
} else {
/* It didn't work. */
dest._ptr = nullptr;
}
return res;
}
Common::Error Glulx::readSaveData(Common::SeekableReadStream *rs) {
Common::ErrorCode errCode = Common::kNoError;
QuetzalReader r;
if (r.open(rs))
// Load in the savegame chunks
errCode = loadGameChunks(r).getCode();
return errCode;
}
Common::Error Glulx::writeGameData(Common::WriteStream *ws) {
QuetzalWriter w;
Common::ErrorCode errCode = saveGameChunks(w).getCode();
if (errCode == Common::kNoError) {
w.save(ws, _savegameDescription);
}
return errCode;
}
Common::Error Glulx::loadGameChunks(QuetzalReader &quetzal) {
uint res = 0;
uint heapsumlen = 0;
uint *heapsumarr = nullptr;
for (QuetzalReader::Iterator it = quetzal.begin();
it != quetzal.end() && !res; ++it) {
Common::SeekableReadStream *rs = it.getStream();
dest_t dest;
dest._src = rs;
switch ((*it)._id) {
case ID_IFhd:
for (int ix = 0; ix < 128 && !res; ix++) {
byte v = rs->readByte();
if (Mem1(ix) != v)
// ### non-matching header
res = 1;
}
break;
case ID_CMem:
res = read_memstate(&dest, rs->size());
break;
case MKTAG('M', 'A', 'l', 'l'):
res = read_heapstate(&dest, rs->size(), true, &heapsumlen, &heapsumarr);
break;
case ID_Stks:
res = read_stackstate(&dest, rs->size(), true);
break;
default:
break;
}
delete rs;
}
if (!res) {
if (heapsumarr) {
/* The summary might have come from any interpreter, so it could
be out of order. We'll sort it. */
glulx_sort(heapsumarr + 2, (heapsumlen - 2) / 2, 2 * sizeof(uint), &sort_heap_summary);
res = heap_apply_summary(heapsumlen, heapsumarr);
}
}
return res ? Common::kReadingFailed : Common::kNoError;
}
Common::Error Glulx::saveGameChunks(QuetzalWriter &quetzal) {
uint res = 0;
// IFHd
if (!res) {
Common::WriteStream &ws = quetzal.add(ID_IFhd);
for (int ix = 0; res == 0 && ix < 128; ix++)
ws.writeByte(Mem1(ix));
}
// CMem
if (!res) {
Common::WriteStream &ws = quetzal.add(ID_CMem);
dest_t dest;
dest._dest = &ws;
res = write_memstate(&dest);
}
// MAll
if (!res) {
Common::WriteStream &ws = quetzal.add(MKTAG('M', 'A', 'l', 'l'));
dest_t dest;
dest._dest = &ws;
res = write_heapstate(&dest, true);
}
// Stks
if (!res) {
Common::WriteStream &ws = quetzal.add(ID_Stks);
dest_t dest;
dest._dest = &ws;
res = write_stackstate(&dest, true);
}
// All done
return res ? Common::kUnknownError : Common::kNoError;
}
int Glulx::reposition_write(dest_t *dest, uint pos) {
if (dest->_isMem) {
dest->_pos = pos;
} else {
error("Seeking a WriteStream isn't allowed");
}
return 0;
}
int Glulx::write_buffer(dest_t *dest, const byte *ptr, uint len) {
if (dest->_isMem) {
if (dest->_pos + len > dest->_size) {
dest->_size = dest->_pos + len + 1024;
if (!dest->_ptr) {
dest->_ptr = (byte *)glulx_malloc(dest->_size);
} else {
dest->_ptr = (byte *)glulx_realloc(dest->_ptr, dest->_size);
}
if (!dest->_ptr)
return 1;
}
memcpy(dest->_ptr + dest->_pos, ptr, len);
} else {
dest->_dest->write(ptr, len);
}
dest->_pos += len;
return 0;
}
int Glulx::read_buffer(dest_t *dest, byte *ptr, uint len) {
uint newlen;
if (dest->_isMem) {
memcpy(ptr, dest->_ptr + dest->_pos, len);
} else {
newlen = dest->_src->read(ptr, len);
if (newlen != len)
return 1;
}
dest->_pos += len;
return 0;
}
int Glulx::write_long(dest_t *dest, uint val) {
unsigned char buf[4];
Write4(buf, val);
return write_buffer(dest, buf, 4);
}
int Glulx::write_short(dest_t *dest, uint16 val) {
unsigned char buf[2];
Write2(buf, val);
return write_buffer(dest, buf, 2);
}
int Glulx::write_byte(dest_t *dest, byte val) {
return write_buffer(dest, &val, 1);
}
int Glulx::read_long(dest_t *dest, uint *val) {
unsigned char buf[4];
int res = read_buffer(dest, buf, 4);
if (res)
return res;
*val = Read4(buf);
return 0;
}
int Glulx::read_short(dest_t *dest, uint16 *val) {
unsigned char buf[2];
int res = read_buffer(dest, buf, 2);
if (res)
return res;
*val = Read2(buf);
return 0;
}
int Glulx::read_byte(dest_t *dest, byte *val) {
return read_buffer(dest, val, 1);
}
uint Glulx::write_memstate(dest_t *dest) {
uint res, pos;
int val;
int runlen;
unsigned char ch;
#ifdef SERIALIZE_CACHE_RAM
uint cachepos;
#endif /* SERIALIZE_CACHE_RAM */
res = write_long(dest, endmem);
if (res)
return res;
runlen = 0;
#ifdef SERIALIZE_CACHE_RAM
cachepos = 0;
#else /* SERIALIZE_CACHE_RAM */
_gameFile.seek(gamefile_start + ramstart);
#endif /* SERIALIZE_CACHE_RAM */
for (pos = ramstart; pos < endmem; pos++) {
ch = Mem1(pos);
if (pos < endgamefile) {
#ifdef SERIALIZE_CACHE_RAM
val = ramcache[cachepos];
cachepos++;
#else /* SERIALIZE_CACHE_RAM */
val = glk_get_char_stream(gamefile);
if (val == -1) {
fatal_error("The game file ended unexpectedly while saving.");
}
#endif /* SERIALIZE_CACHE_RAM */
ch ^= (unsigned char)val;
}
if (ch == 0) {
runlen++;
} else {
/* Write any run we've got. */
while (runlen) {
if (runlen >= 0x100)
val = 0x100;
else
val = runlen;
res = write_byte(dest, 0);
if (res)
return res;
res = write_byte(dest, (val - 1));
if (res)
return res;
runlen -= val;
}
/* Write the byte we got. */
res = write_byte(dest, ch);
if (res)
return res;
}
}
/* It's possible we've got a run left over, but we don't write it. */
return 0;
}
uint Glulx::read_memstate(dest_t *dest, uint chunklen) {
uint chunkend = dest->_pos + chunklen;
uint newlen;
uint res, pos;
int val;
int runlen;
unsigned char ch, ch2;
#ifdef SERIALIZE_CACHE_RAM
uint cachepos;
#endif /* SERIALIZE_CACHE_RAM */
heap_clear();
res = read_long(dest, &newlen);
if (res)
return res;
res = change_memsize(newlen, false);
if (res)
return res;
runlen = 0;
#ifdef SERIALIZE_CACHE_RAM
cachepos = 0;
#else /* SERIALIZE_CACHE_RAM */
_gameFile.seek(gamefile_start + ramstart);
#endif /* SERIALIZE_CACHE_RAM */
for (pos = ramstart; pos < endmem; pos++) {
if (pos < endgamefile) {
#ifdef SERIALIZE_CACHE_RAM
val = ramcache[cachepos];
cachepos++;
#else /* SERIALIZE_CACHE_RAM */
if (_gameFile.pos() >= _gameFile.size()) {
fatal_error("The game file ended unexpectedly while restoring.");
val = _gameFile.readByte();
}
#endif /* SERIALIZE_CACHE_RAM */
ch = (unsigned char)val;
} else {
ch = 0;
}
if (dest->_pos >= chunkend) {
/* we're into the final, unstored run. */
} else if (runlen) {
runlen--;
} else {
res = read_byte(dest, &ch2);
if (res)
return res;
if (ch2 == 0) {
res = read_byte(dest, &ch2);
if (res)
return res;
runlen = (uint)ch2;
} else {
ch ^= ch2;
}
}
if (pos >= protectstart && pos < protectend)
continue;
MemW1(pos, ch);
}
return 0;
}
uint Glulx::write_heapstate(dest_t *dest, int portable) {
uint res;
uint sumlen;
uint *sumarray;
res = heap_get_summary(&sumlen, &sumarray);
if (res)
return res;
if (!sumarray)
return 0; /* no heap */
res = write_heapstate_sub(sumlen, sumarray, dest, portable);
glulx_free(sumarray);
return res;
}
uint Glulx::write_heapstate_sub(uint sumlen, uint *sumarray, dest_t *dest, int portable) {
uint res, lx;
/* If we're storing for the purpose of undo, we don't need to do any
byte-swapping, because the result will only be used by this session. */
if (!portable) {
res = write_buffer(dest, (const byte *)sumarray, sumlen * sizeof(uint));
if (res)
return res;
return 0;
}
for (lx = 0; lx < sumlen; lx++) {
res = write_long(dest, sumarray[lx]);
if (res)
return res;
}
return 0;
}
int Glulx::sort_heap_summary(const void *p1, const void *p2) {
uint v1 = *(const uint *)p1;
uint v2 = *(const uint *)p2;
if (v1 < v2)
return -1;
if (v1 > v2)
return 1;
return 0;
}
uint Glulx::read_heapstate(dest_t *dest, uint chunklen, int portable, uint *sumlen, uint **summary) {
uint res, count, lx;
uint *arr;
*sumlen = 0;
*summary = nullptr;
if (chunklen == 0)
return 0; /* no heap */
if (!portable) {
count = chunklen / sizeof(uint);
arr = (uint *)glulx_malloc(chunklen);
if (!arr)
return 1;
res = read_buffer(dest, (byte *)arr, chunklen);
if (res)
return res;
*sumlen = count;
*summary = arr;
return 0;
}
count = chunklen / 4;
arr = (uint *)glulx_malloc(count * sizeof(uint));
if (!arr)
return 1;
for (lx = 0; lx < count; lx++) {
res = read_long(dest, arr + lx);
if (res)
return res;
}
*sumlen = count;
*summary = arr;
return 0;
}
uint Glulx::write_stackstate(dest_t *dest, int portable) {
uint res;
uint lx;
uint lastframe;
/* If we're storing for the purpose of undo, we don't need to do any
byte-swapping, because the result will only be used by this session. */
if (!portable) {
res = write_buffer(dest, stack, stackptr);
if (res)
return res;
return 0;
}
/* Write a portable stack image. To do this, we have to write stack
frames in order, bottom to top. Remember that the last word of
every stack frame is a pointer to the beginning of that stack frame.
(This includes the last frame, because the save opcode pushes on
a call stub before it calls perform_save().) */
lastframe = (uint)(-1);
while (1) {
uint frameend, frm, frm2, frm3;
unsigned char loctype, loccount;
uint numlocals, frlen, locpos;
/* Find the next stack frame (after the one in lastframe). Sadly,
this requires searching the stack from the top down. We have to
do this for *every* frame, which takes N^2 time overall. But
save routines usually aren't nested very deep.
If it becomes a practical problem, we can build a stack-frame
array, which requires dynamic allocation. */
for (frm = stackptr, frameend = stackptr;
frm != 0 && (frm2 = Stk4(frm - 4)) != lastframe;
frameend = frm, frm = frm2) { };
/* Write out the frame. */
frm2 = frm;
frlen = Stk4(frm2);
frm2 += 4;
res = write_long(dest, frlen);
if (res)
return res;
locpos = Stk4(frm2);
frm2 += 4;
res = write_long(dest, locpos);
if (res)
return res;
frm3 = frm2;
numlocals = 0;
while (1) {
loctype = Stk1(frm2);
frm2 += 1;
loccount = Stk1(frm2);
frm2 += 1;
res = write_byte(dest, loctype);
if (res)
return res;
res = write_byte(dest, loccount);
if (res)
return res;
if (loctype == 0 && loccount == 0)
break;
numlocals++;
}
if ((numlocals & 1) == 0) {
res = write_byte(dest, 0);
if (res)
return res;
res = write_byte(dest, 0);
if (res)
return res;
frm2 += 2;
}
if (frm2 != frm + locpos)
fatal_error("Inconsistent stack frame during save.");
/* Write out the locals. */
for (lx = 0; lx < numlocals; lx++) {
loctype = Stk1(frm3);
frm3 += 1;
loccount = Stk1(frm3);
frm3 += 1;
if (loctype == 0 && loccount == 0)
break;
/* Put in up to 0, 1, or 3 bytes of padding, depending on loctype. */
while (frm2 & (loctype - 1)) {
res = write_byte(dest, 0);
if (res)
return res;
frm2 += 1;
}
/* Put in this set of locals. */
switch (loctype) {
case 1:
do {
res = write_byte(dest, Stk1(frm2));
if (res)
return res;
frm2 += 1;
loccount--;
} while (loccount);
break;
case 2:
do {
res = write_short(dest, Stk2(frm2));
if (res)
return res;
frm2 += 2;
loccount--;
} while (loccount);
break;
case 4:
do {
res = write_long(dest, Stk4(frm2));
if (res)
return res;
frm2 += 4;
loccount--;
} while (loccount);
break;
}
}
if (frm2 != frm + frlen)
fatal_error("Inconsistent stack frame during save.");
while (frm2 < frameend) {
res = write_long(dest, Stk4(frm2));
if (res)
return res;
frm2 += 4;
}
/* Go on to the next frame. */
if (frameend == stackptr)
break; /* All done. */
lastframe = frm;
}
return 0;
}
uint Glulx::read_stackstate(dest_t *dest, uint chunklen, int portable) {
uint res;
uint frameend, frm, frm2, frm3, locpos, frlen, numlocals;
if (chunklen > stacksize)
return 1;
stackptr = chunklen;
frameptr = 0;
valstackbase = 0;
localsbase = 0;
if (!portable) {
res = read_buffer(dest, stack, stackptr);
if (res)
return res;
return 0;
}
/* This isn't going to be pleasant; we're going to read the data in
as a block, and then convert it in-place. */
res = read_buffer(dest, stack, stackptr);
if (res)
return res;
frameend = stackptr;
while (frameend != 0) {
/* Read the beginning-of-frame pointer. Remember, right now, the
whole frame is stored big-endian. So we have to read with the
Read*() macros, and then write with the StkW*() macros. */
frm = Read4(stack + (frameend - 4));
frm2 = frm;
frlen = Read4(stack + frm2);
StkW4(frm2, frlen);
frm2 += 4;
locpos = Read4(stack + frm2);
StkW4(frm2, locpos);
frm2 += 4;
/* The locals-format list is in bytes, so we don't have to convert it. */
frm3 = frm2;
frm2 = frm + locpos;
numlocals = 0;
while (1) {
unsigned char loctype, loccount;
loctype = Read1(stack + frm3);
frm3 += 1;
loccount = Read1(stack + frm3);
frm3 += 1;
if (loctype == 0 && loccount == 0)
break;
/* Skip up to 0, 1, or 3 bytes of padding, depending on loctype. */
while (frm2 & (loctype - 1)) {
StkW1(frm2, 0);
frm2++;
}
/* Convert this set of locals. */
switch (loctype) {
case 1:
do {
/* Don't need to convert bytes. */
frm2 += 1;
loccount--;
} while (loccount);
break;
case 2:
do {
uint16 loc = Read2(stack + frm2);
StkW2(frm2, loc);
frm2 += 2;
loccount--;
} while (loccount);
break;
case 4:
do {
uint loc = Read4(stack + frm2);
StkW4(frm2, loc);
frm2 += 4;
loccount--;
} while (loccount);
break;
}
numlocals++;
}
if ((numlocals & 1) == 0) {
StkW1(frm3, 0);
frm3++;
StkW1(frm3, 0);
frm3++;
}
if (frm3 != frm + locpos) {
return 1;
}
while (frm2 & 3) {
StkW1(frm2, 0);
frm2++;
}
if (frm2 != frm + frlen) {
return 1;
}
/* Now, the values pushed on the stack after the call frame itself.
This includes the stub. */
while (frm2 < frameend) {
uint loc = Read4(stack + frm2);
StkW4(frm2, loc);
frm2 += 4;
}
frameend = frm;
}
return 0;
}
uint Glulx::perform_verify() {
uint len, chksum = 0, newlen;
unsigned char buf[4];
uint val, newsum, ix;
len = gamefile_len;
if (len < 256 || (len & 0xFF) != 0)
return 1;
_gameFile.seek(gamefile_start);
newsum = 0;
/* Read the header */
for (ix = 0; ix < 9; ix++) {
newlen = _gameFile.read(buf, 4);
if (newlen != 4)
return 1;
val = Read4(buf);
if (ix == 3) {
if (len != val)
return 1;
}
if (ix == 8)
chksum = val;
else
newsum += val;
}
/* Read everything else */
for (; ix < len / 4; ix++) {
newlen = _gameFile.read(buf, 4);
if (newlen != 4)
return 1;
val = Read4(buf);
newsum += val;
}
if (newsum != chksum)
return 1;
return 0;
}
} // End of namespace Glulx
} // End of namespace Glk
|
/*
* Copyright (c) 2010 Patrick McHardy <kaber@trash.net>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/module.h>
#include <linux/gfp.h>
#include <linux/skbuff.h>
#include <linux/netfilter_ipv4/ip_tables.h>
#include <linux/netfilter_ipv6/ip6_tables.h>
#include <linux/netfilter/x_tables.h>
#include <linux/netfilter/xt_CT.h>
#include <net/netfilter/nf_conntrack.h>
#include <net/netfilter/nf_conntrack_l4proto.h>
#include <net/netfilter/nf_conntrack_helper.h>
#include <net/netfilter/nf_conntrack_ecache.h>
#include <net/netfilter/nf_conntrack_timeout.h>
#include <net/netfilter/nf_conntrack_zones.h>
static inline int xt_ct_target(struct sk_buff *skb, struct nf_conn *ct)
{
/* Previously seen (loopback)? Ignore. */
if (skb->nfct != NULL)
return XT_CONTINUE;
/* special case the untracked ct : we want the percpu object */
if (!ct)
ct = nf_ct_untracked_get();
atomic_inc(&ct->ct_general.use);
skb->nfct = &ct->ct_general;
skb->nfctinfo = IP_CT_NEW;
return XT_CONTINUE;
}
static unsigned int xt_ct_target_v0(struct sk_buff *skb,
const struct xt_action_param *par)
{
const struct xt_ct_target_info *info = par->targinfo;
struct nf_conn *ct = info->ct;
return xt_ct_target(skb, ct);
}
static unsigned int xt_ct_target_v1(struct sk_buff *skb,
const struct xt_action_param *par)
{
const struct xt_ct_target_info_v1 *info = par->targinfo;
struct nf_conn *ct = info->ct;
return xt_ct_target(skb, ct);
}
static u8 xt_ct_find_proto(const struct xt_tgchk_param *par)
{
if (par->family == NFPROTO_IPV4) {
const struct ipt_entry *e = par->entryinfo;
if (e->ip.invflags & IPT_INV_PROTO)
return 0;
return e->ip.proto;
} else if (par->family == NFPROTO_IPV6) {
const struct ip6t_entry *e = par->entryinfo;
if (e->ipv6.invflags & IP6T_INV_PROTO)
return 0;
return e->ipv6.proto;
} else
return 0;
}
static int
xt_ct_set_helper(struct nf_conn *ct, const char *helper_name,
const struct xt_tgchk_param *par)
{
struct nf_conntrack_helper *helper;
struct nf_conn_help *help;
u8 proto;
proto = xt_ct_find_proto(par);
if (!proto) {
pr_info("You must specify a L4 protocol, and not use "
"inversions on it.\n");
return -ENOENT;
}
helper = nf_conntrack_helper_try_module_get(helper_name, par->family,
proto);
if (helper == NULL) {
pr_info("No such helper \"%s\"\n", helper_name);
return -ENOENT;
}
help = nf_ct_helper_ext_add(ct, helper, GFP_KERNEL);
if (help == NULL) {
module_put(helper->me);
return -ENOMEM;
}
help->helper = helper;
return 0;
}
#ifdef CONFIG_NF_CONNTRACK_TIMEOUT
static void __xt_ct_tg_timeout_put(struct ctnl_timeout *timeout)
{
typeof(nf_ct_timeout_put_hook) timeout_put;
timeout_put = rcu_dereference(nf_ct_timeout_put_hook);
if (timeout_put)
timeout_put(timeout);
}
#endif
static int
xt_ct_set_timeout(struct nf_conn *ct, const struct xt_tgchk_param *par,
const char *timeout_name)
{
#ifdef CONFIG_NF_CONNTRACK_TIMEOUT
typeof(nf_ct_timeout_find_get_hook) timeout_find_get;
struct ctnl_timeout *timeout;
struct nf_conn_timeout *timeout_ext;
struct nf_conntrack_l4proto *l4proto;
int ret = 0;
u8 proto;
rcu_read_lock();
timeout_find_get = rcu_dereference(nf_ct_timeout_find_get_hook);
if (timeout_find_get == NULL) {
ret = -ENOENT;
pr_info("Timeout policy base is empty\n");
goto out;
}
proto = xt_ct_find_proto(par);
if (!proto) {
ret = -EINVAL;
pr_info("You must specify a L4 protocol, and not use "
"inversions on it.\n");
goto out;
}
timeout = timeout_find_get(timeout_name);
if (timeout == NULL) {
ret = -ENOENT;
pr_info("No such timeout policy \"%s\"\n", timeout_name);
goto out;
}
if (timeout->l3num != par->family) {
ret = -EINVAL;
pr_info("Timeout policy `%s' can only be used by L3 protocol "
"number %d\n", timeout_name, timeout->l3num);
goto err_put_timeout;
}
/* Make sure the timeout policy matches any existing protocol tracker,
* otherwise default to generic.
*/
l4proto = __nf_ct_l4proto_find(par->family, proto);
if (timeout->l4proto->l4proto != l4proto->l4proto) {
ret = -EINVAL;
pr_info("Timeout policy `%s' can only be used by L4 protocol "
"number %d\n",
timeout_name, timeout->l4proto->l4proto);
goto err_put_timeout;
}
timeout_ext = nf_ct_timeout_ext_add(ct, timeout, GFP_ATOMIC);
if (timeout_ext == NULL)
ret = -ENOMEM;
err_put_timeout:
__xt_ct_tg_timeout_put(timeout);
out:
rcu_read_unlock();
return ret;
#else
return -EOPNOTSUPP;
#endif
}
static int xt_ct_tg_check(const struct xt_tgchk_param *par,
struct xt_ct_target_info_v1 *info)
{
struct nf_conn *ct;
int ret = -EOPNOTSUPP;
if (info->flags & XT_CT_NOTRACK) {
ct = NULL;
goto out;
}
#ifndef CONFIG_NF_CONNTRACK_ZONES
if (info->zone)
goto err1;
#endif
ret = nf_ct_l3proto_try_module_get(par->family);
if (ret < 0)
goto err1;
ct = nf_ct_tmpl_alloc(par->net, info->zone, GFP_KERNEL);
if (!ct) {
ret = -ENOMEM;
goto err2;
}
ret = 0;
if ((info->ct_events || info->exp_events) &&
!nf_ct_ecache_ext_add(ct, info->ct_events, info->exp_events,
GFP_KERNEL)) {
ret = -EINVAL;
goto err3;
}
if (info->helper[0]) {
ret = xt_ct_set_helper(ct, info->helper, par);
if (ret < 0)
goto err3;
}
if (info->timeout[0]) {
ret = xt_ct_set_timeout(ct, par, info->timeout);
if (ret < 0)
goto err3;
}
__set_bit(IPS_CONFIRMED_BIT, &ct->status);
nf_conntrack_get(&ct->ct_general);
out:
info->ct = ct;
return 0;
err3:
nf_ct_tmpl_free(ct);
err2:
nf_ct_l3proto_module_put(par->family);
err1:
return ret;
}
static int xt_ct_tg_check_v0(const struct xt_tgchk_param *par)
{
struct xt_ct_target_info *info = par->targinfo;
struct xt_ct_target_info_v1 info_v1 = {
.flags = info->flags,
.zone = info->zone,
.ct_events = info->ct_events,
.exp_events = info->exp_events,
};
int ret;
if (info->flags & ~XT_CT_NOTRACK)
return -EINVAL;
memcpy(info_v1.helper, info->helper, sizeof(info->helper));
ret = xt_ct_tg_check(par, &info_v1);
if (ret < 0)
return ret;
info->ct = info_v1.ct;
return ret;
}
static int xt_ct_tg_check_v1(const struct xt_tgchk_param *par)
{
struct xt_ct_target_info_v1 *info = par->targinfo;
if (info->flags & ~XT_CT_NOTRACK)
return -EINVAL;
return xt_ct_tg_check(par, par->targinfo);
}
static int xt_ct_tg_check_v2(const struct xt_tgchk_param *par)
{
struct xt_ct_target_info_v1 *info = par->targinfo;
if (info->flags & ~XT_CT_MASK)
return -EINVAL;
return xt_ct_tg_check(par, par->targinfo);
}
static void xt_ct_destroy_timeout(struct nf_conn *ct)
{
#ifdef CONFIG_NF_CONNTRACK_TIMEOUT
struct nf_conn_timeout *timeout_ext;
typeof(nf_ct_timeout_put_hook) timeout_put;
rcu_read_lock();
timeout_put = rcu_dereference(nf_ct_timeout_put_hook);
if (timeout_put) {
timeout_ext = nf_ct_timeout_find(ct);
if (timeout_ext)
timeout_put(timeout_ext->timeout);
}
rcu_read_unlock();
#endif
}
static void xt_ct_tg_destroy(const struct xt_tgdtor_param *par,
struct xt_ct_target_info_v1 *info)
{
struct nf_conn *ct = info->ct;
struct nf_conn_help *help;
if (ct && !nf_ct_is_untracked(ct)) {
help = nfct_help(ct);
if (help)
module_put(help->helper->me);
nf_ct_l3proto_module_put(par->family);
xt_ct_destroy_timeout(ct);
nf_ct_put(info->ct);
}
}
static void xt_ct_tg_destroy_v0(const struct xt_tgdtor_param *par)
{
struct xt_ct_target_info *info = par->targinfo;
struct xt_ct_target_info_v1 info_v1 = {
.flags = info->flags,
.zone = info->zone,
.ct_events = info->ct_events,
.exp_events = info->exp_events,
.ct = info->ct,
};
memcpy(info_v1.helper, info->helper, sizeof(info->helper));
xt_ct_tg_destroy(par, &info_v1);
}
static void xt_ct_tg_destroy_v1(const struct xt_tgdtor_param *par)
{
xt_ct_tg_destroy(par, par->targinfo);
}
static struct xt_target xt_ct_tg_reg[] __read_mostly = {
{
.name = "CT",
.family = NFPROTO_UNSPEC,
.targetsize = sizeof(struct xt_ct_target_info),
.checkentry = xt_ct_tg_check_v0,
.destroy = xt_ct_tg_destroy_v0,
.target = xt_ct_target_v0,
.table = "raw",
.me = THIS_MODULE,
},
{
.name = "CT",
.family = NFPROTO_UNSPEC,
.revision = 1,
.targetsize = sizeof(struct xt_ct_target_info_v1),
.checkentry = xt_ct_tg_check_v1,
.destroy = xt_ct_tg_destroy_v1,
.target = xt_ct_target_v1,
.table = "raw",
.me = THIS_MODULE,
},
{
.name = "CT",
.family = NFPROTO_UNSPEC,
.revision = 2,
.targetsize = sizeof(struct xt_ct_target_info_v1),
.checkentry = xt_ct_tg_check_v2,
.destroy = xt_ct_tg_destroy_v1,
.target = xt_ct_target_v1,
.table = "raw",
.me = THIS_MODULE,
},
};
static unsigned int
notrack_tg(struct sk_buff *skb, const struct xt_action_param *par)
{
/* Previously seen (loopback)? Ignore. */
if (skb->nfct != NULL)
return XT_CONTINUE;
skb->nfct = &nf_ct_untracked_get()->ct_general;
skb->nfctinfo = IP_CT_NEW;
nf_conntrack_get(skb->nfct);
return XT_CONTINUE;
}
static int notrack_chk(const struct xt_tgchk_param *par)
{
if (!par->net->xt.notrack_deprecated_warning) {
pr_info("netfilter: NOTRACK target is deprecated, "
"use CT instead or upgrade iptables\n");
par->net->xt.notrack_deprecated_warning = true;
}
return 0;
}
static struct xt_target notrack_tg_reg __read_mostly = {
.name = "NOTRACK",
.revision = 0,
.family = NFPROTO_UNSPEC,
.checkentry = notrack_chk,
.target = notrack_tg,
.table = "raw",
.me = THIS_MODULE,
};
static int __init xt_ct_tg_init(void)
{
int ret;
ret = xt_register_target(¬rack_tg_reg);
if (ret < 0)
return ret;
ret = xt_register_targets(xt_ct_tg_reg, ARRAY_SIZE(xt_ct_tg_reg));
if (ret < 0) {
xt_unregister_target(¬rack_tg_reg);
return ret;
}
return 0;
}
static void __exit xt_ct_tg_exit(void)
{
xt_unregister_targets(xt_ct_tg_reg, ARRAY_SIZE(xt_ct_tg_reg));
xt_unregister_target(¬rack_tg_reg);
}
module_init(xt_ct_tg_init);
module_exit(xt_ct_tg_exit);
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("Xtables: connection tracking target");
MODULE_ALIAS("ipt_CT");
MODULE_ALIAS("ip6t_CT");
MODULE_ALIAS("ipt_NOTRACK");
MODULE_ALIAS("ip6t_NOTRACK");
|
<?php defined("SYSPATH") or die("No direct script access.");
/**
* Gallery - a web based photo album viewer and editor
* Copyright (C) 2000-2013 Bharat Mediratta
*
* 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.
*/
class Form_Uploadify_Core extends Form_Input {
protected $data = array(
"name" => false,
"type" => "UNKNOWN",
"url" => "",
"text" => "");
public function __construct($name) {
parent::__construct($name);
$this->data["script_data"] = array(
"g3sid" => Session::instance()->id(),
"user_agent" => Input::instance()->server("HTTP_USER_AGENT"),
"csrf" => access::csrf_token());
}
public function album(Item_Model $album) {
$this->data["album"] = $album;
return $this;
}
public function script_data($key, $value) {
$this->data["script_data"][$key] = $value;
}
public function render() {
$v = new View("form_uploadify.html");
$v->album = $this->data["album"];
$v->script_data = $this->data["script_data"];
$v->simultaneous_upload_limit = module::get_var("gallery", "simultaneous_upload_limit");
$v->movies_allowed = movie::allow_uploads();
$v->extensions = legal_file::get_filters();
$v->suhosin_session_encrypt = (bool) ini_get("suhosin.session.encrypt");
list ($toolkit_max_filesize_bytes, $toolkit_max_filesize) = graphics::max_filesize();
$upload_max_filesize = trim(ini_get("upload_max_filesize"));
$upload_max_filesize_bytes = num::convert_to_bytes($upload_max_filesize);
if ($upload_max_filesize_bytes < $toolkit_max_filesize_bytes) {
$v->size_limit_bytes = $upload_max_filesize_bytes;
$v->size_limit = $upload_max_filesize;
} else {
$v->size_limit_bytes = $toolkit_max_filesize_bytes;
$v->size_limit = $toolkit_max_filesize;
}
return $v;
}
public function validate() {
return true;
}
} |
/*
*
* SQUID Web Proxy Cache http://www.squid-cache.org/
* ----------------------------------------------------------
*
* Squid is the result of efforts by numerous individuals from
* the Internet community; see the CONTRIBUTORS file for full
* details. Many organizations have provided support for Squid's
* development; see the SPONSORS file for full details. Squid is
* Copyrighted (C) 2001 by the Regents of the University of
* California; see the COPYRIGHT file for full details. Squid
* incorporates software developed and/or copyrighted by other
* sources; see the CREDITS file for full details.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
*
*/
#ifndef SQUID_CACHEMANAGER_H
#define SQUID_CACHEMANAGER_H
#include "comm/forward.h"
#include "mgr/Action.h"
#include "mgr/ActionProfile.h"
#include "mgr/Command.h"
#include "mgr/forward.h"
#include "typedefs.h"
#include <vector>
/**
\defgroup CacheManagerAPI Cache Manager API
\ingroup Components
*
\defgroup CacheManagerInternal Cache Manager intenal API (not for public use)
\ingroup CacheManagerAPI
*/
class HttpRequest;
namespace Mgr
{
class ActionPasswordList;
} //namespace Mgr
/**
\ingroup CacheManagerAPI
* a CacheManager - the menu system for interacting with squid.
* This is currently just an adapter to the global cachemgr* routines to
* provide looser coupling between modules, but once fully transitioned,
* an instance of this class will represent a single independent manager.
* TODO: update documentation to reflect the new singleton model.
*/
class CacheManager
{
public:
typedef std::vector<Mgr::ActionProfilePointer> Menu;
void registerProfile(char const * action, char const * desc,
OBJH * handler,
int pw_req_flag, int atomic);
void registerProfile(char const * action, char const * desc,
Mgr::ClassActionCreationHandler *handler,
int pw_req_flag, int atomic);
Mgr::ActionProfilePointer findAction(char const * action) const;
Mgr::Action::Pointer createNamedAction(const char *actionName);
Mgr::Action::Pointer createRequestedAction(const Mgr::ActionParams &);
const Menu& menu() const { return menu_; }
void Start(const Comm::ConnectionPointer &client, HttpRequest * request, StoreEntry * entry);
static CacheManager* GetInstance();
const char *ActionProtection(const Mgr::ActionProfilePointer &profile);
protected:
CacheManager() {} ///< use Instance() instead
Mgr::CommandPointer ParseUrl(const char *url);
void ParseHeaders(const HttpRequest * request, Mgr::ActionParams ¶ms);
int CheckPassword(const Mgr::Command &cmd);
char *PasswdGet(Mgr::ActionPasswordList *, const char *);
void registerProfile(const Mgr::ActionProfilePointer &profile);
Menu menu_;
private:
static CacheManager* instance;
};
#endif /* SQUID_CACHEMANAGER_H */
|
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Validate
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id$
*/
/**
* @see Zend_Validate_Barcode_AdapterInterface
*/
//require_once 'Zend/Validate/Barcode/AdapterInterface.php';
/**
* @category Zend
* @package Zend_Validate
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
abstract class Zend_Validate_Barcode_AdapterAbstract
implements Zend_Validate_Barcode_AdapterInterface
{
/**
* Allowed barcode lengths
* @var integer|array|string
*/
protected $_length;
/**
* Allowed barcode characters
* @var string
*/
protected $_characters;
/**
* Callback to checksum function
* @var string|array
*/
protected $_checksum;
/**
* Is a checksum value included?
* @var boolean
*/
protected $_hasChecksum = true;
/**
* Checks the length of a barcode
*
* @param string $value The barcode to check for proper length
* @return boolean
*/
public function checkLength($value)
{
if (!is_string($value)) {
return false;
}
$fixum = strlen($value);
$found = false;
$length = $this->getLength();
if (is_array($length)) {
foreach ($length as $value) {
if ($fixum == $value) {
$found = true;
}
if ($value == -1) {
$found = true;
}
}
} elseif ($fixum == $length) {
$found = true;
} elseif ($length == -1) {
$found = true;
} elseif ($length == 'even') {
$count = $fixum % 2;
$found = ($count == 0) ? true : false;
} elseif ($length == 'odd') {
$count = $fixum % 2;
$found = ($count == 1) ? true : false;
}
return $found;
}
/**
* Checks for allowed characters within the barcode
*
* @param string $value The barcode to check for allowed characters
* @return boolean
*/
public function checkChars($value)
{
if (!is_string($value)) {
return false;
}
$characters = $this->getCharacters();
if ($characters == 128) {
for ($x = 0; $x < 128; ++$x) {
$value = str_replace(chr($x), '', $value);
}
} else {
$chars = str_split($characters);
foreach ($chars as $char) {
$value = str_replace($char, '', $value);
}
}
if (strlen($value) > 0) {
return false;
}
return true;
}
/**
* Validates the checksum
*
* @param string $value The barcode to check the checksum for
* @return boolean
*/
public function checksum($value)
{
$checksum = $this->getChecksum();
if (!empty($checksum)) {
if (method_exists($this, $checksum)) {
return call_user_func(array($this, $checksum), $value);
}
}
return false;
}
/**
* Returns the allowed barcode length
*
* @return string
*/
public function getLength()
{
return $this->_length;
}
/**
* Returns the allowed characters
*
* @return integer|string
*/
public function getCharacters()
{
return $this->_characters;
}
/**
* Returns the checksum function name
*
*/
public function getChecksum()
{
return $this->_checksum;
}
/**
* Returns if barcode uses checksum
*
* @return boolean
*/
public function getCheck()
{
return $this->_hasChecksum;
}
/**
* Sets the checksum validation
*
* @param boolean $check
* @return Zend_Validate_Barcode_AdapterAbstract
*/
public function setCheck($check)
{
$this->_hasChecksum = (boolean) $check;
return $this;
}
/**
* Validates the checksum (Modulo 10)
* GTIN implementation factor 3
*
* @param string $value The barcode to validate
* @return boolean
*/
protected function _gtin($value)
{
$barcode = substr($value, 0, -1);
$sum = 0;
$length = strlen($barcode) - 1;
for ($i = 0; $i <= $length; $i++) {
if (($i % 2) === 0) {
$sum += $barcode[$length - $i] * 3;
} else {
$sum += $barcode[$length - $i];
}
}
$calc = $sum % 10;
$checksum = ($calc === 0) ? 0 : (10 - $calc);
if ($value[$length + 1] != $checksum) {
return false;
}
return true;
}
/**
* Validates the checksum (Modulo 10)
* IDENTCODE implementation factors 9 and 4
*
* @param string $value The barcode to validate
* @return boolean
*/
protected function _identcode($value)
{
$barcode = substr($value, 0, -1);
$sum = 0;
$length = strlen($value) - 2;
for ($i = 0; $i <= $length; $i++) {
if (($i % 2) === 0) {
$sum += $barcode[$length - $i] * 4;
} else {
$sum += $barcode[$length - $i] * 9;
}
}
$calc = $sum % 10;
$checksum = ($calc === 0) ? 0 : (10 - $calc);
if ($value[$length + 1] != $checksum) {
return false;
}
return true;
}
/**
* Validates the checksum (Modulo 10)
* CODE25 implementation factor 3
*
* @param string $value The barcode to validate
* @return boolean
*/
protected function _code25($value)
{
$barcode = substr($value, 0, -1);
$sum = 0;
$length = strlen($barcode) - 1;
for ($i = 0; $i <= $length; $i++) {
if (($i % 2) === 0) {
$sum += $barcode[$i] * 3;
} else {
$sum += $barcode[$i];
}
}
$calc = $sum % 10;
$checksum = ($calc === 0) ? 0 : (10 - $calc);
if ($value[$length + 1] != $checksum) {
return false;
}
return true;
}
/**
* Validates the checksum ()
* POSTNET implementation
*
* @param string $value The barcode to validate
* @return boolean
*/
protected function _postnet($value)
{
$checksum = substr($value, -1, 1);
$values = str_split(substr($value, 0, -1));
$check = 0;
foreach($values as $row) {
$check += $row;
}
$check %= 10;
$check = 10 - $check;
if ($check == $checksum) {
return true;
}
return false;
}
}
|
<?php
/**
* @package Joomla.Administrator
* @subpackage com_messages
*
* @copyright Copyright (C) 2005 - 2015 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
defined('_JEXEC') or die;
// Include the component HTML helpers.
JHtml::addIncludePath(JPATH_COMPONENT . '/helpers/html');
JHtml::_('bootstrap.tooltip');
JHtml::_('behavior.multiselect');
JHtml::_('formbehavior.chosen', 'select');
$user = JFactory::getUser();
$listOrder = $this->escape($this->state->get('list.ordering'));
$listDirn = $this->escape($this->state->get('list.direction'));
JFactory::getDocument()->addStyleDeclaration(
"
@media (min-width: 768px) {
div.modal {
left: none;
width: 500px;
margin-left: -250px;
}
}
"
);
?>
<form action="<?php echo JRoute::_('index.php?option=com_messages&view=messages'); ?>" method="post" name="adminForm" id="adminForm">
<?php if (!empty( $this->sidebar)) : ?>
<div id="j-sidebar-container" class="span2">
<?php echo $this->sidebar; ?>
</div>
<div id="j-main-container" class="span10">
<?php else : ?>
<div id="j-main-container">
<?php endif;?>
<div id="filter-bar" class="btn-toolbar">
<div class="filter-search btn-group pull-left">
<input type="text" name="filter_search" id="filter_search" placeholder="<?php echo JText::_('JSEARCH_FILTER'); ?>" value="<?php echo $this->escape($this->state->get('filter.search')); ?>" class="hasTooltip" title="<?php echo JHtml::tooltipText('COM_MESSAGES_SEARCH_IN_SUBJECT'); ?>" />
</div>
<div class="btn-group pull-left">
<button type="submit" class="btn hasTooltip" title="<?php echo JHtml::tooltipText('JSEARCH_FILTER_SUBMIT'); ?>"><span class="icon-search"></span></button>
<button type="button" class="btn hasTooltip" title="<?php echo JHtml::tooltipText('JSEARCH_FILTER_CLEAR'); ?>" onclick="document.getElementById('filter_search').value='';this.form.submit();"><span class="icon-remove"></span></button>
</div>
<div class="btn-group pull-left hidden-phone">
<select name="filter_state" onchange="this.form.submit()">
<option value=""><?php echo JText::_('JOPTION_SELECT_PUBLISHED');?></option>
<?php echo JHtml::_('select.options', MessagesHelper::getStateOptions(), 'value', 'text', $this->state->get('filter.state'));?>
</select>
</div>
</div>
<div class="clearfix"> </div>
<?php if (empty($this->items)) : ?>
<div class="alert alert-no-items">
<?php echo JText::_('JGLOBAL_NO_MATCHING_RESULTS'); ?>
</div>
<?php else : ?>
<table class="table table-striped">
<thead>
<tr>
<th width="20" class="center">
<?php echo JHtml::_('grid.checkall'); ?>
</th>
<th class="title">
<?php echo JHtml::_('grid.sort', 'COM_MESSAGES_HEADING_SUBJECT', 'a.subject', $listDirn, $listOrder); ?>
</th>
<th width="5%">
<?php echo JHtml::_('grid.sort', 'COM_MESSAGES_HEADING_READ', 'a.state', $listDirn, $listOrder); ?>
</th>
<th width="15%">
<?php echo JHtml::_('grid.sort', 'COM_MESSAGES_HEADING_FROM', 'a.user_id_from', $listDirn, $listOrder); ?>
</th>
<th width="20%" class="nowrap hidden-phone">
<?php echo JHtml::_('grid.sort', 'JDATE', 'a.date_time', $listDirn, $listOrder); ?>
</th>
</tr>
</thead>
<tfoot>
<tr>
<td colspan="6">
<?php echo $this->pagination->getListFooter(); ?>
</td>
</tr>
</tfoot>
<tbody>
<?php foreach ($this->items as $i => $item) :
$canChange = $user->authorise('core.edit.state', 'com_messages');
?>
<tr class="row<?php echo $i % 2; ?>">
<td>
<?php echo JHtml::_('grid.id', $i, $item->message_id); ?>
</td>
<td>
<a href="<?php echo JRoute::_('index.php?option=com_messages&view=message&message_id=' . (int) $item->message_id); ?>">
<?php echo $this->escape($item->subject); ?></a>
</td>
<td class="center">
<?php echo JHtml::_('messages.status', $i, $item->state, $canChange); ?>
</td>
<td>
<?php echo $item->user_from; ?>
</td>
<td class="hidden-phone">
<?php echo JHtml::_('date', $item->date_time, JText::_('DATE_FORMAT_LC2')); ?>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<?php endif; ?>
<div>
<input type="hidden" name="task" value="" />
<input type="hidden" name="boxchecked" value="0" />
<input type="hidden" name="filter_order" value="<?php echo $listOrder; ?>" />
<input type="hidden" name="filter_order_Dir" value="<?php echo $listDirn; ?>" />
<?php echo JHtml::_('form.token'); ?>
</div>
</div>
</form>
|
/*
* 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. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* 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.
*/
/*
* This file is available under and governed by the GNU General Public
* License version 2 only, as published by the Free Software Foundation.
* However, the following notice accompanied the original version of this
* file:
*
* ASM: a very small and fast Java bytecode manipulation framework
* Copyright (c) 2000-2011 INRIA, France Telecom
* 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 copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
package jdk.internal.org.objectweb.asm.commons;
import jdk.internal.org.objectweb.asm.Handle;
import jdk.internal.org.objectweb.asm.Type;
import jdk.internal.org.objectweb.asm.signature.SignatureReader;
import jdk.internal.org.objectweb.asm.signature.SignatureVisitor;
import jdk.internal.org.objectweb.asm.signature.SignatureWriter;
/**
* A class responsible for remapping types and names. Subclasses can override
* the following methods:
*
* <ul>
* <li>{@link #map(String)} - map type</li>
* <li>{@link #mapFieldName(String, String, String)} - map field name</li>
* <li>{@link #mapMethodName(String, String, String)} - map method name</li>
* </ul>
*
* @author Eugene Kuleshov
*/
public abstract class Remapper {
public String mapDesc(String desc) {
Type t = Type.getType(desc);
switch (t.getSort()) {
case Type.ARRAY:
String s = mapDesc(t.getElementType().getDescriptor());
for (int i = 0; i < t.getDimensions(); ++i) {
s = '[' + s;
}
return s;
case Type.OBJECT:
String newType = map(t.getInternalName());
if (newType != null) {
return 'L' + newType + ';';
}
}
return desc;
}
private Type mapType(Type t) {
switch (t.getSort()) {
case Type.ARRAY:
String s = mapDesc(t.getElementType().getDescriptor());
for (int i = 0; i < t.getDimensions(); ++i) {
s = '[' + s;
}
return Type.getType(s);
case Type.OBJECT:
s = map(t.getInternalName());
return s != null ? Type.getObjectType(s) : t;
case Type.METHOD:
return Type.getMethodType(mapMethodDesc(t.getDescriptor()));
}
return t;
}
public String mapType(String type) {
if (type == null) {
return null;
}
return mapType(Type.getObjectType(type)).getInternalName();
}
public String[] mapTypes(String[] types) {
String[] newTypes = null;
boolean needMapping = false;
for (int i = 0; i < types.length; i++) {
String type = types[i];
String newType = map(type);
if (newType != null && newTypes == null) {
newTypes = new String[types.length];
if (i > 0) {
System.arraycopy(types, 0, newTypes, 0, i);
}
needMapping = true;
}
if (needMapping) {
newTypes[i] = newType == null ? type : newType;
}
}
return needMapping ? newTypes : types;
}
public String mapMethodDesc(String desc) {
if ("()V".equals(desc)) {
return desc;
}
Type[] args = Type.getArgumentTypes(desc);
StringBuilder sb = new StringBuilder("(");
for (int i = 0; i < args.length; i++) {
sb.append(mapDesc(args[i].getDescriptor()));
}
Type returnType = Type.getReturnType(desc);
if (returnType == Type.VOID_TYPE) {
sb.append(")V");
return sb.toString();
}
sb.append(')').append(mapDesc(returnType.getDescriptor()));
return sb.toString();
}
public Object mapValue(Object value) {
if (value instanceof Type) {
return mapType((Type) value);
}
if (value instanceof Handle) {
Handle h = (Handle) value;
return new Handle(h.getTag(), mapType(h.getOwner()), mapMethodName(
h.getOwner(), h.getName(), h.getDesc()),
mapMethodDesc(h.getDesc()), h.isInterface());
}
return value;
}
/**
* @param signature
* signature for mapper
* @param typeSignature
* true if signature is a FieldTypeSignature, such as the
* signature parameter of the ClassVisitor.visitField or
* MethodVisitor.visitLocalVariable methods
* @return signature rewritten as a string
*/
public String mapSignature(String signature, boolean typeSignature) {
if (signature == null) {
return null;
}
SignatureReader r = new SignatureReader(signature);
SignatureWriter w = new SignatureWriter();
SignatureVisitor a = createSignatureRemapper(w);
if (typeSignature) {
r.acceptType(a);
} else {
r.accept(a);
}
return w.toString();
}
/**
* @deprecated use {@link #createSignatureRemapper} instead.
*/
@Deprecated
protected SignatureVisitor createRemappingSignatureAdapter(
SignatureVisitor v) {
return new SignatureRemapper(v, this);
}
protected SignatureVisitor createSignatureRemapper(
SignatureVisitor v) {
return createRemappingSignatureAdapter(v);
}
/**
* Map method name to the new name. Subclasses can override.
*
* @param owner
* owner of the method.
* @param name
* name of the method.
* @param desc
* descriptor of the method.
* @return new name of the method
*/
public String mapMethodName(String owner, String name, String desc) {
return name;
}
/**
* Map invokedynamic method name to the new name. Subclasses can override.
*
* @param name
* name of the invokedynamic.
* @param desc
* descriptor of the invokedynamic.
* @return new invokdynamic name.
*/
public String mapInvokeDynamicMethodName(String name, String desc) {
return name;
}
/**
* Map field name to the new name. Subclasses can override.
*
* @param owner
* owner of the field.
* @param name
* name of the field
* @param desc
* descriptor of the field
* @return new name of the field.
*/
public String mapFieldName(String owner, String name, String desc) {
return name;
}
/**
* Map type name to the new name. Subclasses can override.
*
* @param typeName
* the type name
* @return new name, default implementation is the identity.
*/
public String map(String typeName) {
return typeName;
}
}
|
FactoryBot.define do
factory :katello_content_view_environment, :class => Katello::ContentViewEnvironment do
sequence(:name) { |n| "name#{n}" }
sequence(:label) { |n| "label#{n}" }
end
end
|
// Build don't link:
// Origin: Jakub Jelinek <jakub@redhat.com>
namespace N
{
class X;
template <class T>
class Y
{
public:
inline Y () {}
inline operator const Y<X> & () const
{
return *reinterpret_cast<const Y<X> *>(this);
}
};
}
class bar
{
public:
inline bar () {}
inline bar (const ::N::Y< ::N::X>& a);
};
class foo
{
bool b;
public:
foo();
void x () throw(bar);
};
void foo::x() throw(bar)
{
if (!b) throw bar (static_cast<::N::X*>(this)); // ERROR - parse error
}
|
#ifndef THEANO_MOD_HELPER
#define THEANO_MOD_HELPER
#include <Python.h>
#ifndef _WIN32
#define MOD_PUBLIC __attribute__((visibility ("default")))
#else
/* MOD_PUBLIC is only used in PyMODINIT_FUNC, which is declared
* and implemented in mod.cu/cpp, not in headers, so dllexport
* is always correct. */
#define MOD_PUBLIC __declspec( dllexport )
#endif
#ifdef __cplusplus
#define THEANO_EXTERN extern "C"
#else
#define THEANO_EXTERN
#endif
#if PY_MAJOR_VERSION < 3
#define THEANO_RTYPE void
#else
#define THEANO_RTYPE PyObject *
#endif
/* We need to redefine PyMODINIT_FUNC to add MOD_PUBLIC in the middle */
#undef PyMODINIT_FUNC
#define PyMODINIT_FUNC THEANO_EXTERN MOD_PUBLIC THEANO_RTYPE
#endif
|
/* Copyright (c) 2013, The Linux Foundation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/fb.h>
#include <linux/notifier.h>
#include <linux/workqueue.h>
#include <linux/delay.h>
#include <linux/debugfs.h>
#include <linux/slab.h>
#include <linux/uaccess.h>
#include <linux/iopoll.h>
#include <linux/kobject.h>
#include <linux/string.h>
#include <linux/sysfs.h>
#include "mdss_fb.h"
#include "mdss_dsi.h"
#include "mdss_panel.h"
#include "mdss_mdp.h"
#include "mdp3_ctrl.h"
#define STATUS_CHECK_INTERVAL 8000
#define STATUS_CHECK_INTERVAL_MIN 200
struct dsi_status_data {
struct notifier_block fb_notifier;
struct delayed_work check_status;
struct msm_fb_data_type *mfd;
};
struct dsi_status_data *pstatus_data;
static uint32_t interval = STATUS_CHECK_INTERVAL;
/*
* check_dsi_ctrl_status() - Check DSI controller status periodically.
* @work : dsi controller status data
*
* This function calls check_status API on DSI controller to send the BTA
* command. If DSI controller fails to acknowledge the BTA command, it sends
* the PANEL_ALIVE=0 status to HAL layer.
*/
static void check_dsi_ctrl_status(struct work_struct *work)
{
struct dsi_status_data *pdsi_status = NULL;
struct mdss_panel_data *pdata = NULL;
struct mdss_dsi_ctrl_pdata *ctrl_pdata = NULL;
#ifdef CONFIG_FB_MSM_MDSS_MDP3
struct mdp3_session_data *mdp3_session = NULL;
#else
struct mdss_overlay_private *mdp5_data = NULL;
struct mdss_mdp_ctl *ctl = NULL;
#endif
int ret = 0;
pdsi_status = container_of(to_delayed_work(work),
struct dsi_status_data, check_status);
if (!pdsi_status) {
pr_err("%s: DSI status data not available\n", __func__);
return;
}
pdata = dev_get_platdata(&pdsi_status->mfd->pdev->dev);
if (!pdata) {
pr_err("%s: Panel data not available\n", __func__);
return;
}
ctrl_pdata = container_of(pdata, struct mdss_dsi_ctrl_pdata,
panel_data);
if (!ctrl_pdata || !ctrl_pdata->check_status) {
pr_err("%s: DSI ctrl or status_check callback not available\n",
__func__);
return;
}
#ifdef CONFIG_FB_MSM_MDSS_MDP3
mdp3_session = pdsi_status->mfd->mdp.private1;
mutex_lock(&mdp3_session->offlock);
ret = ctrl_pdata->check_status(ctrl_pdata);
mutex_unlock(&mdp3_session->offlock);
#else
if (!pdata->panel_info.cont_splash_esd_rdy) {
pr_warn("%s: Splash not complete, reschedule check status\n",
__func__);
schedule_delayed_work(&pdsi_status->check_status,
msecs_to_jiffies(interval));
return;
}
mdp5_data = mfd_to_mdp5_data(pdsi_status->mfd);
ctl = mfd_to_ctl(pdsi_status->mfd);
if (!ctl) {
pr_warn("%s: mdss_mdp_ctl data not available\n", __func__);
return;
}
mutex_lock(&ctl->offlock);
if (ctl->shared_lock)
mutex_lock(ctl->shared_lock);
mdss_mdp_clk_ctrl(MDP_BLOCK_POWER_ON, false);
ret = ctrl_pdata->check_status(ctrl_pdata);
mdss_mdp_clk_ctrl(MDP_BLOCK_POWER_OFF, false);
if (ctl->shared_lock)
mutex_unlock(ctl->shared_lock);
mutex_unlock(&ctl->offlock);
#endif
if ((pdsi_status->mfd->panel_power_on)) {
if (ret > 0) {
schedule_delayed_work(&pdsi_status->check_status,
msecs_to_jiffies(interval));
} else {
char *envp[2] = {"PANEL_ALIVE=0", NULL};
pdata->panel_info.panel_dead = true;
ret = kobject_uevent_env(
&pdsi_status->mfd->fbi->dev->kobj,
KOBJ_CHANGE, envp);
pr_err("%s: Panel has gone bad, sending uevent - %s\n",
__func__, envp[0]);
}
}
}
/*
* fb_event_callback() - Call back function for the fb_register_client()
* notifying events
* @self : notifier block
* @event : The event that was triggered
* @data : Of type struct fb_event
*
* This function listens for FB_BLANK_UNBLANK and FB_BLANK_POWERDOWN events
* from frame buffer. DSI status check work is either scheduled again after
* PANEL_STATUS_CHECK_INTERVAL or cancelled based on the event.
*/
static int fb_event_callback(struct notifier_block *self,
unsigned long event, void *data)
{
struct fb_event *evdata = data;
struct dsi_status_data *pdata = container_of(self,
struct dsi_status_data, fb_notifier);
struct mdss_dsi_ctrl_pdata *ctrl_pdata = NULL;
pdata->mfd = evdata->info->par;
ctrl_pdata = container_of(dev_get_platdata(&pdata->mfd->pdev->dev),
struct mdss_dsi_ctrl_pdata, panel_data);
if (!ctrl_pdata) {
pr_err("%s: DSI ctrl not available\n", __func__);
return NOTIFY_BAD;
}
if (ctrl_pdata->check_status_disabled) {
pr_debug("%s: status_check disabled\n", __func__);
return NOTIFY_DONE;
}
if (event == FB_EVENT_BLANK && evdata) {
int *blank = evdata->data;
switch (*blank) {
case FB_BLANK_UNBLANK:
schedule_delayed_work(&pdata->check_status,
msecs_to_jiffies(interval));
break;
case FB_BLANK_POWERDOWN:
case FB_BLANK_HSYNC_SUSPEND:
case FB_BLANK_VSYNC_SUSPEND:
case FB_BLANK_NORMAL:
cancel_delayed_work(&pdata->check_status);
break;
default:
pr_err("Unknown case in FB_EVENT_BLANK event\n");
break;
}
}
return 0;
}
static int param_set_interval(const char *val, struct kernel_param *kp)
{
int ret = 0;
int int_val;
ret = kstrtos32(val, 0, &int_val);
if (ret)
return ret;
if (int_val < STATUS_CHECK_INTERVAL_MIN) {
pr_err("%s: Invalid value %d used, ignoring\n",
__func__, int_val);
ret = -EINVAL;
} else {
pr_info("%s: Set check interval to %d msecs\n",
__func__, int_val);
*((int *)kp->arg) = int_val;
}
return ret;
}
int __init mdss_dsi_status_init(void)
{
int rc = 0;
pstatus_data = kzalloc(sizeof(struct dsi_status_data), GFP_KERNEL);
if (!pstatus_data) {
pr_err("%s: can't allocate memory\n", __func__);
return -ENOMEM;
}
pstatus_data->fb_notifier.notifier_call = fb_event_callback;
rc = fb_register_client(&pstatus_data->fb_notifier);
if (rc < 0) {
pr_err("%s: fb_register_client failed, returned with rc=%d\n",
__func__, rc);
kfree(pstatus_data);
return -EPERM;
}
pr_info("%s: DSI status check interval:%d\n", __func__, interval);
INIT_DELAYED_WORK(&pstatus_data->check_status, check_dsi_ctrl_status);
pr_debug("%s: DSI ctrl status work queue initialized\n", __func__);
return rc;
}
void __exit mdss_dsi_status_exit(void)
{
fb_unregister_client(&pstatus_data->fb_notifier);
cancel_delayed_work_sync(&pstatus_data->check_status);
kfree(pstatus_data);
pr_debug("%s: DSI ctrl status work queue removed\n", __func__);
}
module_param_call(interval, param_set_interval, param_get_uint,
&interval, 0644);
MODULE_PARM_DESC(interval,
"Duration in milliseconds to send BTA command for checking"
"DSI status periodically");
module_init(mdss_dsi_status_init);
module_exit(mdss_dsi_status_exit);
MODULE_LICENSE("GPL v2");
|
/*
* This file is part of the coreboot project.
*
* Copyright 2013 Google Inc.
* Copyright (C) 2012 Samsung Electronics
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 2 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#include <arch/io.h>
#include <soc/trustzone.h>
/* Setting TZPC[TrustZone Protection Controller]
* We pretty much disable it all, as the kernel
* expects it that way -- and that's not the default.
*/
void trustzone_init(void)
{
struct exynos_tzpc *tzpc;
unsigned int addr;
for (addr = TZPC10_BASE; addr <= TZPC9_BASE; addr += TZPC_BASE_OFFSET) {
tzpc = (struct exynos_tzpc *)addr;
if (addr == TZPC0_BASE)
write32(&tzpc->r0size, R0SIZE);
write32(&tzpc->decprot0set, DECPROTXSET);
write32(&tzpc->decprot1set, DECPROTXSET);
write32(&tzpc->decprot2set, DECPROTXSET);
write32(&tzpc->decprot3set, DECPROTXSET);
}
}
|
/*
* include/asm-xtensa/atomic.h
*
* Atomic operations that C can't guarantee us. Useful for resource counting..
*
* This file is subject to the terms and conditions of the GNU General Public
* License. See the file "COPYING" in the main directory of this archive
* for more details.
*
* Copyright (C) 2001 - 2008 Tensilica Inc.
*/
#ifndef _XTENSA_ATOMIC_H
#define _XTENSA_ATOMIC_H
#include <linux/stringify.h>
#include <linux/types.h>
#ifdef __KERNEL__
#include <asm/processor.h>
#include <asm/cmpxchg.h>
#include <asm/barrier.h>
#define ATOMIC_INIT(i) { (i) }
/*
* This Xtensa implementation assumes that the right mechanism
* for exclusion is for locking interrupts to level EXCM_LEVEL.
*
* Locking interrupts looks like this:
*
* rsil a15, TOPLEVEL
* <code>
* wsr a15, PS
* rsync
*
* Note that a15 is used here because the register allocation
* done by the compiler is not guaranteed and a window overflow
* may not occur between the rsil and wsr instructions. By using
* a15 in the rsil, the machine is guaranteed to be in a state
* where no register reference will cause an overflow.
*/
/**
* atomic_read - read atomic variable
* @v: pointer of type atomic_t
*
* Atomically reads the value of @v.
*/
#define atomic_read(v) ACCESS_ONCE((v)->counter)
/**
* atomic_set - set atomic variable
* @v: pointer of type atomic_t
* @i: required value
*
* Atomically sets the value of @v to @i.
*/
#define atomic_set(v,i) ((v)->counter = (i))
#if XCHAL_HAVE_S32C1I
#define ATOMIC_OP(op) \
static inline void atomic_##op(int i, atomic_t * v) \
{ \
unsigned long tmp; \
int result; \
\
__asm__ __volatile__( \
"1: l32i %1, %3, 0\n" \
" wsr %1, scompare1\n" \
" " #op " %0, %1, %2\n" \
" s32c1i %0, %3, 0\n" \
" bne %0, %1, 1b\n" \
: "=&a" (result), "=&a" (tmp) \
: "a" (i), "a" (v) \
: "memory" \
); \
} \
#define ATOMIC_OP_RETURN(op) \
static inline int atomic_##op##_return(int i, atomic_t * v) \
{ \
unsigned long tmp; \
int result; \
\
__asm__ __volatile__( \
"1: l32i %1, %3, 0\n" \
" wsr %1, scompare1\n" \
" " #op " %0, %1, %2\n" \
" s32c1i %0, %3, 0\n" \
" bne %0, %1, 1b\n" \
" " #op " %0, %0, %2\n" \
: "=&a" (result), "=&a" (tmp) \
: "a" (i), "a" (v) \
: "memory" \
); \
\
return result; \
}
#else /* XCHAL_HAVE_S32C1I */
#define ATOMIC_OP(op) \
static inline void atomic_##op(int i, atomic_t * v) \
{ \
unsigned int vval; \
\
__asm__ __volatile__( \
" rsil a15, "__stringify(TOPLEVEL)"\n"\
" l32i %0, %2, 0\n" \
" " #op " %0, %0, %1\n" \
" s32i %0, %2, 0\n" \
" wsr a15, ps\n" \
" rsync\n" \
: "=&a" (vval) \
: "a" (i), "a" (v) \
: "a15", "memory" \
); \
} \
#define ATOMIC_OP_RETURN(op) \
static inline int atomic_##op##_return(int i, atomic_t * v) \
{ \
unsigned int vval; \
\
__asm__ __volatile__( \
" rsil a15,"__stringify(TOPLEVEL)"\n" \
" l32i %0, %2, 0\n" \
" " #op " %0, %0, %1\n" \
" s32i %0, %2, 0\n" \
" wsr a15, ps\n" \
" rsync\n" \
: "=&a" (vval) \
: "a" (i), "a" (v) \
: "a15", "memory" \
); \
\
return vval; \
}
#endif /* XCHAL_HAVE_S32C1I */
#define ATOMIC_OPS(op) ATOMIC_OP(op) ATOMIC_OP_RETURN(op)
ATOMIC_OPS(add)
ATOMIC_OPS(sub)
#undef ATOMIC_OPS
#undef ATOMIC_OP_RETURN
#undef ATOMIC_OP
/**
* atomic_sub_and_test - subtract value from variable and test result
* @i: integer value to subtract
* @v: pointer of type atomic_t
*
* Atomically subtracts @i from @v and returns
* true if the result is zero, or false for all
* other cases.
*/
#define atomic_sub_and_test(i,v) (atomic_sub_return((i),(v)) == 0)
/**
* atomic_inc - increment atomic variable
* @v: pointer of type atomic_t
*
* Atomically increments @v by 1.
*/
#define atomic_inc(v) atomic_add(1,(v))
/**
* atomic_inc - increment atomic variable
* @v: pointer of type atomic_t
*
* Atomically increments @v by 1.
*/
#define atomic_inc_return(v) atomic_add_return(1,(v))
/**
* atomic_dec - decrement atomic variable
* @v: pointer of type atomic_t
*
* Atomically decrements @v by 1.
*/
#define atomic_dec(v) atomic_sub(1,(v))
/**
* atomic_dec_return - decrement atomic variable
* @v: pointer of type atomic_t
*
* Atomically decrements @v by 1.
*/
#define atomic_dec_return(v) atomic_sub_return(1,(v))
/**
* atomic_dec_and_test - decrement and test
* @v: pointer of type atomic_t
*
* Atomically decrements @v by 1 and
* returns true if the result is 0, or false for all other
* cases.
*/
#define atomic_dec_and_test(v) (atomic_sub_return(1,(v)) == 0)
/**
* atomic_inc_and_test - increment and test
* @v: pointer of type atomic_t
*
* Atomically increments @v by 1
* and returns true if the result is zero, or false for all
* other cases.
*/
#define atomic_inc_and_test(v) (atomic_add_return(1,(v)) == 0)
/**
* atomic_add_negative - add and test if negative
* @v: pointer of type atomic_t
* @i: integer value to add
*
* Atomically adds @i to @v and returns true
* if the result is negative, or false when
* result is greater than or equal to zero.
*/
#define atomic_add_negative(i,v) (atomic_add_return((i),(v)) < 0)
#define atomic_cmpxchg(v, o, n) ((int)cmpxchg(&((v)->counter), (o), (n)))
#define atomic_xchg(v, new) (xchg(&((v)->counter), new))
/**
* __atomic_add_unless - add unless the number is a given value
* @v: pointer of type atomic_t
* @a: the amount to add to v...
* @u: ...unless v is equal to u.
*
* Atomically adds @a to @v, so long as it was not @u.
* Returns the old value of @v.
*/
static __inline__ int __atomic_add_unless(atomic_t *v, int a, int u)
{
int c, old;
c = atomic_read(v);
for (;;) {
if (unlikely(c == (u)))
break;
old = atomic_cmpxchg((v), c, c + (a));
if (likely(old == c))
break;
c = old;
}
return c;
}
static inline void atomic_clear_mask(unsigned int mask, atomic_t *v)
{
#if XCHAL_HAVE_S32C1I
unsigned long tmp;
int result;
__asm__ __volatile__(
"1: l32i %1, %3, 0\n"
" wsr %1, scompare1\n"
" and %0, %1, %2\n"
" s32c1i %0, %3, 0\n"
" bne %0, %1, 1b\n"
: "=&a" (result), "=&a" (tmp)
: "a" (~mask), "a" (v)
: "memory"
);
#else
unsigned int all_f = -1;
unsigned int vval;
__asm__ __volatile__(
" rsil a15,"__stringify(TOPLEVEL)"\n"
" l32i %0, %2, 0\n"
" xor %1, %4, %3\n"
" and %0, %0, %4\n"
" s32i %0, %2, 0\n"
" wsr a15, ps\n"
" rsync\n"
: "=&a" (vval), "=a" (mask)
: "a" (v), "a" (all_f), "1" (mask)
: "a15", "memory"
);
#endif
}
static inline void atomic_set_mask(unsigned int mask, atomic_t *v)
{
#if XCHAL_HAVE_S32C1I
unsigned long tmp;
int result;
__asm__ __volatile__(
"1: l32i %1, %3, 0\n"
" wsr %1, scompare1\n"
" or %0, %1, %2\n"
" s32c1i %0, %3, 0\n"
" bne %0, %1, 1b\n"
: "=&a" (result), "=&a" (tmp)
: "a" (mask), "a" (v)
: "memory"
);
#else
unsigned int vval;
__asm__ __volatile__(
" rsil a15,"__stringify(TOPLEVEL)"\n"
" l32i %0, %2, 0\n"
" or %0, %0, %1\n"
" s32i %0, %2, 0\n"
" wsr a15, ps\n"
" rsync\n"
: "=&a" (vval)
: "a" (mask), "a" (v)
: "a15", "memory"
);
#endif
}
#endif /* __KERNEL__ */
#endif /* _XTENSA_ATOMIC_H */
|
/*
* RAZE-x86 Z80 emulator.
*
* Copyright (c) 1999 Richard Mitton
*
* This may only be distributed as part of the complete RAZE package.
* See RAZE.TXT for license information.
*/
#ifndef __RAZE_H_INCLUDED__
#define __RAZE_H_INCLUDED__
#ifdef __cplusplus
extern "C" {
#endif
/* Fix this as you need it */
#ifndef UBYTE
#define UBYTE unsigned char
#endif
#ifndef UWORD
#define UWORD unsigned short
#endif
/* Memory map constants */
#define Z80_MAP_DIRECT 0 /* Reads/writes are done directly */
#define Z80_MAP_HANDLED 1 /* Reads/writes use a function handler */
/* Z80 registers */
typedef enum {
Z80_REG_AF=0,
Z80_REG_BC,
Z80_REG_DE,
Z80_REG_HL,
Z80_REG_IX,
Z80_REG_IY,
Z80_REG_PC,
Z80_REG_SP,
Z80_REG_AF2,
Z80_REG_BC2,
Z80_REG_DE2,
Z80_REG_HL2,
Z80_REG_IFF1, /* boolean - 1 or 0 */
Z80_REG_IFF2, /* boolean - 1 or 0 */
Z80_REG_IR,
Z80_REG_IM, /* 0, 1, or 2 */
Z80_REG_IRQVector, /* 0x00 to 0xff */
Z80_REG_IRQLine /* boolean - 1 or 0 */
} z80_register;
/* Z80 main functions */
void z80_reset(void);
int z80_emulate(int cycles);
void z80_raise_IRQ(UBYTE vector);
void z80_lower_IRQ(void);
void z80_cause_NMI(void);
/* Z80 context functions */
int z80_get_context_size(void);
void z80_set_context(void *context);
void z80_get_context(void *context);
UWORD z80_get_reg(z80_register reg);
void z80_set_reg(z80_register reg, UWORD value);
/* Z80 cycle functions */
int z80_get_cycles_elapsed(void);
void z80_stop_emulating(void);
void z80_skip_idle(void);
void z80_do_wait_states(int n);
/* Z80 I/O functions */
void z80_init_memmap(void);
void z80_map_fetch(UWORD start, UWORD end, UBYTE *memory);
void z80_map_read(UWORD start, UWORD end, UBYTE *memory);
void z80_map_write(UWORD start, UWORD end, UBYTE *memory);
void z80_add_read(UWORD start, UWORD end, int method, void *data);
void z80_add_write(UWORD start, UWORD end, int method, void *data);
void z80_set_in(UBYTE (*handler)(UWORD port));
void z80_set_out(void (*handler)(UWORD port, UBYTE value));
void z80_set_reti(void (*handler)(void));
void z80_set_fetch_callback(void (*handler)(UWORD pc));
void z80_end_memmap(void);
#ifdef __cplusplus
};
#endif
#endif /* __RAZE_H_INCLUDED__ */
|
/******************************
*
* This function opens the .mdf file and extracts connectivity information
* into the atoms Atom structure. It also updates the charge from the .car
* file because the charge in the .mdf file has more significant figures.
*
*/
#include "Msi2LMP2.h"
/* Prototype for function to process a single atom
Returns int that flags end of data file */
int get_molecule(char line[], int connect_col_no,
int q_col_no, int *counter);
/* Prototype for function that takes connectivty record as stated in
.mdf file and fills in any default values */
void MakeConnectFullForm(int *counter);
/* prototype for function to clean strange characters out of strings */
void clean_string(char *);
void ReadMdfFile(void)
{
char line[MAX_LINE_LENGTH]; /* Temporary storage for reading lines */
char *col_no; /* Pointer to column number stored as char */
char *col_name; /* Pointer to column name */
int connect_col_no = 0; /* Column number where connection info begins */
int q_col_no = 0; /* Column number containg charge information */
int column_flag=0; /* Flag for finding connect and q col no */
int atom_counter=0; /* Keeps track of current atom number */
int p_flag = 1; /* return value from ProcessConnections() */
int i,j,k,kk,l,n,match,match2,status;
char *temp_string;
char *temp_residue;
char *temp_atom_name;
char *sptr;
char *molecule_name;
unsigned char at_end = 0;
/* Open .mdf file for reading */
sprintf(line,"%s.mdf",rootname);
if (pflag > 0) fprintf(stderr," Reading mdf file: %s\n",line);
if ((MdfF = fopen(line,"r")) == NULL ) {
fprintf(stderr,"Cannot open %s\n",line);
exit(2);
}
while (!at_end) {
sptr = fgets(line,MAX_LINE_LENGTH,MdfF);
if (sptr != NULL) {
clean_string(line);
if (strncmp(line,"#end",4) == 0) {
at_end = 1;
}
else if (strncmp(line,"@column",7) == 0) {
temp_string = strtok(line," ");
col_no = strtok(NULL," ");
col_name = strtok(NULL," ");
if (strncmp(col_name,"charge",6) == 0) {
if (strlen(col_name) < 8) {
q_col_no = atoi(col_no);
}
}
else if (strncmp(col_name,"connect",7) == 0) {
connect_col_no = atoi(col_no);
}
}
else if (strncmp(line,"@molecule",9) == 0) {
temp_string = strtok(line," ");
molecule_name = strtok(NULL," ");
if ((q_col_no == 0) | (connect_col_no == 0)) {
fprintf(stderr,"Unable to process molecule without knowing charge\n");
fprintf(stderr,"and connections columns\n");
}
sptr = fgets(line,MAX_LINE_LENGTH,MdfF);
status = get_molecule(line,connect_col_no,q_col_no,&atom_counter);
if (status == 0) {
fprintf(stderr,"Trouble reading molecule - exiting\n");
}
}
else {
}
}
else {
fprintf(stderr,"End of File found or error reading line\n");
at_end = 1;
}
}
/* Next build list of residues for each molecule This will
facilitate assigning connections numbers as well as figuring
out bonds, angles, etc. This first loop just figures out the
number of residues in each molecule and allocates memory to
store information for each residue. The second loop fills
in starting and ending atom positions for each residue
*/
temp_string = calloc(16,sizeof(char));
temp_string[15] = '\0';
for (n=0; n < no_molecules; n++) {
molecule[n].no_residues = 1;
strncpy(temp_string,atoms[molecule[n].start].residue_string,16);
for (i=molecule[n].start+1; i < molecule[n].end; i++) {
if (strncmp(temp_string,atoms[i].residue_string,16) != 0) {
molecule[n].no_residues++;
strncpy(temp_string,atoms[i].residue_string,16);
}
}
molecule[n].residue = (struct ResidueList *)
calloc(molecule[n].no_residues, sizeof(struct ResidueList));
if (molecule[n].residue == NULL) {
fprintf(stderr,"Unable to allocate memory for residue list - molecule %d\n",
n);
exit(1);
}
}
for (n=0; n < no_molecules; n++) {
j = 0;
strncpy(molecule[n].residue[j].name,
atoms[molecule[n].start].residue_string,16);
molecule[n].residue[j].start = molecule[n].start;
for (i=molecule[n].start+1; i < molecule[n].end; i++) {
if (strncmp(molecule[n].residue[j].name,
atoms[i].residue_string,16) != 0) {
molecule[n].residue[j].end = i;
molecule[n].residue[++j].start = i;
strncpy(molecule[n].residue[j].name,atoms[i].residue_string,16);
}
}
molecule[n].residue[j].end = molecule[n].end;
/*
fprintf(stderr,"Molecule %d has %d residues",n,molecule[n].no_residues);
for (i=0; i < molecule[n].no_residues; i++) {
fprintf(stderr," %s",molecule[n].residue[i].name);
}
fprintf(stderr,"\n");
for (i=molecule[n].start; i < molecule[n].end; i++) {
fprintf(stderr," atom %d residue %s\n",i,atoms[i].residue_string);
}
fprintf(stderr," residue %s start %d end %d\n",molecule[n].residue[i].name,
molecule[n].residue[i].start,molecule[n].residue[i].end);
}
*/
}
/* Assign atom names in connections[] to corresponding atom numbers */
for (n=0; n < no_molecules; n++) {
for (j=0; j < molecule[n].no_residues; j++) {
for (i=molecule[n].residue[j].start; i < molecule[n].residue[j].end;
i++) {
for (l=0; l < atoms[i].no_connect; l++) {
strncpy(temp_string,atoms[i].connections[l],16);
temp_residue = strtok(temp_string,":");
temp_atom_name = strtok(NULL,"%");
if (strcmp(temp_residue,molecule[n].residue[j].name) == 0) {
/* atom and connection are part of same residue
Search names on just that residue */
k = molecule[n].residue[j].start;
match = 0;
while (!match && (k < molecule[n].residue[j].end)) {
if (strcmp(atoms[k].name,temp_atom_name) == 0) {
atoms[i].conn_no[l] = k;
match = 1;
}
else
k++;
}
if (match == 0) {
fprintf(stderr,"Unable to resolve atom number of atom %d conn %d string %s:%s\n Something is wrong in the MDF file\n",
i,l,temp_residue,temp_atom_name);
exit(1);
}
}
else {
/* atom and connection are on different residues
First find the residue that the connection is
on then loop over its atoms
*/
k=0;
match = 0;
while (!match && (k < molecule[n].no_residues)) {
if (strcmp(temp_residue,molecule[n].residue[k].name) == 0) {
kk = molecule[n].residue[k].start;
match2 = 0;
while (!match2 && (kk < molecule[n].residue[k].end)) {
if (strcmp(atoms[kk].name,temp_atom_name) == 0) {
atoms[i].conn_no[l] = kk;
match2 = 1;
}
else
kk++;
}
if (match2 == 0) {
fprintf(stderr,"Unable to resolve atom number of atom %d conn %d string %s\n Something is wrong in the MDF file\n",
i,l,atoms[i].connections[l]);
exit(1);
}
match = 1;
}
else
k++;
}
if (match == 0) {
fprintf(stderr,"Unable to find residue associated with conn %d %s on atom %d\n Something is wrong in the MDF file\n", l,atoms[i].connections[l],i);
exit(1);
}
} /* end if */
} /* l - loop over connections on atom i */
} /* i - loop on atoms in residue j molecule n */
} /* j - loop on residues in molecule n */
} /* n - loop over molecules */
free(temp_string);
/*
for (n=0; n < no_molecules; n++) {
fprintf(stderr,"Molecule %d has %d residues\n",n,molecule[n].no_residues);
for (j=0; j < molecule[n].no_residues; j++) {
fprintf(stderr," Residue %d named %s\n",j,molecule[n].residue[j].name);
for (i=molecule[n].residue[j].start; i < molecule[n].residue[j].end;
i++) {
fprintf(stderr," Atom %d type %s connected to ",i,atoms[i].potential);
for (l=0; l < atoms[i].no_connect; l++) fprintf(stderr," %d ",
atoms[i].conn_no[l]);
fprintf(stderr,"\n");
}
}
}
*/
/* Close .mdf file */
if (fclose(MdfF) !=0) {
printf("Error closing %s.car\n", rootname);
exit(1);
}
} /* End ReadMdfFile function */
/*--------------------- get_molecule Function-----------------------*/
int get_molecule(char *line, int connect_col_no, int q_col_no,
int *counter)
{
char *cur_field; /* For storing current string token */
int i; /* Used in loop counters */
int connect_no; /* Connection number within atom */
int r_val = 1; /* Return value. 1 = successful
0 = EOF encountered */
/* Loop over atoms */
/* blank line signals end of molecule*/
while(!blank_line(fgets(line,MAX_LINE_LENGTH,MdfF))) {
/* while(strlen(fgets(line,MAX_LINE_LENGTH,MdfF)) > 2) { */
clean_string(line);
/* Get atom name */
cur_field = strtok(line,":");
sscanf(cur_field, "%s", atoms[*counter].residue_string);
cur_field = strtok(NULL," ");
/* Compare atom name with that in .car file */
if (strcmp(atoms[*counter].name, cur_field)) {
fprintf(stderr,"Names %s from .car file and %s from .mdf file do not match\n",
atoms[*counter].name, cur_field);
fprintf(stderr,"counter = %d\n",*counter);
fprintf(stderr,"Program Terminating\n");
exit(4);
}
/* Skip unwanted fields until charge column, then update charge */
for (i=1; i < q_col_no; i++) strtok(NULL," ");
cur_field = strtok(NULL, " ");
atoms[*counter].q = atof(cur_field);
/* Continue skipping unwanted fields until connectivity records begin */
for ( i = (q_col_no + 1); i < connect_col_no; i++) strtok(NULL," ");
/* Process connections */
connect_no = 0; /* reset connections counter */
while ((cur_field = strtok(NULL," ")) && (connect_no < MAX_CONNECTIONS)) {
sscanf(cur_field, "%s", atoms[*counter].connections[connect_no++]);
}
atoms[*counter].no_connect = connect_no;
MakeConnectFullForm(counter);
(*counter)++;
} /* End atom processing loop */
return r_val;
} /* End get_molecule function */
/*------------------------MakeConnectFullForm Function--------------------*/
void MakeConnectFullForm(int *counter) {
/* This function processes the connection names after all connections
for an atom have been read in.
It replaces any short forms that use implied default values
with the full form connectivity record */
int i; /* Counter for character array */
int j; /* loop counter */
char tempname[MAX_STRING]; /* name of connection */
char tempcell[10]; /* Values from connectivity record */
char tempsym[5]; /* " " */
char tempbo[6]; /* " " */
char *charptr;
for ( j = 0; j < atoms[*counter].no_connect; j++) {
/* If not full name, make name full */
if (strchr(atoms[*counter].connections[j],':') == NULL) {
strcpy(tempname,atoms[*counter].residue_string);
strcat(tempname,":");
strcat(tempname,
atoms[*counter].connections[j]);
sscanf(tempname, "%s",
atoms[*counter].connections[j]);
}
else
sscanf(atoms[*counter].connections[j], "%s", tempname);
/* Set cell variables */
i=0;
charptr = (strchr(tempname,'%'));
if (charptr != NULL) {
while ( *charptr!='#' && *charptr!='/' && *charptr!='\000')
tempcell[i++] = *(charptr++);
tempcell[i] = '\000';
}
else
strcpy(tempcell, "%000");
/* Set symmetry variables
-- If not 1, cannot handle at this time */
i = 0;
charptr = (strchr(tempname,'#'));
if (charptr != NULL) {
while (*charptr != '/' && *charptr !='\000') {
tempsym[i++] = *(charptr++);
if ((i==2) && (tempsym[1] != '1')) {
fprintf(stderr,"Msi2LMP is not equipped to handle symmetry operations\n");
exit(5);
}
}
tempsym[i] = '\000';
}
else
strcpy(tempsym, "#1");
/* Set bond order and record in data structure */
i = 0;
charptr = strchr(tempname,'/');
if (charptr != NULL) {
charptr++;
while (*charptr != '\000')
tempbo[i++] = *(charptr++);
tempbo[i] = '\000';
}
else
strcpy(tempbo, "1.0");
atoms[*counter].bond_order[j] = atof(tempbo);
/* Build connection name and store in atoms data structure */
strtok( tempname, "%#/");
strcat( tempname, tempcell);
strcat( tempname, tempsym);
strcat( tempname, "/");
strcat( tempname, tempbo);
if (strlen(tempname) > 25) fprintf(stderr,"tempname overrun %s\n",tempname);
sscanf( tempname, "%s", atoms[*counter].connections[j]);
}/*End for loop*/
}/* End function MakeNameLong
*/
void clean_string(char *string) {
int i,n;
short k;
n = strlen(string);
for (i=0; i < n; i++) {
k = (short)string[i];
if ((k<32) | (k>127)) string[i] = '\0';
}
}
|
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Struct template lazy_weighted_variance_impl</title>
<link rel="stylesheet" href="../../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.78.1">
<link rel="home" href="../../../index.html" title="The Boost C++ Libraries BoostBook Documentation Subset">
<link rel="up" href="../../../accumulators/reference.html#header.boost.accumulators.statistics_fwd_hpp" title="Header <boost/accumulators/statistics_fwd.hpp>">
<link rel="prev" href="lazy_variance_impl.html" title="Struct template lazy_variance_impl">
<link rel="next" href="max_impl.html" title="Struct template max_impl">
</head>
<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
<table cellpadding="2" width="100%"><tr>
<td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../../boost.png"></td>
<td align="center"><a href="../../../../../index.html">Home</a></td>
<td align="center"><a href="../../../../../libs/libraries.htm">Libraries</a></td>
<td align="center"><a href="http://www.boost.org/users/people.html">People</a></td>
<td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td>
<td align="center"><a href="../../../../../more/index.htm">More</a></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="lazy_variance_impl.html"><img src="../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../../accumulators/reference.html#header.boost.accumulators.statistics_fwd_hpp"><img src="../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../index.html"><img src="../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="max_impl.html"><img src="../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
<div class="refentry">
<a name="boost.accumulators.impl.lazy_weighted__idp59429040"></a><div class="titlepage"></div>
<div class="refnamediv">
<h2><span class="refentrytitle">Struct template lazy_weighted_variance_impl</span></h2>
<p>boost::accumulators::impl::lazy_weighted_variance_impl — Lazy calculation of variance of weighted samples. </p>
</div>
<h2 xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv-title">Synopsis</h2>
<div xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv"><pre class="synopsis"><span class="comment">// In header: <<a class="link" href="../../../accumulators/reference.html#header.boost.accumulators.statistics_fwd_hpp" title="Header <boost/accumulators/statistics_fwd.hpp>">boost/accumulators/statistics_fwd.hpp</a>>
</span><span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> Sample<span class="special">,</span> <span class="keyword">typename</span> Weight<span class="special">,</span> <span class="keyword">typename</span> MeanFeature<span class="special">></span>
<span class="keyword">struct</span> <a class="link" href="lazy_weighted__idp59429040.html" title="Struct template lazy_weighted_variance_impl">lazy_weighted_variance_impl</a> <span class="special">:</span> <span class="keyword">public</span> <span class="identifier">accumulator_base</span> <span class="special">{</span>
<span class="comment">// <a class="link" href="lazy_weighted__idp59429040.html#boost.accumulators.impl.lazy_weighted__idp59429040construct-copy-destruct">construct/copy/destruct</a></span>
<a class="link" href="lazy_weighted__idp59429040.html#idp59446624-bb"><span class="identifier">lazy_weighted_variance_impl</span></a><span class="special">(</span><span class="identifier">dont_care</span><span class="special">)</span><span class="special">;</span>
<span class="comment">// <a class="link" href="lazy_weighted__idp59429040.html#idp59443248-bb">public member functions</a></span>
<span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> Args<span class="special">></span> <span class="identifier">result_type</span> <a class="link" href="lazy_weighted__idp59429040.html#idp59443808-bb"><span class="identifier">result</span></a><span class="special">(</span><span class="identifier">Args</span> <span class="keyword">const</span> <span class="special">&</span><span class="special">)</span> <span class="keyword">const</span><span class="special">;</span>
<span class="special">}</span><span class="special">;</span></pre></div>
<div class="refsect1">
<a name="idp100643856"></a><h2>Description</h2>
<p>The default implementation of the variance of weighted samples is based on the second moment <span class="inlinemediaobject"><img src="../../../images/accumulators//form_0.png"></span> (weighted_moment<2>) and the mean <span class="inlinemediaobject"><img src="../../../images/accumulators//form_1.png"></span> (weighted_mean): </p>
<div class="equation">
<a name="idp100649488"></a><p class="title"><b>Equation 1.21. </b></p>
<div class="equation-contents"><div class="mediaobject" align="center"><img src="../../../images/accumulators//form_2.png" align="middle"></div></div>
</div>
<p><br class="equation-break"> where <span class="inlinemediaobject"><img src="../../../images/accumulators//form_3.png"></span> is the number of samples. </p>
<div class="refsect2">
<a name="idp100654688"></a><h3>
<a name="boost.accumulators.impl.lazy_weighted__idp59429040construct-copy-destruct"></a><code class="computeroutput">lazy_weighted_variance_impl</code>
public
construct/copy/destruct</h3>
<div class="orderedlist"><ol class="orderedlist" type="1"><li class="listitem"><pre class="literallayout"><a name="idp59446624-bb"></a><span class="identifier">lazy_weighted_variance_impl</span><span class="special">(</span><span class="identifier">dont_care</span><span class="special">)</span><span class="special">;</span></pre></li></ol></div>
</div>
<div class="refsect2">
<a name="idp100661280"></a><h3>
<a name="idp59443248-bb"></a><code class="computeroutput">lazy_weighted_variance_impl</code> public member functions</h3>
<div class="orderedlist"><ol class="orderedlist" type="1"><li class="listitem"><pre class="literallayout"><span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> Args<span class="special">></span> <span class="identifier">result_type</span> <a name="idp59443808-bb"></a><span class="identifier">result</span><span class="special">(</span><span class="identifier">Args</span> <span class="keyword">const</span> <span class="special">&</span> args<span class="special">)</span> <span class="keyword">const</span><span class="special">;</span></pre></li></ol></div>
</div>
</div>
</div>
<table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr>
<td align="left"></td>
<td align="right"><div class="copyright-footer">Copyright © 2005, 2006 Eric Niebler<p>
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>)
</p>
</div></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="lazy_variance_impl.html"><img src="../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../../accumulators/reference.html#header.boost.accumulators.statistics_fwd_hpp"><img src="../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../index.html"><img src="../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="max_impl.html"><img src="../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
</body>
</html>
|
/*******************************************************************************
*
* Module Name: utmutex - local mutex support
*
******************************************************************************/
/*
* Copyright (C) 2000 - 2014, Intel Corp.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions, and the following disclaimer,
* without modification.
* 2. Redistributions in binary form must reproduce at minimum a disclaimer
* substantially similar to the "NO WARRANTY" disclaimer below
* ("Disclaimer") and any redistribution must be conditioned upon
* including a substantially similar Disclaimer requirement for further
* binary redistribution.
* 3. Neither the names of the above-listed copyright holders nor the names
* of any contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* Alternatively, this software may be distributed under the terms of the
* GNU General Public License ("GPL") version 2 as published by the Free
* Software Foundation.
*
* NO WARRANTY
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGES.
*/
#include <acpi/acpi.h>
#include "accommon.h"
#define _COMPONENT ACPI_UTILITIES
ACPI_MODULE_NAME("utmutex")
/* Local prototypes */
static acpi_status acpi_ut_create_mutex(acpi_mutex_handle mutex_id);
static void acpi_ut_delete_mutex(acpi_mutex_handle mutex_id);
/*******************************************************************************
*
* FUNCTION: acpi_ut_mutex_initialize
*
* PARAMETERS: None.
*
* RETURN: Status
*
* DESCRIPTION: Create the system mutex objects. This includes mutexes,
* spin locks, and reader/writer locks.
*
******************************************************************************/
acpi_status acpi_ut_mutex_initialize(void)
{
u32 i;
acpi_status status;
ACPI_FUNCTION_TRACE(ut_mutex_initialize);
/* Create each of the predefined mutex objects */
for (i = 0; i < ACPI_NUM_MUTEX; i++) {
status = acpi_ut_create_mutex(i);
if (ACPI_FAILURE(status)) {
return_ACPI_STATUS(status);
}
}
/* Create the spinlocks for use at interrupt level or for speed */
status = acpi_os_create_lock (&acpi_gbl_gpe_lock);
if (ACPI_FAILURE (status)) {
return_ACPI_STATUS (status);
}
status = acpi_os_create_raw_lock (&acpi_gbl_hardware_lock);
if (ACPI_FAILURE (status)) {
return_ACPI_STATUS (status);
}
status = acpi_os_create_lock(&acpi_gbl_reference_count_lock);
if (ACPI_FAILURE(status)) {
return_ACPI_STATUS(status);
}
/* Mutex for _OSI support */
status = acpi_os_create_mutex(&acpi_gbl_osi_mutex);
if (ACPI_FAILURE(status)) {
return_ACPI_STATUS(status);
}
/* Create the reader/writer lock for namespace access */
status = acpi_ut_create_rw_lock(&acpi_gbl_namespace_rw_lock);
return_ACPI_STATUS(status);
}
/*******************************************************************************
*
* FUNCTION: acpi_ut_mutex_terminate
*
* PARAMETERS: None.
*
* RETURN: None.
*
* DESCRIPTION: Delete all of the system mutex objects. This includes mutexes,
* spin locks, and reader/writer locks.
*
******************************************************************************/
void acpi_ut_mutex_terminate(void)
{
u32 i;
ACPI_FUNCTION_TRACE(ut_mutex_terminate);
/* Delete each predefined mutex object */
for (i = 0; i < ACPI_NUM_MUTEX; i++) {
acpi_ut_delete_mutex(i);
}
acpi_os_delete_mutex(acpi_gbl_osi_mutex);
/* Delete the spinlocks */
acpi_os_delete_lock(acpi_gbl_gpe_lock);
acpi_os_delete_raw_lock(acpi_gbl_hardware_lock);
acpi_os_delete_lock(acpi_gbl_reference_count_lock);
/* Delete the reader/writer lock */
acpi_ut_delete_rw_lock(&acpi_gbl_namespace_rw_lock);
return_VOID;
}
/*******************************************************************************
*
* FUNCTION: acpi_ut_create_mutex
*
* PARAMETERS: mutex_ID - ID of the mutex to be created
*
* RETURN: Status
*
* DESCRIPTION: Create a mutex object.
*
******************************************************************************/
static acpi_status acpi_ut_create_mutex(acpi_mutex_handle mutex_id)
{
acpi_status status = AE_OK;
ACPI_FUNCTION_TRACE_U32(ut_create_mutex, mutex_id);
if (!acpi_gbl_mutex_info[mutex_id].mutex) {
status =
acpi_os_create_mutex(&acpi_gbl_mutex_info[mutex_id].mutex);
acpi_gbl_mutex_info[mutex_id].thread_id =
ACPI_MUTEX_NOT_ACQUIRED;
acpi_gbl_mutex_info[mutex_id].use_count = 0;
}
return_ACPI_STATUS(status);
}
/*******************************************************************************
*
* FUNCTION: acpi_ut_delete_mutex
*
* PARAMETERS: mutex_ID - ID of the mutex to be deleted
*
* RETURN: Status
*
* DESCRIPTION: Delete a mutex object.
*
******************************************************************************/
static void acpi_ut_delete_mutex(acpi_mutex_handle mutex_id)
{
ACPI_FUNCTION_TRACE_U32(ut_delete_mutex, mutex_id);
acpi_os_delete_mutex(acpi_gbl_mutex_info[mutex_id].mutex);
acpi_gbl_mutex_info[mutex_id].mutex = NULL;
acpi_gbl_mutex_info[mutex_id].thread_id = ACPI_MUTEX_NOT_ACQUIRED;
return_VOID;
}
/*******************************************************************************
*
* FUNCTION: acpi_ut_acquire_mutex
*
* PARAMETERS: mutex_ID - ID of the mutex to be acquired
*
* RETURN: Status
*
* DESCRIPTION: Acquire a mutex object.
*
******************************************************************************/
acpi_status acpi_ut_acquire_mutex(acpi_mutex_handle mutex_id)
{
acpi_status status;
acpi_thread_id this_thread_id;
ACPI_FUNCTION_NAME(ut_acquire_mutex);
if (mutex_id > ACPI_MAX_MUTEX) {
return (AE_BAD_PARAMETER);
}
this_thread_id = acpi_os_get_thread_id();
#ifdef ACPI_MUTEX_DEBUG
{
u32 i;
/*
* Mutex debug code, for internal debugging only.
*
* Deadlock prevention. Check if this thread owns any mutexes of value
* greater than or equal to this one. If so, the thread has violated
* the mutex ordering rule. This indicates a coding error somewhere in
* the ACPI subsystem code.
*/
for (i = mutex_id; i < ACPI_NUM_MUTEX; i++) {
if (acpi_gbl_mutex_info[i].thread_id == this_thread_id) {
if (i == mutex_id) {
ACPI_ERROR((AE_INFO,
"Mutex [%s] already acquired by this thread [%u]",
acpi_ut_get_mutex_name
(mutex_id),
(u32)this_thread_id));
return (AE_ALREADY_ACQUIRED);
}
ACPI_ERROR((AE_INFO,
"Invalid acquire order: Thread %u owns [%s], wants [%s]",
(u32)this_thread_id,
acpi_ut_get_mutex_name(i),
acpi_ut_get_mutex_name(mutex_id)));
return (AE_ACQUIRE_DEADLOCK);
}
}
}
#endif
ACPI_DEBUG_PRINT((ACPI_DB_MUTEX,
"Thread %u attempting to acquire Mutex [%s]\n",
(u32)this_thread_id,
acpi_ut_get_mutex_name(mutex_id)));
status = acpi_os_acquire_mutex(acpi_gbl_mutex_info[mutex_id].mutex,
ACPI_WAIT_FOREVER);
if (ACPI_SUCCESS(status)) {
ACPI_DEBUG_PRINT((ACPI_DB_MUTEX,
"Thread %u acquired Mutex [%s]\n",
(u32)this_thread_id,
acpi_ut_get_mutex_name(mutex_id)));
acpi_gbl_mutex_info[mutex_id].use_count++;
acpi_gbl_mutex_info[mutex_id].thread_id = this_thread_id;
} else {
ACPI_EXCEPTION((AE_INFO, status,
"Thread %u could not acquire Mutex [0x%X]",
(u32)this_thread_id, mutex_id));
}
return (status);
}
/*******************************************************************************
*
* FUNCTION: acpi_ut_release_mutex
*
* PARAMETERS: mutex_ID - ID of the mutex to be released
*
* RETURN: Status
*
* DESCRIPTION: Release a mutex object.
*
******************************************************************************/
acpi_status acpi_ut_release_mutex(acpi_mutex_handle mutex_id)
{
ACPI_FUNCTION_NAME(ut_release_mutex);
ACPI_DEBUG_PRINT((ACPI_DB_MUTEX, "Thread %u releasing Mutex [%s]\n",
(u32)acpi_os_get_thread_id(),
acpi_ut_get_mutex_name(mutex_id)));
if (mutex_id > ACPI_MAX_MUTEX) {
return (AE_BAD_PARAMETER);
}
/*
* Mutex must be acquired in order to release it!
*/
if (acpi_gbl_mutex_info[mutex_id].thread_id == ACPI_MUTEX_NOT_ACQUIRED) {
ACPI_ERROR((AE_INFO,
"Mutex [0x%X] is not acquired, cannot release",
mutex_id));
return (AE_NOT_ACQUIRED);
}
#ifdef ACPI_MUTEX_DEBUG
{
u32 i;
/*
* Mutex debug code, for internal debugging only.
*
* Deadlock prevention. Check if this thread owns any mutexes of value
* greater than this one. If so, the thread has violated the mutex
* ordering rule. This indicates a coding error somewhere in
* the ACPI subsystem code.
*/
for (i = mutex_id; i < ACPI_NUM_MUTEX; i++) {
if (acpi_gbl_mutex_info[i].thread_id ==
acpi_os_get_thread_id()) {
if (i == mutex_id) {
continue;
}
ACPI_ERROR((AE_INFO,
"Invalid release order: owns [%s], releasing [%s]",
acpi_ut_get_mutex_name(i),
acpi_ut_get_mutex_name(mutex_id)));
return (AE_RELEASE_DEADLOCK);
}
}
}
#endif
/* Mark unlocked FIRST */
acpi_gbl_mutex_info[mutex_id].thread_id = ACPI_MUTEX_NOT_ACQUIRED;
acpi_os_release_mutex(acpi_gbl_mutex_info[mutex_id].mutex);
return (AE_OK);
}
|
/*
* Backlight driver for OMAP based boards.
*
* Copyright (c) 2006 Andrzej Zaborowski <balrog@zabor.org>
*
* This package 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 package 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 package; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/platform_device.h>
#include <linux/fb.h>
#include <linux/backlight.h>
#include <asm/arch/hardware.h>
#include <asm/arch/board.h>
#include <asm/arch/mux.h>
#define OMAPBL_MAX_INTENSITY 0xff
struct omap_backlight {
int powermode;
int current_intensity;
struct device *dev;
struct omap_backlight_config *pdata;
};
static void inline omapbl_send_intensity(int intensity)
{
omap_writeb(intensity, OMAP_PWL_ENABLE);
}
static void inline omapbl_send_enable(int enable)
{
omap_writeb(enable, OMAP_PWL_CLK_ENABLE);
}
static void omapbl_blank(struct omap_backlight *bl, int mode)
{
if (bl->pdata->set_power)
bl->pdata->set_power(bl->dev, mode);
switch (mode) {
case FB_BLANK_NORMAL:
case FB_BLANK_VSYNC_SUSPEND:
case FB_BLANK_HSYNC_SUSPEND:
case FB_BLANK_POWERDOWN:
omapbl_send_intensity(0);
omapbl_send_enable(0);
break;
case FB_BLANK_UNBLANK:
omapbl_send_intensity(bl->current_intensity);
omapbl_send_enable(1);
break;
}
}
#ifdef CONFIG_PM
static int omapbl_suspend(struct platform_device *pdev, pm_message_t state)
{
struct backlight_device *dev = platform_get_drvdata(pdev);
struct omap_backlight *bl = dev_get_drvdata(&dev->dev);
omapbl_blank(bl, FB_BLANK_POWERDOWN);
return 0;
}
static int omapbl_resume(struct platform_device *pdev)
{
struct backlight_device *dev = platform_get_drvdata(pdev);
struct omap_backlight *bl = dev_get_drvdata(&dev->dev);
omapbl_blank(bl, bl->powermode);
return 0;
}
#else
#define omapbl_suspend NULL
#define omapbl_resume NULL
#endif
static int omapbl_set_power(struct backlight_device *dev, int state)
{
struct omap_backlight *bl = dev_get_drvdata(&dev->dev);
omapbl_blank(bl, state);
bl->powermode = state;
return 0;
}
static int omapbl_update_status(struct backlight_device *dev)
{
struct omap_backlight *bl = dev_get_drvdata(&dev->dev);
if (bl->current_intensity != dev->props.brightness) {
if (bl->powermode == FB_BLANK_UNBLANK)
omapbl_send_intensity(dev->props.brightness);
bl->current_intensity = dev->props.brightness;
}
if (dev->props.fb_blank != bl->powermode)
omapbl_set_power(dev, dev->props.fb_blank);
return 0;
}
static int omapbl_get_intensity(struct backlight_device *dev)
{
struct omap_backlight *bl = dev_get_drvdata(&dev->dev);
return bl->current_intensity;
}
static struct backlight_ops omapbl_ops = {
.get_brightness = omapbl_get_intensity,
.update_status = omapbl_update_status,
};
static int omapbl_probe(struct platform_device *pdev)
{
struct backlight_device *dev;
struct omap_backlight *bl;
struct omap_backlight_config *pdata = pdev->dev.platform_data;
if (!pdata)
return -ENXIO;
omapbl_ops.check_fb = pdata->check_fb;
bl = kzalloc(sizeof(struct omap_backlight), GFP_KERNEL);
if (unlikely(!bl))
return -ENOMEM;
dev = backlight_device_register("omap-bl", &pdev->dev, bl, &omapbl_ops);
if (IS_ERR(dev)) {
kfree(bl);
return PTR_ERR(dev);
}
bl->powermode = FB_BLANK_POWERDOWN;
bl->current_intensity = 0;
bl->pdata = pdata;
bl->dev = &pdev->dev;
platform_set_drvdata(pdev, dev);
omap_cfg_reg(PWL); /* Conflicts with UART3 */
dev->props.fb_blank = FB_BLANK_UNBLANK;
dev->props.max_brightness = OMAPBL_MAX_INTENSITY;
dev->props.brightness = pdata->default_intensity;
omapbl_update_status(dev);
printk(KERN_INFO "OMAP LCD backlight initialised\n");
return 0;
}
static int omapbl_remove(struct platform_device *pdev)
{
struct backlight_device *dev = platform_get_drvdata(pdev);
struct omap_backlight *bl = dev_get_drvdata(&dev->dev);
backlight_device_unregister(dev);
kfree(bl);
return 0;
}
static struct platform_driver omapbl_driver = {
.probe = omapbl_probe,
.remove = omapbl_remove,
.suspend = omapbl_suspend,
.resume = omapbl_resume,
.driver = {
.name = "omap-bl",
},
};
static int __init omapbl_init(void)
{
return platform_driver_register(&omapbl_driver);
}
static void __exit omapbl_exit(void)
{
platform_driver_unregister(&omapbl_driver);
}
module_init(omapbl_init);
module_exit(omapbl_exit);
MODULE_AUTHOR("Andrzej Zaborowski <balrog@zabor.org>");
MODULE_DESCRIPTION("OMAP LCD Backlight driver");
MODULE_LICENSE("GPL");
|
/*
* Copyright (C) 2003 Jana Saout <jana@saout.de>
* Copyright (C) 2004 Clemens Fruhwirth <clemens@endorphin.org>
* Copyright (C) 2006-2020 Red Hat, Inc. All rights reserved.
* Copyright (C) 2013-2020 Milan Broz <gmazyland@gmail.com>
*
* This file is released under the GPL.
*/
#include <linux/completion.h>
#include <linux/err.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/key.h>
#include <linux/bio.h>
#include <linux/blkdev.h>
#include <linux/mempool.h>
#include <linux/slab.h>
#include <linux/crypto.h>
#include <linux/workqueue.h>
#include <linux/kthread.h>
#include <linux/backing-dev.h>
#include <linux/atomic.h>
#include <linux/scatterlist.h>
#include <linux/rbtree.h>
#include <linux/ctype.h>
#include <asm/page.h>
#include <asm/unaligned.h>
#include <crypto/hash.h>
#include <crypto/md5.h>
#include <crypto/algapi.h>
#include <crypto/skcipher.h>
#include <crypto/aead.h>
#include <crypto/authenc.h>
#include <linux/rtnetlink.h> /* for struct rtattr and RTA macros only */
#include <linux/key-type.h>
#include <keys/user-type.h>
#include <keys/encrypted-type.h>
#include <linux/device-mapper.h>
#define DM_MSG_PREFIX "crypt"
/*
* context holding the current state of a multi-part conversion
*/
struct convert_context {
struct completion restart;
struct bio *bio_in;
struct bio *bio_out;
struct bvec_iter iter_in;
struct bvec_iter iter_out;
u64 cc_sector;
atomic_t cc_pending;
union {
struct skcipher_request *req;
struct aead_request *req_aead;
} r;
};
/*
* per bio private data
*/
struct dm_crypt_io {
struct crypt_config *cc;
struct bio *base_bio;
u8 *integrity_metadata;
bool integrity_metadata_from_pool;
struct work_struct work;
struct tasklet_struct tasklet;
struct convert_context ctx;
atomic_t io_pending;
blk_status_t error;
sector_t sector;
struct rb_node rb_node;
} CRYPTO_MINALIGN_ATTR;
struct dm_crypt_request {
struct convert_context *ctx;
struct scatterlist sg_in[4];
struct scatterlist sg_out[4];
u64 iv_sector;
};
struct crypt_config;
struct crypt_iv_operations {
int (*ctr)(struct crypt_config *cc, struct dm_target *ti,
const char *opts);
void (*dtr)(struct crypt_config *cc);
int (*init)(struct crypt_config *cc);
int (*wipe)(struct crypt_config *cc);
int (*generator)(struct crypt_config *cc, u8 *iv,
struct dm_crypt_request *dmreq);
int (*post)(struct crypt_config *cc, u8 *iv,
struct dm_crypt_request *dmreq);
};
struct iv_benbi_private {
int shift;
};
#define LMK_SEED_SIZE 64 /* hash + 0 */
struct iv_lmk_private {
struct crypto_shash *hash_tfm;
u8 *seed;
};
#define TCW_WHITENING_SIZE 16
struct iv_tcw_private {
struct crypto_shash *crc32_tfm;
u8 *iv_seed;
u8 *whitening;
};
#define ELEPHANT_MAX_KEY_SIZE 32
struct iv_elephant_private {
struct crypto_skcipher *tfm;
};
/*
* Crypt: maps a linear range of a block device
* and encrypts / decrypts at the same time.
*/
enum flags { DM_CRYPT_SUSPENDED, DM_CRYPT_KEY_VALID,
DM_CRYPT_SAME_CPU, DM_CRYPT_NO_OFFLOAD,
DM_CRYPT_NO_READ_WORKQUEUE, DM_CRYPT_NO_WRITE_WORKQUEUE,
DM_CRYPT_WRITE_INLINE };
enum cipher_flags {
CRYPT_MODE_INTEGRITY_AEAD, /* Use authenticated mode for cihper */
CRYPT_IV_LARGE_SECTORS, /* Calculate IV from sector_size, not 512B sectors */
CRYPT_ENCRYPT_PREPROCESS, /* Must preprocess data for encryption (elephant) */
};
/*
* The fields in here must be read only after initialization.
*/
struct crypt_config {
struct dm_dev *dev;
sector_t start;
struct percpu_counter n_allocated_pages;
struct workqueue_struct *io_queue;
struct workqueue_struct *crypt_queue;
spinlock_t write_thread_lock;
struct task_struct *write_thread;
struct rb_root write_tree;
char *cipher_string;
char *cipher_auth;
char *key_string;
const struct crypt_iv_operations *iv_gen_ops;
union {
struct iv_benbi_private benbi;
struct iv_lmk_private lmk;
struct iv_tcw_private tcw;
struct iv_elephant_private elephant;
} iv_gen_private;
u64 iv_offset;
unsigned int iv_size;
unsigned short int sector_size;
unsigned char sector_shift;
union {
struct crypto_skcipher **tfms;
struct crypto_aead **tfms_aead;
} cipher_tfm;
unsigned tfms_count;
unsigned long cipher_flags;
/*
* Layout of each crypto request:
*
* struct skcipher_request
* context
* padding
* struct dm_crypt_request
* padding
* IV
*
* The padding is added so that dm_crypt_request and the IV are
* correctly aligned.
*/
unsigned int dmreq_start;
unsigned int per_bio_data_size;
unsigned long flags;
unsigned int key_size;
unsigned int key_parts; /* independent parts in key buffer */
unsigned int key_extra_size; /* additional keys length */
unsigned int key_mac_size; /* MAC key size for authenc(...) */
unsigned int integrity_tag_size;
unsigned int integrity_iv_size;
unsigned int on_disk_tag_size;
/*
* pool for per bio private data, crypto requests,
* encryption requeusts/buffer pages and integrity tags
*/
unsigned tag_pool_max_sectors;
mempool_t tag_pool;
mempool_t req_pool;
mempool_t page_pool;
struct bio_set bs;
struct mutex bio_alloc_lock;
u8 *authenc_key; /* space for keys in authenc() format (if used) */
u8 key[];
};
#define MIN_IOS 64
#define MAX_TAG_SIZE 480
#define POOL_ENTRY_SIZE 512
static DEFINE_SPINLOCK(dm_crypt_clients_lock);
static unsigned dm_crypt_clients_n = 0;
static volatile unsigned long dm_crypt_pages_per_client;
#define DM_CRYPT_MEMORY_PERCENT 2
#define DM_CRYPT_MIN_PAGES_PER_CLIENT (BIO_MAX_PAGES * 16)
static void clone_init(struct dm_crypt_io *, struct bio *);
static void kcryptd_queue_crypt(struct dm_crypt_io *io);
static struct scatterlist *crypt_get_sg_data(struct crypt_config *cc,
struct scatterlist *sg);
static bool crypt_integrity_aead(struct crypt_config *cc);
/*
* Use this to access cipher attributes that are independent of the key.
*/
static struct crypto_skcipher *any_tfm(struct crypt_config *cc)
{
return cc->cipher_tfm.tfms[0];
}
static struct crypto_aead *any_tfm_aead(struct crypt_config *cc)
{
return cc->cipher_tfm.tfms_aead[0];
}
/*
* Different IV generation algorithms:
*
* plain: the initial vector is the 32-bit little-endian version of the sector
* number, padded with zeros if necessary.
*
* plain64: the initial vector is the 64-bit little-endian version of the sector
* number, padded with zeros if necessary.
*
* plain64be: the initial vector is the 64-bit big-endian version of the sector
* number, padded with zeros if necessary.
*
* essiv: "encrypted sector|salt initial vector", the sector number is
* encrypted with the bulk cipher using a salt as key. The salt
* should be derived from the bulk cipher's key via hashing.
*
* benbi: the 64-bit "big-endian 'narrow block'-count", starting at 1
* (needed for LRW-32-AES and possible other narrow block modes)
*
* null: the initial vector is always zero. Provides compatibility with
* obsolete loop_fish2 devices. Do not use for new devices.
*
* lmk: Compatible implementation of the block chaining mode used
* by the Loop-AES block device encryption system
* designed by Jari Ruusu. See http://loop-aes.sourceforge.net/
* It operates on full 512 byte sectors and uses CBC
* with an IV derived from the sector number, the data and
* optionally extra IV seed.
* This means that after decryption the first block
* of sector must be tweaked according to decrypted data.
* Loop-AES can use three encryption schemes:
* version 1: is plain aes-cbc mode
* version 2: uses 64 multikey scheme with lmk IV generator
* version 3: the same as version 2 with additional IV seed
* (it uses 65 keys, last key is used as IV seed)
*
* tcw: Compatible implementation of the block chaining mode used
* by the TrueCrypt device encryption system (prior to version 4.1).
* For more info see: https://gitlab.com/cryptsetup/cryptsetup/wikis/TrueCryptOnDiskFormat
* It operates on full 512 byte sectors and uses CBC
* with an IV derived from initial key and the sector number.
* In addition, whitening value is applied on every sector, whitening
* is calculated from initial key, sector number and mixed using CRC32.
* Note that this encryption scheme is vulnerable to watermarking attacks
* and should be used for old compatible containers access only.
*
* eboiv: Encrypted byte-offset IV (used in Bitlocker in CBC mode)
* The IV is encrypted little-endian byte-offset (with the same key
* and cipher as the volume).
*
* elephant: The extended version of eboiv with additional Elephant diffuser
* used with Bitlocker CBC mode.
* This mode was used in older Windows systems
* https://download.microsoft.com/download/0/2/3/0238acaf-d3bf-4a6d-b3d6-0a0be4bbb36e/bitlockercipher200608.pdf
*/
static int crypt_iv_plain_gen(struct crypt_config *cc, u8 *iv,
struct dm_crypt_request *dmreq)
{
memset(iv, 0, cc->iv_size);
*(__le32 *)iv = cpu_to_le32(dmreq->iv_sector & 0xffffffff);
return 0;
}
static int crypt_iv_plain64_gen(struct crypt_config *cc, u8 *iv,
struct dm_crypt_request *dmreq)
{
memset(iv, 0, cc->iv_size);
*(__le64 *)iv = cpu_to_le64(dmreq->iv_sector);
return 0;
}
static int crypt_iv_plain64be_gen(struct crypt_config *cc, u8 *iv,
struct dm_crypt_request *dmreq)
{
memset(iv, 0, cc->iv_size);
/* iv_size is at least of size u64; usually it is 16 bytes */
*(__be64 *)&iv[cc->iv_size - sizeof(u64)] = cpu_to_be64(dmreq->iv_sector);
return 0;
}
static int crypt_iv_essiv_gen(struct crypt_config *cc, u8 *iv,
struct dm_crypt_request *dmreq)
{
/*
* ESSIV encryption of the IV is now handled by the crypto API,
* so just pass the plain sector number here.
*/
memset(iv, 0, cc->iv_size);
*(__le64 *)iv = cpu_to_le64(dmreq->iv_sector);
return 0;
}
static int crypt_iv_benbi_ctr(struct crypt_config *cc, struct dm_target *ti,
const char *opts)
{
unsigned bs;
int log;
if (crypt_integrity_aead(cc))
bs = crypto_aead_blocksize(any_tfm_aead(cc));
else
bs = crypto_skcipher_blocksize(any_tfm(cc));
log = ilog2(bs);
/* we need to calculate how far we must shift the sector count
* to get the cipher block count, we use this shift in _gen */
if (1 << log != bs) {
ti->error = "cypher blocksize is not a power of 2";
return -EINVAL;
}
if (log > 9) {
ti->error = "cypher blocksize is > 512";
return -EINVAL;
}
cc->iv_gen_private.benbi.shift = 9 - log;
return 0;
}
static void crypt_iv_benbi_dtr(struct crypt_config *cc)
{
}
static int crypt_iv_benbi_gen(struct crypt_config *cc, u8 *iv,
struct dm_crypt_request *dmreq)
{
__be64 val;
memset(iv, 0, cc->iv_size - sizeof(u64)); /* rest is cleared below */
val = cpu_to_be64(((u64)dmreq->iv_sector << cc->iv_gen_private.benbi.shift) + 1);
put_unaligned(val, (__be64 *)(iv + cc->iv_size - sizeof(u64)));
return 0;
}
static int crypt_iv_null_gen(struct crypt_config *cc, u8 *iv,
struct dm_crypt_request *dmreq)
{
memset(iv, 0, cc->iv_size);
return 0;
}
static void crypt_iv_lmk_dtr(struct crypt_config *cc)
{
struct iv_lmk_private *lmk = &cc->iv_gen_private.lmk;
if (lmk->hash_tfm && !IS_ERR(lmk->hash_tfm))
crypto_free_shash(lmk->hash_tfm);
lmk->hash_tfm = NULL;
kfree_sensitive(lmk->seed);
lmk->seed = NULL;
}
static int crypt_iv_lmk_ctr(struct crypt_config *cc, struct dm_target *ti,
const char *opts)
{
struct iv_lmk_private *lmk = &cc->iv_gen_private.lmk;
if (cc->sector_size != (1 << SECTOR_SHIFT)) {
ti->error = "Unsupported sector size for LMK";
return -EINVAL;
}
lmk->hash_tfm = crypto_alloc_shash("md5", 0, 0);
if (IS_ERR(lmk->hash_tfm)) {
ti->error = "Error initializing LMK hash";
return PTR_ERR(lmk->hash_tfm);
}
/* No seed in LMK version 2 */
if (cc->key_parts == cc->tfms_count) {
lmk->seed = NULL;
return 0;
}
lmk->seed = kzalloc(LMK_SEED_SIZE, GFP_KERNEL);
if (!lmk->seed) {
crypt_iv_lmk_dtr(cc);
ti->error = "Error kmallocing seed storage in LMK";
return -ENOMEM;
}
return 0;
}
static int crypt_iv_lmk_init(struct crypt_config *cc)
{
struct iv_lmk_private *lmk = &cc->iv_gen_private.lmk;
int subkey_size = cc->key_size / cc->key_parts;
/* LMK seed is on the position of LMK_KEYS + 1 key */
if (lmk->seed)
memcpy(lmk->seed, cc->key + (cc->tfms_count * subkey_size),
crypto_shash_digestsize(lmk->hash_tfm));
return 0;
}
static int crypt_iv_lmk_wipe(struct crypt_config *cc)
{
struct iv_lmk_private *lmk = &cc->iv_gen_private.lmk;
if (lmk->seed)
memset(lmk->seed, 0, LMK_SEED_SIZE);
return 0;
}
static int crypt_iv_lmk_one(struct crypt_config *cc, u8 *iv,
struct dm_crypt_request *dmreq,
u8 *data)
{
struct iv_lmk_private *lmk = &cc->iv_gen_private.lmk;
SHASH_DESC_ON_STACK(desc, lmk->hash_tfm);
struct md5_state md5state;
__le32 buf[4];
int i, r;
desc->tfm = lmk->hash_tfm;
r = crypto_shash_init(desc);
if (r)
return r;
if (lmk->seed) {
r = crypto_shash_update(desc, lmk->seed, LMK_SEED_SIZE);
if (r)
return r;
}
/* Sector is always 512B, block size 16, add data of blocks 1-31 */
r = crypto_shash_update(desc, data + 16, 16 * 31);
if (r)
return r;
/* Sector is cropped to 56 bits here */
buf[0] = cpu_to_le32(dmreq->iv_sector & 0xFFFFFFFF);
buf[1] = cpu_to_le32((((u64)dmreq->iv_sector >> 32) & 0x00FFFFFF) | 0x80000000);
buf[2] = cpu_to_le32(4024);
buf[3] = 0;
r = crypto_shash_update(desc, (u8 *)buf, sizeof(buf));
if (r)
return r;
/* No MD5 padding here */
r = crypto_shash_export(desc, &md5state);
if (r)
return r;
for (i = 0; i < MD5_HASH_WORDS; i++)
__cpu_to_le32s(&md5state.hash[i]);
memcpy(iv, &md5state.hash, cc->iv_size);
return 0;
}
static int crypt_iv_lmk_gen(struct crypt_config *cc, u8 *iv,
struct dm_crypt_request *dmreq)
{
struct scatterlist *sg;
u8 *src;
int r = 0;
if (bio_data_dir(dmreq->ctx->bio_in) == WRITE) {
sg = crypt_get_sg_data(cc, dmreq->sg_in);
src = kmap_atomic(sg_page(sg));
r = crypt_iv_lmk_one(cc, iv, dmreq, src + sg->offset);
kunmap_atomic(src);
} else
memset(iv, 0, cc->iv_size);
return r;
}
static int crypt_iv_lmk_post(struct crypt_config *cc, u8 *iv,
struct dm_crypt_request *dmreq)
{
struct scatterlist *sg;
u8 *dst;
int r;
if (bio_data_dir(dmreq->ctx->bio_in) == WRITE)
return 0;
sg = crypt_get_sg_data(cc, dmreq->sg_out);
dst = kmap_atomic(sg_page(sg));
r = crypt_iv_lmk_one(cc, iv, dmreq, dst + sg->offset);
/* Tweak the first block of plaintext sector */
if (!r)
crypto_xor(dst + sg->offset, iv, cc->iv_size);
kunmap_atomic(dst);
return r;
}
static void crypt_iv_tcw_dtr(struct crypt_config *cc)
{
struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
kfree_sensitive(tcw->iv_seed);
tcw->iv_seed = NULL;
kfree_sensitive(tcw->whitening);
tcw->whitening = NULL;
if (tcw->crc32_tfm && !IS_ERR(tcw->crc32_tfm))
crypto_free_shash(tcw->crc32_tfm);
tcw->crc32_tfm = NULL;
}
static int crypt_iv_tcw_ctr(struct crypt_config *cc, struct dm_target *ti,
const char *opts)
{
struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
if (cc->sector_size != (1 << SECTOR_SHIFT)) {
ti->error = "Unsupported sector size for TCW";
return -EINVAL;
}
if (cc->key_size <= (cc->iv_size + TCW_WHITENING_SIZE)) {
ti->error = "Wrong key size for TCW";
return -EINVAL;
}
tcw->crc32_tfm = crypto_alloc_shash("crc32", 0, 0);
if (IS_ERR(tcw->crc32_tfm)) {
ti->error = "Error initializing CRC32 in TCW";
return PTR_ERR(tcw->crc32_tfm);
}
tcw->iv_seed = kzalloc(cc->iv_size, GFP_KERNEL);
tcw->whitening = kzalloc(TCW_WHITENING_SIZE, GFP_KERNEL);
if (!tcw->iv_seed || !tcw->whitening) {
crypt_iv_tcw_dtr(cc);
ti->error = "Error allocating seed storage in TCW";
return -ENOMEM;
}
return 0;
}
static int crypt_iv_tcw_init(struct crypt_config *cc)
{
struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
int key_offset = cc->key_size - cc->iv_size - TCW_WHITENING_SIZE;
memcpy(tcw->iv_seed, &cc->key[key_offset], cc->iv_size);
memcpy(tcw->whitening, &cc->key[key_offset + cc->iv_size],
TCW_WHITENING_SIZE);
return 0;
}
static int crypt_iv_tcw_wipe(struct crypt_config *cc)
{
struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
memset(tcw->iv_seed, 0, cc->iv_size);
memset(tcw->whitening, 0, TCW_WHITENING_SIZE);
return 0;
}
static int crypt_iv_tcw_whitening(struct crypt_config *cc,
struct dm_crypt_request *dmreq,
u8 *data)
{
struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
__le64 sector = cpu_to_le64(dmreq->iv_sector);
u8 buf[TCW_WHITENING_SIZE];
SHASH_DESC_ON_STACK(desc, tcw->crc32_tfm);
int i, r;
/* xor whitening with sector number */
crypto_xor_cpy(buf, tcw->whitening, (u8 *)§or, 8);
crypto_xor_cpy(&buf[8], tcw->whitening + 8, (u8 *)§or, 8);
/* calculate crc32 for every 32bit part and xor it */
desc->tfm = tcw->crc32_tfm;
for (i = 0; i < 4; i++) {
r = crypto_shash_init(desc);
if (r)
goto out;
r = crypto_shash_update(desc, &buf[i * 4], 4);
if (r)
goto out;
r = crypto_shash_final(desc, &buf[i * 4]);
if (r)
goto out;
}
crypto_xor(&buf[0], &buf[12], 4);
crypto_xor(&buf[4], &buf[8], 4);
/* apply whitening (8 bytes) to whole sector */
for (i = 0; i < ((1 << SECTOR_SHIFT) / 8); i++)
crypto_xor(data + i * 8, buf, 8);
out:
memzero_explicit(buf, sizeof(buf));
return r;
}
static int crypt_iv_tcw_gen(struct crypt_config *cc, u8 *iv,
struct dm_crypt_request *dmreq)
{
struct scatterlist *sg;
struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
__le64 sector = cpu_to_le64(dmreq->iv_sector);
u8 *src;
int r = 0;
/* Remove whitening from ciphertext */
if (bio_data_dir(dmreq->ctx->bio_in) != WRITE) {
sg = crypt_get_sg_data(cc, dmreq->sg_in);
src = kmap_atomic(sg_page(sg));
r = crypt_iv_tcw_whitening(cc, dmreq, src + sg->offset);
kunmap_atomic(src);
}
/* Calculate IV */
crypto_xor_cpy(iv, tcw->iv_seed, (u8 *)§or, 8);
if (cc->iv_size > 8)
crypto_xor_cpy(&iv[8], tcw->iv_seed + 8, (u8 *)§or,
cc->iv_size - 8);
return r;
}
static int crypt_iv_tcw_post(struct crypt_config *cc, u8 *iv,
struct dm_crypt_request *dmreq)
{
struct scatterlist *sg;
u8 *dst;
int r;
if (bio_data_dir(dmreq->ctx->bio_in) != WRITE)
return 0;
/* Apply whitening on ciphertext */
sg = crypt_get_sg_data(cc, dmreq->sg_out);
dst = kmap_atomic(sg_page(sg));
r = crypt_iv_tcw_whitening(cc, dmreq, dst + sg->offset);
kunmap_atomic(dst);
return r;
}
static int crypt_iv_random_gen(struct crypt_config *cc, u8 *iv,
struct dm_crypt_request *dmreq)
{
/* Used only for writes, there must be an additional space to store IV */
get_random_bytes(iv, cc->iv_size);
return 0;
}
static int crypt_iv_eboiv_ctr(struct crypt_config *cc, struct dm_target *ti,
const char *opts)
{
if (crypt_integrity_aead(cc)) {
ti->error = "AEAD transforms not supported for EBOIV";
return -EINVAL;
}
if (crypto_skcipher_blocksize(any_tfm(cc)) != cc->iv_size) {
ti->error = "Block size of EBOIV cipher does "
"not match IV size of block cipher";
return -EINVAL;
}
return 0;
}
static int crypt_iv_eboiv_gen(struct crypt_config *cc, u8 *iv,
struct dm_crypt_request *dmreq)
{
u8 buf[MAX_CIPHER_BLOCKSIZE] __aligned(__alignof__(__le64));
struct skcipher_request *req;
struct scatterlist src, dst;
struct crypto_wait wait;
int err;
req = skcipher_request_alloc(any_tfm(cc), GFP_NOIO);
if (!req)
return -ENOMEM;
memset(buf, 0, cc->iv_size);
*(__le64 *)buf = cpu_to_le64(dmreq->iv_sector * cc->sector_size);
sg_init_one(&src, page_address(ZERO_PAGE(0)), cc->iv_size);
sg_init_one(&dst, iv, cc->iv_size);
skcipher_request_set_crypt(req, &src, &dst, cc->iv_size, buf);
skcipher_request_set_callback(req, 0, crypto_req_done, &wait);
err = crypto_wait_req(crypto_skcipher_encrypt(req), &wait);
skcipher_request_free(req);
return err;
}
static void crypt_iv_elephant_dtr(struct crypt_config *cc)
{
struct iv_elephant_private *elephant = &cc->iv_gen_private.elephant;
crypto_free_skcipher(elephant->tfm);
elephant->tfm = NULL;
}
static int crypt_iv_elephant_ctr(struct crypt_config *cc, struct dm_target *ti,
const char *opts)
{
struct iv_elephant_private *elephant = &cc->iv_gen_private.elephant;
int r;
elephant->tfm = crypto_alloc_skcipher("ecb(aes)", 0, 0);
if (IS_ERR(elephant->tfm)) {
r = PTR_ERR(elephant->tfm);
elephant->tfm = NULL;
return r;
}
r = crypt_iv_eboiv_ctr(cc, ti, NULL);
if (r)
crypt_iv_elephant_dtr(cc);
return r;
}
static void diffuser_disk_to_cpu(u32 *d, size_t n)
{
#ifndef __LITTLE_ENDIAN
int i;
for (i = 0; i < n; i++)
d[i] = le32_to_cpu((__le32)d[i]);
#endif
}
static void diffuser_cpu_to_disk(__le32 *d, size_t n)
{
#ifndef __LITTLE_ENDIAN
int i;
for (i = 0; i < n; i++)
d[i] = cpu_to_le32((u32)d[i]);
#endif
}
static void diffuser_a_decrypt(u32 *d, size_t n)
{
int i, i1, i2, i3;
for (i = 0; i < 5; i++) {
i1 = 0;
i2 = n - 2;
i3 = n - 5;
while (i1 < (n - 1)) {
d[i1] += d[i2] ^ (d[i3] << 9 | d[i3] >> 23);
i1++; i2++; i3++;
if (i3 >= n)
i3 -= n;
d[i1] += d[i2] ^ d[i3];
i1++; i2++; i3++;
if (i2 >= n)
i2 -= n;
d[i1] += d[i2] ^ (d[i3] << 13 | d[i3] >> 19);
i1++; i2++; i3++;
d[i1] += d[i2] ^ d[i3];
i1++; i2++; i3++;
}
}
}
static void diffuser_a_encrypt(u32 *d, size_t n)
{
int i, i1, i2, i3;
for (i = 0; i < 5; i++) {
i1 = n - 1;
i2 = n - 2 - 1;
i3 = n - 5 - 1;
while (i1 > 0) {
d[i1] -= d[i2] ^ d[i3];
i1--; i2--; i3--;
d[i1] -= d[i2] ^ (d[i3] << 13 | d[i3] >> 19);
i1--; i2--; i3--;
if (i2 < 0)
i2 += n;
d[i1] -= d[i2] ^ d[i3];
i1--; i2--; i3--;
if (i3 < 0)
i3 += n;
d[i1] -= d[i2] ^ (d[i3] << 9 | d[i3] >> 23);
i1--; i2--; i3--;
}
}
}
static void diffuser_b_decrypt(u32 *d, size_t n)
{
int i, i1, i2, i3;
for (i = 0; i < 3; i++) {
i1 = 0;
i2 = 2;
i3 = 5;
while (i1 < (n - 1)) {
d[i1] += d[i2] ^ d[i3];
i1++; i2++; i3++;
d[i1] += d[i2] ^ (d[i3] << 10 | d[i3] >> 22);
i1++; i2++; i3++;
if (i2 >= n)
i2 -= n;
d[i1] += d[i2] ^ d[i3];
i1++; i2++; i3++;
if (i3 >= n)
i3 -= n;
d[i1] += d[i2] ^ (d[i3] << 25 | d[i3] >> 7);
i1++; i2++; i3++;
}
}
}
static void diffuser_b_encrypt(u32 *d, size_t n)
{
int i, i1, i2, i3;
for (i = 0; i < 3; i++) {
i1 = n - 1;
i2 = 2 - 1;
i3 = 5 - 1;
while (i1 > 0) {
d[i1] -= d[i2] ^ (d[i3] << 25 | d[i3] >> 7);
i1--; i2--; i3--;
if (i3 < 0)
i3 += n;
d[i1] -= d[i2] ^ d[i3];
i1--; i2--; i3--;
if (i2 < 0)
i2 += n;
d[i1] -= d[i2] ^ (d[i3] << 10 | d[i3] >> 22);
i1--; i2--; i3--;
d[i1] -= d[i2] ^ d[i3];
i1--; i2--; i3--;
}
}
}
static int crypt_iv_elephant(struct crypt_config *cc, struct dm_crypt_request *dmreq)
{
struct iv_elephant_private *elephant = &cc->iv_gen_private.elephant;
u8 *es, *ks, *data, *data2, *data_offset;
struct skcipher_request *req;
struct scatterlist *sg, *sg2, src, dst;
struct crypto_wait wait;
int i, r;
req = skcipher_request_alloc(elephant->tfm, GFP_NOIO);
es = kzalloc(16, GFP_NOIO); /* Key for AES */
ks = kzalloc(32, GFP_NOIO); /* Elephant sector key */
if (!req || !es || !ks) {
r = -ENOMEM;
goto out;
}
*(__le64 *)es = cpu_to_le64(dmreq->iv_sector * cc->sector_size);
/* E(Ks, e(s)) */
sg_init_one(&src, es, 16);
sg_init_one(&dst, ks, 16);
skcipher_request_set_crypt(req, &src, &dst, 16, NULL);
skcipher_request_set_callback(req, 0, crypto_req_done, &wait);
r = crypto_wait_req(crypto_skcipher_encrypt(req), &wait);
if (r)
goto out;
/* E(Ks, e'(s)) */
es[15] = 0x80;
sg_init_one(&dst, &ks[16], 16);
r = crypto_wait_req(crypto_skcipher_encrypt(req), &wait);
if (r)
goto out;
sg = crypt_get_sg_data(cc, dmreq->sg_out);
data = kmap_atomic(sg_page(sg));
data_offset = data + sg->offset;
/* Cannot modify original bio, copy to sg_out and apply Elephant to it */
if (bio_data_dir(dmreq->ctx->bio_in) == WRITE) {
sg2 = crypt_get_sg_data(cc, dmreq->sg_in);
data2 = kmap_atomic(sg_page(sg2));
memcpy(data_offset, data2 + sg2->offset, cc->sector_size);
kunmap_atomic(data2);
}
if (bio_data_dir(dmreq->ctx->bio_in) != WRITE) {
diffuser_disk_to_cpu((u32*)data_offset, cc->sector_size / sizeof(u32));
diffuser_b_decrypt((u32*)data_offset, cc->sector_size / sizeof(u32));
diffuser_a_decrypt((u32*)data_offset, cc->sector_size / sizeof(u32));
diffuser_cpu_to_disk((__le32*)data_offset, cc->sector_size / sizeof(u32));
}
for (i = 0; i < (cc->sector_size / 32); i++)
crypto_xor(data_offset + i * 32, ks, 32);
if (bio_data_dir(dmreq->ctx->bio_in) == WRITE) {
diffuser_disk_to_cpu((u32*)data_offset, cc->sector_size / sizeof(u32));
diffuser_a_encrypt((u32*)data_offset, cc->sector_size / sizeof(u32));
diffuser_b_encrypt((u32*)data_offset, cc->sector_size / sizeof(u32));
diffuser_cpu_to_disk((__le32*)data_offset, cc->sector_size / sizeof(u32));
}
kunmap_atomic(data);
out:
kfree_sensitive(ks);
kfree_sensitive(es);
skcipher_request_free(req);
return r;
}
static int crypt_iv_elephant_gen(struct crypt_config *cc, u8 *iv,
struct dm_crypt_request *dmreq)
{
int r;
if (bio_data_dir(dmreq->ctx->bio_in) == WRITE) {
r = crypt_iv_elephant(cc, dmreq);
if (r)
return r;
}
return crypt_iv_eboiv_gen(cc, iv, dmreq);
}
static int crypt_iv_elephant_post(struct crypt_config *cc, u8 *iv,
struct dm_crypt_request *dmreq)
{
if (bio_data_dir(dmreq->ctx->bio_in) != WRITE)
return crypt_iv_elephant(cc, dmreq);
return 0;
}
static int crypt_iv_elephant_init(struct crypt_config *cc)
{
struct iv_elephant_private *elephant = &cc->iv_gen_private.elephant;
int key_offset = cc->key_size - cc->key_extra_size;
return crypto_skcipher_setkey(elephant->tfm, &cc->key[key_offset], cc->key_extra_size);
}
static int crypt_iv_elephant_wipe(struct crypt_config *cc)
{
struct iv_elephant_private *elephant = &cc->iv_gen_private.elephant;
u8 key[ELEPHANT_MAX_KEY_SIZE];
memset(key, 0, cc->key_extra_size);
return crypto_skcipher_setkey(elephant->tfm, key, cc->key_extra_size);
}
static const struct crypt_iv_operations crypt_iv_plain_ops = {
.generator = crypt_iv_plain_gen
};
static const struct crypt_iv_operations crypt_iv_plain64_ops = {
.generator = crypt_iv_plain64_gen
};
static const struct crypt_iv_operations crypt_iv_plain64be_ops = {
.generator = crypt_iv_plain64be_gen
};
static const struct crypt_iv_operations crypt_iv_essiv_ops = {
.generator = crypt_iv_essiv_gen
};
static const struct crypt_iv_operations crypt_iv_benbi_ops = {
.ctr = crypt_iv_benbi_ctr,
.dtr = crypt_iv_benbi_dtr,
.generator = crypt_iv_benbi_gen
};
static const struct crypt_iv_operations crypt_iv_null_ops = {
.generator = crypt_iv_null_gen
};
static const struct crypt_iv_operations crypt_iv_lmk_ops = {
.ctr = crypt_iv_lmk_ctr,
.dtr = crypt_iv_lmk_dtr,
.init = crypt_iv_lmk_init,
.wipe = crypt_iv_lmk_wipe,
.generator = crypt_iv_lmk_gen,
.post = crypt_iv_lmk_post
};
static const struct crypt_iv_operations crypt_iv_tcw_ops = {
.ctr = crypt_iv_tcw_ctr,
.dtr = crypt_iv_tcw_dtr,
.init = crypt_iv_tcw_init,
.wipe = crypt_iv_tcw_wipe,
.generator = crypt_iv_tcw_gen,
.post = crypt_iv_tcw_post
};
static struct crypt_iv_operations crypt_iv_random_ops = {
.generator = crypt_iv_random_gen
};
static struct crypt_iv_operations crypt_iv_eboiv_ops = {
.ctr = crypt_iv_eboiv_ctr,
.generator = crypt_iv_eboiv_gen
};
static struct crypt_iv_operations crypt_iv_elephant_ops = {
.ctr = crypt_iv_elephant_ctr,
.dtr = crypt_iv_elephant_dtr,
.init = crypt_iv_elephant_init,
.wipe = crypt_iv_elephant_wipe,
.generator = crypt_iv_elephant_gen,
.post = crypt_iv_elephant_post
};
/*
* Integrity extensions
*/
static bool crypt_integrity_aead(struct crypt_config *cc)
{
return test_bit(CRYPT_MODE_INTEGRITY_AEAD, &cc->cipher_flags);
}
static bool crypt_integrity_hmac(struct crypt_config *cc)
{
return crypt_integrity_aead(cc) && cc->key_mac_size;
}
/* Get sg containing data */
static struct scatterlist *crypt_get_sg_data(struct crypt_config *cc,
struct scatterlist *sg)
{
if (unlikely(crypt_integrity_aead(cc)))
return &sg[2];
return sg;
}
static int dm_crypt_integrity_io_alloc(struct dm_crypt_io *io, struct bio *bio)
{
struct bio_integrity_payload *bip;
unsigned int tag_len;
int ret;
if (!bio_sectors(bio) || !io->cc->on_disk_tag_size)
return 0;
bip = bio_integrity_alloc(bio, GFP_NOIO, 1);
if (IS_ERR(bip))
return PTR_ERR(bip);
tag_len = io->cc->on_disk_tag_size * (bio_sectors(bio) >> io->cc->sector_shift);
bip->bip_iter.bi_size = tag_len;
bip->bip_iter.bi_sector = io->cc->start + io->sector;
ret = bio_integrity_add_page(bio, virt_to_page(io->integrity_metadata),
tag_len, offset_in_page(io->integrity_metadata));
if (unlikely(ret != tag_len))
return -ENOMEM;
return 0;
}
static int crypt_integrity_ctr(struct crypt_config *cc, struct dm_target *ti)
{
#ifdef CONFIG_BLK_DEV_INTEGRITY
struct blk_integrity *bi = blk_get_integrity(cc->dev->bdev->bd_disk);
struct mapped_device *md = dm_table_get_md(ti->table);
/* From now we require underlying device with our integrity profile */
if (!bi || strcasecmp(bi->profile->name, "DM-DIF-EXT-TAG")) {
ti->error = "Integrity profile not supported.";
return -EINVAL;
}
if (bi->tag_size != cc->on_disk_tag_size ||
bi->tuple_size != cc->on_disk_tag_size) {
ti->error = "Integrity profile tag size mismatch.";
return -EINVAL;
}
if (1 << bi->interval_exp != cc->sector_size) {
ti->error = "Integrity profile sector size mismatch.";
return -EINVAL;
}
if (crypt_integrity_aead(cc)) {
cc->integrity_tag_size = cc->on_disk_tag_size - cc->integrity_iv_size;
DMDEBUG("%s: Integrity AEAD, tag size %u, IV size %u.", dm_device_name(md),
cc->integrity_tag_size, cc->integrity_iv_size);
if (crypto_aead_setauthsize(any_tfm_aead(cc), cc->integrity_tag_size)) {
ti->error = "Integrity AEAD auth tag size is not supported.";
return -EINVAL;
}
} else if (cc->integrity_iv_size)
DMDEBUG("%s: Additional per-sector space %u bytes for IV.", dm_device_name(md),
cc->integrity_iv_size);
if ((cc->integrity_tag_size + cc->integrity_iv_size) != bi->tag_size) {
ti->error = "Not enough space for integrity tag in the profile.";
return -EINVAL;
}
return 0;
#else
ti->error = "Integrity profile not supported.";
return -EINVAL;
#endif
}
static void crypt_convert_init(struct crypt_config *cc,
struct convert_context *ctx,
struct bio *bio_out, struct bio *bio_in,
sector_t sector)
{
ctx->bio_in = bio_in;
ctx->bio_out = bio_out;
if (bio_in)
ctx->iter_in = bio_in->bi_iter;
if (bio_out)
ctx->iter_out = bio_out->bi_iter;
ctx->cc_sector = sector + cc->iv_offset;
init_completion(&ctx->restart);
}
static struct dm_crypt_request *dmreq_of_req(struct crypt_config *cc,
void *req)
{
return (struct dm_crypt_request *)((char *)req + cc->dmreq_start);
}
static void *req_of_dmreq(struct crypt_config *cc, struct dm_crypt_request *dmreq)
{
return (void *)((char *)dmreq - cc->dmreq_start);
}
static u8 *iv_of_dmreq(struct crypt_config *cc,
struct dm_crypt_request *dmreq)
{
if (crypt_integrity_aead(cc))
return (u8 *)ALIGN((unsigned long)(dmreq + 1),
crypto_aead_alignmask(any_tfm_aead(cc)) + 1);
else
return (u8 *)ALIGN((unsigned long)(dmreq + 1),
crypto_skcipher_alignmask(any_tfm(cc)) + 1);
}
static u8 *org_iv_of_dmreq(struct crypt_config *cc,
struct dm_crypt_request *dmreq)
{
return iv_of_dmreq(cc, dmreq) + cc->iv_size;
}
static __le64 *org_sector_of_dmreq(struct crypt_config *cc,
struct dm_crypt_request *dmreq)
{
u8 *ptr = iv_of_dmreq(cc, dmreq) + cc->iv_size + cc->iv_size;
return (__le64 *) ptr;
}
static unsigned int *org_tag_of_dmreq(struct crypt_config *cc,
struct dm_crypt_request *dmreq)
{
u8 *ptr = iv_of_dmreq(cc, dmreq) + cc->iv_size +
cc->iv_size + sizeof(uint64_t);
return (unsigned int*)ptr;
}
static void *tag_from_dmreq(struct crypt_config *cc,
struct dm_crypt_request *dmreq)
{
struct convert_context *ctx = dmreq->ctx;
struct dm_crypt_io *io = container_of(ctx, struct dm_crypt_io, ctx);
return &io->integrity_metadata[*org_tag_of_dmreq(cc, dmreq) *
cc->on_disk_tag_size];
}
static void *iv_tag_from_dmreq(struct crypt_config *cc,
struct dm_crypt_request *dmreq)
{
return tag_from_dmreq(cc, dmreq) + cc->integrity_tag_size;
}
static int crypt_convert_block_aead(struct crypt_config *cc,
struct convert_context *ctx,
struct aead_request *req,
unsigned int tag_offset)
{
struct bio_vec bv_in = bio_iter_iovec(ctx->bio_in, ctx->iter_in);
struct bio_vec bv_out = bio_iter_iovec(ctx->bio_out, ctx->iter_out);
struct dm_crypt_request *dmreq;
u8 *iv, *org_iv, *tag_iv, *tag;
__le64 *sector;
int r = 0;
BUG_ON(cc->integrity_iv_size && cc->integrity_iv_size != cc->iv_size);
/* Reject unexpected unaligned bio. */
if (unlikely(bv_in.bv_len & (cc->sector_size - 1)))
return -EIO;
dmreq = dmreq_of_req(cc, req);
dmreq->iv_sector = ctx->cc_sector;
if (test_bit(CRYPT_IV_LARGE_SECTORS, &cc->cipher_flags))
dmreq->iv_sector >>= cc->sector_shift;
dmreq->ctx = ctx;
*org_tag_of_dmreq(cc, dmreq) = tag_offset;
sector = org_sector_of_dmreq(cc, dmreq);
*sector = cpu_to_le64(ctx->cc_sector - cc->iv_offset);
iv = iv_of_dmreq(cc, dmreq);
org_iv = org_iv_of_dmreq(cc, dmreq);
tag = tag_from_dmreq(cc, dmreq);
tag_iv = iv_tag_from_dmreq(cc, dmreq);
/* AEAD request:
* |----- AAD -------|------ DATA -------|-- AUTH TAG --|
* | (authenticated) | (auth+encryption) | |
* | sector_LE | IV | sector in/out | tag in/out |
*/
sg_init_table(dmreq->sg_in, 4);
sg_set_buf(&dmreq->sg_in[0], sector, sizeof(uint64_t));
sg_set_buf(&dmreq->sg_in[1], org_iv, cc->iv_size);
sg_set_page(&dmreq->sg_in[2], bv_in.bv_page, cc->sector_size, bv_in.bv_offset);
sg_set_buf(&dmreq->sg_in[3], tag, cc->integrity_tag_size);
sg_init_table(dmreq->sg_out, 4);
sg_set_buf(&dmreq->sg_out[0], sector, sizeof(uint64_t));
sg_set_buf(&dmreq->sg_out[1], org_iv, cc->iv_size);
sg_set_page(&dmreq->sg_out[2], bv_out.bv_page, cc->sector_size, bv_out.bv_offset);
sg_set_buf(&dmreq->sg_out[3], tag, cc->integrity_tag_size);
if (cc->iv_gen_ops) {
/* For READs use IV stored in integrity metadata */
if (cc->integrity_iv_size && bio_data_dir(ctx->bio_in) != WRITE) {
memcpy(org_iv, tag_iv, cc->iv_size);
} else {
r = cc->iv_gen_ops->generator(cc, org_iv, dmreq);
if (r < 0)
return r;
/* Store generated IV in integrity metadata */
if (cc->integrity_iv_size)
memcpy(tag_iv, org_iv, cc->iv_size);
}
/* Working copy of IV, to be modified in crypto API */
memcpy(iv, org_iv, cc->iv_size);
}
aead_request_set_ad(req, sizeof(uint64_t) + cc->iv_size);
if (bio_data_dir(ctx->bio_in) == WRITE) {
aead_request_set_crypt(req, dmreq->sg_in, dmreq->sg_out,
cc->sector_size, iv);
r = crypto_aead_encrypt(req);
if (cc->integrity_tag_size + cc->integrity_iv_size != cc->on_disk_tag_size)
memset(tag + cc->integrity_tag_size + cc->integrity_iv_size, 0,
cc->on_disk_tag_size - (cc->integrity_tag_size + cc->integrity_iv_size));
} else {
aead_request_set_crypt(req, dmreq->sg_in, dmreq->sg_out,
cc->sector_size + cc->integrity_tag_size, iv);
r = crypto_aead_decrypt(req);
}
if (r == -EBADMSG) {
char b[BDEVNAME_SIZE];
DMERR_LIMIT("%s: INTEGRITY AEAD ERROR, sector %llu", bio_devname(ctx->bio_in, b),
(unsigned long long)le64_to_cpu(*sector));
}
if (!r && cc->iv_gen_ops && cc->iv_gen_ops->post)
r = cc->iv_gen_ops->post(cc, org_iv, dmreq);
bio_advance_iter(ctx->bio_in, &ctx->iter_in, cc->sector_size);
bio_advance_iter(ctx->bio_out, &ctx->iter_out, cc->sector_size);
return r;
}
static int crypt_convert_block_skcipher(struct crypt_config *cc,
struct convert_context *ctx,
struct skcipher_request *req,
unsigned int tag_offset)
{
struct bio_vec bv_in = bio_iter_iovec(ctx->bio_in, ctx->iter_in);
struct bio_vec bv_out = bio_iter_iovec(ctx->bio_out, ctx->iter_out);
struct scatterlist *sg_in, *sg_out;
struct dm_crypt_request *dmreq;
u8 *iv, *org_iv, *tag_iv;
__le64 *sector;
int r = 0;
/* Reject unexpected unaligned bio. */
if (unlikely(bv_in.bv_len & (cc->sector_size - 1)))
return -EIO;
dmreq = dmreq_of_req(cc, req);
dmreq->iv_sector = ctx->cc_sector;
if (test_bit(CRYPT_IV_LARGE_SECTORS, &cc->cipher_flags))
dmreq->iv_sector >>= cc->sector_shift;
dmreq->ctx = ctx;
*org_tag_of_dmreq(cc, dmreq) = tag_offset;
iv = iv_of_dmreq(cc, dmreq);
org_iv = org_iv_of_dmreq(cc, dmreq);
tag_iv = iv_tag_from_dmreq(cc, dmreq);
sector = org_sector_of_dmreq(cc, dmreq);
*sector = cpu_to_le64(ctx->cc_sector - cc->iv_offset);
/* For skcipher we use only the first sg item */
sg_in = &dmreq->sg_in[0];
sg_out = &dmreq->sg_out[0];
sg_init_table(sg_in, 1);
sg_set_page(sg_in, bv_in.bv_page, cc->sector_size, bv_in.bv_offset);
sg_init_table(sg_out, 1);
sg_set_page(sg_out, bv_out.bv_page, cc->sector_size, bv_out.bv_offset);
if (cc->iv_gen_ops) {
/* For READs use IV stored in integrity metadata */
if (cc->integrity_iv_size && bio_data_dir(ctx->bio_in) != WRITE) {
memcpy(org_iv, tag_iv, cc->integrity_iv_size);
} else {
r = cc->iv_gen_ops->generator(cc, org_iv, dmreq);
if (r < 0)
return r;
/* Data can be already preprocessed in generator */
if (test_bit(CRYPT_ENCRYPT_PREPROCESS, &cc->cipher_flags))
sg_in = sg_out;
/* Store generated IV in integrity metadata */
if (cc->integrity_iv_size)
memcpy(tag_iv, org_iv, cc->integrity_iv_size);
}
/* Working copy of IV, to be modified in crypto API */
memcpy(iv, org_iv, cc->iv_size);
}
skcipher_request_set_crypt(req, sg_in, sg_out, cc->sector_size, iv);
if (bio_data_dir(ctx->bio_in) == WRITE)
r = crypto_skcipher_encrypt(req);
else
r = crypto_skcipher_decrypt(req);
if (!r && cc->iv_gen_ops && cc->iv_gen_ops->post)
r = cc->iv_gen_ops->post(cc, org_iv, dmreq);
bio_advance_iter(ctx->bio_in, &ctx->iter_in, cc->sector_size);
bio_advance_iter(ctx->bio_out, &ctx->iter_out, cc->sector_size);
return r;
}
static void kcryptd_async_done(struct crypto_async_request *async_req,
int error);
static void crypt_alloc_req_skcipher(struct crypt_config *cc,
struct convert_context *ctx)
{
unsigned key_index = ctx->cc_sector & (cc->tfms_count - 1);
if (!ctx->r.req)
ctx->r.req = mempool_alloc(&cc->req_pool, GFP_NOIO);
skcipher_request_set_tfm(ctx->r.req, cc->cipher_tfm.tfms[key_index]);
/*
* Use REQ_MAY_BACKLOG so a cipher driver internally backlogs
* requests if driver request queue is full.
*/
skcipher_request_set_callback(ctx->r.req,
CRYPTO_TFM_REQ_MAY_BACKLOG,
kcryptd_async_done, dmreq_of_req(cc, ctx->r.req));
}
static void crypt_alloc_req_aead(struct crypt_config *cc,
struct convert_context *ctx)
{
if (!ctx->r.req_aead)
ctx->r.req_aead = mempool_alloc(&cc->req_pool, GFP_NOIO);
aead_request_set_tfm(ctx->r.req_aead, cc->cipher_tfm.tfms_aead[0]);
/*
* Use REQ_MAY_BACKLOG so a cipher driver internally backlogs
* requests if driver request queue is full.
*/
aead_request_set_callback(ctx->r.req_aead,
CRYPTO_TFM_REQ_MAY_BACKLOG,
kcryptd_async_done, dmreq_of_req(cc, ctx->r.req_aead));
}
static void crypt_alloc_req(struct crypt_config *cc,
struct convert_context *ctx)
{
if (crypt_integrity_aead(cc))
crypt_alloc_req_aead(cc, ctx);
else
crypt_alloc_req_skcipher(cc, ctx);
}
static void crypt_free_req_skcipher(struct crypt_config *cc,
struct skcipher_request *req, struct bio *base_bio)
{
struct dm_crypt_io *io = dm_per_bio_data(base_bio, cc->per_bio_data_size);
if ((struct skcipher_request *)(io + 1) != req)
mempool_free(req, &cc->req_pool);
}
static void crypt_free_req_aead(struct crypt_config *cc,
struct aead_request *req, struct bio *base_bio)
{
struct dm_crypt_io *io = dm_per_bio_data(base_bio, cc->per_bio_data_size);
if ((struct aead_request *)(io + 1) != req)
mempool_free(req, &cc->req_pool);
}
static void crypt_free_req(struct crypt_config *cc, void *req, struct bio *base_bio)
{
if (crypt_integrity_aead(cc))
crypt_free_req_aead(cc, req, base_bio);
else
crypt_free_req_skcipher(cc, req, base_bio);
}
/*
* Encrypt / decrypt data from one bio to another one (can be the same one)
*/
static blk_status_t crypt_convert(struct crypt_config *cc,
struct convert_context *ctx, bool atomic)
{
unsigned int tag_offset = 0;
unsigned int sector_step = cc->sector_size >> SECTOR_SHIFT;
int r;
atomic_set(&ctx->cc_pending, 1);
while (ctx->iter_in.bi_size && ctx->iter_out.bi_size) {
crypt_alloc_req(cc, ctx);
atomic_inc(&ctx->cc_pending);
if (crypt_integrity_aead(cc))
r = crypt_convert_block_aead(cc, ctx, ctx->r.req_aead, tag_offset);
else
r = crypt_convert_block_skcipher(cc, ctx, ctx->r.req, tag_offset);
switch (r) {
/*
* The request was queued by a crypto driver
* but the driver request queue is full, let's wait.
*/
case -EBUSY:
wait_for_completion(&ctx->restart);
reinit_completion(&ctx->restart);
/* fall through */
/*
* The request is queued and processed asynchronously,
* completion function kcryptd_async_done() will be called.
*/
case -EINPROGRESS:
ctx->r.req = NULL;
ctx->cc_sector += sector_step;
tag_offset++;
continue;
/*
* The request was already processed (synchronously).
*/
case 0:
atomic_dec(&ctx->cc_pending);
ctx->cc_sector += sector_step;
tag_offset++;
if (!atomic)
cond_resched();
continue;
/*
* There was a data integrity error.
*/
case -EBADMSG:
atomic_dec(&ctx->cc_pending);
return BLK_STS_PROTECTION;
/*
* There was an error while processing the request.
*/
default:
atomic_dec(&ctx->cc_pending);
return BLK_STS_IOERR;
}
}
return 0;
}
static void crypt_free_buffer_pages(struct crypt_config *cc, struct bio *clone);
/*
* Generate a new unfragmented bio with the given size
* This should never violate the device limitations (but only because
* max_segment_size is being constrained to PAGE_SIZE).
*
* This function may be called concurrently. If we allocate from the mempool
* concurrently, there is a possibility of deadlock. For example, if we have
* mempool of 256 pages, two processes, each wanting 256, pages allocate from
* the mempool concurrently, it may deadlock in a situation where both processes
* have allocated 128 pages and the mempool is exhausted.
*
* In order to avoid this scenario we allocate the pages under a mutex.
*
* In order to not degrade performance with excessive locking, we try
* non-blocking allocations without a mutex first but on failure we fallback
* to blocking allocations with a mutex.
*/
static struct bio *crypt_alloc_buffer(struct dm_crypt_io *io, unsigned size)
{
struct crypt_config *cc = io->cc;
struct bio *clone;
unsigned int nr_iovecs = (size + PAGE_SIZE - 1) >> PAGE_SHIFT;
gfp_t gfp_mask = GFP_NOWAIT | __GFP_HIGHMEM;
unsigned i, len, remaining_size;
struct page *page;
retry:
if (unlikely(gfp_mask & __GFP_DIRECT_RECLAIM))
mutex_lock(&cc->bio_alloc_lock);
clone = bio_alloc_bioset(GFP_NOIO, nr_iovecs, &cc->bs);
if (!clone)
goto out;
clone_init(io, clone);
remaining_size = size;
for (i = 0; i < nr_iovecs; i++) {
page = mempool_alloc(&cc->page_pool, gfp_mask);
if (!page) {
crypt_free_buffer_pages(cc, clone);
bio_put(clone);
gfp_mask |= __GFP_DIRECT_RECLAIM;
goto retry;
}
len = (remaining_size > PAGE_SIZE) ? PAGE_SIZE : remaining_size;
bio_add_page(clone, page, len, 0);
remaining_size -= len;
}
/* Allocate space for integrity tags */
if (dm_crypt_integrity_io_alloc(io, clone)) {
crypt_free_buffer_pages(cc, clone);
bio_put(clone);
clone = NULL;
}
out:
if (unlikely(gfp_mask & __GFP_DIRECT_RECLAIM))
mutex_unlock(&cc->bio_alloc_lock);
return clone;
}
static void crypt_free_buffer_pages(struct crypt_config *cc, struct bio *clone)
{
struct bio_vec *bv;
struct bvec_iter_all iter_all;
bio_for_each_segment_all(bv, clone, iter_all) {
BUG_ON(!bv->bv_page);
mempool_free(bv->bv_page, &cc->page_pool);
}
}
static void crypt_io_init(struct dm_crypt_io *io, struct crypt_config *cc,
struct bio *bio, sector_t sector)
{
io->cc = cc;
io->base_bio = bio;
io->sector = sector;
io->error = 0;
io->ctx.r.req = NULL;
io->integrity_metadata = NULL;
io->integrity_metadata_from_pool = false;
atomic_set(&io->io_pending, 0);
}
static void crypt_inc_pending(struct dm_crypt_io *io)
{
atomic_inc(&io->io_pending);
}
/*
* One of the bios was finished. Check for completion of
* the whole request and correctly clean up the buffer.
*/
static void crypt_dec_pending(struct dm_crypt_io *io)
{
struct crypt_config *cc = io->cc;
struct bio *base_bio = io->base_bio;
blk_status_t error = io->error;
if (!atomic_dec_and_test(&io->io_pending))
return;
if (io->ctx.r.req)
crypt_free_req(cc, io->ctx.r.req, base_bio);
if (unlikely(io->integrity_metadata_from_pool))
mempool_free(io->integrity_metadata, &io->cc->tag_pool);
else
kfree(io->integrity_metadata);
base_bio->bi_status = error;
bio_endio(base_bio);
}
/*
* kcryptd/kcryptd_io:
*
* Needed because it would be very unwise to do decryption in an
* interrupt context.
*
* kcryptd performs the actual encryption or decryption.
*
* kcryptd_io performs the IO submission.
*
* They must be separated as otherwise the final stages could be
* starved by new requests which can block in the first stages due
* to memory allocation.
*
* The work is done per CPU global for all dm-crypt instances.
* They should not depend on each other and do not block.
*/
static void crypt_endio(struct bio *clone)
{
struct dm_crypt_io *io = clone->bi_private;
struct crypt_config *cc = io->cc;
unsigned rw = bio_data_dir(clone);
blk_status_t error;
/*
* free the processed pages
*/
if (rw == WRITE)
crypt_free_buffer_pages(cc, clone);
error = clone->bi_status;
bio_put(clone);
if (rw == READ && !error) {
kcryptd_queue_crypt(io);
return;
}
if (unlikely(error))
io->error = error;
crypt_dec_pending(io);
}
static void clone_init(struct dm_crypt_io *io, struct bio *clone)
{
struct crypt_config *cc = io->cc;
clone->bi_private = io;
clone->bi_end_io = crypt_endio;
bio_set_dev(clone, cc->dev->bdev);
clone->bi_opf = io->base_bio->bi_opf;
}
static int kcryptd_io_read(struct dm_crypt_io *io, gfp_t gfp)
{
struct crypt_config *cc = io->cc;
struct bio *clone;
/*
* We need the original biovec array in order to decrypt
* the whole bio data *afterwards* -- thanks to immutable
* biovecs we don't need to worry about the block layer
* modifying the biovec array; so leverage bio_clone_fast().
*/
clone = bio_clone_fast(io->base_bio, gfp, &cc->bs);
if (!clone)
return 1;
crypt_inc_pending(io);
clone_init(io, clone);
clone->bi_iter.bi_sector = cc->start + io->sector;
if (dm_crypt_integrity_io_alloc(io, clone)) {
crypt_dec_pending(io);
bio_put(clone);
return 1;
}
submit_bio_noacct(clone);
return 0;
}
static void kcryptd_io_read_work(struct work_struct *work)
{
struct dm_crypt_io *io = container_of(work, struct dm_crypt_io, work);
crypt_inc_pending(io);
if (kcryptd_io_read(io, GFP_NOIO))
io->error = BLK_STS_RESOURCE;
crypt_dec_pending(io);
}
static void kcryptd_queue_read(struct dm_crypt_io *io)
{
struct crypt_config *cc = io->cc;
INIT_WORK(&io->work, kcryptd_io_read_work);
queue_work(cc->io_queue, &io->work);
}
static void kcryptd_io_write(struct dm_crypt_io *io)
{
struct bio *clone = io->ctx.bio_out;
submit_bio_noacct(clone);
}
#define crypt_io_from_node(node) rb_entry((node), struct dm_crypt_io, rb_node)
static int dmcrypt_write(void *data)
{
struct crypt_config *cc = data;
struct dm_crypt_io *io;
while (1) {
struct rb_root write_tree;
struct blk_plug plug;
spin_lock_irq(&cc->write_thread_lock);
continue_locked:
if (!RB_EMPTY_ROOT(&cc->write_tree))
goto pop_from_list;
set_current_state(TASK_INTERRUPTIBLE);
spin_unlock_irq(&cc->write_thread_lock);
if (unlikely(kthread_should_stop())) {
set_current_state(TASK_RUNNING);
break;
}
schedule();
set_current_state(TASK_RUNNING);
spin_lock_irq(&cc->write_thread_lock);
goto continue_locked;
pop_from_list:
write_tree = cc->write_tree;
cc->write_tree = RB_ROOT;
spin_unlock_irq(&cc->write_thread_lock);
BUG_ON(rb_parent(write_tree.rb_node));
/*
* Note: we cannot walk the tree here with rb_next because
* the structures may be freed when kcryptd_io_write is called.
*/
blk_start_plug(&plug);
do {
io = crypt_io_from_node(rb_first(&write_tree));
rb_erase(&io->rb_node, &write_tree);
kcryptd_io_write(io);
} while (!RB_EMPTY_ROOT(&write_tree));
blk_finish_plug(&plug);
}
return 0;
}
static void kcryptd_crypt_write_io_submit(struct dm_crypt_io *io, int async)
{
struct bio *clone = io->ctx.bio_out;
struct crypt_config *cc = io->cc;
unsigned long flags;
sector_t sector;
struct rb_node **rbp, *parent;
if (unlikely(io->error)) {
crypt_free_buffer_pages(cc, clone);
bio_put(clone);
crypt_dec_pending(io);
return;
}
/* crypt_convert should have filled the clone bio */
BUG_ON(io->ctx.iter_out.bi_size);
clone->bi_iter.bi_sector = cc->start + io->sector;
if ((likely(!async) && test_bit(DM_CRYPT_NO_OFFLOAD, &cc->flags)) ||
test_bit(DM_CRYPT_NO_WRITE_WORKQUEUE, &cc->flags)) {
submit_bio_noacct(clone);
return;
}
spin_lock_irqsave(&cc->write_thread_lock, flags);
if (RB_EMPTY_ROOT(&cc->write_tree))
wake_up_process(cc->write_thread);
rbp = &cc->write_tree.rb_node;
parent = NULL;
sector = io->sector;
while (*rbp) {
parent = *rbp;
if (sector < crypt_io_from_node(parent)->sector)
rbp = &(*rbp)->rb_left;
else
rbp = &(*rbp)->rb_right;
}
rb_link_node(&io->rb_node, parent, rbp);
rb_insert_color(&io->rb_node, &cc->write_tree);
spin_unlock_irqrestore(&cc->write_thread_lock, flags);
}
static bool kcryptd_crypt_write_inline(struct crypt_config *cc,
struct convert_context *ctx)
{
if (!test_bit(DM_CRYPT_WRITE_INLINE, &cc->flags))
return false;
/*
* Note: zone append writes (REQ_OP_ZONE_APPEND) do not have ordering
* constraints so they do not need to be issued inline by
* kcryptd_crypt_write_convert().
*/
switch (bio_op(ctx->bio_in)) {
case REQ_OP_WRITE:
case REQ_OP_WRITE_SAME:
case REQ_OP_WRITE_ZEROES:
return true;
default:
return false;
}
}
static void kcryptd_crypt_write_convert(struct dm_crypt_io *io)
{
struct crypt_config *cc = io->cc;
struct convert_context *ctx = &io->ctx;
struct bio *clone;
int crypt_finished;
sector_t sector = io->sector;
blk_status_t r;
/*
* Prevent io from disappearing until this function completes.
*/
crypt_inc_pending(io);
crypt_convert_init(cc, ctx, NULL, io->base_bio, sector);
clone = crypt_alloc_buffer(io, io->base_bio->bi_iter.bi_size);
if (unlikely(!clone)) {
io->error = BLK_STS_IOERR;
goto dec;
}
io->ctx.bio_out = clone;
io->ctx.iter_out = clone->bi_iter;
sector += bio_sectors(clone);
crypt_inc_pending(io);
r = crypt_convert(cc, ctx,
test_bit(DM_CRYPT_NO_WRITE_WORKQUEUE, &cc->flags));
if (r)
io->error = r;
crypt_finished = atomic_dec_and_test(&ctx->cc_pending);
if (!crypt_finished && kcryptd_crypt_write_inline(cc, ctx)) {
/* Wait for completion signaled by kcryptd_async_done() */
wait_for_completion(&ctx->restart);
crypt_finished = 1;
}
/* Encryption was already finished, submit io now */
if (crypt_finished) {
kcryptd_crypt_write_io_submit(io, 0);
io->sector = sector;
}
dec:
crypt_dec_pending(io);
}
static void kcryptd_crypt_read_done(struct dm_crypt_io *io)
{
crypt_dec_pending(io);
}
static void kcryptd_crypt_read_convert(struct dm_crypt_io *io)
{
struct crypt_config *cc = io->cc;
blk_status_t r;
crypt_inc_pending(io);
crypt_convert_init(cc, &io->ctx, io->base_bio, io->base_bio,
io->sector);
r = crypt_convert(cc, &io->ctx,
test_bit(DM_CRYPT_NO_READ_WORKQUEUE, &cc->flags));
if (r)
io->error = r;
if (atomic_dec_and_test(&io->ctx.cc_pending))
kcryptd_crypt_read_done(io);
crypt_dec_pending(io);
}
static void kcryptd_async_done(struct crypto_async_request *async_req,
int error)
{
struct dm_crypt_request *dmreq = async_req->data;
struct convert_context *ctx = dmreq->ctx;
struct dm_crypt_io *io = container_of(ctx, struct dm_crypt_io, ctx);
struct crypt_config *cc = io->cc;
/*
* A request from crypto driver backlog is going to be processed now,
* finish the completion and continue in crypt_convert().
* (Callback will be called for the second time for this request.)
*/
if (error == -EINPROGRESS) {
complete(&ctx->restart);
return;
}
if (!error && cc->iv_gen_ops && cc->iv_gen_ops->post)
error = cc->iv_gen_ops->post(cc, org_iv_of_dmreq(cc, dmreq), dmreq);
if (error == -EBADMSG) {
char b[BDEVNAME_SIZE];
DMERR_LIMIT("%s: INTEGRITY AEAD ERROR, sector %llu", bio_devname(ctx->bio_in, b),
(unsigned long long)le64_to_cpu(*org_sector_of_dmreq(cc, dmreq)));
io->error = BLK_STS_PROTECTION;
} else if (error < 0)
io->error = BLK_STS_IOERR;
crypt_free_req(cc, req_of_dmreq(cc, dmreq), io->base_bio);
if (!atomic_dec_and_test(&ctx->cc_pending))
return;
/*
* The request is fully completed: for inline writes, let
* kcryptd_crypt_write_convert() do the IO submission.
*/
if (bio_data_dir(io->base_bio) == READ) {
kcryptd_crypt_read_done(io);
return;
}
if (kcryptd_crypt_write_inline(cc, ctx)) {
complete(&ctx->restart);
return;
}
kcryptd_crypt_write_io_submit(io, 1);
}
static void kcryptd_crypt(struct work_struct *work)
{
struct dm_crypt_io *io = container_of(work, struct dm_crypt_io, work);
if (bio_data_dir(io->base_bio) == READ)
kcryptd_crypt_read_convert(io);
else
kcryptd_crypt_write_convert(io);
}
static void kcryptd_crypt_tasklet(unsigned long work)
{
kcryptd_crypt((struct work_struct *)work);
}
static void kcryptd_queue_crypt(struct dm_crypt_io *io)
{
struct crypt_config *cc = io->cc;
if ((bio_data_dir(io->base_bio) == READ && test_bit(DM_CRYPT_NO_READ_WORKQUEUE, &cc->flags)) ||
(bio_data_dir(io->base_bio) == WRITE && test_bit(DM_CRYPT_NO_WRITE_WORKQUEUE, &cc->flags))) {
if (in_irq()) {
/* Crypto API's "skcipher_walk_first() refuses to work in hard IRQ context */
tasklet_init(&io->tasklet, kcryptd_crypt_tasklet, (unsigned long)&io->work);
tasklet_schedule(&io->tasklet);
return;
}
kcryptd_crypt(&io->work);
return;
}
INIT_WORK(&io->work, kcryptd_crypt);
queue_work(cc->crypt_queue, &io->work);
}
static void crypt_free_tfms_aead(struct crypt_config *cc)
{
if (!cc->cipher_tfm.tfms_aead)
return;
if (cc->cipher_tfm.tfms_aead[0] && !IS_ERR(cc->cipher_tfm.tfms_aead[0])) {
crypto_free_aead(cc->cipher_tfm.tfms_aead[0]);
cc->cipher_tfm.tfms_aead[0] = NULL;
}
kfree(cc->cipher_tfm.tfms_aead);
cc->cipher_tfm.tfms_aead = NULL;
}
static void crypt_free_tfms_skcipher(struct crypt_config *cc)
{
unsigned i;
if (!cc->cipher_tfm.tfms)
return;
for (i = 0; i < cc->tfms_count; i++)
if (cc->cipher_tfm.tfms[i] && !IS_ERR(cc->cipher_tfm.tfms[i])) {
crypto_free_skcipher(cc->cipher_tfm.tfms[i]);
cc->cipher_tfm.tfms[i] = NULL;
}
kfree(cc->cipher_tfm.tfms);
cc->cipher_tfm.tfms = NULL;
}
static void crypt_free_tfms(struct crypt_config *cc)
{
if (crypt_integrity_aead(cc))
crypt_free_tfms_aead(cc);
else
crypt_free_tfms_skcipher(cc);
}
static int crypt_alloc_tfms_skcipher(struct crypt_config *cc, char *ciphermode)
{
unsigned i;
int err;
cc->cipher_tfm.tfms = kcalloc(cc->tfms_count,
sizeof(struct crypto_skcipher *),
GFP_KERNEL);
if (!cc->cipher_tfm.tfms)
return -ENOMEM;
for (i = 0; i < cc->tfms_count; i++) {
cc->cipher_tfm.tfms[i] = crypto_alloc_skcipher(ciphermode, 0, 0);
if (IS_ERR(cc->cipher_tfm.tfms[i])) {
err = PTR_ERR(cc->cipher_tfm.tfms[i]);
crypt_free_tfms(cc);
return err;
}
}
/*
* dm-crypt performance can vary greatly depending on which crypto
* algorithm implementation is used. Help people debug performance
* problems by logging the ->cra_driver_name.
*/
DMDEBUG_LIMIT("%s using implementation \"%s\"", ciphermode,
crypto_skcipher_alg(any_tfm(cc))->base.cra_driver_name);
return 0;
}
static int crypt_alloc_tfms_aead(struct crypt_config *cc, char *ciphermode)
{
int err;
cc->cipher_tfm.tfms = kmalloc(sizeof(struct crypto_aead *), GFP_KERNEL);
if (!cc->cipher_tfm.tfms)
return -ENOMEM;
cc->cipher_tfm.tfms_aead[0] = crypto_alloc_aead(ciphermode, 0, 0);
if (IS_ERR(cc->cipher_tfm.tfms_aead[0])) {
err = PTR_ERR(cc->cipher_tfm.tfms_aead[0]);
crypt_free_tfms(cc);
return err;
}
DMDEBUG_LIMIT("%s using implementation \"%s\"", ciphermode,
crypto_aead_alg(any_tfm_aead(cc))->base.cra_driver_name);
return 0;
}
static int crypt_alloc_tfms(struct crypt_config *cc, char *ciphermode)
{
if (crypt_integrity_aead(cc))
return crypt_alloc_tfms_aead(cc, ciphermode);
else
return crypt_alloc_tfms_skcipher(cc, ciphermode);
}
static unsigned crypt_subkey_size(struct crypt_config *cc)
{
return (cc->key_size - cc->key_extra_size) >> ilog2(cc->tfms_count);
}
static unsigned crypt_authenckey_size(struct crypt_config *cc)
{
return crypt_subkey_size(cc) + RTA_SPACE(sizeof(struct crypto_authenc_key_param));
}
/*
* If AEAD is composed like authenc(hmac(sha256),xts(aes)),
* the key must be for some reason in special format.
* This funcion converts cc->key to this special format.
*/
static void crypt_copy_authenckey(char *p, const void *key,
unsigned enckeylen, unsigned authkeylen)
{
struct crypto_authenc_key_param *param;
struct rtattr *rta;
rta = (struct rtattr *)p;
param = RTA_DATA(rta);
param->enckeylen = cpu_to_be32(enckeylen);
rta->rta_len = RTA_LENGTH(sizeof(*param));
rta->rta_type = CRYPTO_AUTHENC_KEYA_PARAM;
p += RTA_SPACE(sizeof(*param));
memcpy(p, key + enckeylen, authkeylen);
p += authkeylen;
memcpy(p, key, enckeylen);
}
static int crypt_setkey(struct crypt_config *cc)
{
unsigned subkey_size;
int err = 0, i, r;
/* Ignore extra keys (which are used for IV etc) */
subkey_size = crypt_subkey_size(cc);
if (crypt_integrity_hmac(cc)) {
if (subkey_size < cc->key_mac_size)
return -EINVAL;
crypt_copy_authenckey(cc->authenc_key, cc->key,
subkey_size - cc->key_mac_size,
cc->key_mac_size);
}
for (i = 0; i < cc->tfms_count; i++) {
if (crypt_integrity_hmac(cc))
r = crypto_aead_setkey(cc->cipher_tfm.tfms_aead[i],
cc->authenc_key, crypt_authenckey_size(cc));
else if (crypt_integrity_aead(cc))
r = crypto_aead_setkey(cc->cipher_tfm.tfms_aead[i],
cc->key + (i * subkey_size),
subkey_size);
else
r = crypto_skcipher_setkey(cc->cipher_tfm.tfms[i],
cc->key + (i * subkey_size),
subkey_size);
if (r)
err = r;
}
if (crypt_integrity_hmac(cc))
memzero_explicit(cc->authenc_key, crypt_authenckey_size(cc));
return err;
}
#ifdef CONFIG_KEYS
static bool contains_whitespace(const char *str)
{
while (*str)
if (isspace(*str++))
return true;
return false;
}
static int set_key_user(struct crypt_config *cc, struct key *key)
{
const struct user_key_payload *ukp;
ukp = user_key_payload_locked(key);
if (!ukp)
return -EKEYREVOKED;
if (cc->key_size != ukp->datalen)
return -EINVAL;
memcpy(cc->key, ukp->data, cc->key_size);
return 0;
}
#if defined(CONFIG_ENCRYPTED_KEYS) || defined(CONFIG_ENCRYPTED_KEYS_MODULE)
static int set_key_encrypted(struct crypt_config *cc, struct key *key)
{
const struct encrypted_key_payload *ekp;
ekp = key->payload.data[0];
if (!ekp)
return -EKEYREVOKED;
if (cc->key_size != ekp->decrypted_datalen)
return -EINVAL;
memcpy(cc->key, ekp->decrypted_data, cc->key_size);
return 0;
}
#endif /* CONFIG_ENCRYPTED_KEYS */
static int crypt_set_keyring_key(struct crypt_config *cc, const char *key_string)
{
char *new_key_string, *key_desc;
int ret;
struct key_type *type;
struct key *key;
int (*set_key)(struct crypt_config *cc, struct key *key);
/*
* Reject key_string with whitespace. dm core currently lacks code for
* proper whitespace escaping in arguments on DM_TABLE_STATUS path.
*/
if (contains_whitespace(key_string)) {
DMERR("whitespace chars not allowed in key string");
return -EINVAL;
}
/* look for next ':' separating key_type from key_description */
key_desc = strpbrk(key_string, ":");
if (!key_desc || key_desc == key_string || !strlen(key_desc + 1))
return -EINVAL;
if (!strncmp(key_string, "logon:", key_desc - key_string + 1)) {
type = &key_type_logon;
set_key = set_key_user;
} else if (!strncmp(key_string, "user:", key_desc - key_string + 1)) {
type = &key_type_user;
set_key = set_key_user;
#if defined(CONFIG_ENCRYPTED_KEYS) || defined(CONFIG_ENCRYPTED_KEYS_MODULE)
} else if (!strncmp(key_string, "encrypted:", key_desc - key_string + 1)) {
type = &key_type_encrypted;
set_key = set_key_encrypted;
#endif
} else {
return -EINVAL;
}
new_key_string = kstrdup(key_string, GFP_KERNEL);
if (!new_key_string)
return -ENOMEM;
key = request_key(type, key_desc + 1, NULL);
if (IS_ERR(key)) {
kfree_sensitive(new_key_string);
return PTR_ERR(key);
}
down_read(&key->sem);
ret = set_key(cc, key);
if (ret < 0) {
up_read(&key->sem);
key_put(key);
kfree_sensitive(new_key_string);
return ret;
}
up_read(&key->sem);
key_put(key);
/* clear the flag since following operations may invalidate previously valid key */
clear_bit(DM_CRYPT_KEY_VALID, &cc->flags);
ret = crypt_setkey(cc);
if (!ret) {
set_bit(DM_CRYPT_KEY_VALID, &cc->flags);
kfree_sensitive(cc->key_string);
cc->key_string = new_key_string;
} else
kfree_sensitive(new_key_string);
return ret;
}
static int get_key_size(char **key_string)
{
char *colon, dummy;
int ret;
if (*key_string[0] != ':')
return strlen(*key_string) >> 1;
/* look for next ':' in key string */
colon = strpbrk(*key_string + 1, ":");
if (!colon)
return -EINVAL;
if (sscanf(*key_string + 1, "%u%c", &ret, &dummy) != 2 || dummy != ':')
return -EINVAL;
*key_string = colon;
/* remaining key string should be :<logon|user>:<key_desc> */
return ret;
}
#else
static int crypt_set_keyring_key(struct crypt_config *cc, const char *key_string)
{
return -EINVAL;
}
static int get_key_size(char **key_string)
{
return (*key_string[0] == ':') ? -EINVAL : strlen(*key_string) >> 1;
}
#endif /* CONFIG_KEYS */
static int crypt_set_key(struct crypt_config *cc, char *key)
{
int r = -EINVAL;
int key_string_len = strlen(key);
/* Hyphen (which gives a key_size of zero) means there is no key. */
if (!cc->key_size && strcmp(key, "-"))
goto out;
/* ':' means the key is in kernel keyring, short-circuit normal key processing */
if (key[0] == ':') {
r = crypt_set_keyring_key(cc, key + 1);
goto out;
}
/* clear the flag since following operations may invalidate previously valid key */
clear_bit(DM_CRYPT_KEY_VALID, &cc->flags);
/* wipe references to any kernel keyring key */
kfree_sensitive(cc->key_string);
cc->key_string = NULL;
/* Decode key from its hex representation. */
if (cc->key_size && hex2bin(cc->key, key, cc->key_size) < 0)
goto out;
r = crypt_setkey(cc);
if (!r)
set_bit(DM_CRYPT_KEY_VALID, &cc->flags);
out:
/* Hex key string not needed after here, so wipe it. */
memset(key, '0', key_string_len);
return r;
}
static int crypt_wipe_key(struct crypt_config *cc)
{
int r;
clear_bit(DM_CRYPT_KEY_VALID, &cc->flags);
get_random_bytes(&cc->key, cc->key_size);
/* Wipe IV private keys */
if (cc->iv_gen_ops && cc->iv_gen_ops->wipe) {
r = cc->iv_gen_ops->wipe(cc);
if (r)
return r;
}
kfree_sensitive(cc->key_string);
cc->key_string = NULL;
r = crypt_setkey(cc);
memset(&cc->key, 0, cc->key_size * sizeof(u8));
return r;
}
static void crypt_calculate_pages_per_client(void)
{
unsigned long pages = (totalram_pages() - totalhigh_pages()) * DM_CRYPT_MEMORY_PERCENT / 100;
if (!dm_crypt_clients_n)
return;
pages /= dm_crypt_clients_n;
if (pages < DM_CRYPT_MIN_PAGES_PER_CLIENT)
pages = DM_CRYPT_MIN_PAGES_PER_CLIENT;
dm_crypt_pages_per_client = pages;
}
static void *crypt_page_alloc(gfp_t gfp_mask, void *pool_data)
{
struct crypt_config *cc = pool_data;
struct page *page;
if (unlikely(percpu_counter_compare(&cc->n_allocated_pages, dm_crypt_pages_per_client) >= 0) &&
likely(gfp_mask & __GFP_NORETRY))
return NULL;
page = alloc_page(gfp_mask);
if (likely(page != NULL))
percpu_counter_add(&cc->n_allocated_pages, 1);
return page;
}
static void crypt_page_free(void *page, void *pool_data)
{
struct crypt_config *cc = pool_data;
__free_page(page);
percpu_counter_sub(&cc->n_allocated_pages, 1);
}
static void crypt_dtr(struct dm_target *ti)
{
struct crypt_config *cc = ti->private;
ti->private = NULL;
if (!cc)
return;
if (cc->write_thread)
kthread_stop(cc->write_thread);
if (cc->io_queue)
destroy_workqueue(cc->io_queue);
if (cc->crypt_queue)
destroy_workqueue(cc->crypt_queue);
crypt_free_tfms(cc);
bioset_exit(&cc->bs);
mempool_exit(&cc->page_pool);
mempool_exit(&cc->req_pool);
mempool_exit(&cc->tag_pool);
WARN_ON(percpu_counter_sum(&cc->n_allocated_pages) != 0);
percpu_counter_destroy(&cc->n_allocated_pages);
if (cc->iv_gen_ops && cc->iv_gen_ops->dtr)
cc->iv_gen_ops->dtr(cc);
if (cc->dev)
dm_put_device(ti, cc->dev);
kfree_sensitive(cc->cipher_string);
kfree_sensitive(cc->key_string);
kfree_sensitive(cc->cipher_auth);
kfree_sensitive(cc->authenc_key);
mutex_destroy(&cc->bio_alloc_lock);
/* Must zero key material before freeing */
kfree_sensitive(cc);
spin_lock(&dm_crypt_clients_lock);
WARN_ON(!dm_crypt_clients_n);
dm_crypt_clients_n--;
crypt_calculate_pages_per_client();
spin_unlock(&dm_crypt_clients_lock);
}
static int crypt_ctr_ivmode(struct dm_target *ti, const char *ivmode)
{
struct crypt_config *cc = ti->private;
if (crypt_integrity_aead(cc))
cc->iv_size = crypto_aead_ivsize(any_tfm_aead(cc));
else
cc->iv_size = crypto_skcipher_ivsize(any_tfm(cc));
if (cc->iv_size)
/* at least a 64 bit sector number should fit in our buffer */
cc->iv_size = max(cc->iv_size,
(unsigned int)(sizeof(u64) / sizeof(u8)));
else if (ivmode) {
DMWARN("Selected cipher does not support IVs");
ivmode = NULL;
}
/* Choose ivmode, see comments at iv code. */
if (ivmode == NULL)
cc->iv_gen_ops = NULL;
else if (strcmp(ivmode, "plain") == 0)
cc->iv_gen_ops = &crypt_iv_plain_ops;
else if (strcmp(ivmode, "plain64") == 0)
cc->iv_gen_ops = &crypt_iv_plain64_ops;
else if (strcmp(ivmode, "plain64be") == 0)
cc->iv_gen_ops = &crypt_iv_plain64be_ops;
else if (strcmp(ivmode, "essiv") == 0)
cc->iv_gen_ops = &crypt_iv_essiv_ops;
else if (strcmp(ivmode, "benbi") == 0)
cc->iv_gen_ops = &crypt_iv_benbi_ops;
else if (strcmp(ivmode, "null") == 0)
cc->iv_gen_ops = &crypt_iv_null_ops;
else if (strcmp(ivmode, "eboiv") == 0)
cc->iv_gen_ops = &crypt_iv_eboiv_ops;
else if (strcmp(ivmode, "elephant") == 0) {
cc->iv_gen_ops = &crypt_iv_elephant_ops;
cc->key_parts = 2;
cc->key_extra_size = cc->key_size / 2;
if (cc->key_extra_size > ELEPHANT_MAX_KEY_SIZE)
return -EINVAL;
set_bit(CRYPT_ENCRYPT_PREPROCESS, &cc->cipher_flags);
} else if (strcmp(ivmode, "lmk") == 0) {
cc->iv_gen_ops = &crypt_iv_lmk_ops;
/*
* Version 2 and 3 is recognised according
* to length of provided multi-key string.
* If present (version 3), last key is used as IV seed.
* All keys (including IV seed) are always the same size.
*/
if (cc->key_size % cc->key_parts) {
cc->key_parts++;
cc->key_extra_size = cc->key_size / cc->key_parts;
}
} else if (strcmp(ivmode, "tcw") == 0) {
cc->iv_gen_ops = &crypt_iv_tcw_ops;
cc->key_parts += 2; /* IV + whitening */
cc->key_extra_size = cc->iv_size + TCW_WHITENING_SIZE;
} else if (strcmp(ivmode, "random") == 0) {
cc->iv_gen_ops = &crypt_iv_random_ops;
/* Need storage space in integrity fields. */
cc->integrity_iv_size = cc->iv_size;
} else {
ti->error = "Invalid IV mode";
return -EINVAL;
}
return 0;
}
/*
* Workaround to parse HMAC algorithm from AEAD crypto API spec.
* The HMAC is needed to calculate tag size (HMAC digest size).
* This should be probably done by crypto-api calls (once available...)
*/
static int crypt_ctr_auth_cipher(struct crypt_config *cc, char *cipher_api)
{
char *start, *end, *mac_alg = NULL;
struct crypto_ahash *mac;
if (!strstarts(cipher_api, "authenc("))
return 0;
start = strchr(cipher_api, '(');
end = strchr(cipher_api, ',');
if (!start || !end || ++start > end)
return -EINVAL;
mac_alg = kzalloc(end - start + 1, GFP_KERNEL);
if (!mac_alg)
return -ENOMEM;
strncpy(mac_alg, start, end - start);
mac = crypto_alloc_ahash(mac_alg, 0, 0);
kfree(mac_alg);
if (IS_ERR(mac))
return PTR_ERR(mac);
cc->key_mac_size = crypto_ahash_digestsize(mac);
crypto_free_ahash(mac);
cc->authenc_key = kmalloc(crypt_authenckey_size(cc), GFP_KERNEL);
if (!cc->authenc_key)
return -ENOMEM;
return 0;
}
static int crypt_ctr_cipher_new(struct dm_target *ti, char *cipher_in, char *key,
char **ivmode, char **ivopts)
{
struct crypt_config *cc = ti->private;
char *tmp, *cipher_api, buf[CRYPTO_MAX_ALG_NAME];
int ret = -EINVAL;
cc->tfms_count = 1;
/*
* New format (capi: prefix)
* capi:cipher_api_spec-iv:ivopts
*/
tmp = &cipher_in[strlen("capi:")];
/* Separate IV options if present, it can contain another '-' in hash name */
*ivopts = strrchr(tmp, ':');
if (*ivopts) {
**ivopts = '\0';
(*ivopts)++;
}
/* Parse IV mode */
*ivmode = strrchr(tmp, '-');
if (*ivmode) {
**ivmode = '\0';
(*ivmode)++;
}
/* The rest is crypto API spec */
cipher_api = tmp;
/* Alloc AEAD, can be used only in new format. */
if (crypt_integrity_aead(cc)) {
ret = crypt_ctr_auth_cipher(cc, cipher_api);
if (ret < 0) {
ti->error = "Invalid AEAD cipher spec";
return -ENOMEM;
}
}
if (*ivmode && !strcmp(*ivmode, "lmk"))
cc->tfms_count = 64;
if (*ivmode && !strcmp(*ivmode, "essiv")) {
if (!*ivopts) {
ti->error = "Digest algorithm missing for ESSIV mode";
return -EINVAL;
}
ret = snprintf(buf, CRYPTO_MAX_ALG_NAME, "essiv(%s,%s)",
cipher_api, *ivopts);
if (ret < 0 || ret >= CRYPTO_MAX_ALG_NAME) {
ti->error = "Cannot allocate cipher string";
return -ENOMEM;
}
cipher_api = buf;
}
cc->key_parts = cc->tfms_count;
/* Allocate cipher */
ret = crypt_alloc_tfms(cc, cipher_api);
if (ret < 0) {
ti->error = "Error allocating crypto tfm";
return ret;
}
if (crypt_integrity_aead(cc))
cc->iv_size = crypto_aead_ivsize(any_tfm_aead(cc));
else
cc->iv_size = crypto_skcipher_ivsize(any_tfm(cc));
return 0;
}
static int crypt_ctr_cipher_old(struct dm_target *ti, char *cipher_in, char *key,
char **ivmode, char **ivopts)
{
struct crypt_config *cc = ti->private;
char *tmp, *cipher, *chainmode, *keycount;
char *cipher_api = NULL;
int ret = -EINVAL;
char dummy;
if (strchr(cipher_in, '(') || crypt_integrity_aead(cc)) {
ti->error = "Bad cipher specification";
return -EINVAL;
}
/*
* Legacy dm-crypt cipher specification
* cipher[:keycount]-mode-iv:ivopts
*/
tmp = cipher_in;
keycount = strsep(&tmp, "-");
cipher = strsep(&keycount, ":");
if (!keycount)
cc->tfms_count = 1;
else if (sscanf(keycount, "%u%c", &cc->tfms_count, &dummy) != 1 ||
!is_power_of_2(cc->tfms_count)) {
ti->error = "Bad cipher key count specification";
return -EINVAL;
}
cc->key_parts = cc->tfms_count;
chainmode = strsep(&tmp, "-");
*ivmode = strsep(&tmp, ":");
*ivopts = tmp;
/*
* For compatibility with the original dm-crypt mapping format, if
* only the cipher name is supplied, use cbc-plain.
*/
if (!chainmode || (!strcmp(chainmode, "plain") && !*ivmode)) {
chainmode = "cbc";
*ivmode = "plain";
}
if (strcmp(chainmode, "ecb") && !*ivmode) {
ti->error = "IV mechanism required";
return -EINVAL;
}
cipher_api = kmalloc(CRYPTO_MAX_ALG_NAME, GFP_KERNEL);
if (!cipher_api)
goto bad_mem;
if (*ivmode && !strcmp(*ivmode, "essiv")) {
if (!*ivopts) {
ti->error = "Digest algorithm missing for ESSIV mode";
kfree(cipher_api);
return -EINVAL;
}
ret = snprintf(cipher_api, CRYPTO_MAX_ALG_NAME,
"essiv(%s(%s),%s)", chainmode, cipher, *ivopts);
} else {
ret = snprintf(cipher_api, CRYPTO_MAX_ALG_NAME,
"%s(%s)", chainmode, cipher);
}
if (ret < 0 || ret >= CRYPTO_MAX_ALG_NAME) {
kfree(cipher_api);
goto bad_mem;
}
/* Allocate cipher */
ret = crypt_alloc_tfms(cc, cipher_api);
if (ret < 0) {
ti->error = "Error allocating crypto tfm";
kfree(cipher_api);
return ret;
}
kfree(cipher_api);
return 0;
bad_mem:
ti->error = "Cannot allocate cipher strings";
return -ENOMEM;
}
static int crypt_ctr_cipher(struct dm_target *ti, char *cipher_in, char *key)
{
struct crypt_config *cc = ti->private;
char *ivmode = NULL, *ivopts = NULL;
int ret;
cc->cipher_string = kstrdup(cipher_in, GFP_KERNEL);
if (!cc->cipher_string) {
ti->error = "Cannot allocate cipher strings";
return -ENOMEM;
}
if (strstarts(cipher_in, "capi:"))
ret = crypt_ctr_cipher_new(ti, cipher_in, key, &ivmode, &ivopts);
else
ret = crypt_ctr_cipher_old(ti, cipher_in, key, &ivmode, &ivopts);
if (ret)
return ret;
/* Initialize IV */
ret = crypt_ctr_ivmode(ti, ivmode);
if (ret < 0)
return ret;
/* Initialize and set key */
ret = crypt_set_key(cc, key);
if (ret < 0) {
ti->error = "Error decoding and setting key";
return ret;
}
/* Allocate IV */
if (cc->iv_gen_ops && cc->iv_gen_ops->ctr) {
ret = cc->iv_gen_ops->ctr(cc, ti, ivopts);
if (ret < 0) {
ti->error = "Error creating IV";
return ret;
}
}
/* Initialize IV (set keys for ESSIV etc) */
if (cc->iv_gen_ops && cc->iv_gen_ops->init) {
ret = cc->iv_gen_ops->init(cc);
if (ret < 0) {
ti->error = "Error initialising IV";
return ret;
}
}
/* wipe the kernel key payload copy */
if (cc->key_string)
memset(cc->key, 0, cc->key_size * sizeof(u8));
return ret;
}
static int crypt_ctr_optional(struct dm_target *ti, unsigned int argc, char **argv)
{
struct crypt_config *cc = ti->private;
struct dm_arg_set as;
static const struct dm_arg _args[] = {
{0, 8, "Invalid number of feature args"},
};
unsigned int opt_params, val;
const char *opt_string, *sval;
char dummy;
int ret;
/* Optional parameters */
as.argc = argc;
as.argv = argv;
ret = dm_read_arg_group(_args, &as, &opt_params, &ti->error);
if (ret)
return ret;
while (opt_params--) {
opt_string = dm_shift_arg(&as);
if (!opt_string) {
ti->error = "Not enough feature arguments";
return -EINVAL;
}
if (!strcasecmp(opt_string, "allow_discards"))
ti->num_discard_bios = 1;
else if (!strcasecmp(opt_string, "same_cpu_crypt"))
set_bit(DM_CRYPT_SAME_CPU, &cc->flags);
else if (!strcasecmp(opt_string, "submit_from_crypt_cpus"))
set_bit(DM_CRYPT_NO_OFFLOAD, &cc->flags);
else if (!strcasecmp(opt_string, "no_read_workqueue"))
set_bit(DM_CRYPT_NO_READ_WORKQUEUE, &cc->flags);
else if (!strcasecmp(opt_string, "no_write_workqueue"))
set_bit(DM_CRYPT_NO_WRITE_WORKQUEUE, &cc->flags);
else if (sscanf(opt_string, "integrity:%u:", &val) == 1) {
if (val == 0 || val > MAX_TAG_SIZE) {
ti->error = "Invalid integrity arguments";
return -EINVAL;
}
cc->on_disk_tag_size = val;
sval = strchr(opt_string + strlen("integrity:"), ':') + 1;
if (!strcasecmp(sval, "aead")) {
set_bit(CRYPT_MODE_INTEGRITY_AEAD, &cc->cipher_flags);
} else if (strcasecmp(sval, "none")) {
ti->error = "Unknown integrity profile";
return -EINVAL;
}
cc->cipher_auth = kstrdup(sval, GFP_KERNEL);
if (!cc->cipher_auth)
return -ENOMEM;
} else if (sscanf(opt_string, "sector_size:%hu%c", &cc->sector_size, &dummy) == 1) {
if (cc->sector_size < (1 << SECTOR_SHIFT) ||
cc->sector_size > 4096 ||
(cc->sector_size & (cc->sector_size - 1))) {
ti->error = "Invalid feature value for sector_size";
return -EINVAL;
}
if (ti->len & ((cc->sector_size >> SECTOR_SHIFT) - 1)) {
ti->error = "Device size is not multiple of sector_size feature";
return -EINVAL;
}
cc->sector_shift = __ffs(cc->sector_size) - SECTOR_SHIFT;
} else if (!strcasecmp(opt_string, "iv_large_sectors"))
set_bit(CRYPT_IV_LARGE_SECTORS, &cc->cipher_flags);
else {
ti->error = "Invalid feature arguments";
return -EINVAL;
}
}
return 0;
}
#ifdef CONFIG_BLK_DEV_ZONED
static int crypt_report_zones(struct dm_target *ti,
struct dm_report_zones_args *args, unsigned int nr_zones)
{
struct crypt_config *cc = ti->private;
sector_t sector = cc->start + dm_target_offset(ti, args->next_sector);
args->start = cc->start;
return blkdev_report_zones(cc->dev->bdev, sector, nr_zones,
dm_report_zones_cb, args);
}
#endif
/*
* Construct an encryption mapping:
* <cipher> [<key>|:<key_size>:<user|logon>:<key_description>] <iv_offset> <dev_path> <start>
*/
static int crypt_ctr(struct dm_target *ti, unsigned int argc, char **argv)
{
struct crypt_config *cc;
const char *devname = dm_table_device_name(ti->table);
int key_size;
unsigned int align_mask;
unsigned long long tmpll;
int ret;
size_t iv_size_padding, additional_req_size;
char dummy;
if (argc < 5) {
ti->error = "Not enough arguments";
return -EINVAL;
}
key_size = get_key_size(&argv[1]);
if (key_size < 0) {
ti->error = "Cannot parse key size";
return -EINVAL;
}
cc = kzalloc(struct_size(cc, key, key_size), GFP_KERNEL);
if (!cc) {
ti->error = "Cannot allocate encryption context";
return -ENOMEM;
}
cc->key_size = key_size;
cc->sector_size = (1 << SECTOR_SHIFT);
cc->sector_shift = 0;
ti->private = cc;
spin_lock(&dm_crypt_clients_lock);
dm_crypt_clients_n++;
crypt_calculate_pages_per_client();
spin_unlock(&dm_crypt_clients_lock);
ret = percpu_counter_init(&cc->n_allocated_pages, 0, GFP_KERNEL);
if (ret < 0)
goto bad;
/* Optional parameters need to be read before cipher constructor */
if (argc > 5) {
ret = crypt_ctr_optional(ti, argc - 5, &argv[5]);
if (ret)
goto bad;
}
ret = crypt_ctr_cipher(ti, argv[0], argv[1]);
if (ret < 0)
goto bad;
if (crypt_integrity_aead(cc)) {
cc->dmreq_start = sizeof(struct aead_request);
cc->dmreq_start += crypto_aead_reqsize(any_tfm_aead(cc));
align_mask = crypto_aead_alignmask(any_tfm_aead(cc));
} else {
cc->dmreq_start = sizeof(struct skcipher_request);
cc->dmreq_start += crypto_skcipher_reqsize(any_tfm(cc));
align_mask = crypto_skcipher_alignmask(any_tfm(cc));
}
cc->dmreq_start = ALIGN(cc->dmreq_start, __alignof__(struct dm_crypt_request));
if (align_mask < CRYPTO_MINALIGN) {
/* Allocate the padding exactly */
iv_size_padding = -(cc->dmreq_start + sizeof(struct dm_crypt_request))
& align_mask;
} else {
/*
* If the cipher requires greater alignment than kmalloc
* alignment, we don't know the exact position of the
* initialization vector. We must assume worst case.
*/
iv_size_padding = align_mask;
}
/* ...| IV + padding | original IV | original sec. number | bio tag offset | */
additional_req_size = sizeof(struct dm_crypt_request) +
iv_size_padding + cc->iv_size +
cc->iv_size +
sizeof(uint64_t) +
sizeof(unsigned int);
ret = mempool_init_kmalloc_pool(&cc->req_pool, MIN_IOS, cc->dmreq_start + additional_req_size);
if (ret) {
ti->error = "Cannot allocate crypt request mempool";
goto bad;
}
cc->per_bio_data_size = ti->per_io_data_size =
ALIGN(sizeof(struct dm_crypt_io) + cc->dmreq_start + additional_req_size,
ARCH_KMALLOC_MINALIGN);
ret = mempool_init(&cc->page_pool, BIO_MAX_PAGES, crypt_page_alloc, crypt_page_free, cc);
if (ret) {
ti->error = "Cannot allocate page mempool";
goto bad;
}
ret = bioset_init(&cc->bs, MIN_IOS, 0, BIOSET_NEED_BVECS);
if (ret) {
ti->error = "Cannot allocate crypt bioset";
goto bad;
}
mutex_init(&cc->bio_alloc_lock);
ret = -EINVAL;
if ((sscanf(argv[2], "%llu%c", &tmpll, &dummy) != 1) ||
(tmpll & ((cc->sector_size >> SECTOR_SHIFT) - 1))) {
ti->error = "Invalid iv_offset sector";
goto bad;
}
cc->iv_offset = tmpll;
ret = dm_get_device(ti, argv[3], dm_table_get_mode(ti->table), &cc->dev);
if (ret) {
ti->error = "Device lookup failed";
goto bad;
}
ret = -EINVAL;
if (sscanf(argv[4], "%llu%c", &tmpll, &dummy) != 1 || tmpll != (sector_t)tmpll) {
ti->error = "Invalid device sector";
goto bad;
}
cc->start = tmpll;
/*
* For zoned block devices, we need to preserve the issuer write
* ordering. To do so, disable write workqueues and force inline
* encryption completion.
*/
if (bdev_is_zoned(cc->dev->bdev)) {
set_bit(DM_CRYPT_NO_WRITE_WORKQUEUE, &cc->flags);
set_bit(DM_CRYPT_WRITE_INLINE, &cc->flags);
}
if (crypt_integrity_aead(cc) || cc->integrity_iv_size) {
ret = crypt_integrity_ctr(cc, ti);
if (ret)
goto bad;
cc->tag_pool_max_sectors = POOL_ENTRY_SIZE / cc->on_disk_tag_size;
if (!cc->tag_pool_max_sectors)
cc->tag_pool_max_sectors = 1;
ret = mempool_init_kmalloc_pool(&cc->tag_pool, MIN_IOS,
cc->tag_pool_max_sectors * cc->on_disk_tag_size);
if (ret) {
ti->error = "Cannot allocate integrity tags mempool";
goto bad;
}
cc->tag_pool_max_sectors <<= cc->sector_shift;
}
ret = -ENOMEM;
cc->io_queue = alloc_workqueue("kcryptd_io/%s", WQ_MEM_RECLAIM, 1, devname);
if (!cc->io_queue) {
ti->error = "Couldn't create kcryptd io queue";
goto bad;
}
if (test_bit(DM_CRYPT_SAME_CPU, &cc->flags))
cc->crypt_queue = alloc_workqueue("kcryptd/%s", WQ_CPU_INTENSIVE | WQ_MEM_RECLAIM,
1, devname);
else
cc->crypt_queue = alloc_workqueue("kcryptd/%s",
WQ_CPU_INTENSIVE | WQ_MEM_RECLAIM | WQ_UNBOUND,
num_online_cpus(), devname);
if (!cc->crypt_queue) {
ti->error = "Couldn't create kcryptd queue";
goto bad;
}
spin_lock_init(&cc->write_thread_lock);
cc->write_tree = RB_ROOT;
cc->write_thread = kthread_create(dmcrypt_write, cc, "dmcrypt_write/%s", devname);
if (IS_ERR(cc->write_thread)) {
ret = PTR_ERR(cc->write_thread);
cc->write_thread = NULL;
ti->error = "Couldn't spawn write thread";
goto bad;
}
wake_up_process(cc->write_thread);
ti->num_flush_bios = 1;
return 0;
bad:
crypt_dtr(ti);
return ret;
}
static int crypt_map(struct dm_target *ti, struct bio *bio)
{
struct dm_crypt_io *io;
struct crypt_config *cc = ti->private;
/*
* If bio is REQ_PREFLUSH or REQ_OP_DISCARD, just bypass crypt queues.
* - for REQ_PREFLUSH device-mapper core ensures that no IO is in-flight
* - for REQ_OP_DISCARD caller must use flush if IO ordering matters
*/
if (unlikely(bio->bi_opf & REQ_PREFLUSH ||
bio_op(bio) == REQ_OP_DISCARD)) {
bio_set_dev(bio, cc->dev->bdev);
if (bio_sectors(bio))
bio->bi_iter.bi_sector = cc->start +
dm_target_offset(ti, bio->bi_iter.bi_sector);
return DM_MAPIO_REMAPPED;
}
/*
* Check if bio is too large, split as needed.
*/
if (unlikely(bio->bi_iter.bi_size > (BIO_MAX_PAGES << PAGE_SHIFT)) &&
(bio_data_dir(bio) == WRITE || cc->on_disk_tag_size))
dm_accept_partial_bio(bio, ((BIO_MAX_PAGES << PAGE_SHIFT) >> SECTOR_SHIFT));
/*
* Ensure that bio is a multiple of internal sector encryption size
* and is aligned to this size as defined in IO hints.
*/
if (unlikely((bio->bi_iter.bi_sector & ((cc->sector_size >> SECTOR_SHIFT) - 1)) != 0))
return DM_MAPIO_KILL;
if (unlikely(bio->bi_iter.bi_size & (cc->sector_size - 1)))
return DM_MAPIO_KILL;
io = dm_per_bio_data(bio, cc->per_bio_data_size);
crypt_io_init(io, cc, bio, dm_target_offset(ti, bio->bi_iter.bi_sector));
if (cc->on_disk_tag_size) {
unsigned tag_len = cc->on_disk_tag_size * (bio_sectors(bio) >> cc->sector_shift);
if (unlikely(tag_len > KMALLOC_MAX_SIZE) ||
unlikely(!(io->integrity_metadata = kmalloc(tag_len,
GFP_NOIO | __GFP_NORETRY | __GFP_NOMEMALLOC | __GFP_NOWARN)))) {
if (bio_sectors(bio) > cc->tag_pool_max_sectors)
dm_accept_partial_bio(bio, cc->tag_pool_max_sectors);
io->integrity_metadata = mempool_alloc(&cc->tag_pool, GFP_NOIO);
io->integrity_metadata_from_pool = true;
}
}
if (crypt_integrity_aead(cc))
io->ctx.r.req_aead = (struct aead_request *)(io + 1);
else
io->ctx.r.req = (struct skcipher_request *)(io + 1);
if (bio_data_dir(io->base_bio) == READ) {
if (kcryptd_io_read(io, GFP_NOWAIT))
kcryptd_queue_read(io);
} else
kcryptd_queue_crypt(io);
return DM_MAPIO_SUBMITTED;
}
static void crypt_status(struct dm_target *ti, status_type_t type,
unsigned status_flags, char *result, unsigned maxlen)
{
struct crypt_config *cc = ti->private;
unsigned i, sz = 0;
int num_feature_args = 0;
switch (type) {
case STATUSTYPE_INFO:
result[0] = '\0';
break;
case STATUSTYPE_TABLE:
DMEMIT("%s ", cc->cipher_string);
if (cc->key_size > 0) {
if (cc->key_string)
DMEMIT(":%u:%s", cc->key_size, cc->key_string);
else
for (i = 0; i < cc->key_size; i++)
DMEMIT("%02x", cc->key[i]);
} else
DMEMIT("-");
DMEMIT(" %llu %s %llu", (unsigned long long)cc->iv_offset,
cc->dev->name, (unsigned long long)cc->start);
num_feature_args += !!ti->num_discard_bios;
num_feature_args += test_bit(DM_CRYPT_SAME_CPU, &cc->flags);
num_feature_args += test_bit(DM_CRYPT_NO_OFFLOAD, &cc->flags);
num_feature_args += test_bit(DM_CRYPT_NO_READ_WORKQUEUE, &cc->flags);
num_feature_args += test_bit(DM_CRYPT_NO_WRITE_WORKQUEUE, &cc->flags);
num_feature_args += cc->sector_size != (1 << SECTOR_SHIFT);
num_feature_args += test_bit(CRYPT_IV_LARGE_SECTORS, &cc->cipher_flags);
if (cc->on_disk_tag_size)
num_feature_args++;
if (num_feature_args) {
DMEMIT(" %d", num_feature_args);
if (ti->num_discard_bios)
DMEMIT(" allow_discards");
if (test_bit(DM_CRYPT_SAME_CPU, &cc->flags))
DMEMIT(" same_cpu_crypt");
if (test_bit(DM_CRYPT_NO_OFFLOAD, &cc->flags))
DMEMIT(" submit_from_crypt_cpus");
if (test_bit(DM_CRYPT_NO_READ_WORKQUEUE, &cc->flags))
DMEMIT(" no_read_workqueue");
if (test_bit(DM_CRYPT_NO_WRITE_WORKQUEUE, &cc->flags))
DMEMIT(" no_write_workqueue");
if (cc->on_disk_tag_size)
DMEMIT(" integrity:%u:%s", cc->on_disk_tag_size, cc->cipher_auth);
if (cc->sector_size != (1 << SECTOR_SHIFT))
DMEMIT(" sector_size:%d", cc->sector_size);
if (test_bit(CRYPT_IV_LARGE_SECTORS, &cc->cipher_flags))
DMEMIT(" iv_large_sectors");
}
break;
}
}
static void crypt_postsuspend(struct dm_target *ti)
{
struct crypt_config *cc = ti->private;
set_bit(DM_CRYPT_SUSPENDED, &cc->flags);
}
static int crypt_preresume(struct dm_target *ti)
{
struct crypt_config *cc = ti->private;
if (!test_bit(DM_CRYPT_KEY_VALID, &cc->flags)) {
DMERR("aborting resume - crypt key is not set.");
return -EAGAIN;
}
return 0;
}
static void crypt_resume(struct dm_target *ti)
{
struct crypt_config *cc = ti->private;
clear_bit(DM_CRYPT_SUSPENDED, &cc->flags);
}
/* Message interface
* key set <key>
* key wipe
*/
static int crypt_message(struct dm_target *ti, unsigned argc, char **argv,
char *result, unsigned maxlen)
{
struct crypt_config *cc = ti->private;
int key_size, ret = -EINVAL;
if (argc < 2)
goto error;
if (!strcasecmp(argv[0], "key")) {
if (!test_bit(DM_CRYPT_SUSPENDED, &cc->flags)) {
DMWARN("not suspended during key manipulation.");
return -EINVAL;
}
if (argc == 3 && !strcasecmp(argv[1], "set")) {
/* The key size may not be changed. */
key_size = get_key_size(&argv[2]);
if (key_size < 0 || cc->key_size != key_size) {
memset(argv[2], '0', strlen(argv[2]));
return -EINVAL;
}
ret = crypt_set_key(cc, argv[2]);
if (ret)
return ret;
if (cc->iv_gen_ops && cc->iv_gen_ops->init)
ret = cc->iv_gen_ops->init(cc);
/* wipe the kernel key payload copy */
if (cc->key_string)
memset(cc->key, 0, cc->key_size * sizeof(u8));
return ret;
}
if (argc == 2 && !strcasecmp(argv[1], "wipe"))
return crypt_wipe_key(cc);
}
error:
DMWARN("unrecognised message received.");
return -EINVAL;
}
static int crypt_iterate_devices(struct dm_target *ti,
iterate_devices_callout_fn fn, void *data)
{
struct crypt_config *cc = ti->private;
return fn(ti, cc->dev, cc->start, ti->len, data);
}
static void crypt_io_hints(struct dm_target *ti, struct queue_limits *limits)
{
struct crypt_config *cc = ti->private;
/*
* Unfortunate constraint that is required to avoid the potential
* for exceeding underlying device's max_segments limits -- due to
* crypt_alloc_buffer() possibly allocating pages for the encryption
* bio that are not as physically contiguous as the original bio.
*/
limits->max_segment_size = PAGE_SIZE;
limits->logical_block_size =
max_t(unsigned, limits->logical_block_size, cc->sector_size);
limits->physical_block_size =
max_t(unsigned, limits->physical_block_size, cc->sector_size);
limits->io_min = max_t(unsigned, limits->io_min, cc->sector_size);
}
static struct target_type crypt_target = {
.name = "crypt",
.version = {1, 22, 0},
.module = THIS_MODULE,
.ctr = crypt_ctr,
.dtr = crypt_dtr,
#ifdef CONFIG_BLK_DEV_ZONED
.features = DM_TARGET_ZONED_HM,
.report_zones = crypt_report_zones,
#endif
.map = crypt_map,
.status = crypt_status,
.postsuspend = crypt_postsuspend,
.preresume = crypt_preresume,
.resume = crypt_resume,
.message = crypt_message,
.iterate_devices = crypt_iterate_devices,
.io_hints = crypt_io_hints,
};
static int __init dm_crypt_init(void)
{
int r;
r = dm_register_target(&crypt_target);
if (r < 0)
DMERR("register failed %d", r);
return r;
}
static void __exit dm_crypt_exit(void)
{
dm_unregister_target(&crypt_target);
}
module_init(dm_crypt_init);
module_exit(dm_crypt_exit);
MODULE_AUTHOR("Jana Saout <jana@saout.de>");
MODULE_DESCRIPTION(DM_NAME " target for transparent encryption / decryption");
MODULE_LICENSE("GPL");
|
/*
*
* Copyright 2003 Blur Studio Inc.
*
* This file is part of Arsenal.
*
* Arsenal 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.
*
* Arsenal 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 Arsenal; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
/*
* $Id$
*/
#ifdef COMPILE_AUTODESK_BURNER
#ifndef AUTODESKBURN_BURNER_H
#define AUTODESKBURN_BURNER_H
#include "jobburner.h"
/*
* This class is used to Burn Autodesk Burn (Inferno, Flame) jobs
*
*/
class QTimer;
/// \ingroup ABurner
/// @{
class AutodeskBurnBurner : public JobBurner
{
Q_OBJECT
public:
AutodeskBurnBurner( const Job & job, Slave * slave );
~AutodeskBurnBurner();
virtual QStringList processNames() const;
virtual QString executable();
virtual QStringList buildCmdArgs();
void slotProcessOutputLine( const QString &, QProcess::ProcessChannel );
void startProcess();
void cleanup();
public slots:
void slotReadLog();
protected:
QProcess * mLogCmd;
bool mTaskRunning;
QRegExp mCompleteRE;
};
/// @}
#endif // SYNC_BURNER_H
#endif
|
// version 1.0 - original version
jQuery(document).ready(function () {
var version = jQuery.fn.jquery.split('.');
if (parseFloat(version[1]) < 7) {
// use .live as we are on jQuery prior to 1.7
jQuery('.colorpickerField').live('click', function () {
if (jQuery(this).attr('id').search("__i__") === -1) {
var picker,
field = jQuery(this).attr('id').substr(0, 20);
jQuery('.s2_colorpicker').hide();
jQuery('.s2_colorpicker').each(function () {
if (jQuery(this).attr('id').search(field) !== -1) {
picker = jQuery(this).attr('id');
}
});
jQuery.farbtastic('#' + picker).linkTo(this);
jQuery('#' + picker).slideDown();
}
});
} else {
// use .on as we are using jQuery 1.7 and up where .live is deprecated
jQuery(document).on('focus', '.colorpickerField', function () {
if (jQuery(this).is('.s2_initialised') || this.id.search('__i__') !== -1) {
return; // exit early, already initialized or not activated
}
jQuery(this).addClass('s2_initialised');
var picker,
field = jQuery(this).attr('id').substr(0, 20);
jQuery('.s2_colorpicker').each(function () {
if (jQuery(this).attr('id').search(field) !== -1) {
picker = jQuery(this).attr('id');
return false; // stop looping
}
});
jQuery(this).on('focusin', function (event) {
jQuery('.s2_colorpicker').hide();
jQuery.farbtastic('#' + picker).linkTo(this);
jQuery('#' + picker).slideDown();
});
jQuery(this).on('focusout', function (event) {
jQuery('#' + picker).slideUp();
});
jQuery(this).trigger('focus'); // retrigger focus event for plugin to work
});
}
});
|
# -*- coding: utf-8 -*-
#
# synapsecollection.py
#
# This file is part of NEST.
#
# Copyright (C) 2004 The NEST Initiative
#
# NEST 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.
#
# NEST 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 NEST. If not, see <http://www.gnu.org/licenses/>.
"""
Example script to show some of the possibilities of the SynapseCollection class. We
connect neurons, and get the SynapseCollection with a GetConnections call. To get
a better understanding of the connections, we plot the weights between the
source and targets.
"""
import nest
import matplotlib.pyplot as plt
import numpy as np
def makeMatrix(sources, targets, weights):
"""
Returns a matrix with the weights between the source and target node_ids.
"""
aa = np.zeros((max(sources)+1, max(targets)+1))
for src, trg, wght in zip(sources, targets, weights):
aa[src, trg] += wght
return aa
def plotMatrix(srcs, tgts, weights, title, pos):
"""
Plots weight matrix.
"""
plt.subplot(pos)
plt.matshow(makeMatrix(srcs, tgts, weights), fignum=False)
plt.xlim([min(tgts)-0.5, max(tgts)+0.5])
plt.xlabel('target')
plt.ylim([max(srcs)+0.5, min(srcs)-0.5])
plt.ylabel('source')
plt.title(title)
plt.colorbar(fraction=0.046, pad=0.04)
"""
Start with a simple, one_to_one example.
We create the neurons, connect them, and get the connections. From this we can
get the connected sources, targets, and weights. The corresponding matrix will
be the identity matrix, as we have a one_to_one connection.
"""
nest.ResetKernel()
nrns = nest.Create('iaf_psc_alpha', 10)
nest.Connect(nrns, nrns, 'one_to_one')
conns = nest.GetConnections(nrns, nrns) # This returns a SynapseCollection
# We can get desired information of the SynapseCollection with simple get() call.
g = conns.get(['source', 'target', 'weight'])
srcs = g['source']
tgts = g['target']
weights = g['weight']
# Plot the matrix consisting of the weights between the sources and targets
plt.figure(figsize=(12, 10))
plotMatrix(srcs, tgts, weights, 'Uniform weight', 121)
"""
Add some weights to the connections, and plot the updated weight matrix.
"""
# We can set data of the connections with a simple set() call.
w = [{'weight': x*1.0} for x in range(1, 11)]
conns.set(w)
weights = conns.weight
plotMatrix(srcs, tgts, weights, 'Set weight', 122)
"""
We can also plot an all_to_all connection, with uniformly distributed weights,
and different number of sources and targets.
"""
nest.ResetKernel()
pre = nest.Create('iaf_psc_alpha', 10)
post = nest.Create('iaf_psc_delta', 5)
nest.Connect(pre, post,
syn_spec={'weight':
{'distribution': 'uniform', 'low': 0.5, 'high': 4.5}})
# Get a SynapseCollection with all connections
conns = nest.GetConnections()
srcs = conns.source
tgts = conns.target
weights = conns.weight
plt.figure(figsize=(12, 10))
plotMatrix(srcs, tgts, weights, 'All to all connection', 111)
"""
Lastly, we'll do an exmple that is a bit more complex. We connect different
neurons with different rules, synapse models and weight distributions, and get
different SynapseCollections by calling GetConnections with different inputs.
"""
nest.ResetKernel()
nrns = nest.Create('iaf_psc_alpha', 15)
nest.Connect(nrns[:5], nrns[:5],
'one_to_one',
{'synapse_model': 'stdp_synapse',
'weight': {'distribution': 'normal', 'mu': 5.0, 'sigma': 2.0}})
nest.Connect(nrns[:10], nrns[5:12],
{'rule': 'pairwise_bernoulli', 'p': 0.4},
{'weight': 4.0})
nest.Connect(nrns[5:10], nrns[:5],
{'rule': 'fixed_total_number', 'N': 5},
{'weight': 3.0})
nest.Connect(nrns[10:], nrns[:12],
'all_to_all',
{'synapse_model': 'stdp_synapse',
'weight': {'distribution': 'uniform', 'low': 1., 'high': 5.}})
nest.Connect(nrns, nrns[12:],
{'rule': 'fixed_indegree', 'indegree': 3})
# First get a SynapseCollection consisting of all the connections
conns = nest.GetConnections()
srcs = conns.source
tgts = conns.target
weights = conns.weight
plt.figure(figsize=(14, 12))
plotMatrix(list(srcs), list(tgts), weights, 'All connections', 221)
# Get SynapseCollection consisting of a subset of connections
conns = nest.GetConnections(nrns[:10], nrns[:10])
g = conns.get(['source', 'target', 'weight'])
srcs = g['source']
tgts = g['target']
weights = g['weight']
plotMatrix(srcs, tgts, weights, 'Connections of the first ten neurons', 222)
# Get SynapseCollection consisting of just the stdp_synapses
conns = nest.GetConnections(synapse_model='stdp_synapse')
g = conns.get(['source', 'target', 'weight'])
srcs = g['source']
tgts = g['target']
weights = g['weight']
plotMatrix(srcs, tgts, weights, 'Connections with stdp_synapse', 223)
# Get SynapseCollection consisting of the fixed_total_number connections, but set
# weight before plotting
conns = nest.GetConnections(nrns[5:10], nrns[:5])
w = [{'weight': x*1.0} for x in range(1, 6)]
conns.set(w)
g = conns.get(['source', 'target', 'weight'])
srcs = g['source']
tgts = g['target']
weights = g['weight']
plotMatrix(srcs, tgts, weights, 'fixed_total_number, set weight', 224)
plt.show()
|
// PR c++/20148
// { dg-options "-fshow-column -ansi -pedantic-errors -Wno-long-long" }
void foo()
{
if (({int c[2];})) ; // { dg-error "7:ISO C.. forbids" "7" }
// { dg-error "7:could not convert" "17" { target *-*-* } .-1 }
}
void bar()
{
if (({})); // { dg-error "7:ISO C.. forbids" "7" }
// { dg-error "11:could not convert" "11" { target *-*-* } .-1 }
}
|
/* cell.c: AFS cell and server record management
*
* Copyright (C) 2002 Red Hat, Inc. All Rights Reserved.
* Written by David Howells (dhowells@redhat.com)
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*/
#include <linux/module.h>
#include <linux/sched.h>
#include <linux/slab.h>
#include <rxrpc/peer.h>
#include <rxrpc/connection.h>
#include "volume.h"
#include "cell.h"
#include "server.h"
#include "transport.h"
#include "vlclient.h"
#include "kafstimod.h"
#include "super.h"
#include "internal.h"
DECLARE_RWSEM(afs_proc_cells_sem);
LIST_HEAD(afs_proc_cells);
static struct list_head afs_cells = LIST_HEAD_INIT(afs_cells);
static DEFINE_RWLOCK(afs_cells_lock);
static DECLARE_RWSEM(afs_cells_sem); /* add/remove serialisation */
static struct afs_cell *afs_cell_root;
#ifdef AFS_CACHING_SUPPORT
static cachefs_match_val_t afs_cell_cache_match(void *target,
const void *entry);
static void afs_cell_cache_update(void *source, void *entry);
struct cachefs_index_def afs_cache_cell_index_def = {
.name = "cell_ix",
.data_size = sizeof(struct afs_cache_cell),
.keys[0] = { CACHEFS_INDEX_KEYS_ASCIIZ, 64 },
.match = afs_cell_cache_match,
.update = afs_cell_cache_update,
};
#endif
/*****************************************************************************/
/*
* create a cell record
* - "name" is the name of the cell
* - "vllist" is a colon separated list of IP addresses in "a.b.c.d" format
*/
int afs_cell_create(const char *name, char *vllist, struct afs_cell **_cell)
{
struct afs_cell *cell;
char *next;
int ret;
_enter("%s", name);
BUG_ON(!name); /* TODO: want to look up "this cell" in the cache */
/* allocate and initialise a cell record */
cell = kmalloc(sizeof(struct afs_cell) + strlen(name) + 1, GFP_KERNEL);
if (!cell) {
_leave(" = -ENOMEM");
return -ENOMEM;
}
down_write(&afs_cells_sem);
memset(cell, 0, sizeof(struct afs_cell));
atomic_set(&cell->usage, 0);
INIT_LIST_HEAD(&cell->link);
rwlock_init(&cell->sv_lock);
INIT_LIST_HEAD(&cell->sv_list);
INIT_LIST_HEAD(&cell->sv_graveyard);
spin_lock_init(&cell->sv_gylock);
init_rwsem(&cell->vl_sem);
INIT_LIST_HEAD(&cell->vl_list);
INIT_LIST_HEAD(&cell->vl_graveyard);
spin_lock_init(&cell->vl_gylock);
strcpy(cell->name,name);
/* fill in the VL server list from the rest of the string */
ret = -EINVAL;
do {
unsigned a, b, c, d;
next = strchr(vllist, ':');
if (next)
*next++ = 0;
if (sscanf(vllist, "%u.%u.%u.%u", &a, &b, &c, &d) != 4)
goto badaddr;
if (a > 255 || b > 255 || c > 255 || d > 255)
goto badaddr;
cell->vl_addrs[cell->vl_naddrs++].s_addr =
htonl((a << 24) | (b << 16) | (c << 8) | d);
if (cell->vl_naddrs >= AFS_CELL_MAX_ADDRS)
break;
} while(vllist = next, vllist);
/* add a proc dir for this cell */
ret = afs_proc_cell_setup(cell);
if (ret < 0)
goto error;
#ifdef AFS_CACHING_SUPPORT
/* put it up for caching */
cachefs_acquire_cookie(afs_cache_netfs.primary_index,
&afs_vlocation_cache_index_def,
cell,
&cell->cache);
#endif
/* add to the cell lists */
write_lock(&afs_cells_lock);
list_add_tail(&cell->link, &afs_cells);
write_unlock(&afs_cells_lock);
down_write(&afs_proc_cells_sem);
list_add_tail(&cell->proc_link, &afs_proc_cells);
up_write(&afs_proc_cells_sem);
*_cell = cell;
up_write(&afs_cells_sem);
_leave(" = 0 (%p)", cell);
return 0;
badaddr:
printk(KERN_ERR "kAFS: bad VL server IP address: '%s'\n", vllist);
error:
up_write(&afs_cells_sem);
kfree(cell);
_leave(" = %d", ret);
return ret;
} /* end afs_cell_create() */
/*****************************************************************************/
/*
* initialise the cell database from module parameters
*/
int afs_cell_init(char *rootcell)
{
struct afs_cell *old_root, *new_root;
char *cp;
int ret;
_enter("");
if (!rootcell) {
/* module is loaded with no parameters, or built statically.
* - in the future we might initialize cell DB here.
*/
_leave(" = 0 (but no root)");
return 0;
}
cp = strchr(rootcell, ':');
if (!cp) {
printk(KERN_ERR "kAFS: no VL server IP addresses specified\n");
_leave(" = %d (no colon)", -EINVAL);
return -EINVAL;
}
/* allocate a cell record for the root cell */
*cp++ = 0;
ret = afs_cell_create(rootcell, cp, &new_root);
if (ret < 0) {
_leave(" = %d", ret);
return ret;
}
/* as afs_put_cell() takes locks by itself, we have to do
* a little gymnastics to be race-free.
*/
afs_get_cell(new_root);
write_lock(&afs_cells_lock);
while (afs_cell_root) {
old_root = afs_cell_root;
afs_cell_root = NULL;
write_unlock(&afs_cells_lock);
afs_put_cell(old_root);
write_lock(&afs_cells_lock);
}
afs_cell_root = new_root;
write_unlock(&afs_cells_lock);
_leave(" = %d", ret);
return ret;
} /* end afs_cell_init() */
/*****************************************************************************/
/*
* lookup a cell record
*/
int afs_cell_lookup(const char *name, unsigned namesz, struct afs_cell **_cell)
{
struct afs_cell *cell;
int ret;
_enter("\"%*.*s\",", namesz, namesz, name ? name : "");
*_cell = NULL;
if (name) {
/* if the cell was named, look for it in the cell record list */
ret = -ENOENT;
cell = NULL;
read_lock(&afs_cells_lock);
list_for_each_entry(cell, &afs_cells, link) {
if (strncmp(cell->name, name, namesz) == 0) {
afs_get_cell(cell);
goto found;
}
}
cell = NULL;
found:
read_unlock(&afs_cells_lock);
if (cell)
ret = 0;
}
else {
read_lock(&afs_cells_lock);
cell = afs_cell_root;
if (!cell) {
/* this should not happen unless user tries to mount
* when root cell is not set. Return an impossibly
* bizzare errno to alert the user. Things like
* ENOENT might be "more appropriate" but they happen
* for other reasons.
*/
ret = -EDESTADDRREQ;
}
else {
afs_get_cell(cell);
ret = 0;
}
read_unlock(&afs_cells_lock);
}
*_cell = cell;
_leave(" = %d (%p)", ret, cell);
return ret;
} /* end afs_cell_lookup() */
/*****************************************************************************/
/*
* try and get a cell record
*/
struct afs_cell *afs_get_cell_maybe(struct afs_cell **_cell)
{
struct afs_cell *cell;
write_lock(&afs_cells_lock);
cell = *_cell;
if (cell && !list_empty(&cell->link))
afs_get_cell(cell);
else
cell = NULL;
write_unlock(&afs_cells_lock);
return cell;
} /* end afs_get_cell_maybe() */
/*****************************************************************************/
/*
* destroy a cell record
*/
void afs_put_cell(struct afs_cell *cell)
{
if (!cell)
return;
_enter("%p{%d,%s}", cell, atomic_read(&cell->usage), cell->name);
/* sanity check */
BUG_ON(atomic_read(&cell->usage) <= 0);
/* to prevent a race, the decrement and the dequeue must be effectively
* atomic */
write_lock(&afs_cells_lock);
if (likely(!atomic_dec_and_test(&cell->usage))) {
write_unlock(&afs_cells_lock);
_leave("");
return;
}
write_unlock(&afs_cells_lock);
BUG_ON(!list_empty(&cell->sv_list));
BUG_ON(!list_empty(&cell->sv_graveyard));
BUG_ON(!list_empty(&cell->vl_list));
BUG_ON(!list_empty(&cell->vl_graveyard));
_leave(" [unused]");
} /* end afs_put_cell() */
/*****************************************************************************/
/*
* destroy a cell record
*/
static void afs_cell_destroy(struct afs_cell *cell)
{
_enter("%p{%d,%s}", cell, atomic_read(&cell->usage), cell->name);
/* to prevent a race, the decrement and the dequeue must be effectively
* atomic */
write_lock(&afs_cells_lock);
/* sanity check */
BUG_ON(atomic_read(&cell->usage) != 0);
list_del_init(&cell->link);
write_unlock(&afs_cells_lock);
down_write(&afs_cells_sem);
afs_proc_cell_remove(cell);
down_write(&afs_proc_cells_sem);
list_del_init(&cell->proc_link);
up_write(&afs_proc_cells_sem);
#ifdef AFS_CACHING_SUPPORT
cachefs_relinquish_cookie(cell->cache, 0);
#endif
up_write(&afs_cells_sem);
BUG_ON(!list_empty(&cell->sv_list));
BUG_ON(!list_empty(&cell->sv_graveyard));
BUG_ON(!list_empty(&cell->vl_list));
BUG_ON(!list_empty(&cell->vl_graveyard));
/* finish cleaning up the cell */
kfree(cell);
_leave(" [destroyed]");
} /* end afs_cell_destroy() */
/*****************************************************************************/
/*
* lookup the server record corresponding to an Rx RPC peer
*/
int afs_server_find_by_peer(const struct rxrpc_peer *peer,
struct afs_server **_server)
{
struct afs_server *server;
struct afs_cell *cell;
_enter("%p{a=%08x},", peer, ntohl(peer->addr.s_addr));
/* search the cell list */
read_lock(&afs_cells_lock);
list_for_each_entry(cell, &afs_cells, link) {
_debug("? cell %s",cell->name);
write_lock(&cell->sv_lock);
/* check the active list */
list_for_each_entry(server, &cell->sv_list, link) {
_debug("?? server %08x", ntohl(server->addr.s_addr));
if (memcmp(&server->addr, &peer->addr,
sizeof(struct in_addr)) == 0)
goto found_server;
}
/* check the inactive list */
spin_lock(&cell->sv_gylock);
list_for_each_entry(server, &cell->sv_graveyard, link) {
_debug("?? dead server %08x",
ntohl(server->addr.s_addr));
if (memcmp(&server->addr, &peer->addr,
sizeof(struct in_addr)) == 0)
goto found_dead_server;
}
spin_unlock(&cell->sv_gylock);
write_unlock(&cell->sv_lock);
}
read_unlock(&afs_cells_lock);
_leave(" = -ENOENT");
return -ENOENT;
/* we found it in the graveyard - resurrect it */
found_dead_server:
list_move_tail(&server->link, &cell->sv_list);
afs_get_server(server);
afs_kafstimod_del_timer(&server->timeout);
spin_unlock(&cell->sv_gylock);
goto success;
/* we found it - increment its ref count and return it */
found_server:
afs_get_server(server);
success:
write_unlock(&cell->sv_lock);
read_unlock(&afs_cells_lock);
*_server = server;
_leave(" = 0 (s=%p c=%p)", server, cell);
return 0;
} /* end afs_server_find_by_peer() */
/*****************************************************************************/
/*
* purge in-memory cell database on module unload or afs_init() failure
* - the timeout daemon is stopped before calling this
*/
void afs_cell_purge(void)
{
struct afs_vlocation *vlocation;
struct afs_cell *cell;
_enter("");
afs_put_cell(afs_cell_root);
while (!list_empty(&afs_cells)) {
cell = NULL;
/* remove the next cell from the front of the list */
write_lock(&afs_cells_lock);
if (!list_empty(&afs_cells)) {
cell = list_entry(afs_cells.next,
struct afs_cell, link);
list_del_init(&cell->link);
}
write_unlock(&afs_cells_lock);
if (cell) {
_debug("PURGING CELL %s (%d)",
cell->name, atomic_read(&cell->usage));
BUG_ON(!list_empty(&cell->sv_list));
BUG_ON(!list_empty(&cell->vl_list));
/* purge the cell's VL graveyard list */
_debug(" - clearing VL graveyard");
spin_lock(&cell->vl_gylock);
while (!list_empty(&cell->vl_graveyard)) {
vlocation = list_entry(cell->vl_graveyard.next,
struct afs_vlocation,
link);
list_del_init(&vlocation->link);
afs_kafstimod_del_timer(&vlocation->timeout);
spin_unlock(&cell->vl_gylock);
afs_vlocation_do_timeout(vlocation);
/* TODO: race if move to use krxtimod instead
* of kafstimod */
spin_lock(&cell->vl_gylock);
}
spin_unlock(&cell->vl_gylock);
/* purge the cell's server graveyard list */
_debug(" - clearing server graveyard");
spin_lock(&cell->sv_gylock);
while (!list_empty(&cell->sv_graveyard)) {
struct afs_server *server;
server = list_entry(cell->sv_graveyard.next,
struct afs_server, link);
list_del_init(&server->link);
afs_kafstimod_del_timer(&server->timeout);
spin_unlock(&cell->sv_gylock);
afs_server_do_timeout(server);
spin_lock(&cell->sv_gylock);
}
spin_unlock(&cell->sv_gylock);
/* now the cell should be left with no references */
afs_cell_destroy(cell);
}
}
_leave("");
} /* end afs_cell_purge() */
/*****************************************************************************/
/*
* match a cell record obtained from the cache
*/
#ifdef AFS_CACHING_SUPPORT
static cachefs_match_val_t afs_cell_cache_match(void *target,
const void *entry)
{
const struct afs_cache_cell *ccell = entry;
struct afs_cell *cell = target;
_enter("{%s},{%s}", ccell->name, cell->name);
if (strncmp(ccell->name, cell->name, sizeof(ccell->name)) == 0) {
_leave(" = SUCCESS");
return CACHEFS_MATCH_SUCCESS;
}
_leave(" = FAILED");
return CACHEFS_MATCH_FAILED;
} /* end afs_cell_cache_match() */
#endif
/*****************************************************************************/
/*
* update a cell record in the cache
*/
#ifdef AFS_CACHING_SUPPORT
static void afs_cell_cache_update(void *source, void *entry)
{
struct afs_cache_cell *ccell = entry;
struct afs_cell *cell = source;
_enter("%p,%p", source, entry);
strncpy(ccell->name, cell->name, sizeof(ccell->name));
memcpy(ccell->vl_servers,
cell->vl_addrs,
min(sizeof(ccell->vl_servers), sizeof(cell->vl_addrs)));
} /* end afs_cell_cache_update() */
#endif
|
/* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil; -*- */
/*
* Copyright (c) 2011 Centre Tecnologic de Telecomunicacions de Catalunya (CTTC)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation;
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Author: Manuel Requena <manuel.requena@cttc.es>
*/
#include "ns3/simulator.h"
#include "ns3/log.h"
#include "ns3/lte-rlc-header.h"
#include "ns3/lte-rlc-um.h"
#include "ns3/lte-rlc-sdu-status-tag.h"
#include "ns3/lte-rlc-tag.h"
NS_LOG_COMPONENT_DEFINE ("LteRlcUm");
namespace ns3 {
NS_OBJECT_ENSURE_REGISTERED (LteRlcUm);
LteRlcUm::LteRlcUm ()
: m_maxTxBufferSize (2 * 1024 * 1024),
m_txBufferSize (0),
m_sequenceNumber (0),
m_vrUr (0),
m_vrUx (0),
m_vrUh (0),
m_windowSize (512),
m_expectedSeqNumber (0)
{
NS_LOG_FUNCTION (this);
m_reassemblingState = WAITING_S0_FULL;
}
LteRlcUm::~LteRlcUm ()
{
NS_LOG_FUNCTION (this);
}
TypeId
LteRlcUm::GetTypeId (void)
{
static TypeId tid = TypeId ("ns3::LteRlcUm")
.SetParent<LteRlc> ()
.AddConstructor<LteRlcUm> ()
.AddAttribute ("MaxTxBufferSize",
"Maximum Size of the Transmission Buffer (in Bytes)",
UintegerValue (2 * 1024 * 1024),
MakeUintegerAccessor (&LteRlcUm::m_maxTxBufferSize),
MakeUintegerChecker<uint32_t> ())
;
return tid;
}
void
LteRlcUm::DoDispose ()
{
NS_LOG_FUNCTION (this);
m_reorderingTimer.Cancel ();
m_rbsTimer.Cancel ();
LteRlc::DoDispose ();
}
/**
* RLC SAP
*/
void
LteRlcUm::DoTransmitPdcpPdu (Ptr<Packet> p)
{
NS_LOG_FUNCTION (this << m_rnti << (uint32_t) m_lcid << p->GetSize ());
if (m_txBufferSize + p->GetSize () <= m_maxTxBufferSize)
{
/** Store arrival time */
RlcTag timeTag (Simulator::Now ());
p->AddPacketTag (timeTag);
/** Store PDCP PDU */
LteRlcSduStatusTag tag;
tag.SetStatus (LteRlcSduStatusTag::FULL_SDU);
p->AddPacketTag (tag);
NS_LOG_LOGIC ("Tx Buffer: New packet added");
m_txBuffer.push_back (p);
m_txBufferSize += p->GetSize ();
NS_LOG_LOGIC ("NumOfBuffers = " << m_txBuffer.size() );
NS_LOG_LOGIC ("txBufferSize = " << m_txBufferSize);
}
else
{
// Discard full RLC SDU
NS_LOG_LOGIC ("TxBuffer is full. RLC SDU discarded");
NS_LOG_LOGIC ("MaxTxBufferSize = " << m_maxTxBufferSize);
NS_LOG_LOGIC ("txBufferSize = " << m_txBufferSize);
NS_LOG_LOGIC ("packet size = " << p->GetSize ());
}
/** Report Buffer Status */
DoReportBufferStatus ();
m_rbsTimer.Cancel ();
}
/**
* MAC SAP
*/
void
LteRlcUm::DoNotifyTxOpportunity (uint32_t bytes, uint8_t layer, uint8_t harqId)
{
NS_LOG_FUNCTION (this << m_rnti << (uint32_t) m_lcid << bytes);
if (bytes <= 2)
{
// Stingy MAC: Header fix part is 2 bytes, we need more bytes for the data
NS_LOG_LOGIC ("TX opportunity too small = " << bytes);
return;
}
Ptr<Packet> packet = Create<Packet> ();
LteRlcHeader rlcHeader;
// Build Data field
uint32_t nextSegmentSize = bytes - 2;
uint32_t nextSegmentId = 1;
uint32_t dataFieldTotalSize = 0;
uint32_t dataFieldAddedSize = 0;
std::vector < Ptr<Packet> > dataField;
// Remove the first packet from the transmission buffer.
// If only a segment of the packet is taken, then the remaining is given back later
if ( m_txBuffer.size () == 0 )
{
NS_LOG_LOGIC ("No data pending");
return;
}
NS_LOG_LOGIC ("SDUs in TxBuffer = " << m_txBuffer.size ());
NS_LOG_LOGIC ("First SDU buffer = " << *(m_txBuffer.begin()));
NS_LOG_LOGIC ("First SDU size = " << (*(m_txBuffer.begin()))->GetSize ());
NS_LOG_LOGIC ("Next segment size = " << nextSegmentSize);
NS_LOG_LOGIC ("Remove SDU from TxBuffer");
Ptr<Packet> firstSegment = (*(m_txBuffer.begin ()))->Copy ();
m_txBufferSize -= (*(m_txBuffer.begin()))->GetSize ();
NS_LOG_LOGIC ("txBufferSize = " << m_txBufferSize );
m_txBuffer.erase (m_txBuffer.begin ());
while ( firstSegment && (firstSegment->GetSize () > 0) && (nextSegmentSize > 0) )
{
NS_LOG_LOGIC ("WHILE ( firstSegment && firstSegment->GetSize > 0 && nextSegmentSize > 0 )");
NS_LOG_LOGIC (" firstSegment size = " << firstSegment->GetSize ());
NS_LOG_LOGIC (" nextSegmentSize = " << nextSegmentSize);
if ( (firstSegment->GetSize () > nextSegmentSize) ||
// Segment larger than 2047 octets can only be mapped to the end of the Data field
(firstSegment->GetSize () > 2047)
)
{
// Take the minimum size, due to the 2047-bytes 3GPP exception
// This exception is due to the length of the LI field (just 11 bits)
uint32_t currSegmentSize = std::min (firstSegment->GetSize (), nextSegmentSize);
NS_LOG_LOGIC (" IF ( firstSegment > nextSegmentSize ||");
NS_LOG_LOGIC (" firstSegment > 2047 )");
// Segment txBuffer.FirstBuffer and
// Give back the remaining segment to the transmission buffer
Ptr<Packet> newSegment = firstSegment->CreateFragment (0, currSegmentSize);
NS_LOG_LOGIC (" newSegment size = " << newSegment->GetSize ());
// Status tag of the new and remaining segments
// Note: This is the only place where a PDU is segmented and
// therefore its status can change
LteRlcSduStatusTag oldTag, newTag;
firstSegment->RemovePacketTag (oldTag);
newSegment->RemovePacketTag (newTag);
if (oldTag.GetStatus () == LteRlcSduStatusTag::FULL_SDU)
{
newTag.SetStatus (LteRlcSduStatusTag::FIRST_SEGMENT);
oldTag.SetStatus (LteRlcSduStatusTag::LAST_SEGMENT);
}
else if (oldTag.GetStatus () == LteRlcSduStatusTag::LAST_SEGMENT)
{
newTag.SetStatus (LteRlcSduStatusTag::MIDDLE_SEGMENT);
//oldTag.SetStatus (LteRlcSduStatusTag::LAST_SEGMENT);
}
// Give back the remaining segment to the transmission buffer
firstSegment->RemoveAtStart (currSegmentSize);
NS_LOG_LOGIC (" firstSegment size (after RemoveAtStart) = " << firstSegment->GetSize ());
if (firstSegment->GetSize () > 0)
{
firstSegment->AddPacketTag (oldTag);
m_txBuffer.insert (m_txBuffer.begin (), firstSegment);
m_txBufferSize += (*(m_txBuffer.begin()))->GetSize ();
NS_LOG_LOGIC (" TX buffer: Give back the remaining segment");
NS_LOG_LOGIC (" TX buffers = " << m_txBuffer.size ());
NS_LOG_LOGIC (" Front buffer size = " << (*(m_txBuffer.begin()))->GetSize ());
NS_LOG_LOGIC (" txBufferSize = " << m_txBufferSize );
}
else
{
// Whole segment was taken, so adjust tag
if (newTag.GetStatus () == LteRlcSduStatusTag::FIRST_SEGMENT)
{
newTag.SetStatus (LteRlcSduStatusTag::FULL_SDU);
}
else if (newTag.GetStatus () == LteRlcSduStatusTag::MIDDLE_SEGMENT)
{
newTag.SetStatus (LteRlcSduStatusTag::LAST_SEGMENT);
}
}
// Segment is completely taken or
// the remaining segment is given back to the transmission buffer
firstSegment = 0;
// Put status tag once it has been adjusted
newSegment->AddPacketTag (newTag);
// Add Segment to Data field
dataFieldAddedSize = newSegment->GetSize ();
dataFieldTotalSize += dataFieldAddedSize;
dataField.push_back (newSegment);
newSegment = 0;
// ExtensionBit (Next_Segment - 1) = 0
rlcHeader.PushExtensionBit (LteRlcHeader::DATA_FIELD_FOLLOWS);
// no LengthIndicator for the last one
nextSegmentSize -= dataFieldAddedSize;
nextSegmentId++;
// nextSegmentSize MUST be zero (only if segment is smaller or equal to 2047)
// (NO more segments) → exit
// break;
}
else if ( (nextSegmentSize - firstSegment->GetSize () <= 2) || (m_txBuffer.size () == 0) )
{
NS_LOG_LOGIC (" IF nextSegmentSize - firstSegment->GetSize () <= 2 || txBuffer.size == 0");
// Add txBuffer.FirstBuffer to DataField
dataFieldAddedSize = firstSegment->GetSize ();
dataFieldTotalSize += dataFieldAddedSize;
dataField.push_back (firstSegment);
firstSegment = 0;
// ExtensionBit (Next_Segment - 1) = 0
rlcHeader.PushExtensionBit (LteRlcHeader::DATA_FIELD_FOLLOWS);
// no LengthIndicator for the last one
nextSegmentSize -= dataFieldAddedSize;
nextSegmentId++;
NS_LOG_LOGIC (" SDUs in TxBuffer = " << m_txBuffer.size ());
if (m_txBuffer.size () > 0)
{
NS_LOG_LOGIC (" First SDU buffer = " << *(m_txBuffer.begin()));
NS_LOG_LOGIC (" First SDU size = " << (*(m_txBuffer.begin()))->GetSize ());
}
NS_LOG_LOGIC (" Next segment size = " << nextSegmentSize);
// nextSegmentSize <= 2 (only if txBuffer is not empty)
// (NO more segments) → exit
// break;
}
else // (firstSegment->GetSize () < m_nextSegmentSize) && (m_txBuffer.size () > 0)
{
NS_LOG_LOGIC (" IF firstSegment < NextSegmentSize && txBuffer.size > 0");
// Add txBuffer.FirstBuffer to DataField
dataFieldAddedSize = firstSegment->GetSize ();
dataFieldTotalSize += dataFieldAddedSize;
dataField.push_back (firstSegment);
// ExtensionBit (Next_Segment - 1) = 1
rlcHeader.PushExtensionBit (LteRlcHeader::E_LI_FIELDS_FOLLOWS);
// LengthIndicator (Next_Segment) = txBuffer.FirstBuffer.length()
rlcHeader.PushLengthIndicator (firstSegment->GetSize ());
nextSegmentSize -= ((nextSegmentId % 2) ? (2) : (1)) + dataFieldAddedSize;
nextSegmentId++;
NS_LOG_LOGIC (" SDUs in TxBuffer = " << m_txBuffer.size ());
if (m_txBuffer.size () > 0)
{
NS_LOG_LOGIC (" First SDU buffer = " << *(m_txBuffer.begin()));
NS_LOG_LOGIC (" First SDU size = " << (*(m_txBuffer.begin()))->GetSize ());
}
NS_LOG_LOGIC (" Next segment size = " << nextSegmentSize);
NS_LOG_LOGIC (" Remove SDU from TxBuffer");
// (more segments)
firstSegment = (*(m_txBuffer.begin ()))->Copy ();
m_txBufferSize -= (*(m_txBuffer.begin()))->GetSize ();
m_txBuffer.erase (m_txBuffer.begin ());
NS_LOG_LOGIC (" txBufferSize = " << m_txBufferSize );
}
}
// Build RLC header
rlcHeader.SetSequenceNumber (m_sequenceNumber++);
// Build RLC PDU with DataField and Header
std::vector< Ptr<Packet> >::iterator it;
it = dataField.begin ();
uint8_t framingInfo = 0;
// FIRST SEGMENT
LteRlcSduStatusTag tag;
(*it)->RemovePacketTag (tag);
if ( (tag.GetStatus () == LteRlcSduStatusTag::FULL_SDU) ||
(tag.GetStatus () == LteRlcSduStatusTag::FIRST_SEGMENT) )
{
framingInfo |= LteRlcHeader::FIRST_BYTE;
}
else
{
framingInfo |= LteRlcHeader::NO_FIRST_BYTE;
}
(*it)->AddPacketTag (tag);
while (it < dataField.end ())
{
NS_LOG_LOGIC ("Adding SDU/segment to packet, length = " << (*it)->GetSize ());
packet->AddAtEnd (*it);
it++;
}
// LAST SEGMENT (Note: There could be only one and be the first one)
it--;
(*it)->RemovePacketTag (tag);
if ( (tag.GetStatus () == LteRlcSduStatusTag::FULL_SDU) ||
(tag.GetStatus () == LteRlcSduStatusTag::LAST_SEGMENT) )
{
framingInfo |= LteRlcHeader::LAST_BYTE;
}
else
{
framingInfo |= LteRlcHeader::NO_LAST_BYTE;
}
(*it)->AddPacketTag (tag);
rlcHeader.SetFramingInfo (framingInfo);
NS_LOG_LOGIC ("RLC header: " << rlcHeader);
packet->AddHeader (rlcHeader);
// Sender timestamp
RlcTag rlcTag (Simulator::Now ());
packet->AddByteTag (rlcTag);
m_txPdu (m_rnti, m_lcid, packet->GetSize ());
// Send RLC PDU to MAC layer
LteMacSapProvider::TransmitPduParameters params;
params.pdu = packet;
params.rnti = m_rnti;
params.lcid = m_lcid;
params.layer = layer;
params.harqProcessId = harqId;
m_macSapProvider->TransmitPdu (params);
if (! m_txBuffer.empty ())
{
m_rbsTimer.Cancel ();
m_rbsTimer = Simulator::Schedule (MilliSeconds (10), &LteRlcUm::ExpireRbsTimer, this);
}
}
void
LteRlcUm::DoNotifyHarqDeliveryFailure ()
{
NS_LOG_FUNCTION (this);
}
void
LteRlcUm::DoReceivePdu (Ptr<Packet> p)
{
NS_LOG_FUNCTION (this << m_rnti << (uint32_t) m_lcid << p->GetSize ());
// Receiver timestamp
RlcTag rlcTag;
Time delay;
if (p->FindFirstMatchingByteTag (rlcTag))
{
delay = Simulator::Now() - rlcTag.GetSenderTimestamp ();
}
m_rxPdu (m_rnti, m_lcid, p->GetSize (), delay.GetNanoSeconds ());
// 5.1.2.2 Receive operations
// Get RLC header parameters
LteRlcHeader rlcHeader;
p->PeekHeader (rlcHeader);
NS_LOG_LOGIC ("RLC header: " << rlcHeader);
SequenceNumber10 seqNumber = rlcHeader.GetSequenceNumber ();
// 5.1.2.2.1 General
// The receiving UM RLC entity shall maintain a reordering window according to state variable VR(UH) as follows:
// - a SN falls within the reordering window if (VR(UH) - UM_Window_Size) <= SN < VR(UH);
// - a SN falls outside of the reordering window otherwise.
// When receiving an UMD PDU from lower layer, the receiving UM RLC entity shall:
// - either discard the received UMD PDU or place it in the reception buffer (see sub clause 5.1.2.2.2);
// - if the received UMD PDU was placed in the reception buffer:
// - update state variables, reassemble and deliver RLC SDUs to upper layer and start/stop t-Reordering as needed (see sub clause 5.1.2.2.3);
// When t-Reordering expires, the receiving UM RLC entity shall:
// - update state variables, reassemble and deliver RLC SDUs to upper layer and start t-Reordering as needed (see sub clause 5.1.2.2.4).
// 5.1.2.2.2 Actions when an UMD PDU is received from lower layer
// When an UMD PDU with SN = x is received from lower layer, the receiving UM RLC entity shall:
// - if VR(UR) < x < VR(UH) and the UMD PDU with SN = x has been received before; or
// - if (VR(UH) - UM_Window_Size) <= x < VR(UR):
// - discard the received UMD PDU;
// - else:
// - place the received UMD PDU in the reception buffer.
NS_LOG_LOGIC ("VR(UR) = " << m_vrUr);
NS_LOG_LOGIC ("VR(UX) = " << m_vrUx);
NS_LOG_LOGIC ("VR(UH) = " << m_vrUh);
NS_LOG_LOGIC ("SN = " << seqNumber);
m_vrUr.SetModulusBase (m_vrUh - m_windowSize);
m_vrUh.SetModulusBase (m_vrUh - m_windowSize);
seqNumber.SetModulusBase (m_vrUh - m_windowSize);
if ( ( (m_vrUr < seqNumber) && (seqNumber < m_vrUh) && (m_rxBuffer.count (seqNumber.GetValue ()) > 0) ) ||
( ((m_vrUh - m_windowSize) <= seqNumber) && (seqNumber < m_vrUr) )
)
{
NS_LOG_LOGIC ("PDU discarded");
p = 0;
return;
}
else
{
NS_LOG_LOGIC ("Place PDU in the reception buffer");
m_rxBuffer[seqNumber.GetValue ()] = p;
}
// 5.1.2.2.3 Actions when an UMD PDU is placed in the reception buffer
// When an UMD PDU with SN = x is placed in the reception buffer, the receiving UM RLC entity shall:
// - if x falls outside of the reordering window:
// - update VR(UH) to x + 1;
// - reassemble RLC SDUs from any UMD PDUs with SN that falls outside of the reordering window, remove
// RLC headers when doing so and deliver the reassembled RLC SDUs to upper layer in ascending order of the
// RLC SN if not delivered before;
// - if VR(UR) falls outside of the reordering window:
// - set VR(UR) to (VR(UH) - UM_Window_Size);
if ( ! IsInsideReorderingWindow (seqNumber))
{
NS_LOG_LOGIC ("SN is outside the reordering window");
m_vrUh = seqNumber + 1;
NS_LOG_LOGIC ("New VR(UH) = " << m_vrUh);
ReassembleOutsideWindow ();
if ( ! IsInsideReorderingWindow (m_vrUr) )
{
m_vrUr = m_vrUh - m_windowSize;
NS_LOG_LOGIC ("VR(UR) is outside the reordering window");
NS_LOG_LOGIC ("New VR(UR) = " << m_vrUr);
}
}
// - if the reception buffer contains an UMD PDU with SN = VR(UR):
// - update VR(UR) to the SN of the first UMD PDU with SN > current VR(UR) that has not been received;
// - reassemble RLC SDUs from any UMD PDUs with SN < updated VR(UR), remove RLC headers when doing
// so and deliver the reassembled RLC SDUs to upper layer in ascending order of the RLC SN if not delivered
// before;
if ( m_rxBuffer.count (m_vrUr.GetValue ()) > 0 )
{
NS_LOG_LOGIC ("Reception buffer contains SN = " << m_vrUr);
std::map <uint16_t, Ptr<Packet> >::iterator it;
uint16_t newVrUr;
SequenceNumber10 oldVrUr = m_vrUr;
it = m_rxBuffer.find (m_vrUr.GetValue ());
newVrUr = (it->first) + 1;
while ( m_rxBuffer.count (newVrUr) > 0 )
{
newVrUr++;
}
m_vrUr = newVrUr;
NS_LOG_LOGIC ("New VR(UR) = " << m_vrUr);
ReassembleSnInterval (oldVrUr, m_vrUr);
}
// m_vrUh can change previously, set new modulus base
// for the t-Reordering timer-related comparisons
m_vrUr.SetModulusBase (m_vrUh - m_windowSize);
m_vrUx.SetModulusBase (m_vrUh - m_windowSize);
m_vrUh.SetModulusBase (m_vrUh - m_windowSize);
// - if t-Reordering is running:
// - if VR(UX) <= VR(UR); or
// - if VR(UX) falls outside of the reordering window and VR(UX) is not equal to VR(UH)::
// - stop and reset t-Reordering;
if ( m_reorderingTimer.IsRunning () )
{
NS_LOG_LOGIC ("Reordering timer is running");
if ( (m_vrUx <= m_vrUr) ||
((! IsInsideReorderingWindow (m_vrUx)) && (m_vrUx != m_vrUh)) )
{
NS_LOG_LOGIC ("Stop reordering timer");
m_reorderingTimer.Cancel ();
}
}
// - if t-Reordering is not running (includes the case when t-Reordering is stopped due to actions above):
// - if VR(UH) > VR(UR):
// - start t-Reordering;
// - set VR(UX) to VR(UH).
if ( ! m_reorderingTimer.IsRunning () )
{
NS_LOG_LOGIC ("Reordering timer is not running");
if ( m_vrUh > m_vrUr )
{
NS_LOG_LOGIC ("VR(UH) > VR(UR)");
NS_LOG_LOGIC ("Start reordering timer");
m_reorderingTimer = Simulator::Schedule (Time ("0.1s"),
&LteRlcUm::ExpireReorderingTimer ,this);
m_vrUx = m_vrUh;
NS_LOG_LOGIC ("New VR(UX) = " << m_vrUx);
}
}
}
bool
LteRlcUm::IsInsideReorderingWindow (SequenceNumber10 seqNumber)
{
NS_LOG_FUNCTION (this << seqNumber);
NS_LOG_LOGIC ("Reordering Window: " <<
m_vrUh << " - " << m_windowSize << " <= " << seqNumber << " < " << m_vrUh);
m_vrUh.SetModulusBase (m_vrUh - m_windowSize);
seqNumber.SetModulusBase (m_vrUh - m_windowSize);
if ( ((m_vrUh - m_windowSize) <= seqNumber) && (seqNumber < m_vrUh))
{
NS_LOG_LOGIC (seqNumber << " is INSIDE the reordering window");
return true;
}
else
{
NS_LOG_LOGIC (seqNumber << " is OUTSIDE the reordering window");
return false;
}
}
void
LteRlcUm::ReassembleAndDeliver (Ptr<Packet> packet)
{
LteRlcHeader rlcHeader;
packet->RemoveHeader (rlcHeader);
uint8_t framingInfo = rlcHeader.GetFramingInfo ();
SequenceNumber10 currSeqNumber = rlcHeader.GetSequenceNumber ();
bool expectedSnLost;
if ( currSeqNumber != m_expectedSeqNumber )
{
expectedSnLost = true;
NS_LOG_LOGIC ("There are losses. Expected SN = " << m_expectedSeqNumber << ". Current SN = " << currSeqNumber);
m_expectedSeqNumber = currSeqNumber + 1;
}
else
{
expectedSnLost = false;
NS_LOG_LOGIC ("No losses. Expected SN = " << m_expectedSeqNumber << ". Current SN = " << currSeqNumber);
m_expectedSeqNumber++;
}
// Build list of SDUs
uint8_t extensionBit;
uint16_t lengthIndicator;
do
{
extensionBit = rlcHeader.PopExtensionBit ();
NS_LOG_LOGIC ("E = " << (uint16_t)extensionBit);
if ( extensionBit == 0 )
{
m_sdusBuffer.push_back (packet);
}
else // extensionBit == 1
{
lengthIndicator = rlcHeader.PopLengthIndicator ();
NS_LOG_LOGIC ("LI = " << lengthIndicator);
// Check if there is enough data in the packet
if ( lengthIndicator >= packet->GetSize () )
{
NS_LOG_LOGIC ("INTERNAL ERROR: Not enough data in the packet (" << packet->GetSize () << "). Needed LI=" << lengthIndicator);
}
// Split packet in two fragments
Ptr<Packet> data_field = packet->CreateFragment (0, lengthIndicator);
packet->RemoveAtStart (lengthIndicator);
m_sdusBuffer.push_back (data_field);
}
}
while ( extensionBit == 1 );
std::list < Ptr<Packet> >::iterator it;
// Current reassembling state
if (m_reassemblingState == WAITING_S0_FULL) NS_LOG_LOGIC ("Reassembling State = 'WAITING_S0_FULL'");
else if (m_reassemblingState == WAITING_SI_SF) NS_LOG_LOGIC ("Reassembling State = 'WAITING_SI_SF'");
else NS_LOG_LOGIC ("Reassembling State = Unknown state");
// Received framing Info
NS_LOG_LOGIC ("Framing Info = " << (uint16_t)framingInfo);
// Reassemble the list of SDUs (when there is no losses)
if (!expectedSnLost)
{
switch (m_reassemblingState)
{
case WAITING_S0_FULL:
switch (framingInfo)
{
case (LteRlcHeader::FIRST_BYTE | LteRlcHeader::LAST_BYTE):
m_reassemblingState = WAITING_S0_FULL;
/**
* Deliver one or multiple PDUs
*/
for ( it = m_sdusBuffer.begin () ; it != m_sdusBuffer.end () ; it++ )
{
m_rlcSapUser->ReceivePdcpPdu (*it);
}
m_sdusBuffer.clear ();
break;
case (LteRlcHeader::FIRST_BYTE | LteRlcHeader::NO_LAST_BYTE):
m_reassemblingState = WAITING_SI_SF;
/**
* Deliver full PDUs
*/
while ( m_sdusBuffer.size () > 1 )
{
m_rlcSapUser->ReceivePdcpPdu (m_sdusBuffer.front ());
m_sdusBuffer.pop_front ();
}
/**
* Keep S0
*/
m_keepS0 = m_sdusBuffer.front ();
m_sdusBuffer.pop_front ();
break;
case (LteRlcHeader::NO_FIRST_BYTE | LteRlcHeader::LAST_BYTE):
m_reassemblingState = WAITING_S0_FULL;
/**
* Discard SI or SN
*/
m_sdusBuffer.pop_front ();
/**
* Deliver zero, one or multiple PDUs
*/
while ( ! m_sdusBuffer.empty () )
{
m_rlcSapUser->ReceivePdcpPdu (m_sdusBuffer.front ());
m_sdusBuffer.pop_front ();
}
break;
case (LteRlcHeader::NO_FIRST_BYTE | LteRlcHeader::NO_LAST_BYTE):
if ( m_sdusBuffer.size () == 1 )
{
m_reassemblingState = WAITING_S0_FULL;
}
else
{
m_reassemblingState = WAITING_SI_SF;
}
/**
* Discard SI or SN
*/
m_sdusBuffer.pop_front ();
if ( m_sdusBuffer.size () > 0 )
{
/**
* Deliver zero, one or multiple PDUs
*/
while ( m_sdusBuffer.size () > 1 )
{
m_rlcSapUser->ReceivePdcpPdu (m_sdusBuffer.front ());
m_sdusBuffer.pop_front ();
}
/**
* Keep S0
*/
m_keepS0 = m_sdusBuffer.front ();
m_sdusBuffer.pop_front ();
}
break;
default:
/**
* ERROR: Transition not possible
*/
NS_LOG_LOGIC ("INTERNAL ERROR: Transition not possible. FI = " << (uint32_t) framingInfo);
break;
}
break;
case WAITING_SI_SF:
switch (framingInfo)
{
case (LteRlcHeader::NO_FIRST_BYTE | LteRlcHeader::LAST_BYTE):
m_reassemblingState = WAITING_S0_FULL;
/**
* Deliver (Kept)S0 + SN
*/
m_keepS0->AddAtEnd (m_sdusBuffer.front ());
m_sdusBuffer.pop_front ();
m_rlcSapUser->ReceivePdcpPdu (m_keepS0);
/**
* Deliver zero, one or multiple PDUs
*/
while ( ! m_sdusBuffer.empty () )
{
m_rlcSapUser->ReceivePdcpPdu (m_sdusBuffer.front ());
m_sdusBuffer.pop_front ();
}
break;
case (LteRlcHeader::NO_FIRST_BYTE | LteRlcHeader::NO_LAST_BYTE):
m_reassemblingState = WAITING_SI_SF;
/**
* Keep SI
*/
if ( m_sdusBuffer.size () == 1 )
{
m_keepS0->AddAtEnd (m_sdusBuffer.front ());
m_sdusBuffer.pop_front ();
}
else // m_sdusBuffer.size () > 1
{
/**
* Deliver (Kept)S0 + SN
*/
m_keepS0->AddAtEnd (m_sdusBuffer.front ());
m_sdusBuffer.pop_front ();
m_rlcSapUser->ReceivePdcpPdu (m_keepS0);
/**
* Deliver zero, one or multiple PDUs
*/
while ( m_sdusBuffer.size () > 1 )
{
m_rlcSapUser->ReceivePdcpPdu (m_sdusBuffer.front ());
m_sdusBuffer.pop_front ();
}
/**
* Keep S0
*/
m_keepS0 = m_sdusBuffer.front ();
m_sdusBuffer.pop_front ();
}
break;
case (LteRlcHeader::FIRST_BYTE | LteRlcHeader::LAST_BYTE):
case (LteRlcHeader::FIRST_BYTE | LteRlcHeader::NO_LAST_BYTE):
default:
/**
* ERROR: Transition not possible
*/
NS_LOG_LOGIC ("INTERNAL ERROR: Transition not possible. FI = " << (uint32_t) framingInfo);
break;
}
break;
default:
NS_LOG_LOGIC ("INTERNAL ERROR: Wrong reassembling state = " << (uint32_t) m_reassemblingState);
break;
}
}
else // Reassemble the list of SDUs (when there are losses, i.e. the received SN is not the expected one)
{
switch (m_reassemblingState)
{
case WAITING_S0_FULL:
switch (framingInfo)
{
case (LteRlcHeader::FIRST_BYTE | LteRlcHeader::LAST_BYTE):
m_reassemblingState = WAITING_S0_FULL;
/**
* Deliver one or multiple PDUs
*/
for ( it = m_sdusBuffer.begin () ; it != m_sdusBuffer.end () ; it++ )
{
m_rlcSapUser->ReceivePdcpPdu (*it);
}
m_sdusBuffer.clear ();
break;
case (LteRlcHeader::FIRST_BYTE | LteRlcHeader::NO_LAST_BYTE):
m_reassemblingState = WAITING_SI_SF;
/**
* Deliver full PDUs
*/
while ( m_sdusBuffer.size () > 1 )
{
m_rlcSapUser->ReceivePdcpPdu (m_sdusBuffer.front ());
m_sdusBuffer.pop_front ();
}
/**
* Keep S0
*/
m_keepS0 = m_sdusBuffer.front ();
m_sdusBuffer.pop_front ();
break;
case (LteRlcHeader::NO_FIRST_BYTE | LteRlcHeader::LAST_BYTE):
m_reassemblingState = WAITING_S0_FULL;
/**
* Discard SN
*/
m_sdusBuffer.pop_front ();
/**
* Deliver zero, one or multiple PDUs
*/
while ( ! m_sdusBuffer.empty () )
{
m_rlcSapUser->ReceivePdcpPdu (m_sdusBuffer.front ());
m_sdusBuffer.pop_front ();
}
break;
case (LteRlcHeader::NO_FIRST_BYTE | LteRlcHeader::NO_LAST_BYTE):
if ( m_sdusBuffer.size () == 1 )
{
m_reassemblingState = WAITING_S0_FULL;
}
else
{
m_reassemblingState = WAITING_SI_SF;
}
/**
* Discard SI or SN
*/
m_sdusBuffer.pop_front ();
if ( m_sdusBuffer.size () > 0 )
{
/**
* Deliver zero, one or multiple PDUs
*/
while ( m_sdusBuffer.size () > 1 )
{
m_rlcSapUser->ReceivePdcpPdu (m_sdusBuffer.front ());
m_sdusBuffer.pop_front ();
}
/**
* Keep S0
*/
m_keepS0 = m_sdusBuffer.front ();
m_sdusBuffer.pop_front ();
}
break;
default:
/**
* ERROR: Transition not possible
*/
NS_LOG_LOGIC ("INTERNAL ERROR: Transition not possible. FI = " << (uint32_t) framingInfo);
break;
}
break;
case WAITING_SI_SF:
switch (framingInfo)
{
case (LteRlcHeader::FIRST_BYTE | LteRlcHeader::LAST_BYTE):
m_reassemblingState = WAITING_S0_FULL;
/**
* Discard S0
*/
m_keepS0 = 0;
/**
* Deliver one or multiple PDUs
*/
while ( ! m_sdusBuffer.empty () )
{
m_rlcSapUser->ReceivePdcpPdu (m_sdusBuffer.front ());
m_sdusBuffer.pop_front ();
}
break;
case (LteRlcHeader::FIRST_BYTE | LteRlcHeader::NO_LAST_BYTE):
m_reassemblingState = WAITING_SI_SF;
/**
* Discard S0
*/
m_keepS0 = 0;
/**
* Deliver zero, one or multiple PDUs
*/
while ( m_sdusBuffer.size () > 1 )
{
m_rlcSapUser->ReceivePdcpPdu (m_sdusBuffer.front ());
m_sdusBuffer.pop_front ();
}
/**
* Keep S0
*/
m_keepS0 = m_sdusBuffer.front ();
m_sdusBuffer.pop_front ();
break;
case (LteRlcHeader::NO_FIRST_BYTE | LteRlcHeader::LAST_BYTE):
m_reassemblingState = WAITING_S0_FULL;
/**
* Discard S0
*/
m_keepS0 = 0;
/**
* Discard SI or SN
*/
m_sdusBuffer.pop_front ();
/**
* Deliver zero, one or multiple PDUs
*/
while ( ! m_sdusBuffer.empty () )
{
m_rlcSapUser->ReceivePdcpPdu (m_sdusBuffer.front ());
m_sdusBuffer.pop_front ();
}
break;
case (LteRlcHeader::NO_FIRST_BYTE | LteRlcHeader::NO_LAST_BYTE):
if ( m_sdusBuffer.size () == 1 )
{
m_reassemblingState = WAITING_S0_FULL;
}
else
{
m_reassemblingState = WAITING_SI_SF;
}
/**
* Discard S0
*/
m_keepS0 = 0;
/**
* Discard SI or SN
*/
m_sdusBuffer.pop_front ();
if ( m_sdusBuffer.size () > 0 )
{
/**
* Deliver zero, one or multiple PDUs
*/
while ( m_sdusBuffer.size () > 1 )
{
m_rlcSapUser->ReceivePdcpPdu (m_sdusBuffer.front ());
m_sdusBuffer.pop_front ();
}
/**
* Keep S0
*/
m_keepS0 = m_sdusBuffer.front ();
m_sdusBuffer.pop_front ();
}
break;
default:
/**
* ERROR: Transition not possible
*/
NS_LOG_LOGIC ("INTERNAL ERROR: Transition not possible. FI = " << (uint32_t) framingInfo);
break;
}
break;
default:
NS_LOG_LOGIC ("INTERNAL ERROR: Wrong reassembling state = " << (uint32_t) m_reassemblingState);
break;
}
}
}
void
LteRlcUm::ReassembleOutsideWindow (void)
{
NS_LOG_LOGIC ("Reassemble Outside Window");
std::map <uint16_t, Ptr<Packet> >::iterator it;
it = m_rxBuffer.begin ();
while ( (it != m_rxBuffer.end ()) && ! IsInsideReorderingWindow (SequenceNumber10 (it->first)) )
{
NS_LOG_LOGIC ("SN = " << it->first);
// Reassemble RLC SDUs and deliver the PDCP PDU to upper layer
ReassembleAndDeliver (it->second);
std::map <uint16_t, Ptr<Packet> >::iterator it_tmp = it;
++it;
m_rxBuffer.erase (it_tmp);
}
if (it != m_rxBuffer.end ())
{
NS_LOG_LOGIC ("(SN = " << it->first << ") is inside the reordering window");
}
}
void
LteRlcUm::ReassembleSnInterval (SequenceNumber10 lowSeqNumber, SequenceNumber10 highSeqNumber)
{
NS_LOG_LOGIC ("Reassemble SN between " << lowSeqNumber << " and " << highSeqNumber);
std::map <uint16_t, Ptr<Packet> >::iterator it;
SequenceNumber10 reassembleSn = lowSeqNumber;
NS_LOG_LOGIC ("reassembleSN = " << reassembleSn);
NS_LOG_LOGIC ("highSeqNumber = " << highSeqNumber);
while (reassembleSn < highSeqNumber)
{
NS_LOG_LOGIC ("reassembleSn < highSeqNumber");
it = m_rxBuffer.find (reassembleSn.GetValue ());
NS_LOG_LOGIC ("it->first = " << it->first);
NS_LOG_LOGIC ("it->second = " << it->second);
if (it != m_rxBuffer.end () )
{
NS_LOG_LOGIC ("SN = " << it->first);
// Reassemble RLC SDUs and deliver the PDCP PDU to upper layer
ReassembleAndDeliver (it->second);
m_rxBuffer.erase (it);
}
reassembleSn++;
}
}
void
LteRlcUm::DoReportBufferStatus (void)
{
Time holDelay (0);
uint32_t queueSize = 0;
if (! m_txBuffer.empty ())
{
RlcTag holTimeTag;
m_txBuffer.front ()->PeekPacketTag (holTimeTag);
holDelay = Simulator::Now () - holTimeTag.GetSenderTimestamp ();
queueSize = m_txBufferSize + 2 * m_txBuffer.size (); // Data in tx queue + estimated headers size
}
LteMacSapProvider::ReportBufferStatusParameters r;
r.rnti = m_rnti;
r.lcid = m_lcid;
r.txQueueSize = queueSize;
r.txQueueHolDelay = holDelay.GetMilliSeconds () ;
r.retxQueueSize = 0;
r.retxQueueHolDelay = 0;
r.statusPduSize = 0;
NS_LOG_LOGIC ("Send ReportBufferStatus = " << r.txQueueSize << ", " << r.txQueueHolDelay );
m_macSapProvider->ReportBufferStatus (r);
}
void
LteRlcUm::ExpireReorderingTimer (void)
{
NS_LOG_FUNCTION (this << m_rnti << (uint32_t) m_lcid);
NS_LOG_LOGIC ("Reordering timer has expired");
// 5.1.2.2.4 Actions when t-Reordering expires
// When t-Reordering expires, the receiving UM RLC entity shall:
// - update VR(UR) to the SN of the first UMD PDU with SN >= VR(UX) that has not been received;
// - reassemble RLC SDUs from any UMD PDUs with SN < updated VR(UR), remove RLC headers when doing so
// and deliver the reassembled RLC SDUs to upper layer in ascending order of the RLC SN if not delivered before;
// - if VR(UH) > VR(UR):
// - start t-Reordering;
// - set VR(UX) to VR(UH).
std::map <uint16_t, Ptr<Packet> >::iterator it;
SequenceNumber10 newVrUr = m_vrUx;
while ( (it = m_rxBuffer.find (newVrUr.GetValue ())) != m_rxBuffer.end () )
{
newVrUr++;
}
SequenceNumber10 oldVrUr = m_vrUr;
m_vrUr = newVrUr;
NS_LOG_LOGIC ("New VR(UR) = " << m_vrUr);
ReassembleSnInterval (oldVrUr, m_vrUr);
if ( m_vrUh > m_vrUr)
{
NS_LOG_LOGIC ("Start reordering timer");
m_reorderingTimer = Simulator::Schedule (Time ("0.1s"),
&LteRlcUm::ExpireReorderingTimer, this);
m_vrUx = m_vrUh;
NS_LOG_LOGIC ("New VR(UX) = " << m_vrUx);
}
}
void
LteRlcUm::ExpireRbsTimer (void)
{
NS_LOG_LOGIC ("RBS Timer expires");
if (! m_txBuffer.empty ())
{
DoReportBufferStatus ();
m_rbsTimer = Simulator::Schedule (MilliSeconds (10), &LteRlcUm::ExpireRbsTimer, this);
}
}
} // namespace ns3
|
/*
* linux/fs/ext4/super.c
*
* Copyright (C) 1992, 1993, 1994, 1995
* Remy Card (card@masi.ibp.fr)
* Laboratoire MASI - Institut Blaise Pascal
* Universite Pierre et Marie Curie (Paris VI)
*
* from
*
* linux/fs/minix/inode.c
*
* Copyright (C) 1991, 1992 Linus Torvalds
*
* Big-endian to little-endian byte-swapping/bitmaps by
* David S. Miller (davem@caip.rutgers.edu), 1995
*/
#include <linux/module.h>
#include <linux/string.h>
#include <linux/fs.h>
#include <linux/time.h>
#include <linux/vmalloc.h>
#include <linux/jbd2.h>
#include <linux/slab.h>
#include <linux/init.h>
#include <linux/blkdev.h>
#include <linux/parser.h>
#include <linux/buffer_head.h>
#include <linux/exportfs.h>
#include <linux/vfs.h>
#include <linux/random.h>
#include <linux/mount.h>
#include <linux/namei.h>
#include <linux/quotaops.h>
#include <linux/seq_file.h>
#include <linux/proc_fs.h>
#include <linux/ctype.h>
#include <linux/log2.h>
#include <linux/crc16.h>
#include <linux/cleancache.h>
#include <asm/uaccess.h>
#include <linux/kthread.h>
#include <linux/freezer.h>
#include "ext4.h"
#include "ext4_extents.h" /* Needed for trace points definition */
#include "ext4_jbd2.h"
#include "xattr.h"
#include "acl.h"
#include "mballoc.h"
#define CREATE_TRACE_POINTS
#include <trace/events/ext4.h>
static struct proc_dir_entry *ext4_proc_root;
static struct kset *ext4_kset;
static struct ext4_lazy_init *ext4_li_info;
static struct mutex ext4_li_mtx;
static struct ext4_features *ext4_feat;
static int ext4_mballoc_ready;
static int ext4_load_journal(struct super_block *, struct ext4_super_block *,
unsigned long journal_devnum);
static int ext4_show_options(struct seq_file *seq, struct dentry *root);
static int ext4_commit_super(struct super_block *sb, int sync);
static void ext4_mark_recovery_complete(struct super_block *sb,
struct ext4_super_block *es);
static void ext4_clear_journal_err(struct super_block *sb,
struct ext4_super_block *es);
static int ext4_sync_fs(struct super_block *sb, int wait);
static int ext4_remount(struct super_block *sb, int *flags, char *data);
static int ext4_statfs(struct dentry *dentry, struct kstatfs *buf);
static int ext4_unfreeze(struct super_block *sb);
static int ext4_freeze(struct super_block *sb);
static struct dentry *ext4_mount(struct file_system_type *fs_type, int flags,
const char *dev_name, void *data);
static inline int ext2_feature_set_ok(struct super_block *sb);
static inline int ext3_feature_set_ok(struct super_block *sb);
static int ext4_feature_set_ok(struct super_block *sb, int readonly);
static void ext4_destroy_lazyinit_thread(void);
static void ext4_unregister_li_request(struct super_block *sb);
static void ext4_clear_request_list(void);
static int ext4_reserve_clusters(struct ext4_sb_info *, ext4_fsblk_t);
#if !defined(CONFIG_EXT2_FS) && !defined(CONFIG_EXT2_FS_MODULE) && defined(CONFIG_EXT4_USE_FOR_EXT23)
static struct file_system_type ext2_fs_type = {
.owner = THIS_MODULE,
.name = "ext2",
.mount = ext4_mount,
.kill_sb = kill_block_super,
.fs_flags = FS_REQUIRES_DEV,
};
MODULE_ALIAS_FS("ext2");
MODULE_ALIAS("ext2");
#define IS_EXT2_SB(sb) ((sb)->s_bdev->bd_holder == &ext2_fs_type)
#else
#define IS_EXT2_SB(sb) (0)
#endif
#if !defined(CONFIG_EXT3_FS) && !defined(CONFIG_EXT3_FS_MODULE) && defined(CONFIG_EXT4_USE_FOR_EXT23)
static struct file_system_type ext3_fs_type = {
.owner = THIS_MODULE,
.name = "ext3",
.mount = ext4_mount,
.kill_sb = kill_block_super,
.fs_flags = FS_REQUIRES_DEV,
};
MODULE_ALIAS_FS("ext3");
MODULE_ALIAS("ext3");
#define IS_EXT3_SB(sb) ((sb)->s_bdev->bd_holder == &ext3_fs_type)
#else
#define IS_EXT3_SB(sb) (0)
#endif
static int ext4_verify_csum_type(struct super_block *sb,
struct ext4_super_block *es)
{
if (!EXT4_HAS_RO_COMPAT_FEATURE(sb,
EXT4_FEATURE_RO_COMPAT_METADATA_CSUM))
return 1;
return es->s_checksum_type == EXT4_CRC32C_CHKSUM;
}
static __le32 ext4_superblock_csum(struct super_block *sb,
struct ext4_super_block *es)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
int offset = offsetof(struct ext4_super_block, s_checksum);
__u32 csum;
csum = ext4_chksum(sbi, ~0, (char *)es, offset);
return cpu_to_le32(csum);
}
static int ext4_superblock_csum_verify(struct super_block *sb,
struct ext4_super_block *es)
{
if (!ext4_has_metadata_csum(sb))
return 1;
return es->s_checksum == ext4_superblock_csum(sb, es);
}
void ext4_superblock_csum_set(struct super_block *sb)
{
struct ext4_super_block *es = EXT4_SB(sb)->s_es;
if (!ext4_has_metadata_csum(sb))
return;
es->s_checksum = ext4_superblock_csum(sb, es);
}
void *ext4_kvmalloc(size_t size, gfp_t flags)
{
void *ret;
ret = kmalloc(size, flags | __GFP_NOWARN);
if (!ret)
ret = __vmalloc(size, flags, PAGE_KERNEL);
return ret;
}
void *ext4_kvzalloc(size_t size, gfp_t flags)
{
void *ret;
ret = kzalloc(size, flags | __GFP_NOWARN);
if (!ret)
ret = __vmalloc(size, flags | __GFP_ZERO, PAGE_KERNEL);
return ret;
}
void ext4_kvfree(void *ptr)
{
if (is_vmalloc_addr(ptr))
vfree(ptr);
else
kfree(ptr);
}
ext4_fsblk_t ext4_block_bitmap(struct super_block *sb,
struct ext4_group_desc *bg)
{
return le32_to_cpu(bg->bg_block_bitmap_lo) |
(EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT ?
(ext4_fsblk_t)le32_to_cpu(bg->bg_block_bitmap_hi) << 32 : 0);
}
ext4_fsblk_t ext4_inode_bitmap(struct super_block *sb,
struct ext4_group_desc *bg)
{
return le32_to_cpu(bg->bg_inode_bitmap_lo) |
(EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT ?
(ext4_fsblk_t)le32_to_cpu(bg->bg_inode_bitmap_hi) << 32 : 0);
}
ext4_fsblk_t ext4_inode_table(struct super_block *sb,
struct ext4_group_desc *bg)
{
return le32_to_cpu(bg->bg_inode_table_lo) |
(EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT ?
(ext4_fsblk_t)le32_to_cpu(bg->bg_inode_table_hi) << 32 : 0);
}
__u32 ext4_free_group_clusters(struct super_block *sb,
struct ext4_group_desc *bg)
{
return le16_to_cpu(bg->bg_free_blocks_count_lo) |
(EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT ?
(__u32)le16_to_cpu(bg->bg_free_blocks_count_hi) << 16 : 0);
}
__u32 ext4_free_inodes_count(struct super_block *sb,
struct ext4_group_desc *bg)
{
return le16_to_cpu(bg->bg_free_inodes_count_lo) |
(EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT ?
(__u32)le16_to_cpu(bg->bg_free_inodes_count_hi) << 16 : 0);
}
__u32 ext4_used_dirs_count(struct super_block *sb,
struct ext4_group_desc *bg)
{
return le16_to_cpu(bg->bg_used_dirs_count_lo) |
(EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT ?
(__u32)le16_to_cpu(bg->bg_used_dirs_count_hi) << 16 : 0);
}
__u32 ext4_itable_unused_count(struct super_block *sb,
struct ext4_group_desc *bg)
{
return le16_to_cpu(bg->bg_itable_unused_lo) |
(EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT ?
(__u32)le16_to_cpu(bg->bg_itable_unused_hi) << 16 : 0);
}
void ext4_block_bitmap_set(struct super_block *sb,
struct ext4_group_desc *bg, ext4_fsblk_t blk)
{
bg->bg_block_bitmap_lo = cpu_to_le32((u32)blk);
if (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT)
bg->bg_block_bitmap_hi = cpu_to_le32(blk >> 32);
}
void ext4_inode_bitmap_set(struct super_block *sb,
struct ext4_group_desc *bg, ext4_fsblk_t blk)
{
bg->bg_inode_bitmap_lo = cpu_to_le32((u32)blk);
if (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT)
bg->bg_inode_bitmap_hi = cpu_to_le32(blk >> 32);
}
void ext4_inode_table_set(struct super_block *sb,
struct ext4_group_desc *bg, ext4_fsblk_t blk)
{
bg->bg_inode_table_lo = cpu_to_le32((u32)blk);
if (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT)
bg->bg_inode_table_hi = cpu_to_le32(blk >> 32);
}
void ext4_free_group_clusters_set(struct super_block *sb,
struct ext4_group_desc *bg, __u32 count)
{
bg->bg_free_blocks_count_lo = cpu_to_le16((__u16)count);
if (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT)
bg->bg_free_blocks_count_hi = cpu_to_le16(count >> 16);
}
void ext4_free_inodes_set(struct super_block *sb,
struct ext4_group_desc *bg, __u32 count)
{
bg->bg_free_inodes_count_lo = cpu_to_le16((__u16)count);
if (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT)
bg->bg_free_inodes_count_hi = cpu_to_le16(count >> 16);
}
void ext4_used_dirs_set(struct super_block *sb,
struct ext4_group_desc *bg, __u32 count)
{
bg->bg_used_dirs_count_lo = cpu_to_le16((__u16)count);
if (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT)
bg->bg_used_dirs_count_hi = cpu_to_le16(count >> 16);
}
void ext4_itable_unused_set(struct super_block *sb,
struct ext4_group_desc *bg, __u32 count)
{
bg->bg_itable_unused_lo = cpu_to_le16((__u16)count);
if (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT)
bg->bg_itable_unused_hi = cpu_to_le16(count >> 16);
}
static void __save_error_info(struct super_block *sb, const char *func,
unsigned int line)
{
struct ext4_super_block *es = EXT4_SB(sb)->s_es;
EXT4_SB(sb)->s_mount_state |= EXT4_ERROR_FS;
es->s_state |= cpu_to_le16(EXT4_ERROR_FS);
es->s_last_error_time = cpu_to_le32(get_seconds());
strncpy(es->s_last_error_func, func, sizeof(es->s_last_error_func));
es->s_last_error_line = cpu_to_le32(line);
if (!es->s_first_error_time) {
es->s_first_error_time = es->s_last_error_time;
strncpy(es->s_first_error_func, func,
sizeof(es->s_first_error_func));
es->s_first_error_line = cpu_to_le32(line);
es->s_first_error_ino = es->s_last_error_ino;
es->s_first_error_block = es->s_last_error_block;
}
/*
* Start the daily error reporting function if it hasn't been
* started already
*/
if (!es->s_error_count)
mod_timer(&EXT4_SB(sb)->s_err_report, jiffies + 24*60*60*HZ);
le32_add_cpu(&es->s_error_count, 1);
}
static void save_error_info(struct super_block *sb, const char *func,
unsigned int line)
{
__save_error_info(sb, func, line);
ext4_commit_super(sb, 1);
}
/*
* The del_gendisk() function uninitializes the disk-specific data
* structures, including the bdi structure, without telling anyone
* else. Once this happens, any attempt to call mark_buffer_dirty()
* (for example, by ext4_commit_super), will cause a kernel OOPS.
* This is a kludge to prevent these oops until we can put in a proper
* hook in del_gendisk() to inform the VFS and file system layers.
*/
static int block_device_ejected(struct super_block *sb)
{
struct inode *bd_inode = sb->s_bdev->bd_inode;
struct backing_dev_info *bdi = bd_inode->i_mapping->backing_dev_info;
return bdi->dev == NULL;
}
static void ext4_journal_commit_callback(journal_t *journal, transaction_t *txn)
{
struct super_block *sb = journal->j_private;
struct ext4_sb_info *sbi = EXT4_SB(sb);
int error = is_journal_aborted(journal);
struct ext4_journal_cb_entry *jce;
BUG_ON(txn->t_state == T_FINISHED);
spin_lock(&sbi->s_md_lock);
while (!list_empty(&txn->t_private_list)) {
jce = list_entry(txn->t_private_list.next,
struct ext4_journal_cb_entry, jce_list);
list_del_init(&jce->jce_list);
spin_unlock(&sbi->s_md_lock);
jce->jce_func(sb, jce, error);
spin_lock(&sbi->s_md_lock);
}
spin_unlock(&sbi->s_md_lock);
}
/* Deal with the reporting of failure conditions on a filesystem such as
* inconsistencies detected or read IO failures.
*
* On ext2, we can store the error state of the filesystem in the
* superblock. That is not possible on ext4, because we may have other
* write ordering constraints on the superblock which prevent us from
* writing it out straight away; and given that the journal is about to
* be aborted, we can't rely on the current, or future, transactions to
* write out the superblock safely.
*
* We'll just use the jbd2_journal_abort() error code to record an error in
* the journal instead. On recovery, the journal will complain about
* that error until we've noted it down and cleared it.
*/
static void ext4_handle_error(struct super_block *sb)
{
if (sb->s_flags & MS_RDONLY)
return;
if (!test_opt(sb, ERRORS_CONT)) {
journal_t *journal = EXT4_SB(sb)->s_journal;
EXT4_SB(sb)->s_mount_flags |= EXT4_MF_FS_ABORTED;
if (journal)
jbd2_journal_abort(journal, -EIO);
}
if (test_opt(sb, ERRORS_RO)) {
ext4_msg(sb, KERN_CRIT, "Remounting filesystem read-only");
/*
* Make sure updated value of ->s_mount_flags will be visible
* before ->s_flags update
*/
smp_wmb();
sb->s_flags |= MS_RDONLY;
}
if (test_opt(sb, ERRORS_PANIC))
panic("EXT4-fs (device %s): panic forced after error\n",
sb->s_id);
}
#define ext4_error_ratelimit(sb) \
___ratelimit(&(EXT4_SB(sb)->s_err_ratelimit_state), \
"EXT4-fs error")
void __ext4_error(struct super_block *sb, const char *function,
unsigned int line, const char *fmt, ...)
{
struct va_format vaf;
va_list args;
if (ext4_error_ratelimit(sb)) {
va_start(args, fmt);
vaf.fmt = fmt;
vaf.va = &args;
printk(KERN_CRIT
"EXT4-fs error (device %s): %s:%d: comm %s: %pV\n",
sb->s_id, function, line, current->comm, &vaf);
va_end(args);
}
save_error_info(sb, function, line);
ext4_handle_error(sb);
}
void __ext4_error_inode(struct inode *inode, const char *function,
unsigned int line, ext4_fsblk_t block,
const char *fmt, ...)
{
va_list args;
struct va_format vaf;
struct ext4_super_block *es = EXT4_SB(inode->i_sb)->s_es;
es->s_last_error_ino = cpu_to_le32(inode->i_ino);
es->s_last_error_block = cpu_to_le64(block);
if (ext4_error_ratelimit(inode->i_sb)) {
va_start(args, fmt);
vaf.fmt = fmt;
vaf.va = &args;
if (block)
printk(KERN_CRIT "EXT4-fs error (device %s): %s:%d: "
"inode #%lu: block %llu: comm %s: %pV\n",
inode->i_sb->s_id, function, line, inode->i_ino,
block, current->comm, &vaf);
else
printk(KERN_CRIT "EXT4-fs error (device %s): %s:%d: "
"inode #%lu: comm %s: %pV\n",
inode->i_sb->s_id, function, line, inode->i_ino,
current->comm, &vaf);
va_end(args);
}
save_error_info(inode->i_sb, function, line);
ext4_handle_error(inode->i_sb);
}
void __ext4_error_file(struct file *file, const char *function,
unsigned int line, ext4_fsblk_t block,
const char *fmt, ...)
{
va_list args;
struct va_format vaf;
struct ext4_super_block *es;
struct inode *inode = file_inode(file);
char pathname[80], *path;
es = EXT4_SB(inode->i_sb)->s_es;
es->s_last_error_ino = cpu_to_le32(inode->i_ino);
if (ext4_error_ratelimit(inode->i_sb)) {
path = d_path(&(file->f_path), pathname, sizeof(pathname));
if (IS_ERR(path))
path = "(unknown)";
va_start(args, fmt);
vaf.fmt = fmt;
vaf.va = &args;
if (block)
printk(KERN_CRIT
"EXT4-fs error (device %s): %s:%d: inode #%lu: "
"block %llu: comm %s: path %s: %pV\n",
inode->i_sb->s_id, function, line, inode->i_ino,
block, current->comm, path, &vaf);
else
printk(KERN_CRIT
"EXT4-fs error (device %s): %s:%d: inode #%lu: "
"comm %s: path %s: %pV\n",
inode->i_sb->s_id, function, line, inode->i_ino,
current->comm, path, &vaf);
va_end(args);
}
save_error_info(inode->i_sb, function, line);
ext4_handle_error(inode->i_sb);
}
const char *ext4_decode_error(struct super_block *sb, int errno,
char nbuf[16])
{
char *errstr = NULL;
switch (errno) {
case -EIO:
errstr = "IO failure";
break;
case -ENOMEM:
errstr = "Out of memory";
break;
case -EROFS:
if (!sb || (EXT4_SB(sb)->s_journal &&
EXT4_SB(sb)->s_journal->j_flags & JBD2_ABORT))
errstr = "Journal has aborted";
else
errstr = "Readonly filesystem";
break;
default:
/* If the caller passed in an extra buffer for unknown
* errors, textualise them now. Else we just return
* NULL. */
if (nbuf) {
/* Check for truncated error codes... */
if (snprintf(nbuf, 16, "error %d", -errno) >= 0)
errstr = nbuf;
}
break;
}
return errstr;
}
/* __ext4_std_error decodes expected errors from journaling functions
* automatically and invokes the appropriate error response. */
void __ext4_std_error(struct super_block *sb, const char *function,
unsigned int line, int errno)
{
char nbuf[16];
const char *errstr;
/* Special case: if the error is EROFS, and we're not already
* inside a transaction, then there's really no point in logging
* an error. */
if (errno == -EROFS && journal_current_handle() == NULL &&
(sb->s_flags & MS_RDONLY))
return;
if (ext4_error_ratelimit(sb)) {
errstr = ext4_decode_error(sb, errno, nbuf);
printk(KERN_CRIT "EXT4-fs error (device %s) in %s:%d: %s\n",
sb->s_id, function, line, errstr);
}
save_error_info(sb, function, line);
ext4_handle_error(sb);
}
/*
* ext4_abort is a much stronger failure handler than ext4_error. The
* abort function may be used to deal with unrecoverable failures such
* as journal IO errors or ENOMEM at a critical moment in log management.
*
* We unconditionally force the filesystem into an ABORT|READONLY state,
* unless the error response on the fs has been set to panic in which
* case we take the easy way out and panic immediately.
*/
void __ext4_abort(struct super_block *sb, const char *function,
unsigned int line, const char *fmt, ...)
{
va_list args;
save_error_info(sb, function, line);
va_start(args, fmt);
printk(KERN_CRIT "EXT4-fs error (device %s): %s:%d: ", sb->s_id,
function, line);
vprintk(fmt, args);
printk("\n");
va_end(args);
if ((sb->s_flags & MS_RDONLY) == 0) {
ext4_msg(sb, KERN_CRIT, "Remounting filesystem read-only");
EXT4_SB(sb)->s_mount_flags |= EXT4_MF_FS_ABORTED;
/*
* Make sure updated value of ->s_mount_flags will be visible
* before ->s_flags update
*/
smp_wmb();
sb->s_flags |= MS_RDONLY;
if (EXT4_SB(sb)->s_journal)
jbd2_journal_abort(EXT4_SB(sb)->s_journal, -EIO);
save_error_info(sb, function, line);
}
if (test_opt(sb, ERRORS_PANIC))
panic("EXT4-fs panic from previous error\n");
}
void __ext4_msg(struct super_block *sb,
const char *prefix, const char *fmt, ...)
{
struct va_format vaf;
va_list args;
if (!___ratelimit(&(EXT4_SB(sb)->s_msg_ratelimit_state), "EXT4-fs"))
return;
va_start(args, fmt);
vaf.fmt = fmt;
vaf.va = &args;
printk("%sEXT4-fs (%s): %pV\n", prefix, sb->s_id, &vaf);
va_end(args);
}
void __ext4_warning(struct super_block *sb, const char *function,
unsigned int line, const char *fmt, ...)
{
struct va_format vaf;
va_list args;
if (!___ratelimit(&(EXT4_SB(sb)->s_warning_ratelimit_state),
"EXT4-fs warning"))
return;
va_start(args, fmt);
vaf.fmt = fmt;
vaf.va = &args;
printk(KERN_WARNING "EXT4-fs warning (device %s): %s:%d: %pV\n",
sb->s_id, function, line, &vaf);
va_end(args);
}
void __ext4_grp_locked_error(const char *function, unsigned int line,
struct super_block *sb, ext4_group_t grp,
unsigned long ino, ext4_fsblk_t block,
const char *fmt, ...)
__releases(bitlock)
__acquires(bitlock)
{
struct va_format vaf;
va_list args;
struct ext4_super_block *es = EXT4_SB(sb)->s_es;
es->s_last_error_ino = cpu_to_le32(ino);
es->s_last_error_block = cpu_to_le64(block);
__save_error_info(sb, function, line);
if (ext4_error_ratelimit(sb)) {
va_start(args, fmt);
vaf.fmt = fmt;
vaf.va = &args;
printk(KERN_CRIT "EXT4-fs error (device %s): %s:%d: group %u, ",
sb->s_id, function, line, grp);
if (ino)
printk(KERN_CONT "inode %lu: ", ino);
if (block)
printk(KERN_CONT "block %llu:",
(unsigned long long) block);
printk(KERN_CONT "%pV\n", &vaf);
va_end(args);
}
if (test_opt(sb, ERRORS_CONT)) {
ext4_commit_super(sb, 0);
return;
}
ext4_unlock_group(sb, grp);
ext4_handle_error(sb);
/*
* We only get here in the ERRORS_RO case; relocking the group
* may be dangerous, but nothing bad will happen since the
* filesystem will have already been marked read/only and the
* journal has been aborted. We return 1 as a hint to callers
* who might what to use the return value from
* ext4_grp_locked_error() to distinguish between the
* ERRORS_CONT and ERRORS_RO case, and perhaps return more
* aggressively from the ext4 function in question, with a
* more appropriate error code.
*/
ext4_lock_group(sb, grp);
return;
}
void ext4_update_dynamic_rev(struct super_block *sb)
{
struct ext4_super_block *es = EXT4_SB(sb)->s_es;
if (le32_to_cpu(es->s_rev_level) > EXT4_GOOD_OLD_REV)
return;
ext4_warning(sb,
"updating to rev %d because of new feature flag, "
"running e2fsck is recommended",
EXT4_DYNAMIC_REV);
es->s_first_ino = cpu_to_le32(EXT4_GOOD_OLD_FIRST_INO);
es->s_inode_size = cpu_to_le16(EXT4_GOOD_OLD_INODE_SIZE);
es->s_rev_level = cpu_to_le32(EXT4_DYNAMIC_REV);
/* leave es->s_feature_*compat flags alone */
/* es->s_uuid will be set by e2fsck if empty */
/*
* The rest of the superblock fields should be zero, and if not it
* means they are likely already in use, so leave them alone. We
* can leave it up to e2fsck to clean up any inconsistencies there.
*/
}
/*
* Open the external journal device
*/
static struct block_device *ext4_blkdev_get(dev_t dev, struct super_block *sb)
{
struct block_device *bdev;
char b[BDEVNAME_SIZE];
bdev = blkdev_get_by_dev(dev, FMODE_READ|FMODE_WRITE|FMODE_EXCL, sb);
if (IS_ERR(bdev))
goto fail;
return bdev;
fail:
ext4_msg(sb, KERN_ERR, "failed to open journal device %s: %ld",
__bdevname(dev, b), PTR_ERR(bdev));
return NULL;
}
/*
* Release the journal device
*/
static void ext4_blkdev_put(struct block_device *bdev)
{
blkdev_put(bdev, FMODE_READ|FMODE_WRITE|FMODE_EXCL);
}
static void ext4_blkdev_remove(struct ext4_sb_info *sbi)
{
struct block_device *bdev;
bdev = sbi->journal_bdev;
if (bdev) {
ext4_blkdev_put(bdev);
sbi->journal_bdev = NULL;
}
}
static inline struct inode *orphan_list_entry(struct list_head *l)
{
return &list_entry(l, struct ext4_inode_info, i_orphan)->vfs_inode;
}
static void dump_orphan_list(struct super_block *sb, struct ext4_sb_info *sbi)
{
struct list_head *l;
ext4_msg(sb, KERN_ERR, "sb orphan head is %d",
le32_to_cpu(sbi->s_es->s_last_orphan));
printk(KERN_ERR "sb_info orphan list:\n");
list_for_each(l, &sbi->s_orphan) {
struct inode *inode = orphan_list_entry(l);
printk(KERN_ERR " "
"inode %s:%lu at %p: mode %o, nlink %d, next %d\n",
inode->i_sb->s_id, inode->i_ino, inode,
inode->i_mode, inode->i_nlink,
NEXT_ORPHAN(inode));
}
}
static void ext4_put_super(struct super_block *sb)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
struct ext4_super_block *es = sbi->s_es;
int i, err;
ext4_unregister_li_request(sb);
dquot_disable(sb, -1, DQUOT_USAGE_ENABLED | DQUOT_LIMITS_ENABLED);
flush_workqueue(sbi->rsv_conversion_wq);
destroy_workqueue(sbi->rsv_conversion_wq);
if (sbi->s_journal) {
err = jbd2_journal_destroy(sbi->s_journal);
sbi->s_journal = NULL;
if (err < 0)
ext4_abort(sb, "Couldn't clean up the journal");
}
ext4_es_unregister_shrinker(sbi);
del_timer_sync(&sbi->s_err_report);
ext4_release_system_zone(sb);
ext4_mb_release(sb);
ext4_ext_release(sb);
ext4_xattr_put_super(sb);
if (!(sb->s_flags & MS_RDONLY)) {
EXT4_CLEAR_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_RECOVER);
es->s_state = cpu_to_le16(sbi->s_mount_state);
}
if (!(sb->s_flags & MS_RDONLY))
ext4_commit_super(sb, 1);
if (sbi->s_proc) {
remove_proc_entry("options", sbi->s_proc);
remove_proc_entry(sb->s_id, ext4_proc_root);
}
kobject_del(&sbi->s_kobj);
for (i = 0; i < sbi->s_gdb_count; i++)
brelse(sbi->s_group_desc[i]);
ext4_kvfree(sbi->s_group_desc);
ext4_kvfree(sbi->s_flex_groups);
percpu_counter_destroy(&sbi->s_freeclusters_counter);
percpu_counter_destroy(&sbi->s_freeinodes_counter);
percpu_counter_destroy(&sbi->s_dirs_counter);
percpu_counter_destroy(&sbi->s_dirtyclusters_counter);
brelse(sbi->s_sbh);
#ifdef CONFIG_QUOTA
for (i = 0; i < EXT4_MAXQUOTAS; i++)
kfree(sbi->s_qf_names[i]);
#endif
/* Debugging code just in case the in-memory inode orphan list
* isn't empty. The on-disk one can be non-empty if we've
* detected an error and taken the fs readonly, but the
* in-memory list had better be clean by this point. */
if (!list_empty(&sbi->s_orphan))
dump_orphan_list(sb, sbi);
J_ASSERT(list_empty(&sbi->s_orphan));
invalidate_bdev(sb->s_bdev);
if (sbi->journal_bdev && sbi->journal_bdev != sb->s_bdev) {
/*
* Invalidate the journal device's buffers. We don't want them
* floating about in memory - the physical journal device may
* hotswapped, and it breaks the `ro-after' testing code.
*/
sync_blockdev(sbi->journal_bdev);
invalidate_bdev(sbi->journal_bdev);
ext4_blkdev_remove(sbi);
}
if (sbi->s_mb_cache) {
ext4_xattr_destroy_cache(sbi->s_mb_cache);
sbi->s_mb_cache = NULL;
}
if (sbi->s_mmp_tsk)
kthread_stop(sbi->s_mmp_tsk);
sb->s_fs_info = NULL;
/*
* Now that we are completely done shutting down the
* superblock, we need to actually destroy the kobject.
*/
kobject_put(&sbi->s_kobj);
wait_for_completion(&sbi->s_kobj_unregister);
if (sbi->s_chksum_driver)
crypto_free_shash(sbi->s_chksum_driver);
kfree(sbi->s_blockgroup_lock);
kfree(sbi);
}
static struct kmem_cache *ext4_inode_cachep;
/*
* Called inside transaction, so use GFP_NOFS
*/
static struct inode *ext4_alloc_inode(struct super_block *sb)
{
struct ext4_inode_info *ei;
ei = kmem_cache_alloc(ext4_inode_cachep, GFP_NOFS);
if (!ei)
return NULL;
ei->vfs_inode.i_version = 1;
spin_lock_init(&ei->i_raw_lock);
INIT_LIST_HEAD(&ei->i_prealloc_list);
spin_lock_init(&ei->i_prealloc_lock);
ext4_es_init_tree(&ei->i_es_tree);
rwlock_init(&ei->i_es_lock);
INIT_LIST_HEAD(&ei->i_es_lru);
ei->i_es_all_nr = 0;
ei->i_es_lru_nr = 0;
ei->i_touch_when = 0;
ei->i_reserved_data_blocks = 0;
ei->i_reserved_meta_blocks = 0;
ei->i_allocated_meta_blocks = 0;
ei->i_da_metadata_calc_len = 0;
ei->i_da_metadata_calc_last_lblock = 0;
spin_lock_init(&(ei->i_block_reservation_lock));
#ifdef CONFIG_QUOTA
ei->i_reserved_quota = 0;
#endif
ei->jinode = NULL;
INIT_LIST_HEAD(&ei->i_rsv_conversion_list);
spin_lock_init(&ei->i_completed_io_lock);
ei->i_sync_tid = 0;
ei->i_datasync_tid = 0;
atomic_set(&ei->i_ioend_count, 0);
atomic_set(&ei->i_unwritten, 0);
INIT_WORK(&ei->i_rsv_conversion_work, ext4_end_io_rsv_work);
#ifdef CONFIG_EXT4_FS_ENCRYPTION
ei->i_crypt_info = NULL;
#endif
return &ei->vfs_inode;
}
static int ext4_drop_inode(struct inode *inode)
{
int drop = generic_drop_inode(inode);
trace_ext4_drop_inode(inode, drop);
return drop;
}
static void ext4_i_callback(struct rcu_head *head)
{
struct inode *inode = container_of(head, struct inode, i_rcu);
kmem_cache_free(ext4_inode_cachep, EXT4_I(inode));
}
static void ext4_destroy_inode(struct inode *inode)
{
if (!list_empty(&(EXT4_I(inode)->i_orphan))) {
ext4_msg(inode->i_sb, KERN_ERR,
"Inode %lu (%p): orphan list check failed!",
inode->i_ino, EXT4_I(inode));
print_hex_dump(KERN_INFO, "", DUMP_PREFIX_ADDRESS, 16, 4,
EXT4_I(inode), sizeof(struct ext4_inode_info),
true);
dump_stack();
}
call_rcu(&inode->i_rcu, ext4_i_callback);
}
static void init_once(void *foo)
{
struct ext4_inode_info *ei = (struct ext4_inode_info *) foo;
INIT_LIST_HEAD(&ei->i_orphan);
init_rwsem(&ei->xattr_sem);
init_rwsem(&ei->i_data_sem);
inode_init_once(&ei->vfs_inode);
}
static int __init init_inodecache(void)
{
ext4_inode_cachep = kmem_cache_create("ext4_inode_cache",
sizeof(struct ext4_inode_info),
0, (SLAB_RECLAIM_ACCOUNT|
SLAB_MEM_SPREAD),
init_once);
if (ext4_inode_cachep == NULL)
return -ENOMEM;
return 0;
}
static void destroy_inodecache(void)
{
/*
* Make sure all delayed rcu free inodes are flushed before we
* destroy cache.
*/
rcu_barrier();
kmem_cache_destroy(ext4_inode_cachep);
}
void ext4_clear_inode(struct inode *inode)
{
invalidate_inode_buffers(inode);
clear_inode(inode);
dquot_drop(inode);
ext4_discard_preallocations(inode);
ext4_es_remove_extent(inode, 0, EXT_MAX_BLOCKS);
ext4_es_lru_del(inode);
if (EXT4_I(inode)->jinode) {
jbd2_journal_release_jbd_inode(EXT4_JOURNAL(inode),
EXT4_I(inode)->jinode);
jbd2_free_inode(EXT4_I(inode)->jinode);
EXT4_I(inode)->jinode = NULL;
}
#ifdef CONFIG_EXT4_FS_ENCRYPTION
if (EXT4_I(inode)->i_crypt_info)
ext4_free_encryption_info(inode, EXT4_I(inode)->i_crypt_info);
#endif
}
static struct inode *ext4_nfs_get_inode(struct super_block *sb,
u64 ino, u32 generation)
{
struct inode *inode;
if (ino < EXT4_FIRST_INO(sb) && ino != EXT4_ROOT_INO)
return ERR_PTR(-ESTALE);
if (ino > le32_to_cpu(EXT4_SB(sb)->s_es->s_inodes_count))
return ERR_PTR(-ESTALE);
/* iget isn't really right if the inode is currently unallocated!!
*
* ext4_read_inode will return a bad_inode if the inode had been
* deleted, so we should be safe.
*
* Currently we don't know the generation for parent directory, so
* a generation of 0 means "accept any"
*/
inode = ext4_iget_normal(sb, ino);
if (IS_ERR(inode))
return ERR_CAST(inode);
if (generation && inode->i_generation != generation) {
iput(inode);
return ERR_PTR(-ESTALE);
}
return inode;
}
static struct dentry *ext4_fh_to_dentry(struct super_block *sb, struct fid *fid,
int fh_len, int fh_type)
{
return generic_fh_to_dentry(sb, fid, fh_len, fh_type,
ext4_nfs_get_inode);
}
static struct dentry *ext4_fh_to_parent(struct super_block *sb, struct fid *fid,
int fh_len, int fh_type)
{
return generic_fh_to_parent(sb, fid, fh_len, fh_type,
ext4_nfs_get_inode);
}
/*
* Try to release metadata pages (indirect blocks, directories) which are
* mapped via the block device. Since these pages could have journal heads
* which would prevent try_to_free_buffers() from freeing them, we must use
* jbd2 layer's try_to_free_buffers() function to release them.
*/
static int bdev_try_to_free_page(struct super_block *sb, struct page *page,
gfp_t wait)
{
journal_t *journal = EXT4_SB(sb)->s_journal;
WARN_ON(PageChecked(page));
if (!page_has_buffers(page))
return 0;
if (journal)
return jbd2_journal_try_to_free_buffers(journal, page,
wait & ~__GFP_WAIT);
return try_to_free_buffers(page);
}
#ifdef CONFIG_QUOTA
#define QTYPE2NAME(t) ((t) == USRQUOTA ? "user" : "group")
#define QTYPE2MOPT(on, t) ((t) == USRQUOTA?((on)##USRJQUOTA):((on)##GRPJQUOTA))
static int ext4_write_dquot(struct dquot *dquot);
static int ext4_acquire_dquot(struct dquot *dquot);
static int ext4_release_dquot(struct dquot *dquot);
static int ext4_mark_dquot_dirty(struct dquot *dquot);
static int ext4_write_info(struct super_block *sb, int type);
static int ext4_quota_on(struct super_block *sb, int type, int format_id,
struct path *path);
static int ext4_quota_on_sysfile(struct super_block *sb, int type,
int format_id);
static int ext4_quota_off(struct super_block *sb, int type);
static int ext4_quota_off_sysfile(struct super_block *sb, int type);
static int ext4_quota_on_mount(struct super_block *sb, int type);
static ssize_t ext4_quota_read(struct super_block *sb, int type, char *data,
size_t len, loff_t off);
static ssize_t ext4_quota_write(struct super_block *sb, int type,
const char *data, size_t len, loff_t off);
static int ext4_quota_enable(struct super_block *sb, int type, int format_id,
unsigned int flags);
static int ext4_enable_quotas(struct super_block *sb);
static const struct dquot_operations ext4_quota_operations = {
.get_reserved_space = ext4_get_reserved_space,
.write_dquot = ext4_write_dquot,
.acquire_dquot = ext4_acquire_dquot,
.release_dquot = ext4_release_dquot,
.mark_dirty = ext4_mark_dquot_dirty,
.write_info = ext4_write_info,
.alloc_dquot = dquot_alloc,
.destroy_dquot = dquot_destroy,
};
static const struct quotactl_ops ext4_qctl_operations = {
.quota_on = ext4_quota_on,
.quota_off = ext4_quota_off,
.quota_sync = dquot_quota_sync,
.get_info = dquot_get_dqinfo,
.set_info = dquot_set_dqinfo,
.get_dqblk = dquot_get_dqblk,
.set_dqblk = dquot_set_dqblk
};
static const struct quotactl_ops ext4_qctl_sysfile_operations = {
.quota_on_meta = ext4_quota_on_sysfile,
.quota_off = ext4_quota_off_sysfile,
.quota_sync = dquot_quota_sync,
.get_info = dquot_get_dqinfo,
.set_info = dquot_set_dqinfo,
.get_dqblk = dquot_get_dqblk,
.set_dqblk = dquot_set_dqblk
};
#endif
static const struct super_operations ext4_sops = {
.alloc_inode = ext4_alloc_inode,
.destroy_inode = ext4_destroy_inode,
.write_inode = ext4_write_inode,
.dirty_inode = ext4_dirty_inode,
.drop_inode = ext4_drop_inode,
.evict_inode = ext4_evict_inode,
.put_super = ext4_put_super,
.sync_fs = ext4_sync_fs,
.freeze_fs = ext4_freeze,
.unfreeze_fs = ext4_unfreeze,
.statfs = ext4_statfs,
.remount_fs = ext4_remount,
.show_options = ext4_show_options,
#ifdef CONFIG_QUOTA
.quota_read = ext4_quota_read,
.quota_write = ext4_quota_write,
#endif
.bdev_try_to_free_page = bdev_try_to_free_page,
};
static const struct export_operations ext4_export_ops = {
.fh_to_dentry = ext4_fh_to_dentry,
.fh_to_parent = ext4_fh_to_parent,
.get_parent = ext4_get_parent,
};
enum {
Opt_bsd_df, Opt_minix_df, Opt_grpid, Opt_nogrpid,
Opt_resgid, Opt_resuid, Opt_sb, Opt_err_cont, Opt_err_panic, Opt_err_ro,
Opt_nouid32, Opt_debug, Opt_removed,
Opt_user_xattr, Opt_nouser_xattr, Opt_acl, Opt_noacl,
Opt_auto_da_alloc, Opt_noauto_da_alloc, Opt_noload,
Opt_commit, Opt_min_batch_time, Opt_max_batch_time, Opt_journal_dev,
Opt_journal_path, Opt_journal_checksum, Opt_journal_async_commit,
Opt_abort, Opt_data_journal, Opt_data_ordered, Opt_data_writeback,
Opt_data_err_abort, Opt_data_err_ignore, Opt_test_dummy_encryption,
Opt_usrjquota, Opt_grpjquota, Opt_offusrjquota, Opt_offgrpjquota,
Opt_jqfmt_vfsold, Opt_jqfmt_vfsv0, Opt_jqfmt_vfsv1, Opt_quota,
Opt_noquota, Opt_barrier, Opt_nobarrier, Opt_err,
Opt_usrquota, Opt_grpquota, Opt_i_version,
Opt_stripe, Opt_delalloc, Opt_nodelalloc, Opt_mblk_io_submit,
Opt_nomblk_io_submit, Opt_block_validity, Opt_noblock_validity,
Opt_inode_readahead_blks, Opt_journal_ioprio,
Opt_dioread_nolock, Opt_dioread_lock,
Opt_discard, Opt_nodiscard, Opt_init_itable, Opt_noinit_itable,
Opt_max_dir_size_kb,
};
static const match_table_t tokens = {
{Opt_bsd_df, "bsddf"},
{Opt_minix_df, "minixdf"},
{Opt_grpid, "grpid"},
{Opt_grpid, "bsdgroups"},
{Opt_nogrpid, "nogrpid"},
{Opt_nogrpid, "sysvgroups"},
{Opt_resgid, "resgid=%u"},
{Opt_resuid, "resuid=%u"},
{Opt_sb, "sb=%u"},
{Opt_err_cont, "errors=continue"},
{Opt_err_panic, "errors=panic"},
{Opt_err_ro, "errors=remount-ro"},
{Opt_nouid32, "nouid32"},
{Opt_debug, "debug"},
{Opt_removed, "oldalloc"},
{Opt_removed, "orlov"},
{Opt_user_xattr, "user_xattr"},
{Opt_nouser_xattr, "nouser_xattr"},
{Opt_acl, "acl"},
{Opt_noacl, "noacl"},
{Opt_noload, "norecovery"},
{Opt_noload, "noload"},
{Opt_removed, "nobh"},
{Opt_removed, "bh"},
{Opt_commit, "commit=%u"},
{Opt_min_batch_time, "min_batch_time=%u"},
{Opt_max_batch_time, "max_batch_time=%u"},
{Opt_journal_dev, "journal_dev=%u"},
{Opt_journal_path, "journal_path=%s"},
{Opt_journal_checksum, "journal_checksum"},
{Opt_journal_async_commit, "journal_async_commit"},
{Opt_abort, "abort"},
{Opt_data_journal, "data=journal"},
{Opt_data_ordered, "data=ordered"},
{Opt_data_writeback, "data=writeback"},
{Opt_data_err_abort, "data_err=abort"},
{Opt_data_err_ignore, "data_err=ignore"},
{Opt_offusrjquota, "usrjquota="},
{Opt_usrjquota, "usrjquota=%s"},
{Opt_offgrpjquota, "grpjquota="},
{Opt_grpjquota, "grpjquota=%s"},
{Opt_jqfmt_vfsold, "jqfmt=vfsold"},
{Opt_jqfmt_vfsv0, "jqfmt=vfsv0"},
{Opt_jqfmt_vfsv1, "jqfmt=vfsv1"},
{Opt_grpquota, "grpquota"},
{Opt_noquota, "noquota"},
{Opt_quota, "quota"},
{Opt_usrquota, "usrquota"},
{Opt_barrier, "barrier=%u"},
{Opt_barrier, "barrier"},
{Opt_nobarrier, "nobarrier"},
{Opt_i_version, "i_version"},
{Opt_stripe, "stripe=%u"},
{Opt_delalloc, "delalloc"},
{Opt_nodelalloc, "nodelalloc"},
{Opt_removed, "mblk_io_submit"},
{Opt_removed, "nomblk_io_submit"},
{Opt_block_validity, "block_validity"},
{Opt_noblock_validity, "noblock_validity"},
{Opt_inode_readahead_blks, "inode_readahead_blks=%u"},
{Opt_journal_ioprio, "journal_ioprio=%u"},
{Opt_auto_da_alloc, "auto_da_alloc=%u"},
{Opt_auto_da_alloc, "auto_da_alloc"},
{Opt_noauto_da_alloc, "noauto_da_alloc"},
{Opt_dioread_nolock, "dioread_nolock"},
{Opt_dioread_lock, "dioread_lock"},
{Opt_discard, "discard"},
{Opt_nodiscard, "nodiscard"},
{Opt_init_itable, "init_itable=%u"},
{Opt_init_itable, "init_itable"},
{Opt_noinit_itable, "noinit_itable"},
{Opt_max_dir_size_kb, "max_dir_size_kb=%u"},
{Opt_test_dummy_encryption, "test_dummy_encryption"},
{Opt_removed, "check=none"}, /* mount option from ext2/3 */
{Opt_removed, "nocheck"}, /* mount option from ext2/3 */
{Opt_removed, "reservation"}, /* mount option from ext2/3 */
{Opt_removed, "noreservation"}, /* mount option from ext2/3 */
{Opt_removed, "journal=%u"}, /* mount option from ext2/3 */
{Opt_err, NULL},
};
static ext4_fsblk_t get_sb_block(void **data)
{
ext4_fsblk_t sb_block;
char *options = (char *) *data;
if (!options || strncmp(options, "sb=", 3) != 0)
return 1; /* Default location */
options += 3;
/* TODO: use simple_strtoll with >32bit ext4 */
sb_block = simple_strtoul(options, &options, 0);
if (*options && *options != ',') {
printk(KERN_ERR "EXT4-fs: Invalid sb specification: %s\n",
(char *) *data);
return 1;
}
if (*options == ',')
options++;
*data = (void *) options;
return sb_block;
}
#define DEFAULT_JOURNAL_IOPRIO (IOPRIO_PRIO_VALUE(IOPRIO_CLASS_BE, 3))
static char deprecated_msg[] = "Mount option \"%s\" will be removed by %s\n"
"Contact linux-ext4@vger.kernel.org if you think we should keep it.\n";
#ifdef CONFIG_QUOTA
static int set_qf_name(struct super_block *sb, int qtype, substring_t *args)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
char *qname;
int ret = -1;
if (sb_any_quota_loaded(sb) &&
!sbi->s_qf_names[qtype]) {
ext4_msg(sb, KERN_ERR,
"Cannot change journaled "
"quota options when quota turned on");
return -1;
}
if (EXT4_HAS_RO_COMPAT_FEATURE(sb, EXT4_FEATURE_RO_COMPAT_QUOTA)) {
ext4_msg(sb, KERN_ERR, "Cannot set journaled quota options "
"when QUOTA feature is enabled");
return -1;
}
qname = match_strdup(args);
if (!qname) {
ext4_msg(sb, KERN_ERR,
"Not enough memory for storing quotafile name");
return -1;
}
if (sbi->s_qf_names[qtype]) {
if (strcmp(sbi->s_qf_names[qtype], qname) == 0)
ret = 1;
else
ext4_msg(sb, KERN_ERR,
"%s quota file already specified",
QTYPE2NAME(qtype));
goto errout;
}
if (strchr(qname, '/')) {
ext4_msg(sb, KERN_ERR,
"quotafile must be on filesystem root");
goto errout;
}
sbi->s_qf_names[qtype] = qname;
set_opt(sb, QUOTA);
return 1;
errout:
kfree(qname);
return ret;
}
static int clear_qf_name(struct super_block *sb, int qtype)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
if (sb_any_quota_loaded(sb) &&
sbi->s_qf_names[qtype]) {
ext4_msg(sb, KERN_ERR, "Cannot change journaled quota options"
" when quota turned on");
return -1;
}
kfree(sbi->s_qf_names[qtype]);
sbi->s_qf_names[qtype] = NULL;
return 1;
}
#endif
#define MOPT_SET 0x0001
#define MOPT_CLEAR 0x0002
#define MOPT_NOSUPPORT 0x0004
#define MOPT_EXPLICIT 0x0008
#define MOPT_CLEAR_ERR 0x0010
#define MOPT_GTE0 0x0020
#ifdef CONFIG_QUOTA
#define MOPT_Q 0
#define MOPT_QFMT 0x0040
#else
#define MOPT_Q MOPT_NOSUPPORT
#define MOPT_QFMT MOPT_NOSUPPORT
#endif
#define MOPT_DATAJ 0x0080
#define MOPT_NO_EXT2 0x0100
#define MOPT_NO_EXT3 0x0200
#define MOPT_EXT4_ONLY (MOPT_NO_EXT2 | MOPT_NO_EXT3)
#define MOPT_STRING 0x0400
static const struct mount_opts {
int token;
int mount_opt;
int flags;
} ext4_mount_opts[] = {
{Opt_minix_df, EXT4_MOUNT_MINIX_DF, MOPT_SET},
{Opt_bsd_df, EXT4_MOUNT_MINIX_DF, MOPT_CLEAR},
{Opt_grpid, EXT4_MOUNT_GRPID, MOPT_SET},
{Opt_nogrpid, EXT4_MOUNT_GRPID, MOPT_CLEAR},
{Opt_block_validity, EXT4_MOUNT_BLOCK_VALIDITY, MOPT_SET},
{Opt_noblock_validity, EXT4_MOUNT_BLOCK_VALIDITY, MOPT_CLEAR},
{Opt_dioread_nolock, EXT4_MOUNT_DIOREAD_NOLOCK,
MOPT_EXT4_ONLY | MOPT_SET},
{Opt_dioread_lock, EXT4_MOUNT_DIOREAD_NOLOCK,
MOPT_EXT4_ONLY | MOPT_CLEAR},
{Opt_discard, EXT4_MOUNT_DISCARD, MOPT_SET},
{Opt_nodiscard, EXT4_MOUNT_DISCARD, MOPT_CLEAR},
{Opt_delalloc, EXT4_MOUNT_DELALLOC,
MOPT_EXT4_ONLY | MOPT_SET | MOPT_EXPLICIT},
{Opt_nodelalloc, EXT4_MOUNT_DELALLOC,
MOPT_EXT4_ONLY | MOPT_CLEAR},
{Opt_journal_checksum, EXT4_MOUNT_JOURNAL_CHECKSUM,
MOPT_EXT4_ONLY | MOPT_SET},
{Opt_journal_async_commit, (EXT4_MOUNT_JOURNAL_ASYNC_COMMIT |
EXT4_MOUNT_JOURNAL_CHECKSUM),
MOPT_EXT4_ONLY | MOPT_SET},
{Opt_noload, EXT4_MOUNT_NOLOAD, MOPT_NO_EXT2 | MOPT_SET},
{Opt_err_panic, EXT4_MOUNT_ERRORS_PANIC, MOPT_SET | MOPT_CLEAR_ERR},
{Opt_err_ro, EXT4_MOUNT_ERRORS_RO, MOPT_SET | MOPT_CLEAR_ERR},
{Opt_err_cont, EXT4_MOUNT_ERRORS_CONT, MOPT_SET | MOPT_CLEAR_ERR},
{Opt_data_err_abort, EXT4_MOUNT_DATA_ERR_ABORT,
MOPT_NO_EXT2 | MOPT_SET},
{Opt_data_err_ignore, EXT4_MOUNT_DATA_ERR_ABORT,
MOPT_NO_EXT2 | MOPT_CLEAR},
{Opt_barrier, EXT4_MOUNT_BARRIER, MOPT_SET},
{Opt_nobarrier, EXT4_MOUNT_BARRIER, MOPT_CLEAR},
{Opt_noauto_da_alloc, EXT4_MOUNT_NO_AUTO_DA_ALLOC, MOPT_SET},
{Opt_auto_da_alloc, EXT4_MOUNT_NO_AUTO_DA_ALLOC, MOPT_CLEAR},
{Opt_noinit_itable, EXT4_MOUNT_INIT_INODE_TABLE, MOPT_CLEAR},
{Opt_commit, 0, MOPT_GTE0},
{Opt_max_batch_time, 0, MOPT_GTE0},
{Opt_min_batch_time, 0, MOPT_GTE0},
{Opt_inode_readahead_blks, 0, MOPT_GTE0},
{Opt_init_itable, 0, MOPT_GTE0},
{Opt_stripe, 0, MOPT_GTE0},
{Opt_resuid, 0, MOPT_GTE0},
{Opt_resgid, 0, MOPT_GTE0},
{Opt_journal_dev, 0, MOPT_GTE0},
{Opt_journal_path, 0, MOPT_STRING},
{Opt_journal_ioprio, 0, MOPT_GTE0},
{Opt_data_journal, EXT4_MOUNT_JOURNAL_DATA, MOPT_NO_EXT2 | MOPT_DATAJ},
{Opt_data_ordered, EXT4_MOUNT_ORDERED_DATA, MOPT_NO_EXT2 | MOPT_DATAJ},
{Opt_data_writeback, EXT4_MOUNT_WRITEBACK_DATA,
MOPT_NO_EXT2 | MOPT_DATAJ},
{Opt_user_xattr, EXT4_MOUNT_XATTR_USER, MOPT_SET},
{Opt_nouser_xattr, EXT4_MOUNT_XATTR_USER, MOPT_CLEAR},
#ifdef CONFIG_EXT4_FS_POSIX_ACL
{Opt_acl, EXT4_MOUNT_POSIX_ACL, MOPT_SET},
{Opt_noacl, EXT4_MOUNT_POSIX_ACL, MOPT_CLEAR},
#else
{Opt_acl, 0, MOPT_NOSUPPORT},
{Opt_noacl, 0, MOPT_NOSUPPORT},
#endif
{Opt_nouid32, EXT4_MOUNT_NO_UID32, MOPT_SET},
{Opt_debug, EXT4_MOUNT_DEBUG, MOPT_SET},
{Opt_quota, EXT4_MOUNT_QUOTA | EXT4_MOUNT_USRQUOTA, MOPT_SET | MOPT_Q},
{Opt_usrquota, EXT4_MOUNT_QUOTA | EXT4_MOUNT_USRQUOTA,
MOPT_SET | MOPT_Q},
{Opt_grpquota, EXT4_MOUNT_QUOTA | EXT4_MOUNT_GRPQUOTA,
MOPT_SET | MOPT_Q},
{Opt_noquota, (EXT4_MOUNT_QUOTA | EXT4_MOUNT_USRQUOTA |
EXT4_MOUNT_GRPQUOTA), MOPT_CLEAR | MOPT_Q},
{Opt_usrjquota, 0, MOPT_Q},
{Opt_grpjquota, 0, MOPT_Q},
{Opt_offusrjquota, 0, MOPT_Q},
{Opt_offgrpjquota, 0, MOPT_Q},
{Opt_jqfmt_vfsold, QFMT_VFS_OLD, MOPT_QFMT},
{Opt_jqfmt_vfsv0, QFMT_VFS_V0, MOPT_QFMT},
{Opt_jqfmt_vfsv1, QFMT_VFS_V1, MOPT_QFMT},
{Opt_max_dir_size_kb, 0, MOPT_GTE0},
{Opt_test_dummy_encryption, 0, MOPT_GTE0},
{Opt_err, 0, 0}
};
static int handle_mount_opt(struct super_block *sb, char *opt, int token,
substring_t *args, unsigned long *journal_devnum,
unsigned int *journal_ioprio, int is_remount)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
const struct mount_opts *m;
kuid_t uid;
kgid_t gid;
int arg = 0;
#ifdef CONFIG_QUOTA
if (token == Opt_usrjquota)
return set_qf_name(sb, USRQUOTA, &args[0]);
else if (token == Opt_grpjquota)
return set_qf_name(sb, GRPQUOTA, &args[0]);
else if (token == Opt_offusrjquota)
return clear_qf_name(sb, USRQUOTA);
else if (token == Opt_offgrpjquota)
return clear_qf_name(sb, GRPQUOTA);
#endif
switch (token) {
case Opt_noacl:
case Opt_nouser_xattr:
ext4_msg(sb, KERN_WARNING, deprecated_msg, opt, "3.5");
break;
case Opt_sb:
return 1; /* handled by get_sb_block() */
case Opt_removed:
ext4_msg(sb, KERN_WARNING, "Ignoring removed %s option", opt);
return 1;
case Opt_abort:
sbi->s_mount_flags |= EXT4_MF_FS_ABORTED;
return 1;
case Opt_i_version:
sb->s_flags |= MS_I_VERSION;
return 1;
}
for (m = ext4_mount_opts; m->token != Opt_err; m++)
if (token == m->token)
break;
if (m->token == Opt_err) {
ext4_msg(sb, KERN_ERR, "Unrecognized mount option \"%s\" "
"or missing value", opt);
return -1;
}
if ((m->flags & MOPT_NO_EXT2) && IS_EXT2_SB(sb)) {
ext4_msg(sb, KERN_ERR,
"Mount option \"%s\" incompatible with ext2", opt);
return -1;
}
if ((m->flags & MOPT_NO_EXT3) && IS_EXT3_SB(sb)) {
ext4_msg(sb, KERN_ERR,
"Mount option \"%s\" incompatible with ext3", opt);
return -1;
}
if (args->from && !(m->flags & MOPT_STRING) && match_int(args, &arg))
return -1;
if (args->from && (m->flags & MOPT_GTE0) && (arg < 0))
return -1;
if (m->flags & MOPT_EXPLICIT)
set_opt2(sb, EXPLICIT_DELALLOC);
if (m->flags & MOPT_CLEAR_ERR)
clear_opt(sb, ERRORS_MASK);
if (token == Opt_noquota && sb_any_quota_loaded(sb)) {
ext4_msg(sb, KERN_ERR, "Cannot change quota "
"options when quota turned on");
return -1;
}
if (m->flags & MOPT_NOSUPPORT) {
ext4_msg(sb, KERN_ERR, "%s option not supported", opt);
} else if (token == Opt_commit) {
if (arg == 0)
arg = JBD2_DEFAULT_MAX_COMMIT_AGE;
sbi->s_commit_interval = HZ * arg;
} else if (token == Opt_max_batch_time) {
sbi->s_max_batch_time = arg;
} else if (token == Opt_min_batch_time) {
sbi->s_min_batch_time = arg;
} else if (token == Opt_inode_readahead_blks) {
if (arg && (arg > (1 << 30) || !is_power_of_2(arg))) {
ext4_msg(sb, KERN_ERR,
"EXT4-fs: inode_readahead_blks must be "
"0 or a power of 2 smaller than 2^31");
return -1;
}
sbi->s_inode_readahead_blks = arg;
} else if (token == Opt_init_itable) {
set_opt(sb, INIT_INODE_TABLE);
if (!args->from)
arg = EXT4_DEF_LI_WAIT_MULT;
sbi->s_li_wait_mult = arg;
} else if (token == Opt_max_dir_size_kb) {
sbi->s_max_dir_size_kb = arg;
} else if (token == Opt_stripe) {
sbi->s_stripe = arg;
} else if (token == Opt_resuid) {
uid = make_kuid(current_user_ns(), arg);
if (!uid_valid(uid)) {
ext4_msg(sb, KERN_ERR, "Invalid uid value %d", arg);
return -1;
}
sbi->s_resuid = uid;
} else if (token == Opt_resgid) {
gid = make_kgid(current_user_ns(), arg);
if (!gid_valid(gid)) {
ext4_msg(sb, KERN_ERR, "Invalid gid value %d", arg);
return -1;
}
sbi->s_resgid = gid;
} else if (token == Opt_journal_dev) {
if (is_remount) {
ext4_msg(sb, KERN_ERR,
"Cannot specify journal on remount");
return -1;
}
*journal_devnum = arg;
} else if (token == Opt_journal_path) {
char *journal_path;
struct inode *journal_inode;
struct path path;
int error;
if (is_remount) {
ext4_msg(sb, KERN_ERR,
"Cannot specify journal on remount");
return -1;
}
journal_path = match_strdup(&args[0]);
if (!journal_path) {
ext4_msg(sb, KERN_ERR, "error: could not dup "
"journal device string");
return -1;
}
error = kern_path(journal_path, LOOKUP_FOLLOW, &path);
if (error) {
ext4_msg(sb, KERN_ERR, "error: could not find "
"journal device path: error %d", error);
kfree(journal_path);
return -1;
}
journal_inode = path.dentry->d_inode;
if (!S_ISBLK(journal_inode->i_mode)) {
ext4_msg(sb, KERN_ERR, "error: journal path %s "
"is not a block device", journal_path);
path_put(&path);
kfree(journal_path);
return -1;
}
*journal_devnum = new_encode_dev(journal_inode->i_rdev);
path_put(&path);
kfree(journal_path);
} else if (token == Opt_journal_ioprio) {
if (arg > 7) {
ext4_msg(sb, KERN_ERR, "Invalid journal IO priority"
" (must be 0-7)");
return -1;
}
*journal_ioprio =
IOPRIO_PRIO_VALUE(IOPRIO_CLASS_BE, arg);
} else if (token == Opt_test_dummy_encryption) {
#ifdef CONFIG_EXT4_FS_ENCRYPTION
sbi->s_mount_flags |= EXT4_MF_TEST_DUMMY_ENCRYPTION;
ext4_msg(sb, KERN_WARNING,
"Test dummy encryption mode enabled");
#else
ext4_msg(sb, KERN_WARNING,
"Test dummy encryption mount option ignored");
#endif
} else if (m->flags & MOPT_DATAJ) {
if (is_remount) {
if (!sbi->s_journal)
ext4_msg(sb, KERN_WARNING, "Remounting file system with no journal so ignoring journalled data option");
else if (test_opt(sb, DATA_FLAGS) != m->mount_opt) {
ext4_msg(sb, KERN_ERR,
"Cannot change data mode on remount");
return -1;
}
} else {
clear_opt(sb, DATA_FLAGS);
sbi->s_mount_opt |= m->mount_opt;
}
#ifdef CONFIG_QUOTA
} else if (m->flags & MOPT_QFMT) {
if (sb_any_quota_loaded(sb) &&
sbi->s_jquota_fmt != m->mount_opt) {
ext4_msg(sb, KERN_ERR, "Cannot change journaled "
"quota options when quota turned on");
return -1;
}
if (EXT4_HAS_RO_COMPAT_FEATURE(sb,
EXT4_FEATURE_RO_COMPAT_QUOTA)) {
ext4_msg(sb, KERN_ERR,
"Cannot set journaled quota options "
"when QUOTA feature is enabled");
return -1;
}
sbi->s_jquota_fmt = m->mount_opt;
#endif
} else {
if (!args->from)
arg = 1;
if (m->flags & MOPT_CLEAR)
arg = !arg;
else if (unlikely(!(m->flags & MOPT_SET))) {
ext4_msg(sb, KERN_WARNING,
"buggy handling of option %s", opt);
WARN_ON(1);
return -1;
}
if (arg != 0)
sbi->s_mount_opt |= m->mount_opt;
else
sbi->s_mount_opt &= ~m->mount_opt;
}
return 1;
}
static int parse_options(char *options, struct super_block *sb,
unsigned long *journal_devnum,
unsigned int *journal_ioprio,
int is_remount)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
char *p;
substring_t args[MAX_OPT_ARGS];
int token;
if (!options)
return 1;
while ((p = strsep(&options, ",")) != NULL) {
if (!*p)
continue;
/*
* Initialize args struct so we know whether arg was
* found; some options take optional arguments.
*/
args[0].to = args[0].from = NULL;
token = match_token(p, tokens, args);
if (handle_mount_opt(sb, p, token, args, journal_devnum,
journal_ioprio, is_remount) < 0)
return 0;
}
#ifdef CONFIG_QUOTA
if (EXT4_HAS_RO_COMPAT_FEATURE(sb, EXT4_FEATURE_RO_COMPAT_QUOTA) &&
(test_opt(sb, USRQUOTA) || test_opt(sb, GRPQUOTA))) {
ext4_msg(sb, KERN_ERR, "Cannot set quota options when QUOTA "
"feature is enabled");
return 0;
}
if (sbi->s_qf_names[USRQUOTA] || sbi->s_qf_names[GRPQUOTA]) {
if (test_opt(sb, USRQUOTA) && sbi->s_qf_names[USRQUOTA])
clear_opt(sb, USRQUOTA);
if (test_opt(sb, GRPQUOTA) && sbi->s_qf_names[GRPQUOTA])
clear_opt(sb, GRPQUOTA);
if (test_opt(sb, GRPQUOTA) || test_opt(sb, USRQUOTA)) {
ext4_msg(sb, KERN_ERR, "old and new quota "
"format mixing");
return 0;
}
if (!sbi->s_jquota_fmt) {
ext4_msg(sb, KERN_ERR, "journaled quota format "
"not specified");
return 0;
}
}
#endif
if (test_opt(sb, DIOREAD_NOLOCK)) {
int blocksize =
BLOCK_SIZE << le32_to_cpu(sbi->s_es->s_log_block_size);
if (blocksize < PAGE_CACHE_SIZE) {
ext4_msg(sb, KERN_ERR, "can't mount with "
"dioread_nolock if block size != PAGE_SIZE");
return 0;
}
}
return 1;
}
static inline void ext4_show_quota_options(struct seq_file *seq,
struct super_block *sb)
{
#if defined(CONFIG_QUOTA)
struct ext4_sb_info *sbi = EXT4_SB(sb);
if (sbi->s_jquota_fmt) {
char *fmtname = "";
switch (sbi->s_jquota_fmt) {
case QFMT_VFS_OLD:
fmtname = "vfsold";
break;
case QFMT_VFS_V0:
fmtname = "vfsv0";
break;
case QFMT_VFS_V1:
fmtname = "vfsv1";
break;
}
seq_printf(seq, ",jqfmt=%s", fmtname);
}
if (sbi->s_qf_names[USRQUOTA])
seq_printf(seq, ",usrjquota=%s", sbi->s_qf_names[USRQUOTA]);
if (sbi->s_qf_names[GRPQUOTA])
seq_printf(seq, ",grpjquota=%s", sbi->s_qf_names[GRPQUOTA]);
#endif
}
static const char *token2str(int token)
{
const struct match_token *t;
for (t = tokens; t->token != Opt_err; t++)
if (t->token == token && !strchr(t->pattern, '='))
break;
return t->pattern;
}
/*
* Show an option if
* - it's set to a non-default value OR
* - if the per-sb default is different from the global default
*/
static int _ext4_show_options(struct seq_file *seq, struct super_block *sb,
int nodefs)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
struct ext4_super_block *es = sbi->s_es;
int def_errors, def_mount_opt = nodefs ? 0 : sbi->s_def_mount_opt;
const struct mount_opts *m;
char sep = nodefs ? '\n' : ',';
#define SEQ_OPTS_PUTS(str) seq_printf(seq, "%c" str, sep)
#define SEQ_OPTS_PRINT(str, arg) seq_printf(seq, "%c" str, sep, arg)
if (sbi->s_sb_block != 1)
SEQ_OPTS_PRINT("sb=%llu", sbi->s_sb_block);
for (m = ext4_mount_opts; m->token != Opt_err; m++) {
int want_set = m->flags & MOPT_SET;
if (((m->flags & (MOPT_SET|MOPT_CLEAR)) == 0) ||
(m->flags & MOPT_CLEAR_ERR))
continue;
if (!(m->mount_opt & (sbi->s_mount_opt ^ def_mount_opt)))
continue; /* skip if same as the default */
if ((want_set &&
(sbi->s_mount_opt & m->mount_opt) != m->mount_opt) ||
(!want_set && (sbi->s_mount_opt & m->mount_opt)))
continue; /* select Opt_noFoo vs Opt_Foo */
SEQ_OPTS_PRINT("%s", token2str(m->token));
}
if (nodefs || !uid_eq(sbi->s_resuid, make_kuid(&init_user_ns, EXT4_DEF_RESUID)) ||
le16_to_cpu(es->s_def_resuid) != EXT4_DEF_RESUID)
SEQ_OPTS_PRINT("resuid=%u",
from_kuid_munged(&init_user_ns, sbi->s_resuid));
if (nodefs || !gid_eq(sbi->s_resgid, make_kgid(&init_user_ns, EXT4_DEF_RESGID)) ||
le16_to_cpu(es->s_def_resgid) != EXT4_DEF_RESGID)
SEQ_OPTS_PRINT("resgid=%u",
from_kgid_munged(&init_user_ns, sbi->s_resgid));
def_errors = nodefs ? -1 : le16_to_cpu(es->s_errors);
if (test_opt(sb, ERRORS_RO) && def_errors != EXT4_ERRORS_RO)
SEQ_OPTS_PUTS("errors=remount-ro");
if (test_opt(sb, ERRORS_CONT) && def_errors != EXT4_ERRORS_CONTINUE)
SEQ_OPTS_PUTS("errors=continue");
if (test_opt(sb, ERRORS_PANIC) && def_errors != EXT4_ERRORS_PANIC)
SEQ_OPTS_PUTS("errors=panic");
if (nodefs || sbi->s_commit_interval != JBD2_DEFAULT_MAX_COMMIT_AGE*HZ)
SEQ_OPTS_PRINT("commit=%lu", sbi->s_commit_interval / HZ);
if (nodefs || sbi->s_min_batch_time != EXT4_DEF_MIN_BATCH_TIME)
SEQ_OPTS_PRINT("min_batch_time=%u", sbi->s_min_batch_time);
if (nodefs || sbi->s_max_batch_time != EXT4_DEF_MAX_BATCH_TIME)
SEQ_OPTS_PRINT("max_batch_time=%u", sbi->s_max_batch_time);
if (sb->s_flags & MS_I_VERSION)
SEQ_OPTS_PUTS("i_version");
if (nodefs || sbi->s_stripe)
SEQ_OPTS_PRINT("stripe=%lu", sbi->s_stripe);
if (EXT4_MOUNT_DATA_FLAGS & (sbi->s_mount_opt ^ def_mount_opt)) {
if (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_JOURNAL_DATA)
SEQ_OPTS_PUTS("data=journal");
else if (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_ORDERED_DATA)
SEQ_OPTS_PUTS("data=ordered");
else if (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_WRITEBACK_DATA)
SEQ_OPTS_PUTS("data=writeback");
}
if (nodefs ||
sbi->s_inode_readahead_blks != EXT4_DEF_INODE_READAHEAD_BLKS)
SEQ_OPTS_PRINT("inode_readahead_blks=%u",
sbi->s_inode_readahead_blks);
if (nodefs || (test_opt(sb, INIT_INODE_TABLE) &&
(sbi->s_li_wait_mult != EXT4_DEF_LI_WAIT_MULT)))
SEQ_OPTS_PRINT("init_itable=%u", sbi->s_li_wait_mult);
if (nodefs || sbi->s_max_dir_size_kb)
SEQ_OPTS_PRINT("max_dir_size_kb=%u", sbi->s_max_dir_size_kb);
ext4_show_quota_options(seq, sb);
return 0;
}
static int ext4_show_options(struct seq_file *seq, struct dentry *root)
{
return _ext4_show_options(seq, root->d_sb, 0);
}
static int options_seq_show(struct seq_file *seq, void *offset)
{
struct super_block *sb = seq->private;
int rc;
seq_puts(seq, (sb->s_flags & MS_RDONLY) ? "ro" : "rw");
rc = _ext4_show_options(seq, sb, 1);
seq_puts(seq, "\n");
return rc;
}
static int options_open_fs(struct inode *inode, struct file *file)
{
return single_open(file, options_seq_show, PDE_DATA(inode));
}
static const struct file_operations ext4_seq_options_fops = {
.owner = THIS_MODULE,
.open = options_open_fs,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
};
static int ext4_setup_super(struct super_block *sb, struct ext4_super_block *es,
int read_only)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
int res = 0;
if (le32_to_cpu(es->s_rev_level) > EXT4_MAX_SUPP_REV) {
ext4_msg(sb, KERN_ERR, "revision level too high, "
"forcing read-only mode");
res = MS_RDONLY;
}
if (read_only)
goto done;
if (!(sbi->s_mount_state & EXT4_VALID_FS))
ext4_msg(sb, KERN_WARNING, "warning: mounting unchecked fs, "
"running e2fsck is recommended");
else if (sbi->s_mount_state & EXT4_ERROR_FS)
ext4_msg(sb, KERN_WARNING,
"warning: mounting fs with errors, "
"running e2fsck is recommended");
else if ((__s16) le16_to_cpu(es->s_max_mnt_count) > 0 &&
le16_to_cpu(es->s_mnt_count) >=
(unsigned short) (__s16) le16_to_cpu(es->s_max_mnt_count))
ext4_msg(sb, KERN_WARNING,
"warning: maximal mount count reached, "
"running e2fsck is recommended");
else if (le32_to_cpu(es->s_checkinterval) &&
(le32_to_cpu(es->s_lastcheck) +
le32_to_cpu(es->s_checkinterval) <= get_seconds()))
ext4_msg(sb, KERN_WARNING,
"warning: checktime reached, "
"running e2fsck is recommended");
if (!sbi->s_journal)
es->s_state &= cpu_to_le16(~EXT4_VALID_FS);
if (!(__s16) le16_to_cpu(es->s_max_mnt_count))
es->s_max_mnt_count = cpu_to_le16(EXT4_DFL_MAX_MNT_COUNT);
le16_add_cpu(&es->s_mnt_count, 1);
es->s_mtime = cpu_to_le32(get_seconds());
ext4_update_dynamic_rev(sb);
if (sbi->s_journal)
EXT4_SET_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_RECOVER);
ext4_commit_super(sb, 1);
done:
if (test_opt(sb, DEBUG))
printk(KERN_INFO "[EXT4 FS bs=%lu, gc=%u, "
"bpg=%lu, ipg=%lu, mo=%04x, mo2=%04x]\n",
sb->s_blocksize,
sbi->s_groups_count,
EXT4_BLOCKS_PER_GROUP(sb),
EXT4_INODES_PER_GROUP(sb),
sbi->s_mount_opt, sbi->s_mount_opt2);
cleancache_init_fs(sb);
return res;
}
int ext4_alloc_flex_bg_array(struct super_block *sb, ext4_group_t ngroup)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
struct flex_groups *new_groups;
int size;
if (!sbi->s_log_groups_per_flex)
return 0;
size = ext4_flex_group(sbi, ngroup - 1) + 1;
if (size <= sbi->s_flex_groups_allocated)
return 0;
size = roundup_pow_of_two(size * sizeof(struct flex_groups));
new_groups = ext4_kvzalloc(size, GFP_KERNEL);
if (!new_groups) {
ext4_msg(sb, KERN_ERR, "not enough memory for %d flex groups",
size / (int) sizeof(struct flex_groups));
return -ENOMEM;
}
if (sbi->s_flex_groups) {
memcpy(new_groups, sbi->s_flex_groups,
(sbi->s_flex_groups_allocated *
sizeof(struct flex_groups)));
ext4_kvfree(sbi->s_flex_groups);
}
sbi->s_flex_groups = new_groups;
sbi->s_flex_groups_allocated = size / sizeof(struct flex_groups);
return 0;
}
static int ext4_fill_flex_info(struct super_block *sb)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
struct ext4_group_desc *gdp = NULL;
ext4_group_t flex_group;
int i, err;
sbi->s_log_groups_per_flex = sbi->s_es->s_log_groups_per_flex;
if (sbi->s_log_groups_per_flex < 1 || sbi->s_log_groups_per_flex > 31) {
sbi->s_log_groups_per_flex = 0;
return 1;
}
err = ext4_alloc_flex_bg_array(sb, sbi->s_groups_count);
if (err)
goto failed;
for (i = 0; i < sbi->s_groups_count; i++) {
gdp = ext4_get_group_desc(sb, i, NULL);
flex_group = ext4_flex_group(sbi, i);
atomic_add(ext4_free_inodes_count(sb, gdp),
&sbi->s_flex_groups[flex_group].free_inodes);
atomic64_add(ext4_free_group_clusters(sb, gdp),
&sbi->s_flex_groups[flex_group].free_clusters);
atomic_add(ext4_used_dirs_count(sb, gdp),
&sbi->s_flex_groups[flex_group].used_dirs);
}
return 1;
failed:
return 0;
}
static __le16 ext4_group_desc_csum(struct ext4_sb_info *sbi, __u32 block_group,
struct ext4_group_desc *gdp)
{
int offset;
__u16 crc = 0;
__le32 le_group = cpu_to_le32(block_group);
if (ext4_has_metadata_csum(sbi->s_sb)) {
/* Use new metadata_csum algorithm */
__le16 save_csum;
__u32 csum32;
save_csum = gdp->bg_checksum;
gdp->bg_checksum = 0;
csum32 = ext4_chksum(sbi, sbi->s_csum_seed, (__u8 *)&le_group,
sizeof(le_group));
csum32 = ext4_chksum(sbi, csum32, (__u8 *)gdp,
sbi->s_desc_size);
gdp->bg_checksum = save_csum;
crc = csum32 & 0xFFFF;
goto out;
}
/* old crc16 code */
if (!(sbi->s_es->s_feature_ro_compat &
cpu_to_le32(EXT4_FEATURE_RO_COMPAT_GDT_CSUM)))
return 0;
offset = offsetof(struct ext4_group_desc, bg_checksum);
crc = crc16(~0, sbi->s_es->s_uuid, sizeof(sbi->s_es->s_uuid));
crc = crc16(crc, (__u8 *)&le_group, sizeof(le_group));
crc = crc16(crc, (__u8 *)gdp, offset);
offset += sizeof(gdp->bg_checksum); /* skip checksum */
/* for checksum of struct ext4_group_desc do the rest...*/
if ((sbi->s_es->s_feature_incompat &
cpu_to_le32(EXT4_FEATURE_INCOMPAT_64BIT)) &&
offset < le16_to_cpu(sbi->s_es->s_desc_size))
crc = crc16(crc, (__u8 *)gdp + offset,
le16_to_cpu(sbi->s_es->s_desc_size) -
offset);
out:
return cpu_to_le16(crc);
}
int ext4_group_desc_csum_verify(struct super_block *sb, __u32 block_group,
struct ext4_group_desc *gdp)
{
if (ext4_has_group_desc_csum(sb) &&
(gdp->bg_checksum != ext4_group_desc_csum(EXT4_SB(sb),
block_group, gdp)))
return 0;
return 1;
}
void ext4_group_desc_csum_set(struct super_block *sb, __u32 block_group,
struct ext4_group_desc *gdp)
{
if (!ext4_has_group_desc_csum(sb))
return;
gdp->bg_checksum = ext4_group_desc_csum(EXT4_SB(sb), block_group, gdp);
}
/* Called at mount-time, super-block is locked */
static int ext4_check_descriptors(struct super_block *sb,
ext4_group_t *first_not_zeroed)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
ext4_fsblk_t first_block = le32_to_cpu(sbi->s_es->s_first_data_block);
ext4_fsblk_t last_block;
ext4_fsblk_t block_bitmap;
ext4_fsblk_t inode_bitmap;
ext4_fsblk_t inode_table;
int flexbg_flag = 0;
ext4_group_t i, grp = sbi->s_groups_count;
if (EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_FLEX_BG))
flexbg_flag = 1;
ext4_debug("Checking group descriptors");
for (i = 0; i < sbi->s_groups_count; i++) {
struct ext4_group_desc *gdp = ext4_get_group_desc(sb, i, NULL);
if (i == sbi->s_groups_count - 1 || flexbg_flag)
last_block = ext4_blocks_count(sbi->s_es) - 1;
else
last_block = first_block +
(EXT4_BLOCKS_PER_GROUP(sb) - 1);
if ((grp == sbi->s_groups_count) &&
!(gdp->bg_flags & cpu_to_le16(EXT4_BG_INODE_ZEROED)))
grp = i;
block_bitmap = ext4_block_bitmap(sb, gdp);
if (block_bitmap < first_block || block_bitmap > last_block) {
ext4_msg(sb, KERN_ERR, "ext4_check_descriptors: "
"Block bitmap for group %u not in group "
"(block %llu)!", i, block_bitmap);
return 0;
}
inode_bitmap = ext4_inode_bitmap(sb, gdp);
if (inode_bitmap < first_block || inode_bitmap > last_block) {
ext4_msg(sb, KERN_ERR, "ext4_check_descriptors: "
"Inode bitmap for group %u not in group "
"(block %llu)!", i, inode_bitmap);
return 0;
}
inode_table = ext4_inode_table(sb, gdp);
if (inode_table < first_block ||
inode_table + sbi->s_itb_per_group - 1 > last_block) {
ext4_msg(sb, KERN_ERR, "ext4_check_descriptors: "
"Inode table for group %u not in group "
"(block %llu)!", i, inode_table);
return 0;
}
ext4_lock_group(sb, i);
if (!ext4_group_desc_csum_verify(sb, i, gdp)) {
ext4_msg(sb, KERN_ERR, "ext4_check_descriptors: "
"Checksum for group %u failed (%u!=%u)",
i, le16_to_cpu(ext4_group_desc_csum(sbi, i,
gdp)), le16_to_cpu(gdp->bg_checksum));
if (!(sb->s_flags & MS_RDONLY)) {
ext4_unlock_group(sb, i);
return 0;
}
}
ext4_unlock_group(sb, i);
if (!flexbg_flag)
first_block += EXT4_BLOCKS_PER_GROUP(sb);
}
if (NULL != first_not_zeroed)
*first_not_zeroed = grp;
return 1;
}
/* ext4_orphan_cleanup() walks a singly-linked list of inodes (starting at
* the superblock) which were deleted from all directories, but held open by
* a process at the time of a crash. We walk the list and try to delete these
* inodes at recovery time (only with a read-write filesystem).
*
* In order to keep the orphan inode chain consistent during traversal (in
* case of crash during recovery), we link each inode into the superblock
* orphan list_head and handle it the same way as an inode deletion during
* normal operation (which journals the operations for us).
*
* We only do an iget() and an iput() on each inode, which is very safe if we
* accidentally point at an in-use or already deleted inode. The worst that
* can happen in this case is that we get a "bit already cleared" message from
* ext4_free_inode(). The only reason we would point at a wrong inode is if
* e2fsck was run on this filesystem, and it must have already done the orphan
* inode cleanup for us, so we can safely abort without any further action.
*/
static void ext4_orphan_cleanup(struct super_block *sb,
struct ext4_super_block *es)
{
unsigned int s_flags = sb->s_flags;
int nr_orphans = 0, nr_truncates = 0;
#ifdef CONFIG_QUOTA
int i;
#endif
if (!es->s_last_orphan) {
jbd_debug(4, "no orphan inodes to clean up\n");
return;
}
if (bdev_read_only(sb->s_bdev)) {
ext4_msg(sb, KERN_ERR, "write access "
"unavailable, skipping orphan cleanup");
return;
}
/* Check if feature set would not allow a r/w mount */
if (!ext4_feature_set_ok(sb, 0)) {
ext4_msg(sb, KERN_INFO, "Skipping orphan cleanup due to "
"unknown ROCOMPAT features");
return;
}
if (EXT4_SB(sb)->s_mount_state & EXT4_ERROR_FS) {
/* don't clear list on RO mount w/ errors */
if (es->s_last_orphan && !(s_flags & MS_RDONLY)) {
ext4_msg(sb, KERN_INFO, "Errors on filesystem, "
"clearing orphan list.\n");
es->s_last_orphan = 0;
}
jbd_debug(1, "Skipping orphan recovery on fs with errors.\n");
return;
}
if (s_flags & MS_RDONLY) {
ext4_msg(sb, KERN_INFO, "orphan cleanup on readonly fs");
sb->s_flags &= ~MS_RDONLY;
}
#ifdef CONFIG_QUOTA
/* Needed for iput() to work correctly and not trash data */
sb->s_flags |= MS_ACTIVE;
/* Turn on quotas so that they are updated correctly */
for (i = 0; i < EXT4_MAXQUOTAS; i++) {
if (EXT4_SB(sb)->s_qf_names[i]) {
int ret = ext4_quota_on_mount(sb, i);
if (ret < 0)
ext4_msg(sb, KERN_ERR,
"Cannot turn on journaled "
"quota: error %d", ret);
}
}
#endif
while (es->s_last_orphan) {
struct inode *inode;
inode = ext4_orphan_get(sb, le32_to_cpu(es->s_last_orphan));
if (IS_ERR(inode)) {
es->s_last_orphan = 0;
break;
}
list_add(&EXT4_I(inode)->i_orphan, &EXT4_SB(sb)->s_orphan);
dquot_initialize(inode);
if (inode->i_nlink) {
if (test_opt(sb, DEBUG))
ext4_msg(sb, KERN_DEBUG,
"%s: truncating inode %lu to %lld bytes",
__func__, inode->i_ino, inode->i_size);
jbd_debug(2, "truncating inode %lu to %lld bytes\n",
inode->i_ino, inode->i_size);
mutex_lock(&inode->i_mutex);
truncate_inode_pages(inode->i_mapping, inode->i_size);
ext4_truncate(inode);
mutex_unlock(&inode->i_mutex);
nr_truncates++;
} else {
if (test_opt(sb, DEBUG))
ext4_msg(sb, KERN_DEBUG,
"%s: deleting unreferenced inode %lu",
__func__, inode->i_ino);
jbd_debug(2, "deleting unreferenced inode %lu\n",
inode->i_ino);
nr_orphans++;
}
iput(inode); /* The delete magic happens here! */
}
#define PLURAL(x) (x), ((x) == 1) ? "" : "s"
if (nr_orphans)
ext4_msg(sb, KERN_INFO, "%d orphan inode%s deleted",
PLURAL(nr_orphans));
if (nr_truncates)
ext4_msg(sb, KERN_INFO, "%d truncate%s cleaned up",
PLURAL(nr_truncates));
#ifdef CONFIG_QUOTA
/* Turn quotas off */
for (i = 0; i < EXT4_MAXQUOTAS; i++) {
if (sb_dqopt(sb)->files[i])
dquot_quota_off(sb, i);
}
#endif
sb->s_flags = s_flags; /* Restore MS_RDONLY status */
}
/*
* Maximal extent format file size.
* Resulting logical blkno at s_maxbytes must fit in our on-disk
* extent format containers, within a sector_t, and within i_blocks
* in the vfs. ext4 inode has 48 bits of i_block in fsblock units,
* so that won't be a limiting factor.
*
* However there is other limiting factor. We do store extents in the form
* of starting block and length, hence the resulting length of the extent
* covering maximum file size must fit into on-disk format containers as
* well. Given that length is always by 1 unit bigger than max unit (because
* we count 0 as well) we have to lower the s_maxbytes by one fs block.
*
* Note, this does *not* consider any metadata overhead for vfs i_blocks.
*/
static loff_t ext4_max_size(int blkbits, int has_huge_files)
{
loff_t res;
loff_t upper_limit = MAX_LFS_FILESIZE;
/* small i_blocks in vfs inode? */
if (!has_huge_files || sizeof(blkcnt_t) < sizeof(u64)) {
/*
* CONFIG_LBDAF is not enabled implies the inode
* i_block represent total blocks in 512 bytes
* 32 == size of vfs inode i_blocks * 8
*/
upper_limit = (1LL << 32) - 1;
/* total blocks in file system block size */
upper_limit >>= (blkbits - 9);
upper_limit <<= blkbits;
}
/*
* 32-bit extent-start container, ee_block. We lower the maxbytes
* by one fs block, so ee_len can cover the extent of maximum file
* size
*/
res = (1LL << 32) - 1;
res <<= blkbits;
/* Sanity check against vm- & vfs- imposed limits */
if (res > upper_limit)
res = upper_limit;
return res;
}
/*
* Maximal bitmap file size. There is a direct, and {,double-,triple-}indirect
* block limit, and also a limit of (2^48 - 1) 512-byte sectors in i_blocks.
* We need to be 1 filesystem block less than the 2^48 sector limit.
*/
static loff_t ext4_max_bitmap_size(int bits, int has_huge_files)
{
loff_t res = EXT4_NDIR_BLOCKS;
int meta_blocks;
loff_t upper_limit;
/* This is calculated to be the largest file size for a dense, block
* mapped file such that the file's total number of 512-byte sectors,
* including data and all indirect blocks, does not exceed (2^48 - 1).
*
* __u32 i_blocks_lo and _u16 i_blocks_high represent the total
* number of 512-byte sectors of the file.
*/
if (!has_huge_files || sizeof(blkcnt_t) < sizeof(u64)) {
/*
* !has_huge_files or CONFIG_LBDAF not enabled implies that
* the inode i_block field represents total file blocks in
* 2^32 512-byte sectors == size of vfs inode i_blocks * 8
*/
upper_limit = (1LL << 32) - 1;
/* total blocks in file system block size */
upper_limit >>= (bits - 9);
} else {
/*
* We use 48 bit ext4_inode i_blocks
* With EXT4_HUGE_FILE_FL set the i_blocks
* represent total number of blocks in
* file system block size
*/
upper_limit = (1LL << 48) - 1;
}
/* indirect blocks */
meta_blocks = 1;
/* double indirect blocks */
meta_blocks += 1 + (1LL << (bits-2));
/* tripple indirect blocks */
meta_blocks += 1 + (1LL << (bits-2)) + (1LL << (2*(bits-2)));
upper_limit -= meta_blocks;
upper_limit <<= bits;
res += 1LL << (bits-2);
res += 1LL << (2*(bits-2));
res += 1LL << (3*(bits-2));
res <<= bits;
if (res > upper_limit)
res = upper_limit;
if (res > MAX_LFS_FILESIZE)
res = MAX_LFS_FILESIZE;
return res;
}
static ext4_fsblk_t descriptor_loc(struct super_block *sb,
ext4_fsblk_t logical_sb_block, int nr)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
ext4_group_t bg, first_meta_bg;
int has_super = 0;
first_meta_bg = le32_to_cpu(sbi->s_es->s_first_meta_bg);
if (!EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_META_BG) ||
nr < first_meta_bg)
return logical_sb_block + nr + 1;
bg = sbi->s_desc_per_block * nr;
if (ext4_bg_has_super(sb, bg))
has_super = 1;
/*
* If we have a meta_bg fs with 1k blocks, group 0's GDT is at
* block 2, not 1. If s_first_data_block == 0 (bigalloc is enabled
* on modern mke2fs or blksize > 1k on older mke2fs) then we must
* compensate.
*/
if (sb->s_blocksize == 1024 && nr == 0 &&
le32_to_cpu(EXT4_SB(sb)->s_es->s_first_data_block) == 0)
has_super++;
return (has_super + ext4_group_first_block_no(sb, bg));
}
/**
* ext4_get_stripe_size: Get the stripe size.
* @sbi: In memory super block info
*
* If we have specified it via mount option, then
* use the mount option value. If the value specified at mount time is
* greater than the blocks per group use the super block value.
* If the super block value is greater than blocks per group return 0.
* Allocator needs it be less than blocks per group.
*
*/
static unsigned long ext4_get_stripe_size(struct ext4_sb_info *sbi)
{
unsigned long stride = le16_to_cpu(sbi->s_es->s_raid_stride);
unsigned long stripe_width =
le32_to_cpu(sbi->s_es->s_raid_stripe_width);
int ret;
if (sbi->s_stripe && sbi->s_stripe <= sbi->s_blocks_per_group)
ret = sbi->s_stripe;
else if (stripe_width <= sbi->s_blocks_per_group)
ret = stripe_width;
else if (stride <= sbi->s_blocks_per_group)
ret = stride;
else
ret = 0;
/*
* If the stripe width is 1, this makes no sense and
* we set it to 0 to turn off stripe handling code.
*/
if (ret <= 1)
ret = 0;
return ret;
}
/* sysfs supprt */
struct ext4_attr {
struct attribute attr;
ssize_t (*show)(struct ext4_attr *, struct ext4_sb_info *, char *);
ssize_t (*store)(struct ext4_attr *, struct ext4_sb_info *,
const char *, size_t);
union {
int offset;
int deprecated_val;
} u;
};
static int parse_strtoull(const char *buf,
unsigned long long max, unsigned long long *value)
{
int ret;
ret = kstrtoull(skip_spaces(buf), 0, value);
if (!ret && *value > max)
ret = -EINVAL;
return ret;
}
static ssize_t delayed_allocation_blocks_show(struct ext4_attr *a,
struct ext4_sb_info *sbi,
char *buf)
{
return snprintf(buf, PAGE_SIZE, "%llu\n",
(s64) EXT4_C2B(sbi,
percpu_counter_sum(&sbi->s_dirtyclusters_counter)));
}
static ssize_t session_write_kbytes_show(struct ext4_attr *a,
struct ext4_sb_info *sbi, char *buf)
{
struct super_block *sb = sbi->s_buddy_cache->i_sb;
if (!sb->s_bdev->bd_part)
return snprintf(buf, PAGE_SIZE, "0\n");
return snprintf(buf, PAGE_SIZE, "%lu\n",
(part_stat_read(sb->s_bdev->bd_part, sectors[1]) -
sbi->s_sectors_written_start) >> 1);
}
static ssize_t lifetime_write_kbytes_show(struct ext4_attr *a,
struct ext4_sb_info *sbi, char *buf)
{
struct super_block *sb = sbi->s_buddy_cache->i_sb;
if (!sb->s_bdev->bd_part)
return snprintf(buf, PAGE_SIZE, "0\n");
return snprintf(buf, PAGE_SIZE, "%llu\n",
(unsigned long long)(sbi->s_kbytes_written +
((part_stat_read(sb->s_bdev->bd_part, sectors[1]) -
EXT4_SB(sb)->s_sectors_written_start) >> 1)));
}
static ssize_t inode_readahead_blks_store(struct ext4_attr *a,
struct ext4_sb_info *sbi,
const char *buf, size_t count)
{
unsigned long t;
int ret;
ret = kstrtoul(skip_spaces(buf), 0, &t);
if (ret)
return ret;
if (t && (!is_power_of_2(t) || t > 0x40000000))
return -EINVAL;
sbi->s_inode_readahead_blks = t;
return count;
}
static ssize_t sbi_ui_show(struct ext4_attr *a,
struct ext4_sb_info *sbi, char *buf)
{
unsigned int *ui = (unsigned int *) (((char *) sbi) + a->u.offset);
return snprintf(buf, PAGE_SIZE, "%u\n", *ui);
}
static ssize_t sbi_ui_store(struct ext4_attr *a,
struct ext4_sb_info *sbi,
const char *buf, size_t count)
{
unsigned int *ui = (unsigned int *) (((char *) sbi) + a->u.offset);
unsigned long t;
int ret;
ret = kstrtoul(skip_spaces(buf), 0, &t);
if (ret)
return ret;
*ui = t;
return count;
}
static ssize_t es_ui_show(struct ext4_attr *a,
struct ext4_sb_info *sbi, char *buf)
{
unsigned int *ui = (unsigned int *) (((char *) sbi->s_es) +
a->u.offset);
return snprintf(buf, PAGE_SIZE, "%u\n", *ui);
}
static ssize_t reserved_clusters_show(struct ext4_attr *a,
struct ext4_sb_info *sbi, char *buf)
{
return snprintf(buf, PAGE_SIZE, "%llu\n",
(unsigned long long) atomic64_read(&sbi->s_resv_clusters));
}
static ssize_t reserved_clusters_store(struct ext4_attr *a,
struct ext4_sb_info *sbi,
const char *buf, size_t count)
{
unsigned long long val;
int ret;
if (parse_strtoull(buf, -1ULL, &val))
return -EINVAL;
ret = ext4_reserve_clusters(sbi, val);
return ret ? ret : count;
}
static ssize_t trigger_test_error(struct ext4_attr *a,
struct ext4_sb_info *sbi,
const char *buf, size_t count)
{
int len = count;
if (!capable(CAP_SYS_ADMIN))
return -EPERM;
if (len && buf[len-1] == '\n')
len--;
if (len)
ext4_error(sbi->s_sb, "%.*s", len, buf);
return count;
}
static ssize_t sbi_deprecated_show(struct ext4_attr *a,
struct ext4_sb_info *sbi, char *buf)
{
return snprintf(buf, PAGE_SIZE, "%d\n", a->u.deprecated_val);
}
#define EXT4_ATTR_OFFSET(_name,_mode,_show,_store,_elname) \
static struct ext4_attr ext4_attr_##_name = { \
.attr = {.name = __stringify(_name), .mode = _mode }, \
.show = _show, \
.store = _store, \
.u = { \
.offset = offsetof(struct ext4_sb_info, _elname),\
}, \
}
#define EXT4_ATTR_OFFSET_ES(_name,_mode,_show,_store,_elname) \
static struct ext4_attr ext4_attr_##_name = { \
.attr = {.name = __stringify(_name), .mode = _mode }, \
.show = _show, \
.store = _store, \
.u = { \
.offset = offsetof(struct ext4_super_block, _elname), \
}, \
}
#define EXT4_ATTR(name, mode, show, store) \
static struct ext4_attr ext4_attr_##name = __ATTR(name, mode, show, store)
#define EXT4_INFO_ATTR(name) EXT4_ATTR(name, 0444, NULL, NULL)
#define EXT4_RO_ATTR(name) EXT4_ATTR(name, 0444, name##_show, NULL)
#define EXT4_RW_ATTR(name) EXT4_ATTR(name, 0644, name##_show, name##_store)
#define EXT4_RO_ATTR_ES_UI(name, elname) \
EXT4_ATTR_OFFSET_ES(name, 0444, es_ui_show, NULL, elname)
#define EXT4_RW_ATTR_SBI_UI(name, elname) \
EXT4_ATTR_OFFSET(name, 0644, sbi_ui_show, sbi_ui_store, elname)
#define ATTR_LIST(name) &ext4_attr_##name.attr
#define EXT4_DEPRECATED_ATTR(_name, _val) \
static struct ext4_attr ext4_attr_##_name = { \
.attr = {.name = __stringify(_name), .mode = 0444 }, \
.show = sbi_deprecated_show, \
.u = { \
.deprecated_val = _val, \
}, \
}
EXT4_RO_ATTR(delayed_allocation_blocks);
EXT4_RO_ATTR(session_write_kbytes);
EXT4_RO_ATTR(lifetime_write_kbytes);
EXT4_RW_ATTR(reserved_clusters);
EXT4_ATTR_OFFSET(inode_readahead_blks, 0644, sbi_ui_show,
inode_readahead_blks_store, s_inode_readahead_blks);
EXT4_RW_ATTR_SBI_UI(inode_goal, s_inode_goal);
EXT4_RW_ATTR_SBI_UI(mb_stats, s_mb_stats);
EXT4_RW_ATTR_SBI_UI(mb_max_to_scan, s_mb_max_to_scan);
EXT4_RW_ATTR_SBI_UI(mb_min_to_scan, s_mb_min_to_scan);
EXT4_RW_ATTR_SBI_UI(mb_order2_req, s_mb_order2_reqs);
EXT4_RW_ATTR_SBI_UI(mb_stream_req, s_mb_stream_request);
EXT4_RW_ATTR_SBI_UI(mb_group_prealloc, s_mb_group_prealloc);
EXT4_DEPRECATED_ATTR(max_writeback_mb_bump, 128);
EXT4_RW_ATTR_SBI_UI(extent_max_zeroout_kb, s_extent_max_zeroout_kb);
EXT4_ATTR(trigger_fs_error, 0200, NULL, trigger_test_error);
EXT4_RW_ATTR_SBI_UI(err_ratelimit_interval_ms, s_err_ratelimit_state.interval);
EXT4_RW_ATTR_SBI_UI(err_ratelimit_burst, s_err_ratelimit_state.burst);
EXT4_RW_ATTR_SBI_UI(warning_ratelimit_interval_ms, s_warning_ratelimit_state.interval);
EXT4_RW_ATTR_SBI_UI(warning_ratelimit_burst, s_warning_ratelimit_state.burst);
EXT4_RW_ATTR_SBI_UI(msg_ratelimit_interval_ms, s_msg_ratelimit_state.interval);
EXT4_RW_ATTR_SBI_UI(msg_ratelimit_burst, s_msg_ratelimit_state.burst);
EXT4_RO_ATTR_ES_UI(errors_count, s_error_count);
EXT4_RO_ATTR_ES_UI(first_error_time, s_first_error_time);
EXT4_RO_ATTR_ES_UI(last_error_time, s_last_error_time);
static struct attribute *ext4_attrs[] = {
ATTR_LIST(delayed_allocation_blocks),
ATTR_LIST(session_write_kbytes),
ATTR_LIST(lifetime_write_kbytes),
ATTR_LIST(reserved_clusters),
ATTR_LIST(inode_readahead_blks),
ATTR_LIST(inode_goal),
ATTR_LIST(mb_stats),
ATTR_LIST(mb_max_to_scan),
ATTR_LIST(mb_min_to_scan),
ATTR_LIST(mb_order2_req),
ATTR_LIST(mb_stream_req),
ATTR_LIST(mb_group_prealloc),
ATTR_LIST(max_writeback_mb_bump),
ATTR_LIST(extent_max_zeroout_kb),
ATTR_LIST(trigger_fs_error),
ATTR_LIST(err_ratelimit_interval_ms),
ATTR_LIST(err_ratelimit_burst),
ATTR_LIST(warning_ratelimit_interval_ms),
ATTR_LIST(warning_ratelimit_burst),
ATTR_LIST(msg_ratelimit_interval_ms),
ATTR_LIST(msg_ratelimit_burst),
ATTR_LIST(errors_count),
ATTR_LIST(first_error_time),
ATTR_LIST(last_error_time),
NULL,
};
/* Features this copy of ext4 supports */
EXT4_INFO_ATTR(lazy_itable_init);
EXT4_INFO_ATTR(batched_discard);
EXT4_INFO_ATTR(meta_bg_resize);
EXT4_INFO_ATTR(encryption);
static struct attribute *ext4_feat_attrs[] = {
ATTR_LIST(lazy_itable_init),
ATTR_LIST(batched_discard),
ATTR_LIST(meta_bg_resize),
ATTR_LIST(encryption),
NULL,
};
static ssize_t ext4_attr_show(struct kobject *kobj,
struct attribute *attr, char *buf)
{
struct ext4_sb_info *sbi = container_of(kobj, struct ext4_sb_info,
s_kobj);
struct ext4_attr *a = container_of(attr, struct ext4_attr, attr);
return a->show ? a->show(a, sbi, buf) : 0;
}
static ssize_t ext4_attr_store(struct kobject *kobj,
struct attribute *attr,
const char *buf, size_t len)
{
struct ext4_sb_info *sbi = container_of(kobj, struct ext4_sb_info,
s_kobj);
struct ext4_attr *a = container_of(attr, struct ext4_attr, attr);
return a->store ? a->store(a, sbi, buf, len) : 0;
}
static void ext4_sb_release(struct kobject *kobj)
{
struct ext4_sb_info *sbi = container_of(kobj, struct ext4_sb_info,
s_kobj);
complete(&sbi->s_kobj_unregister);
}
static const struct sysfs_ops ext4_attr_ops = {
.show = ext4_attr_show,
.store = ext4_attr_store,
};
static struct kobj_type ext4_ktype = {
.default_attrs = ext4_attrs,
.sysfs_ops = &ext4_attr_ops,
.release = ext4_sb_release,
};
static void ext4_feat_release(struct kobject *kobj)
{
complete(&ext4_feat->f_kobj_unregister);
}
static ssize_t ext4_feat_show(struct kobject *kobj,
struct attribute *attr, char *buf)
{
return snprintf(buf, PAGE_SIZE, "supported\n");
}
/*
* We can not use ext4_attr_show/store because it relies on the kobject
* being embedded in the ext4_sb_info structure which is definitely not
* true in this case.
*/
static const struct sysfs_ops ext4_feat_ops = {
.show = ext4_feat_show,
.store = NULL,
};
static struct kobj_type ext4_feat_ktype = {
.default_attrs = ext4_feat_attrs,
.sysfs_ops = &ext4_feat_ops,
.release = ext4_feat_release,
};
/*
* Check whether this filesystem can be mounted based on
* the features present and the RDONLY/RDWR mount requested.
* Returns 1 if this filesystem can be mounted as requested,
* 0 if it cannot be.
*/
static int ext4_feature_set_ok(struct super_block *sb, int readonly)
{
if (EXT4_HAS_INCOMPAT_FEATURE(sb, ~EXT4_FEATURE_INCOMPAT_SUPP)) {
ext4_msg(sb, KERN_ERR,
"Couldn't mount because of "
"unsupported optional features (%x)",
(le32_to_cpu(EXT4_SB(sb)->s_es->s_feature_incompat) &
~EXT4_FEATURE_INCOMPAT_SUPP));
return 0;
}
if (readonly)
return 1;
/* Check that feature set is OK for a read-write mount */
if (EXT4_HAS_RO_COMPAT_FEATURE(sb, ~EXT4_FEATURE_RO_COMPAT_SUPP)) {
ext4_msg(sb, KERN_ERR, "couldn't mount RDWR because of "
"unsupported optional features (%x)",
(le32_to_cpu(EXT4_SB(sb)->s_es->s_feature_ro_compat) &
~EXT4_FEATURE_RO_COMPAT_SUPP));
return 0;
}
/*
* Large file size enabled file system can only be mounted
* read-write on 32-bit systems if kernel is built with CONFIG_LBDAF
*/
if (EXT4_HAS_RO_COMPAT_FEATURE(sb, EXT4_FEATURE_RO_COMPAT_HUGE_FILE)) {
if (sizeof(blkcnt_t) < sizeof(u64)) {
ext4_msg(sb, KERN_ERR, "Filesystem with huge files "
"cannot be mounted RDWR without "
"CONFIG_LBDAF");
return 0;
}
}
if (EXT4_HAS_RO_COMPAT_FEATURE(sb, EXT4_FEATURE_RO_COMPAT_BIGALLOC) &&
!EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_EXTENTS)) {
ext4_msg(sb, KERN_ERR,
"Can't support bigalloc feature without "
"extents feature\n");
return 0;
}
#ifndef CONFIG_QUOTA
if (EXT4_HAS_RO_COMPAT_FEATURE(sb, EXT4_FEATURE_RO_COMPAT_QUOTA) &&
!readonly) {
ext4_msg(sb, KERN_ERR,
"Filesystem with quota feature cannot be mounted RDWR "
"without CONFIG_QUOTA");
return 0;
}
#endif /* CONFIG_QUOTA */
return 1;
}
/*
* This function is called once a day if we have errors logged
* on the file system
*/
static void print_daily_error_info(unsigned long arg)
{
struct super_block *sb = (struct super_block *) arg;
struct ext4_sb_info *sbi;
struct ext4_super_block *es;
sbi = EXT4_SB(sb);
es = sbi->s_es;
if (es->s_error_count)
/* fsck newer than v1.41.13 is needed to clean this condition. */
ext4_msg(sb, KERN_NOTICE, "error count since last fsck: %u",
le32_to_cpu(es->s_error_count));
if (es->s_first_error_time) {
printk(KERN_NOTICE "EXT4-fs (%s): initial error at time %u: %.*s:%d",
sb->s_id, le32_to_cpu(es->s_first_error_time),
(int) sizeof(es->s_first_error_func),
es->s_first_error_func,
le32_to_cpu(es->s_first_error_line));
if (es->s_first_error_ino)
printk(": inode %u",
le32_to_cpu(es->s_first_error_ino));
if (es->s_first_error_block)
printk(": block %llu", (unsigned long long)
le64_to_cpu(es->s_first_error_block));
printk("\n");
}
if (es->s_last_error_time) {
printk(KERN_NOTICE "EXT4-fs (%s): last error at time %u: %.*s:%d",
sb->s_id, le32_to_cpu(es->s_last_error_time),
(int) sizeof(es->s_last_error_func),
es->s_last_error_func,
le32_to_cpu(es->s_last_error_line));
if (es->s_last_error_ino)
printk(": inode %u",
le32_to_cpu(es->s_last_error_ino));
if (es->s_last_error_block)
printk(": block %llu", (unsigned long long)
le64_to_cpu(es->s_last_error_block));
printk("\n");
}
mod_timer(&sbi->s_err_report, jiffies + 24*60*60*HZ); /* Once a day */
}
/* Find next suitable group and run ext4_init_inode_table */
static int ext4_run_li_request(struct ext4_li_request *elr)
{
struct ext4_group_desc *gdp = NULL;
ext4_group_t group, ngroups;
struct super_block *sb;
unsigned long timeout = 0;
int ret = 0;
sb = elr->lr_super;
ngroups = EXT4_SB(sb)->s_groups_count;
sb_start_write(sb);
for (group = elr->lr_next_group; group < ngroups; group++) {
gdp = ext4_get_group_desc(sb, group, NULL);
if (!gdp) {
ret = 1;
break;
}
if (!(gdp->bg_flags & cpu_to_le16(EXT4_BG_INODE_ZEROED)))
break;
}
if (group >= ngroups)
ret = 1;
if (!ret) {
timeout = jiffies;
ret = ext4_init_inode_table(sb, group,
elr->lr_timeout ? 0 : 1);
if (elr->lr_timeout == 0) {
timeout = (jiffies - timeout) *
elr->lr_sbi->s_li_wait_mult;
elr->lr_timeout = timeout;
}
elr->lr_next_sched = jiffies + elr->lr_timeout;
elr->lr_next_group = group + 1;
}
sb_end_write(sb);
return ret;
}
/*
* Remove lr_request from the list_request and free the
* request structure. Should be called with li_list_mtx held
*/
static void ext4_remove_li_request(struct ext4_li_request *elr)
{
struct ext4_sb_info *sbi;
if (!elr)
return;
sbi = elr->lr_sbi;
list_del(&elr->lr_request);
sbi->s_li_request = NULL;
kfree(elr);
}
static void ext4_unregister_li_request(struct super_block *sb)
{
mutex_lock(&ext4_li_mtx);
if (!ext4_li_info) {
mutex_unlock(&ext4_li_mtx);
return;
}
mutex_lock(&ext4_li_info->li_list_mtx);
ext4_remove_li_request(EXT4_SB(sb)->s_li_request);
mutex_unlock(&ext4_li_info->li_list_mtx);
mutex_unlock(&ext4_li_mtx);
}
static struct task_struct *ext4_lazyinit_task;
/*
* This is the function where ext4lazyinit thread lives. It walks
* through the request list searching for next scheduled filesystem.
* When such a fs is found, run the lazy initialization request
* (ext4_rn_li_request) and keep track of the time spend in this
* function. Based on that time we compute next schedule time of
* the request. When walking through the list is complete, compute
* next waking time and put itself into sleep.
*/
static int ext4_lazyinit_thread(void *arg)
{
struct ext4_lazy_init *eli = (struct ext4_lazy_init *)arg;
struct list_head *pos, *n;
struct ext4_li_request *elr;
unsigned long next_wakeup, cur;
BUG_ON(NULL == eli);
cont_thread:
while (true) {
next_wakeup = MAX_JIFFY_OFFSET;
mutex_lock(&eli->li_list_mtx);
if (list_empty(&eli->li_request_list)) {
mutex_unlock(&eli->li_list_mtx);
goto exit_thread;
}
list_for_each_safe(pos, n, &eli->li_request_list) {
elr = list_entry(pos, struct ext4_li_request,
lr_request);
if (time_after_eq(jiffies, elr->lr_next_sched)) {
if (ext4_run_li_request(elr) != 0) {
/* error, remove the lazy_init job */
ext4_remove_li_request(elr);
continue;
}
}
if (time_before(elr->lr_next_sched, next_wakeup))
next_wakeup = elr->lr_next_sched;
}
mutex_unlock(&eli->li_list_mtx);
try_to_freeze();
cur = jiffies;
if ((time_after_eq(cur, next_wakeup)) ||
(MAX_JIFFY_OFFSET == next_wakeup)) {
cond_resched();
continue;
}
schedule_timeout_interruptible(next_wakeup - cur);
if (kthread_should_stop()) {
ext4_clear_request_list();
goto exit_thread;
}
}
exit_thread:
/*
* It looks like the request list is empty, but we need
* to check it under the li_list_mtx lock, to prevent any
* additions into it, and of course we should lock ext4_li_mtx
* to atomically free the list and ext4_li_info, because at
* this point another ext4 filesystem could be registering
* new one.
*/
mutex_lock(&ext4_li_mtx);
mutex_lock(&eli->li_list_mtx);
if (!list_empty(&eli->li_request_list)) {
mutex_unlock(&eli->li_list_mtx);
mutex_unlock(&ext4_li_mtx);
goto cont_thread;
}
mutex_unlock(&eli->li_list_mtx);
kfree(ext4_li_info);
ext4_li_info = NULL;
mutex_unlock(&ext4_li_mtx);
return 0;
}
static void ext4_clear_request_list(void)
{
struct list_head *pos, *n;
struct ext4_li_request *elr;
mutex_lock(&ext4_li_info->li_list_mtx);
list_for_each_safe(pos, n, &ext4_li_info->li_request_list) {
elr = list_entry(pos, struct ext4_li_request,
lr_request);
ext4_remove_li_request(elr);
}
mutex_unlock(&ext4_li_info->li_list_mtx);
}
static int ext4_run_lazyinit_thread(void)
{
ext4_lazyinit_task = kthread_run(ext4_lazyinit_thread,
ext4_li_info, "ext4lazyinit");
if (IS_ERR(ext4_lazyinit_task)) {
int err = PTR_ERR(ext4_lazyinit_task);
ext4_clear_request_list();
kfree(ext4_li_info);
ext4_li_info = NULL;
printk(KERN_CRIT "EXT4-fs: error %d creating inode table "
"initialization thread\n",
err);
return err;
}
ext4_li_info->li_state |= EXT4_LAZYINIT_RUNNING;
return 0;
}
/*
* Check whether it make sense to run itable init. thread or not.
* If there is at least one uninitialized inode table, return
* corresponding group number, else the loop goes through all
* groups and return total number of groups.
*/
static ext4_group_t ext4_has_uninit_itable(struct super_block *sb)
{
ext4_group_t group, ngroups = EXT4_SB(sb)->s_groups_count;
struct ext4_group_desc *gdp = NULL;
for (group = 0; group < ngroups; group++) {
gdp = ext4_get_group_desc(sb, group, NULL);
if (!gdp)
continue;
if (!(gdp->bg_flags & cpu_to_le16(EXT4_BG_INODE_ZEROED)))
break;
}
return group;
}
static int ext4_li_info_new(void)
{
struct ext4_lazy_init *eli = NULL;
eli = kzalloc(sizeof(*eli), GFP_KERNEL);
if (!eli)
return -ENOMEM;
INIT_LIST_HEAD(&eli->li_request_list);
mutex_init(&eli->li_list_mtx);
eli->li_state |= EXT4_LAZYINIT_QUIT;
ext4_li_info = eli;
return 0;
}
static struct ext4_li_request *ext4_li_request_new(struct super_block *sb,
ext4_group_t start)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
struct ext4_li_request *elr;
elr = kzalloc(sizeof(*elr), GFP_KERNEL);
if (!elr)
return NULL;
elr->lr_super = sb;
elr->lr_sbi = sbi;
elr->lr_next_group = start;
/*
* Randomize first schedule time of the request to
* spread the inode table initialization requests
* better.
*/
elr->lr_next_sched = jiffies + (prandom_u32() %
(EXT4_DEF_LI_MAX_START_DELAY * HZ));
return elr;
}
int ext4_register_li_request(struct super_block *sb,
ext4_group_t first_not_zeroed)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
struct ext4_li_request *elr = NULL;
ext4_group_t ngroups = EXT4_SB(sb)->s_groups_count;
int ret = 0;
mutex_lock(&ext4_li_mtx);
if (sbi->s_li_request != NULL) {
/*
* Reset timeout so it can be computed again, because
* s_li_wait_mult might have changed.
*/
sbi->s_li_request->lr_timeout = 0;
goto out;
}
if (first_not_zeroed == ngroups ||
(sb->s_flags & MS_RDONLY) ||
!test_opt(sb, INIT_INODE_TABLE))
goto out;
elr = ext4_li_request_new(sb, first_not_zeroed);
if (!elr) {
ret = -ENOMEM;
goto out;
}
if (NULL == ext4_li_info) {
ret = ext4_li_info_new();
if (ret)
goto out;
}
mutex_lock(&ext4_li_info->li_list_mtx);
list_add(&elr->lr_request, &ext4_li_info->li_request_list);
mutex_unlock(&ext4_li_info->li_list_mtx);
sbi->s_li_request = elr;
/*
* set elr to NULL here since it has been inserted to
* the request_list and the removal and free of it is
* handled by ext4_clear_request_list from now on.
*/
elr = NULL;
if (!(ext4_li_info->li_state & EXT4_LAZYINIT_RUNNING)) {
ret = ext4_run_lazyinit_thread();
if (ret)
goto out;
}
out:
mutex_unlock(&ext4_li_mtx);
if (ret)
kfree(elr);
return ret;
}
/*
* We do not need to lock anything since this is called on
* module unload.
*/
static void ext4_destroy_lazyinit_thread(void)
{
/*
* If thread exited earlier
* there's nothing to be done.
*/
if (!ext4_li_info || !ext4_lazyinit_task)
return;
kthread_stop(ext4_lazyinit_task);
}
static int set_journal_csum_feature_set(struct super_block *sb)
{
int ret = 1;
int compat, incompat;
struct ext4_sb_info *sbi = EXT4_SB(sb);
if (ext4_has_metadata_csum(sb)) {
/* journal checksum v3 */
compat = 0;
incompat = JBD2_FEATURE_INCOMPAT_CSUM_V3;
} else {
/* journal checksum v1 */
compat = JBD2_FEATURE_COMPAT_CHECKSUM;
incompat = 0;
}
jbd2_journal_clear_features(sbi->s_journal,
JBD2_FEATURE_COMPAT_CHECKSUM, 0,
JBD2_FEATURE_INCOMPAT_CSUM_V3 |
JBD2_FEATURE_INCOMPAT_CSUM_V2);
if (test_opt(sb, JOURNAL_ASYNC_COMMIT)) {
ret = jbd2_journal_set_features(sbi->s_journal,
compat, 0,
JBD2_FEATURE_INCOMPAT_ASYNC_COMMIT |
incompat);
} else if (test_opt(sb, JOURNAL_CHECKSUM)) {
ret = jbd2_journal_set_features(sbi->s_journal,
compat, 0,
incompat);
jbd2_journal_clear_features(sbi->s_journal, 0, 0,
JBD2_FEATURE_INCOMPAT_ASYNC_COMMIT);
} else {
jbd2_journal_clear_features(sbi->s_journal, 0, 0,
JBD2_FEATURE_INCOMPAT_ASYNC_COMMIT);
}
return ret;
}
/*
* Note: calculating the overhead so we can be compatible with
* historical BSD practice is quite difficult in the face of
* clusters/bigalloc. This is because multiple metadata blocks from
* different block group can end up in the same allocation cluster.
* Calculating the exact overhead in the face of clustered allocation
* requires either O(all block bitmaps) in memory or O(number of block
* groups**2) in time. We will still calculate the superblock for
* older file systems --- and if we come across with a bigalloc file
* system with zero in s_overhead_clusters the estimate will be close to
* correct especially for very large cluster sizes --- but for newer
* file systems, it's better to calculate this figure once at mkfs
* time, and store it in the superblock. If the superblock value is
* present (even for non-bigalloc file systems), we will use it.
*/
static int count_overhead(struct super_block *sb, ext4_group_t grp,
char *buf)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
struct ext4_group_desc *gdp;
ext4_fsblk_t first_block, last_block, b;
ext4_group_t i, ngroups = ext4_get_groups_count(sb);
int s, j, count = 0;
if (!EXT4_HAS_RO_COMPAT_FEATURE(sb, EXT4_FEATURE_RO_COMPAT_BIGALLOC))
return (ext4_bg_has_super(sb, grp) + ext4_bg_num_gdb(sb, grp) +
sbi->s_itb_per_group + 2);
first_block = le32_to_cpu(sbi->s_es->s_first_data_block) +
(grp * EXT4_BLOCKS_PER_GROUP(sb));
last_block = first_block + EXT4_BLOCKS_PER_GROUP(sb) - 1;
for (i = 0; i < ngroups; i++) {
gdp = ext4_get_group_desc(sb, i, NULL);
b = ext4_block_bitmap(sb, gdp);
if (b >= first_block && b <= last_block) {
ext4_set_bit(EXT4_B2C(sbi, b - first_block), buf);
count++;
}
b = ext4_inode_bitmap(sb, gdp);
if (b >= first_block && b <= last_block) {
ext4_set_bit(EXT4_B2C(sbi, b - first_block), buf);
count++;
}
b = ext4_inode_table(sb, gdp);
if (b >= first_block && b + sbi->s_itb_per_group <= last_block)
for (j = 0; j < sbi->s_itb_per_group; j++, b++) {
int c = EXT4_B2C(sbi, b - first_block);
ext4_set_bit(c, buf);
count++;
}
if (i != grp)
continue;
s = 0;
if (ext4_bg_has_super(sb, grp)) {
ext4_set_bit(s++, buf);
count++;
}
for (j = ext4_bg_num_gdb(sb, grp); j > 0; j--) {
ext4_set_bit(EXT4_B2C(sbi, s++), buf);
count++;
}
}
if (!count)
return 0;
return EXT4_CLUSTERS_PER_GROUP(sb) -
ext4_count_free(buf, EXT4_CLUSTERS_PER_GROUP(sb) / 8);
}
/*
* Compute the overhead and stash it in sbi->s_overhead
*/
int ext4_calculate_overhead(struct super_block *sb)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
struct ext4_super_block *es = sbi->s_es;
ext4_group_t i, ngroups = ext4_get_groups_count(sb);
ext4_fsblk_t overhead = 0;
char *buf = (char *) get_zeroed_page(GFP_KERNEL);
if (!buf)
return -ENOMEM;
/*
* Compute the overhead (FS structures). This is constant
* for a given filesystem unless the number of block groups
* changes so we cache the previous value until it does.
*/
/*
* All of the blocks before first_data_block are overhead
*/
overhead = EXT4_B2C(sbi, le32_to_cpu(es->s_first_data_block));
/*
* Add the overhead found in each block group
*/
for (i = 0; i < ngroups; i++) {
int blks;
blks = count_overhead(sb, i, buf);
overhead += blks;
if (blks)
memset(buf, 0, PAGE_SIZE);
cond_resched();
}
/* Add the journal blocks as well */
if (sbi->s_journal)
overhead += EXT4_NUM_B2C(sbi, sbi->s_journal->j_maxlen);
sbi->s_overhead = overhead;
smp_wmb();
free_page((unsigned long) buf);
return 0;
}
static ext4_fsblk_t ext4_calculate_resv_clusters(struct super_block *sb)
{
ext4_fsblk_t resv_clusters;
/*
* There's no need to reserve anything when we aren't using extents.
* The space estimates are exact, there are no unwritten extents,
* hole punching doesn't need new metadata... This is needed especially
* to keep ext2/3 backward compatibility.
*/
if (!EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_EXTENTS))
return 0;
/*
* By default we reserve 2% or 4096 clusters, whichever is smaller.
* This should cover the situations where we can not afford to run
* out of space like for example punch hole, or converting
* unwritten extents in delalloc path. In most cases such
* allocation would require 1, or 2 blocks, higher numbers are
* very rare.
*/
resv_clusters = ext4_blocks_count(EXT4_SB(sb)->s_es) >>
EXT4_SB(sb)->s_cluster_bits;
do_div(resv_clusters, 50);
resv_clusters = min_t(ext4_fsblk_t, resv_clusters, 4096);
return resv_clusters;
}
static int ext4_reserve_clusters(struct ext4_sb_info *sbi, ext4_fsblk_t count)
{
ext4_fsblk_t clusters = ext4_blocks_count(sbi->s_es) >>
sbi->s_cluster_bits;
if (count >= clusters)
return -EINVAL;
atomic64_set(&sbi->s_resv_clusters, count);
return 0;
}
static int ext4_fill_super(struct super_block *sb, void *data, int silent)
{
char *orig_data = kstrdup(data, GFP_KERNEL);
struct buffer_head *bh;
struct ext4_super_block *es = NULL;
struct ext4_sb_info *sbi;
ext4_fsblk_t block;
ext4_fsblk_t sb_block = get_sb_block(&data);
ext4_fsblk_t logical_sb_block;
unsigned long offset = 0;
unsigned long journal_devnum = 0;
unsigned long def_mount_opts;
struct inode *root;
char *cp;
const char *descr;
int ret = -ENOMEM;
int blocksize, clustersize;
unsigned int db_count;
unsigned int i;
int needs_recovery, has_huge_files, has_bigalloc;
__u64 blocks_count;
int err = 0;
unsigned int journal_ioprio = DEFAULT_JOURNAL_IOPRIO;
ext4_group_t first_not_zeroed;
sbi = kzalloc(sizeof(*sbi), GFP_KERNEL);
if (!sbi)
goto out_free_orig;
sbi->s_blockgroup_lock =
kzalloc(sizeof(struct blockgroup_lock), GFP_KERNEL);
if (!sbi->s_blockgroup_lock) {
kfree(sbi);
goto out_free_orig;
}
sb->s_fs_info = sbi;
sbi->s_sb = sb;
sbi->s_inode_readahead_blks = EXT4_DEF_INODE_READAHEAD_BLKS;
sbi->s_sb_block = sb_block;
if (sb->s_bdev->bd_part)
sbi->s_sectors_written_start =
part_stat_read(sb->s_bdev->bd_part, sectors[1]);
/* Cleanup superblock name */
for (cp = sb->s_id; (cp = strchr(cp, '/'));)
*cp = '!';
/* -EINVAL is default */
ret = -EINVAL;
blocksize = sb_min_blocksize(sb, EXT4_MIN_BLOCK_SIZE);
if (!blocksize) {
ext4_msg(sb, KERN_ERR, "unable to set blocksize");
goto out_fail;
}
/*
* The ext4 superblock will not be buffer aligned for other than 1kB
* block sizes. We need to calculate the offset from buffer start.
*/
if (blocksize != EXT4_MIN_BLOCK_SIZE) {
logical_sb_block = sb_block * EXT4_MIN_BLOCK_SIZE;
offset = do_div(logical_sb_block, blocksize);
} else {
logical_sb_block = sb_block;
}
if (!(bh = sb_bread_unmovable(sb, logical_sb_block))) {
ext4_msg(sb, KERN_ERR, "unable to read superblock");
goto out_fail;
}
/*
* Note: s_es must be initialized as soon as possible because
* some ext4 macro-instructions depend on its value
*/
es = (struct ext4_super_block *) (bh->b_data + offset);
sbi->s_es = es;
sb->s_magic = le16_to_cpu(es->s_magic);
if (sb->s_magic != EXT4_SUPER_MAGIC)
goto cantfind_ext4;
sbi->s_kbytes_written = le64_to_cpu(es->s_kbytes_written);
/* Warn if metadata_csum and gdt_csum are both set. */
if (EXT4_HAS_RO_COMPAT_FEATURE(sb,
EXT4_FEATURE_RO_COMPAT_METADATA_CSUM) &&
EXT4_HAS_RO_COMPAT_FEATURE(sb, EXT4_FEATURE_RO_COMPAT_GDT_CSUM))
ext4_warning(sb, KERN_INFO "metadata_csum and uninit_bg are "
"redundant flags; please run fsck.");
/* Check for a known checksum algorithm */
if (!ext4_verify_csum_type(sb, es)) {
ext4_msg(sb, KERN_ERR, "VFS: Found ext4 filesystem with "
"unknown checksum algorithm.");
silent = 1;
goto cantfind_ext4;
}
/* Load the checksum driver */
if (EXT4_HAS_RO_COMPAT_FEATURE(sb,
EXT4_FEATURE_RO_COMPAT_METADATA_CSUM)) {
sbi->s_chksum_driver = crypto_alloc_shash("crc32c", 0, 0);
if (IS_ERR(sbi->s_chksum_driver)) {
ext4_msg(sb, KERN_ERR, "Cannot load crc32c driver.");
ret = PTR_ERR(sbi->s_chksum_driver);
sbi->s_chksum_driver = NULL;
goto failed_mount;
}
}
/* Check superblock checksum */
if (!ext4_superblock_csum_verify(sb, es)) {
ext4_msg(sb, KERN_ERR, "VFS: Found ext4 filesystem with "
"invalid superblock checksum. Run e2fsck?");
silent = 1;
goto cantfind_ext4;
}
/* Precompute checksum seed for all metadata */
if (ext4_has_metadata_csum(sb))
sbi->s_csum_seed = ext4_chksum(sbi, ~0, es->s_uuid,
sizeof(es->s_uuid));
/* Set defaults before we parse the mount options */
def_mount_opts = le32_to_cpu(es->s_default_mount_opts);
set_opt(sb, INIT_INODE_TABLE);
if (def_mount_opts & EXT4_DEFM_DEBUG)
set_opt(sb, DEBUG);
if (def_mount_opts & EXT4_DEFM_BSDGROUPS)
set_opt(sb, GRPID);
if (def_mount_opts & EXT4_DEFM_UID16)
set_opt(sb, NO_UID32);
/* xattr user namespace & acls are now defaulted on */
set_opt(sb, XATTR_USER);
#ifdef CONFIG_EXT4_FS_POSIX_ACL
set_opt(sb, POSIX_ACL);
#endif
/* don't forget to enable journal_csum when metadata_csum is enabled. */
if (ext4_has_metadata_csum(sb))
set_opt(sb, JOURNAL_CHECKSUM);
if ((def_mount_opts & EXT4_DEFM_JMODE) == EXT4_DEFM_JMODE_DATA)
set_opt(sb, JOURNAL_DATA);
else if ((def_mount_opts & EXT4_DEFM_JMODE) == EXT4_DEFM_JMODE_ORDERED)
set_opt(sb, ORDERED_DATA);
else if ((def_mount_opts & EXT4_DEFM_JMODE) == EXT4_DEFM_JMODE_WBACK)
set_opt(sb, WRITEBACK_DATA);
if (le16_to_cpu(sbi->s_es->s_errors) == EXT4_ERRORS_PANIC)
set_opt(sb, ERRORS_PANIC);
else if (le16_to_cpu(sbi->s_es->s_errors) == EXT4_ERRORS_CONTINUE)
set_opt(sb, ERRORS_CONT);
else
set_opt(sb, ERRORS_RO);
/* block_validity enabled by default; disable with noblock_validity */
set_opt(sb, BLOCK_VALIDITY);
if (def_mount_opts & EXT4_DEFM_DISCARD)
set_opt(sb, DISCARD);
sbi->s_resuid = make_kuid(&init_user_ns, le16_to_cpu(es->s_def_resuid));
sbi->s_resgid = make_kgid(&init_user_ns, le16_to_cpu(es->s_def_resgid));
sbi->s_commit_interval = JBD2_DEFAULT_MAX_COMMIT_AGE * HZ;
sbi->s_min_batch_time = EXT4_DEF_MIN_BATCH_TIME;
sbi->s_max_batch_time = EXT4_DEF_MAX_BATCH_TIME;
if ((def_mount_opts & EXT4_DEFM_NOBARRIER) == 0)
set_opt(sb, BARRIER);
/*
* enable delayed allocation by default
* Use -o nodelalloc to turn it off
*/
if (!IS_EXT3_SB(sb) && !IS_EXT2_SB(sb) &&
((def_mount_opts & EXT4_DEFM_NODELALLOC) == 0))
set_opt(sb, DELALLOC);
/*
* set default s_li_wait_mult for lazyinit, for the case there is
* no mount option specified.
*/
sbi->s_li_wait_mult = EXT4_DEF_LI_WAIT_MULT;
if (!parse_options((char *) sbi->s_es->s_mount_opts, sb,
&journal_devnum, &journal_ioprio, 0)) {
ext4_msg(sb, KERN_WARNING,
"failed to parse options in superblock: %s",
sbi->s_es->s_mount_opts);
}
sbi->s_def_mount_opt = sbi->s_mount_opt;
if (!parse_options((char *) data, sb, &journal_devnum,
&journal_ioprio, 0))
goto failed_mount;
if (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_JOURNAL_DATA) {
printk_once(KERN_WARNING "EXT4-fs: Warning: mounting "
"with data=journal disables delayed "
"allocation and O_DIRECT support!\n");
if (test_opt2(sb, EXPLICIT_DELALLOC)) {
ext4_msg(sb, KERN_ERR, "can't mount with "
"both data=journal and delalloc");
goto failed_mount;
}
if (test_opt(sb, DIOREAD_NOLOCK)) {
ext4_msg(sb, KERN_ERR, "can't mount with "
"both data=journal and dioread_nolock");
goto failed_mount;
}
if (test_opt(sb, DELALLOC))
clear_opt(sb, DELALLOC);
}
sb->s_flags = (sb->s_flags & ~MS_POSIXACL) |
(test_opt(sb, POSIX_ACL) ? MS_POSIXACL : 0);
if (le32_to_cpu(es->s_rev_level) == EXT4_GOOD_OLD_REV &&
(EXT4_HAS_COMPAT_FEATURE(sb, ~0U) ||
EXT4_HAS_RO_COMPAT_FEATURE(sb, ~0U) ||
EXT4_HAS_INCOMPAT_FEATURE(sb, ~0U)))
ext4_msg(sb, KERN_WARNING,
"feature flags set on rev 0 fs, "
"running e2fsck is recommended");
if (es->s_creator_os == cpu_to_le32(EXT4_OS_HURD)) {
set_opt2(sb, HURD_COMPAT);
if (EXT4_HAS_INCOMPAT_FEATURE(sb,
EXT4_FEATURE_INCOMPAT_64BIT)) {
ext4_msg(sb, KERN_ERR,
"The Hurd can't support 64-bit file systems");
goto failed_mount;
}
}
if (IS_EXT2_SB(sb)) {
if (ext2_feature_set_ok(sb))
ext4_msg(sb, KERN_INFO, "mounting ext2 file system "
"using the ext4 subsystem");
else {
ext4_msg(sb, KERN_ERR, "couldn't mount as ext2 due "
"to feature incompatibilities");
goto failed_mount;
}
}
if (IS_EXT3_SB(sb)) {
if (ext3_feature_set_ok(sb))
ext4_msg(sb, KERN_INFO, "mounting ext3 file system "
"using the ext4 subsystem");
else {
ext4_msg(sb, KERN_ERR, "couldn't mount as ext3 due "
"to feature incompatibilities");
goto failed_mount;
}
}
/*
* Check feature flags regardless of the revision level, since we
* previously didn't change the revision level when setting the flags,
* so there is a chance incompat flags are set on a rev 0 filesystem.
*/
if (!ext4_feature_set_ok(sb, (sb->s_flags & MS_RDONLY)))
goto failed_mount;
blocksize = BLOCK_SIZE << le32_to_cpu(es->s_log_block_size);
if (blocksize < EXT4_MIN_BLOCK_SIZE ||
blocksize > EXT4_MAX_BLOCK_SIZE) {
ext4_msg(sb, KERN_ERR,
"Unsupported filesystem blocksize %d", blocksize);
goto failed_mount;
}
if (EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_ENCRYPT) &&
es->s_encryption_level) {
ext4_msg(sb, KERN_ERR, "Unsupported encryption level %d",
es->s_encryption_level);
goto failed_mount;
}
if (sb->s_blocksize != blocksize) {
/* Validate the filesystem blocksize */
if (!sb_set_blocksize(sb, blocksize)) {
ext4_msg(sb, KERN_ERR, "bad block size %d",
blocksize);
goto failed_mount;
}
brelse(bh);
logical_sb_block = sb_block * EXT4_MIN_BLOCK_SIZE;
offset = do_div(logical_sb_block, blocksize);
bh = sb_bread_unmovable(sb, logical_sb_block);
if (!bh) {
ext4_msg(sb, KERN_ERR,
"Can't read superblock on 2nd try");
goto failed_mount;
}
es = (struct ext4_super_block *)(bh->b_data + offset);
sbi->s_es = es;
if (es->s_magic != cpu_to_le16(EXT4_SUPER_MAGIC)) {
ext4_msg(sb, KERN_ERR,
"Magic mismatch, very weird!");
goto failed_mount;
}
}
has_huge_files = EXT4_HAS_RO_COMPAT_FEATURE(sb,
EXT4_FEATURE_RO_COMPAT_HUGE_FILE);
sbi->s_bitmap_maxbytes = ext4_max_bitmap_size(sb->s_blocksize_bits,
has_huge_files);
sb->s_maxbytes = ext4_max_size(sb->s_blocksize_bits, has_huge_files);
if (le32_to_cpu(es->s_rev_level) == EXT4_GOOD_OLD_REV) {
sbi->s_inode_size = EXT4_GOOD_OLD_INODE_SIZE;
sbi->s_first_ino = EXT4_GOOD_OLD_FIRST_INO;
} else {
sbi->s_inode_size = le16_to_cpu(es->s_inode_size);
sbi->s_first_ino = le32_to_cpu(es->s_first_ino);
if ((sbi->s_inode_size < EXT4_GOOD_OLD_INODE_SIZE) ||
(!is_power_of_2(sbi->s_inode_size)) ||
(sbi->s_inode_size > blocksize)) {
ext4_msg(sb, KERN_ERR,
"unsupported inode size: %d",
sbi->s_inode_size);
goto failed_mount;
}
if (sbi->s_inode_size > EXT4_GOOD_OLD_INODE_SIZE)
sb->s_time_gran = 1 << (EXT4_EPOCH_BITS - 2);
}
sbi->s_desc_size = le16_to_cpu(es->s_desc_size);
if (EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_64BIT)) {
if (sbi->s_desc_size < EXT4_MIN_DESC_SIZE_64BIT ||
sbi->s_desc_size > EXT4_MAX_DESC_SIZE ||
!is_power_of_2(sbi->s_desc_size)) {
ext4_msg(sb, KERN_ERR,
"unsupported descriptor size %lu",
sbi->s_desc_size);
goto failed_mount;
}
} else
sbi->s_desc_size = EXT4_MIN_DESC_SIZE;
sbi->s_blocks_per_group = le32_to_cpu(es->s_blocks_per_group);
sbi->s_inodes_per_group = le32_to_cpu(es->s_inodes_per_group);
if (EXT4_INODE_SIZE(sb) == 0 || EXT4_INODES_PER_GROUP(sb) == 0)
goto cantfind_ext4;
sbi->s_inodes_per_block = blocksize / EXT4_INODE_SIZE(sb);
if (sbi->s_inodes_per_block == 0)
goto cantfind_ext4;
sbi->s_itb_per_group = sbi->s_inodes_per_group /
sbi->s_inodes_per_block;
sbi->s_desc_per_block = blocksize / EXT4_DESC_SIZE(sb);
sbi->s_sbh = bh;
sbi->s_mount_state = le16_to_cpu(es->s_state);
sbi->s_addr_per_block_bits = ilog2(EXT4_ADDR_PER_BLOCK(sb));
sbi->s_desc_per_block_bits = ilog2(EXT4_DESC_PER_BLOCK(sb));
for (i = 0; i < 4; i++)
sbi->s_hash_seed[i] = le32_to_cpu(es->s_hash_seed[i]);
sbi->s_def_hash_version = es->s_def_hash_version;
if (EXT4_HAS_COMPAT_FEATURE(sb, EXT4_FEATURE_COMPAT_DIR_INDEX)) {
i = le32_to_cpu(es->s_flags);
if (i & EXT2_FLAGS_UNSIGNED_HASH)
sbi->s_hash_unsigned = 3;
else if ((i & EXT2_FLAGS_SIGNED_HASH) == 0) {
#ifdef __CHAR_UNSIGNED__
if (!(sb->s_flags & MS_RDONLY))
es->s_flags |=
cpu_to_le32(EXT2_FLAGS_UNSIGNED_HASH);
sbi->s_hash_unsigned = 3;
#else
if (!(sb->s_flags & MS_RDONLY))
es->s_flags |=
cpu_to_le32(EXT2_FLAGS_SIGNED_HASH);
#endif
}
}
/* Handle clustersize */
clustersize = BLOCK_SIZE << le32_to_cpu(es->s_log_cluster_size);
has_bigalloc = EXT4_HAS_RO_COMPAT_FEATURE(sb,
EXT4_FEATURE_RO_COMPAT_BIGALLOC);
if (has_bigalloc) {
if (clustersize < blocksize) {
ext4_msg(sb, KERN_ERR,
"cluster size (%d) smaller than "
"block size (%d)", clustersize, blocksize);
goto failed_mount;
}
sbi->s_cluster_bits = le32_to_cpu(es->s_log_cluster_size) -
le32_to_cpu(es->s_log_block_size);
sbi->s_clusters_per_group =
le32_to_cpu(es->s_clusters_per_group);
if (sbi->s_clusters_per_group > blocksize * 8) {
ext4_msg(sb, KERN_ERR,
"#clusters per group too big: %lu",
sbi->s_clusters_per_group);
goto failed_mount;
}
if (sbi->s_blocks_per_group !=
(sbi->s_clusters_per_group * (clustersize / blocksize))) {
ext4_msg(sb, KERN_ERR, "blocks per group (%lu) and "
"clusters per group (%lu) inconsistent",
sbi->s_blocks_per_group,
sbi->s_clusters_per_group);
goto failed_mount;
}
} else {
if (clustersize != blocksize) {
ext4_warning(sb, "fragment/cluster size (%d) != "
"block size (%d)", clustersize,
blocksize);
clustersize = blocksize;
}
if (sbi->s_blocks_per_group > blocksize * 8) {
ext4_msg(sb, KERN_ERR,
"#blocks per group too big: %lu",
sbi->s_blocks_per_group);
goto failed_mount;
}
sbi->s_clusters_per_group = sbi->s_blocks_per_group;
sbi->s_cluster_bits = 0;
}
sbi->s_cluster_ratio = clustersize / blocksize;
if (sbi->s_inodes_per_group > blocksize * 8) {
ext4_msg(sb, KERN_ERR,
"#inodes per group too big: %lu",
sbi->s_inodes_per_group);
goto failed_mount;
}
/* Do we have standard group size of clustersize * 8 blocks ? */
if (sbi->s_blocks_per_group == clustersize << 3)
set_opt2(sb, STD_GROUP_SIZE);
/*
* Test whether we have more sectors than will fit in sector_t,
* and whether the max offset is addressable by the page cache.
*/
err = generic_check_addressable(sb->s_blocksize_bits,
ext4_blocks_count(es));
if (err) {
ext4_msg(sb, KERN_ERR, "filesystem"
" too large to mount safely on this system");
if (sizeof(sector_t) < 8)
ext4_msg(sb, KERN_WARNING, "CONFIG_LBDAF not enabled");
goto failed_mount;
}
if (EXT4_BLOCKS_PER_GROUP(sb) == 0)
goto cantfind_ext4;
/* check blocks count against device size */
blocks_count = sb->s_bdev->bd_inode->i_size >> sb->s_blocksize_bits;
if (blocks_count && ext4_blocks_count(es) > blocks_count) {
ext4_msg(sb, KERN_WARNING, "bad geometry: block count %llu "
"exceeds size of device (%llu blocks)",
ext4_blocks_count(es), blocks_count);
goto failed_mount;
}
/*
* It makes no sense for the first data block to be beyond the end
* of the filesystem.
*/
if (le32_to_cpu(es->s_first_data_block) >= ext4_blocks_count(es)) {
ext4_msg(sb, KERN_WARNING, "bad geometry: first data "
"block %u is beyond end of filesystem (%llu)",
le32_to_cpu(es->s_first_data_block),
ext4_blocks_count(es));
goto failed_mount;
}
blocks_count = (ext4_blocks_count(es) -
le32_to_cpu(es->s_first_data_block) +
EXT4_BLOCKS_PER_GROUP(sb) - 1);
do_div(blocks_count, EXT4_BLOCKS_PER_GROUP(sb));
if (blocks_count > ((uint64_t)1<<32) - EXT4_DESC_PER_BLOCK(sb)) {
ext4_msg(sb, KERN_WARNING, "groups count too large: %u "
"(block count %llu, first data block %u, "
"blocks per group %lu)", sbi->s_groups_count,
ext4_blocks_count(es),
le32_to_cpu(es->s_first_data_block),
EXT4_BLOCKS_PER_GROUP(sb));
goto failed_mount;
}
sbi->s_groups_count = blocks_count;
sbi->s_blockfile_groups = min_t(ext4_group_t, sbi->s_groups_count,
(EXT4_MAX_BLOCK_FILE_PHYS / EXT4_BLOCKS_PER_GROUP(sb)));
db_count = (sbi->s_groups_count + EXT4_DESC_PER_BLOCK(sb) - 1) /
EXT4_DESC_PER_BLOCK(sb);
sbi->s_group_desc = ext4_kvmalloc(db_count *
sizeof(struct buffer_head *),
GFP_KERNEL);
if (sbi->s_group_desc == NULL) {
ext4_msg(sb, KERN_ERR, "not enough memory");
ret = -ENOMEM;
goto failed_mount;
}
if (ext4_proc_root)
sbi->s_proc = proc_mkdir(sb->s_id, ext4_proc_root);
if (sbi->s_proc)
proc_create_data("options", S_IRUGO, sbi->s_proc,
&ext4_seq_options_fops, sb);
bgl_lock_init(sbi->s_blockgroup_lock);
for (i = 0; i < db_count; i++) {
block = descriptor_loc(sb, logical_sb_block, i);
sbi->s_group_desc[i] = sb_bread_unmovable(sb, block);
if (!sbi->s_group_desc[i]) {
ext4_msg(sb, KERN_ERR,
"can't read group descriptor %d", i);
db_count = i;
goto failed_mount2;
}
}
if (!ext4_check_descriptors(sb, &first_not_zeroed)) {
ext4_msg(sb, KERN_ERR, "group descriptors corrupted!");
goto failed_mount2;
}
sbi->s_gdb_count = db_count;
get_random_bytes(&sbi->s_next_generation, sizeof(u32));
spin_lock_init(&sbi->s_next_gen_lock);
init_timer(&sbi->s_err_report);
sbi->s_err_report.function = print_daily_error_info;
sbi->s_err_report.data = (unsigned long) sb;
/* Register extent status tree shrinker */
if (ext4_es_register_shrinker(sbi))
goto failed_mount3;
sbi->s_stripe = ext4_get_stripe_size(sbi);
sbi->s_extent_max_zeroout_kb = 32;
/*
* set up enough so that it can read an inode
*/
sb->s_op = &ext4_sops;
sb->s_export_op = &ext4_export_ops;
sb->s_xattr = ext4_xattr_handlers;
#ifdef CONFIG_QUOTA
sb->dq_op = &ext4_quota_operations;
if (EXT4_HAS_RO_COMPAT_FEATURE(sb, EXT4_FEATURE_RO_COMPAT_QUOTA))
sb->s_qcop = &ext4_qctl_sysfile_operations;
else
sb->s_qcop = &ext4_qctl_operations;
#endif
memcpy(sb->s_uuid, es->s_uuid, sizeof(es->s_uuid));
INIT_LIST_HEAD(&sbi->s_orphan); /* unlinked but open files */
mutex_init(&sbi->s_orphan_lock);
sb->s_root = NULL;
needs_recovery = (es->s_last_orphan != 0 ||
EXT4_HAS_INCOMPAT_FEATURE(sb,
EXT4_FEATURE_INCOMPAT_RECOVER));
if (EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_MMP) &&
!(sb->s_flags & MS_RDONLY))
if (ext4_multi_mount_protect(sb, le64_to_cpu(es->s_mmp_block)))
goto failed_mount3a;
/*
* The first inode we look at is the journal inode. Don't try
* root first: it may be modified in the journal!
*/
if (!test_opt(sb, NOLOAD) &&
EXT4_HAS_COMPAT_FEATURE(sb, EXT4_FEATURE_COMPAT_HAS_JOURNAL)) {
if (ext4_load_journal(sb, es, journal_devnum))
goto failed_mount3a;
} else if (test_opt(sb, NOLOAD) && !(sb->s_flags & MS_RDONLY) &&
EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_RECOVER)) {
ext4_msg(sb, KERN_ERR, "required journal recovery "
"suppressed and not mounted read-only");
goto failed_mount_wq;
} else {
clear_opt(sb, DATA_FLAGS);
sbi->s_journal = NULL;
needs_recovery = 0;
goto no_journal;
}
if (EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_64BIT) &&
!jbd2_journal_set_features(EXT4_SB(sb)->s_journal, 0, 0,
JBD2_FEATURE_INCOMPAT_64BIT)) {
ext4_msg(sb, KERN_ERR, "Failed to set 64-bit journal feature");
goto failed_mount_wq;
}
if (!set_journal_csum_feature_set(sb)) {
ext4_msg(sb, KERN_ERR, "Failed to set journal checksum "
"feature set");
goto failed_mount_wq;
}
/* We have now updated the journal if required, so we can
* validate the data journaling mode. */
switch (test_opt(sb, DATA_FLAGS)) {
case 0:
/* No mode set, assume a default based on the journal
* capabilities: ORDERED_DATA if the journal can
* cope, else JOURNAL_DATA
*/
if (jbd2_journal_check_available_features
(sbi->s_journal, 0, 0, JBD2_FEATURE_INCOMPAT_REVOKE))
set_opt(sb, ORDERED_DATA);
else
set_opt(sb, JOURNAL_DATA);
break;
case EXT4_MOUNT_ORDERED_DATA:
case EXT4_MOUNT_WRITEBACK_DATA:
if (!jbd2_journal_check_available_features
(sbi->s_journal, 0, 0, JBD2_FEATURE_INCOMPAT_REVOKE)) {
ext4_msg(sb, KERN_ERR, "Journal does not support "
"requested data journaling mode");
goto failed_mount_wq;
}
default:
break;
}
set_task_ioprio(sbi->s_journal->j_task, journal_ioprio);
sbi->s_journal->j_commit_callback = ext4_journal_commit_callback;
no_journal:
if (ext4_mballoc_ready) {
sbi->s_mb_cache = ext4_xattr_create_cache(sb->s_id);
if (!sbi->s_mb_cache) {
ext4_msg(sb, KERN_ERR, "Failed to create an mb_cache");
goto failed_mount_wq;
}
}
if (unlikely(sbi->s_mount_flags & EXT4_MF_TEST_DUMMY_ENCRYPTION) &&
!(sb->s_flags & MS_RDONLY) &&
!EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_ENCRYPT)) {
EXT4_SET_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_ENCRYPT);
ext4_commit_super(sb, 1);
}
/*
* Get the # of file system overhead blocks from the
* superblock if present.
*/
if (es->s_overhead_clusters)
sbi->s_overhead = le32_to_cpu(es->s_overhead_clusters);
else {
err = ext4_calculate_overhead(sb);
if (err)
goto failed_mount_wq;
}
/*
* The maximum number of concurrent works can be high and
* concurrency isn't really necessary. Limit it to 1.
*/
EXT4_SB(sb)->rsv_conversion_wq =
alloc_workqueue("ext4-rsv-conversion", WQ_MEM_RECLAIM | WQ_UNBOUND, 1);
if (!EXT4_SB(sb)->rsv_conversion_wq) {
printk(KERN_ERR "EXT4-fs: failed to create workqueue\n");
ret = -ENOMEM;
goto failed_mount4;
}
/*
* The jbd2_journal_load will have done any necessary log recovery,
* so we can safely mount the rest of the filesystem now.
*/
root = ext4_iget(sb, EXT4_ROOT_INO);
if (IS_ERR(root)) {
ext4_msg(sb, KERN_ERR, "get root inode failed");
ret = PTR_ERR(root);
root = NULL;
goto failed_mount4;
}
if (!S_ISDIR(root->i_mode) || !root->i_blocks || !root->i_size) {
ext4_msg(sb, KERN_ERR, "corrupt root inode, run e2fsck");
iput(root);
goto failed_mount4;
}
sb->s_root = d_make_root(root);
if (!sb->s_root) {
ext4_msg(sb, KERN_ERR, "get root dentry failed");
ret = -ENOMEM;
goto failed_mount4;
}
if (ext4_setup_super(sb, es, sb->s_flags & MS_RDONLY))
sb->s_flags |= MS_RDONLY;
/* determine the minimum size of new large inodes, if present */
if (sbi->s_inode_size > EXT4_GOOD_OLD_INODE_SIZE) {
sbi->s_want_extra_isize = sizeof(struct ext4_inode) -
EXT4_GOOD_OLD_INODE_SIZE;
if (EXT4_HAS_RO_COMPAT_FEATURE(sb,
EXT4_FEATURE_RO_COMPAT_EXTRA_ISIZE)) {
if (sbi->s_want_extra_isize <
le16_to_cpu(es->s_want_extra_isize))
sbi->s_want_extra_isize =
le16_to_cpu(es->s_want_extra_isize);
if (sbi->s_want_extra_isize <
le16_to_cpu(es->s_min_extra_isize))
sbi->s_want_extra_isize =
le16_to_cpu(es->s_min_extra_isize);
}
}
/* Check if enough inode space is available */
if (EXT4_GOOD_OLD_INODE_SIZE + sbi->s_want_extra_isize >
sbi->s_inode_size) {
sbi->s_want_extra_isize = sizeof(struct ext4_inode) -
EXT4_GOOD_OLD_INODE_SIZE;
ext4_msg(sb, KERN_INFO, "required extra inode space not"
"available");
}
err = ext4_reserve_clusters(sbi, ext4_calculate_resv_clusters(sb));
if (err) {
ext4_msg(sb, KERN_ERR, "failed to reserve %llu clusters for "
"reserved pool", ext4_calculate_resv_clusters(sb));
goto failed_mount4a;
}
err = ext4_setup_system_zone(sb);
if (err) {
ext4_msg(sb, KERN_ERR, "failed to initialize system "
"zone (%d)", err);
goto failed_mount4a;
}
ext4_ext_init(sb);
err = ext4_mb_init(sb);
if (err) {
ext4_msg(sb, KERN_ERR, "failed to initialize mballoc (%d)",
err);
goto failed_mount5;
}
block = ext4_count_free_clusters(sb);
ext4_free_blocks_count_set(sbi->s_es,
EXT4_C2B(sbi, block));
err = percpu_counter_init(&sbi->s_freeclusters_counter, block);
if (!err) {
unsigned long freei = ext4_count_free_inodes(sb);
sbi->s_es->s_free_inodes_count = cpu_to_le32(freei);
err = percpu_counter_init(&sbi->s_freeinodes_counter, freei);
}
if (!err)
err = percpu_counter_init(&sbi->s_dirs_counter,
ext4_count_dirs(sb));
if (!err)
err = percpu_counter_init(&sbi->s_dirtyclusters_counter, 0);
if (err) {
ext4_msg(sb, KERN_ERR, "insufficient memory");
goto failed_mount6;
}
if (EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_FLEX_BG))
if (!ext4_fill_flex_info(sb)) {
ext4_msg(sb, KERN_ERR,
"unable to initialize "
"flex_bg meta info!");
goto failed_mount6;
}
err = ext4_register_li_request(sb, first_not_zeroed);
if (err)
goto failed_mount6;
sbi->s_kobj.kset = ext4_kset;
init_completion(&sbi->s_kobj_unregister);
err = kobject_init_and_add(&sbi->s_kobj, &ext4_ktype, NULL,
"%s", sb->s_id);
if (err)
goto failed_mount7;
#ifdef CONFIG_QUOTA
/* Enable quota usage during mount. */
if (EXT4_HAS_RO_COMPAT_FEATURE(sb, EXT4_FEATURE_RO_COMPAT_QUOTA) &&
!(sb->s_flags & MS_RDONLY)) {
err = ext4_enable_quotas(sb);
if (err)
goto failed_mount8;
}
#endif /* CONFIG_QUOTA */
EXT4_SB(sb)->s_mount_state |= EXT4_ORPHAN_FS;
ext4_orphan_cleanup(sb, es);
EXT4_SB(sb)->s_mount_state &= ~EXT4_ORPHAN_FS;
if (needs_recovery) {
ext4_msg(sb, KERN_INFO, "recovery complete");
ext4_mark_recovery_complete(sb, es);
}
if (EXT4_SB(sb)->s_journal) {
if (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_JOURNAL_DATA)
descr = " journalled data mode";
else if (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_ORDERED_DATA)
descr = " ordered data mode";
else
descr = " writeback data mode";
} else
descr = "out journal";
if (test_opt(sb, DISCARD)) {
struct request_queue *q = bdev_get_queue(sb->s_bdev);
if (!blk_queue_discard(q))
ext4_msg(sb, KERN_WARNING,
"mounting with \"discard\" option, but "
"the device does not support discard");
}
ext4_msg(sb, KERN_INFO, "mounted filesystem with%s. "
"Opts: %s%s%s", descr, sbi->s_es->s_mount_opts,
*sbi->s_es->s_mount_opts ? "; " : "", orig_data);
if (es->s_error_count)
mod_timer(&sbi->s_err_report, jiffies + 300*HZ); /* 5 minutes */
/* Enable message ratelimiting. Default is 10 messages per 5 secs. */
ratelimit_state_init(&sbi->s_err_ratelimit_state, 5 * HZ, 10);
ratelimit_state_init(&sbi->s_warning_ratelimit_state, 5 * HZ, 10);
ratelimit_state_init(&sbi->s_msg_ratelimit_state, 5 * HZ, 10);
kfree(orig_data);
return 0;
cantfind_ext4:
if (!silent)
ext4_msg(sb, KERN_ERR, "VFS: Can't find ext4 filesystem");
goto failed_mount;
#ifdef CONFIG_QUOTA
failed_mount8:
kobject_del(&sbi->s_kobj);
#endif
failed_mount7:
ext4_unregister_li_request(sb);
failed_mount6:
ext4_mb_release(sb);
if (sbi->s_flex_groups)
ext4_kvfree(sbi->s_flex_groups);
percpu_counter_destroy(&sbi->s_freeclusters_counter);
percpu_counter_destroy(&sbi->s_freeinodes_counter);
percpu_counter_destroy(&sbi->s_dirs_counter);
percpu_counter_destroy(&sbi->s_dirtyclusters_counter);
failed_mount5:
ext4_ext_release(sb);
ext4_release_system_zone(sb);
failed_mount4a:
dput(sb->s_root);
sb->s_root = NULL;
failed_mount4:
ext4_msg(sb, KERN_ERR, "mount failed");
if (EXT4_SB(sb)->rsv_conversion_wq)
destroy_workqueue(EXT4_SB(sb)->rsv_conversion_wq);
failed_mount_wq:
if (sbi->s_journal) {
jbd2_journal_destroy(sbi->s_journal);
sbi->s_journal = NULL;
}
failed_mount3a:
ext4_es_unregister_shrinker(sbi);
failed_mount3:
del_timer_sync(&sbi->s_err_report);
if (sbi->s_mmp_tsk)
kthread_stop(sbi->s_mmp_tsk);
failed_mount2:
for (i = 0; i < db_count; i++)
brelse(sbi->s_group_desc[i]);
ext4_kvfree(sbi->s_group_desc);
failed_mount:
if (sbi->s_chksum_driver)
crypto_free_shash(sbi->s_chksum_driver);
if (sbi->s_proc) {
remove_proc_entry("options", sbi->s_proc);
remove_proc_entry(sb->s_id, ext4_proc_root);
}
#ifdef CONFIG_QUOTA
for (i = 0; i < EXT4_MAXQUOTAS; i++)
kfree(sbi->s_qf_names[i]);
#endif
ext4_blkdev_remove(sbi);
brelse(bh);
out_fail:
sb->s_fs_info = NULL;
kfree(sbi->s_blockgroup_lock);
kfree(sbi);
out_free_orig:
kfree(orig_data);
return err ? err : ret;
}
/*
* Setup any per-fs journal parameters now. We'll do this both on
* initial mount, once the journal has been initialised but before we've
* done any recovery; and again on any subsequent remount.
*/
static void ext4_init_journal_params(struct super_block *sb, journal_t *journal)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
journal->j_commit_interval = sbi->s_commit_interval;
journal->j_min_batch_time = sbi->s_min_batch_time;
journal->j_max_batch_time = sbi->s_max_batch_time;
write_lock(&journal->j_state_lock);
if (test_opt(sb, BARRIER))
journal->j_flags |= JBD2_BARRIER;
else
journal->j_flags &= ~JBD2_BARRIER;
if (test_opt(sb, DATA_ERR_ABORT))
journal->j_flags |= JBD2_ABORT_ON_SYNCDATA_ERR;
else
journal->j_flags &= ~JBD2_ABORT_ON_SYNCDATA_ERR;
write_unlock(&journal->j_state_lock);
}
static journal_t *ext4_get_journal(struct super_block *sb,
unsigned int journal_inum)
{
struct inode *journal_inode;
journal_t *journal;
BUG_ON(!EXT4_HAS_COMPAT_FEATURE(sb, EXT4_FEATURE_COMPAT_HAS_JOURNAL));
/* First, test for the existence of a valid inode on disk. Bad
* things happen if we iget() an unused inode, as the subsequent
* iput() will try to delete it. */
journal_inode = ext4_iget(sb, journal_inum);
if (IS_ERR(journal_inode)) {
ext4_msg(sb, KERN_ERR, "no journal found");
return NULL;
}
if (!journal_inode->i_nlink) {
make_bad_inode(journal_inode);
iput(journal_inode);
ext4_msg(sb, KERN_ERR, "journal inode is deleted");
return NULL;
}
jbd_debug(2, "Journal inode found at %p: %lld bytes\n",
journal_inode, journal_inode->i_size);
if (!S_ISREG(journal_inode->i_mode)) {
ext4_msg(sb, KERN_ERR, "invalid journal inode");
iput(journal_inode);
return NULL;
}
journal = jbd2_journal_init_inode(journal_inode);
if (!journal) {
ext4_msg(sb, KERN_ERR, "Could not load journal inode");
iput(journal_inode);
return NULL;
}
journal->j_private = sb;
ext4_init_journal_params(sb, journal);
return journal;
}
static journal_t *ext4_get_dev_journal(struct super_block *sb,
dev_t j_dev)
{
struct buffer_head *bh;
journal_t *journal;
ext4_fsblk_t start;
ext4_fsblk_t len;
int hblock, blocksize;
ext4_fsblk_t sb_block;
unsigned long offset;
struct ext4_super_block *es;
struct block_device *bdev;
BUG_ON(!EXT4_HAS_COMPAT_FEATURE(sb, EXT4_FEATURE_COMPAT_HAS_JOURNAL));
bdev = ext4_blkdev_get(j_dev, sb);
if (bdev == NULL)
return NULL;
blocksize = sb->s_blocksize;
hblock = bdev_logical_block_size(bdev);
if (blocksize < hblock) {
ext4_msg(sb, KERN_ERR,
"blocksize too small for journal device");
goto out_bdev;
}
sb_block = EXT4_MIN_BLOCK_SIZE / blocksize;
offset = EXT4_MIN_BLOCK_SIZE % blocksize;
set_blocksize(bdev, blocksize);
if (!(bh = __bread(bdev, sb_block, blocksize))) {
ext4_msg(sb, KERN_ERR, "couldn't read superblock of "
"external journal");
goto out_bdev;
}
es = (struct ext4_super_block *) (bh->b_data + offset);
if ((le16_to_cpu(es->s_magic) != EXT4_SUPER_MAGIC) ||
!(le32_to_cpu(es->s_feature_incompat) &
EXT4_FEATURE_INCOMPAT_JOURNAL_DEV)) {
ext4_msg(sb, KERN_ERR, "external journal has "
"bad superblock");
brelse(bh);
goto out_bdev;
}
if ((le32_to_cpu(es->s_feature_ro_compat) &
EXT4_FEATURE_RO_COMPAT_METADATA_CSUM) &&
es->s_checksum != ext4_superblock_csum(sb, es)) {
ext4_msg(sb, KERN_ERR, "external journal has "
"corrupt superblock");
brelse(bh);
goto out_bdev;
}
if (memcmp(EXT4_SB(sb)->s_es->s_journal_uuid, es->s_uuid, 16)) {
ext4_msg(sb, KERN_ERR, "journal UUID does not match");
brelse(bh);
goto out_bdev;
}
len = ext4_blocks_count(es);
start = sb_block + 1;
brelse(bh); /* we're done with the superblock */
journal = jbd2_journal_init_dev(bdev, sb->s_bdev,
start, len, blocksize);
if (!journal) {
ext4_msg(sb, KERN_ERR, "failed to create device journal");
goto out_bdev;
}
journal->j_private = sb;
ll_rw_block(READ | REQ_META | REQ_PRIO, 1, &journal->j_sb_buffer);
wait_on_buffer(journal->j_sb_buffer);
if (!buffer_uptodate(journal->j_sb_buffer)) {
ext4_msg(sb, KERN_ERR, "I/O error on journal device");
goto out_journal;
}
if (be32_to_cpu(journal->j_superblock->s_nr_users) != 1) {
ext4_msg(sb, KERN_ERR, "External journal has more than one "
"user (unsupported) - %d",
be32_to_cpu(journal->j_superblock->s_nr_users));
goto out_journal;
}
EXT4_SB(sb)->journal_bdev = bdev;
ext4_init_journal_params(sb, journal);
return journal;
out_journal:
jbd2_journal_destroy(journal);
out_bdev:
ext4_blkdev_put(bdev);
return NULL;
}
static int ext4_load_journal(struct super_block *sb,
struct ext4_super_block *es,
unsigned long journal_devnum)
{
journal_t *journal;
unsigned int journal_inum = le32_to_cpu(es->s_journal_inum);
dev_t journal_dev;
int err = 0;
int really_read_only;
BUG_ON(!EXT4_HAS_COMPAT_FEATURE(sb, EXT4_FEATURE_COMPAT_HAS_JOURNAL));
if (journal_devnum &&
journal_devnum != le32_to_cpu(es->s_journal_dev)) {
ext4_msg(sb, KERN_INFO, "external journal device major/minor "
"numbers have changed");
journal_dev = new_decode_dev(journal_devnum);
} else
journal_dev = new_decode_dev(le32_to_cpu(es->s_journal_dev));
really_read_only = bdev_read_only(sb->s_bdev);
/*
* Are we loading a blank journal or performing recovery after a
* crash? For recovery, we need to check in advance whether we
* can get read-write access to the device.
*/
if (EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_RECOVER)) {
if (sb->s_flags & MS_RDONLY) {
ext4_msg(sb, KERN_INFO, "INFO: recovery "
"required on readonly filesystem");
if (really_read_only) {
ext4_msg(sb, KERN_ERR, "write access "
"unavailable, cannot proceed");
return -EROFS;
}
ext4_msg(sb, KERN_INFO, "write access will "
"be enabled during recovery");
}
}
if (journal_inum && journal_dev) {
ext4_msg(sb, KERN_ERR, "filesystem has both journal "
"and inode journals!");
return -EINVAL;
}
if (journal_inum) {
if (!(journal = ext4_get_journal(sb, journal_inum)))
return -EINVAL;
} else {
if (!(journal = ext4_get_dev_journal(sb, journal_dev)))
return -EINVAL;
}
if (!(journal->j_flags & JBD2_BARRIER))
ext4_msg(sb, KERN_INFO, "barriers disabled");
if (!EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_RECOVER))
err = jbd2_journal_wipe(journal, !really_read_only);
if (!err) {
char *save = kmalloc(EXT4_S_ERR_LEN, GFP_KERNEL);
if (save)
memcpy(save, ((char *) es) +
EXT4_S_ERR_START, EXT4_S_ERR_LEN);
err = jbd2_journal_load(journal);
if (save)
memcpy(((char *) es) + EXT4_S_ERR_START,
save, EXT4_S_ERR_LEN);
kfree(save);
}
if (err) {
ext4_msg(sb, KERN_ERR, "error loading journal");
jbd2_journal_destroy(journal);
return err;
}
EXT4_SB(sb)->s_journal = journal;
ext4_clear_journal_err(sb, es);
if (!really_read_only && journal_devnum &&
journal_devnum != le32_to_cpu(es->s_journal_dev)) {
es->s_journal_dev = cpu_to_le32(journal_devnum);
/* Make sure we flush the recovery flag to disk. */
ext4_commit_super(sb, 1);
}
return 0;
}
static int ext4_commit_super(struct super_block *sb, int sync)
{
struct ext4_super_block *es = EXT4_SB(sb)->s_es;
struct buffer_head *sbh = EXT4_SB(sb)->s_sbh;
int error = 0;
if (!sbh || block_device_ejected(sb))
return error;
if (buffer_write_io_error(sbh)) {
/*
* Oh, dear. A previous attempt to write the
* superblock failed. This could happen because the
* USB device was yanked out. Or it could happen to
* be a transient write error and maybe the block will
* be remapped. Nothing we can do but to retry the
* write and hope for the best.
*/
ext4_msg(sb, KERN_ERR, "previous I/O error to "
"superblock detected");
clear_buffer_write_io_error(sbh);
set_buffer_uptodate(sbh);
}
/*
* If the file system is mounted read-only, don't update the
* superblock write time. This avoids updating the superblock
* write time when we are mounting the root file system
* read/only but we need to replay the journal; at that point,
* for people who are east of GMT and who make their clock
* tick in localtime for Windows bug-for-bug compatibility,
* the clock is set in the future, and this will cause e2fsck
* to complain and force a full file system check.
*/
if (!(sb->s_flags & MS_RDONLY))
es->s_wtime = cpu_to_le32(get_seconds());
if (sb->s_bdev->bd_part)
es->s_kbytes_written =
cpu_to_le64(EXT4_SB(sb)->s_kbytes_written +
((part_stat_read(sb->s_bdev->bd_part, sectors[1]) -
EXT4_SB(sb)->s_sectors_written_start) >> 1));
else
es->s_kbytes_written =
cpu_to_le64(EXT4_SB(sb)->s_kbytes_written);
if (percpu_counter_initialized(&EXT4_SB(sb)->s_freeclusters_counter))
ext4_free_blocks_count_set(es,
EXT4_C2B(EXT4_SB(sb), percpu_counter_sum_positive(
&EXT4_SB(sb)->s_freeclusters_counter)));
if (percpu_counter_initialized(&EXT4_SB(sb)->s_freeinodes_counter))
es->s_free_inodes_count =
cpu_to_le32(percpu_counter_sum_positive(
&EXT4_SB(sb)->s_freeinodes_counter));
BUFFER_TRACE(sbh, "marking dirty");
ext4_superblock_csum_set(sb);
mark_buffer_dirty(sbh);
if (sync) {
error = sync_dirty_buffer(sbh);
if (error)
return error;
error = buffer_write_io_error(sbh);
if (error) {
ext4_msg(sb, KERN_ERR, "I/O error while writing "
"superblock");
clear_buffer_write_io_error(sbh);
set_buffer_uptodate(sbh);
}
}
return error;
}
/*
* Have we just finished recovery? If so, and if we are mounting (or
* remounting) the filesystem readonly, then we will end up with a
* consistent fs on disk. Record that fact.
*/
static void ext4_mark_recovery_complete(struct super_block *sb,
struct ext4_super_block *es)
{
journal_t *journal = EXT4_SB(sb)->s_journal;
if (!EXT4_HAS_COMPAT_FEATURE(sb, EXT4_FEATURE_COMPAT_HAS_JOURNAL)) {
BUG_ON(journal != NULL);
return;
}
jbd2_journal_lock_updates(journal);
if (jbd2_journal_flush(journal) < 0)
goto out;
if (EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_RECOVER) &&
sb->s_flags & MS_RDONLY) {
EXT4_CLEAR_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_RECOVER);
ext4_commit_super(sb, 1);
}
out:
jbd2_journal_unlock_updates(journal);
}
/*
* If we are mounting (or read-write remounting) a filesystem whose journal
* has recorded an error from a previous lifetime, move that error to the
* main filesystem now.
*/
static void ext4_clear_journal_err(struct super_block *sb,
struct ext4_super_block *es)
{
journal_t *journal;
int j_errno;
const char *errstr;
BUG_ON(!EXT4_HAS_COMPAT_FEATURE(sb, EXT4_FEATURE_COMPAT_HAS_JOURNAL));
journal = EXT4_SB(sb)->s_journal;
/*
* Now check for any error status which may have been recorded in the
* journal by a prior ext4_error() or ext4_abort()
*/
j_errno = jbd2_journal_errno(journal);
if (j_errno) {
char nbuf[16];
errstr = ext4_decode_error(sb, j_errno, nbuf);
ext4_warning(sb, "Filesystem error recorded "
"from previous mount: %s", errstr);
ext4_warning(sb, "Marking fs in need of filesystem check.");
EXT4_SB(sb)->s_mount_state |= EXT4_ERROR_FS;
es->s_state |= cpu_to_le16(EXT4_ERROR_FS);
ext4_commit_super(sb, 1);
jbd2_journal_clear_err(journal);
jbd2_journal_update_sb_errno(journal);
}
}
/*
* Force the running and committing transactions to commit,
* and wait on the commit.
*/
int ext4_force_commit(struct super_block *sb)
{
journal_t *journal;
if (sb->s_flags & MS_RDONLY)
return 0;
journal = EXT4_SB(sb)->s_journal;
return ext4_journal_force_commit(journal);
}
static int ext4_sync_fs(struct super_block *sb, int wait)
{
int ret = 0;
tid_t target;
bool needs_barrier = false;
struct ext4_sb_info *sbi = EXT4_SB(sb);
trace_ext4_sync_fs(sb, wait);
flush_workqueue(sbi->rsv_conversion_wq);
/*
* Writeback quota in non-journalled quota case - journalled quota has
* no dirty dquots
*/
dquot_writeback_dquots(sb, -1);
/*
* Data writeback is possible w/o journal transaction, so barrier must
* being sent at the end of the function. But we can skip it if
* transaction_commit will do it for us.
*/
if (sbi->s_journal) {
target = jbd2_get_latest_transaction(sbi->s_journal);
if (wait && sbi->s_journal->j_flags & JBD2_BARRIER &&
!jbd2_trans_will_send_data_barrier(sbi->s_journal, target))
needs_barrier = true;
if (jbd2_journal_start_commit(sbi->s_journal, &target)) {
if (wait)
ret = jbd2_log_wait_commit(sbi->s_journal,
target);
}
} else if (wait && test_opt(sb, BARRIER))
needs_barrier = true;
if (needs_barrier) {
int err;
err = blkdev_issue_flush(sb->s_bdev, GFP_KERNEL, NULL);
if (!ret)
ret = err;
}
return ret;
}
/*
* LVM calls this function before a (read-only) snapshot is created. This
* gives us a chance to flush the journal completely and mark the fs clean.
*
* Note that only this function cannot bring a filesystem to be in a clean
* state independently. It relies on upper layer to stop all data & metadata
* modifications.
*/
static int ext4_freeze(struct super_block *sb)
{
int error = 0;
journal_t *journal;
if (sb->s_flags & MS_RDONLY)
return 0;
journal = EXT4_SB(sb)->s_journal;
if (journal) {
/* Now we set up the journal barrier. */
jbd2_journal_lock_updates(journal);
/*
* Don't clear the needs_recovery flag if we failed to
* flush the journal.
*/
error = jbd2_journal_flush(journal);
if (error < 0)
goto out;
}
/* Journal blocked and flushed, clear needs_recovery flag. */
EXT4_CLEAR_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_RECOVER);
error = ext4_commit_super(sb, 1);
out:
if (journal)
/* we rely on upper layer to stop further updates */
jbd2_journal_unlock_updates(journal);
return error;
}
/*
* Called by LVM after the snapshot is done. We need to reset the RECOVER
* flag here, even though the filesystem is not technically dirty yet.
*/
static int ext4_unfreeze(struct super_block *sb)
{
if (sb->s_flags & MS_RDONLY)
return 0;
/* Reset the needs_recovery flag before the fs is unlocked. */
EXT4_SET_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_RECOVER);
ext4_commit_super(sb, 1);
return 0;
}
/*
* Structure to save mount options for ext4_remount's benefit
*/
struct ext4_mount_options {
unsigned long s_mount_opt;
unsigned long s_mount_opt2;
kuid_t s_resuid;
kgid_t s_resgid;
unsigned long s_commit_interval;
u32 s_min_batch_time, s_max_batch_time;
#ifdef CONFIG_QUOTA
int s_jquota_fmt;
char *s_qf_names[EXT4_MAXQUOTAS];
#endif
};
static int ext4_remount(struct super_block *sb, int *flags, char *data)
{
struct ext4_super_block *es;
struct ext4_sb_info *sbi = EXT4_SB(sb);
unsigned long old_sb_flags;
struct ext4_mount_options old_opts;
int enable_quota = 0;
ext4_group_t g;
unsigned int journal_ioprio = DEFAULT_JOURNAL_IOPRIO;
int err = 0;
#ifdef CONFIG_QUOTA
int i, j;
#endif
char *orig_data = kstrdup(data, GFP_KERNEL);
/* Store the original options */
old_sb_flags = sb->s_flags;
old_opts.s_mount_opt = sbi->s_mount_opt;
old_opts.s_mount_opt2 = sbi->s_mount_opt2;
old_opts.s_resuid = sbi->s_resuid;
old_opts.s_resgid = sbi->s_resgid;
old_opts.s_commit_interval = sbi->s_commit_interval;
old_opts.s_min_batch_time = sbi->s_min_batch_time;
old_opts.s_max_batch_time = sbi->s_max_batch_time;
#ifdef CONFIG_QUOTA
old_opts.s_jquota_fmt = sbi->s_jquota_fmt;
for (i = 0; i < EXT4_MAXQUOTAS; i++)
if (sbi->s_qf_names[i]) {
old_opts.s_qf_names[i] = kstrdup(sbi->s_qf_names[i],
GFP_KERNEL);
if (!old_opts.s_qf_names[i]) {
for (j = 0; j < i; j++)
kfree(old_opts.s_qf_names[j]);
kfree(orig_data);
return -ENOMEM;
}
} else
old_opts.s_qf_names[i] = NULL;
#endif
if (sbi->s_journal && sbi->s_journal->j_task->io_context)
journal_ioprio = sbi->s_journal->j_task->io_context->ioprio;
/*
* Allow the "check" option to be passed as a remount option.
*/
if (!parse_options(data, sb, NULL, &journal_ioprio, 1)) {
err = -EINVAL;
goto restore_opts;
}
if ((old_opts.s_mount_opt & EXT4_MOUNT_JOURNAL_CHECKSUM) ^
test_opt(sb, JOURNAL_CHECKSUM)) {
ext4_msg(sb, KERN_ERR, "changing journal_checksum "
"during remount not supported");
err = -EINVAL;
goto restore_opts;
}
if (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_JOURNAL_DATA) {
if (test_opt2(sb, EXPLICIT_DELALLOC)) {
ext4_msg(sb, KERN_ERR, "can't mount with "
"both data=journal and delalloc");
err = -EINVAL;
goto restore_opts;
}
if (test_opt(sb, DIOREAD_NOLOCK)) {
ext4_msg(sb, KERN_ERR, "can't mount with "
"both data=journal and dioread_nolock");
err = -EINVAL;
goto restore_opts;
}
}
if (sbi->s_mount_flags & EXT4_MF_FS_ABORTED)
ext4_abort(sb, "Abort forced by user");
sb->s_flags = (sb->s_flags & ~MS_POSIXACL) |
(test_opt(sb, POSIX_ACL) ? MS_POSIXACL : 0);
es = sbi->s_es;
if (sbi->s_journal) {
ext4_init_journal_params(sb, sbi->s_journal);
set_task_ioprio(sbi->s_journal->j_task, journal_ioprio);
}
if ((*flags & MS_RDONLY) != (sb->s_flags & MS_RDONLY)) {
if (sbi->s_mount_flags & EXT4_MF_FS_ABORTED) {
err = -EROFS;
goto restore_opts;
}
if (*flags & MS_RDONLY) {
err = sync_filesystem(sb);
if (err < 0)
goto restore_opts;
err = dquot_suspend(sb, -1);
if (err < 0)
goto restore_opts;
/*
* First of all, the unconditional stuff we have to do
* to disable replay of the journal when we next remount
*/
sb->s_flags |= MS_RDONLY;
/*
* OK, test if we are remounting a valid rw partition
* readonly, and if so set the rdonly flag and then
* mark the partition as valid again.
*/
if (!(es->s_state & cpu_to_le16(EXT4_VALID_FS)) &&
(sbi->s_mount_state & EXT4_VALID_FS))
es->s_state = cpu_to_le16(sbi->s_mount_state);
if (sbi->s_journal)
ext4_mark_recovery_complete(sb, es);
} else {
/* Make sure we can mount this feature set readwrite */
if (!ext4_feature_set_ok(sb, 0)) {
err = -EROFS;
goto restore_opts;
}
/*
* Make sure the group descriptor checksums
* are sane. If they aren't, refuse to remount r/w.
*/
for (g = 0; g < sbi->s_groups_count; g++) {
struct ext4_group_desc *gdp =
ext4_get_group_desc(sb, g, NULL);
if (!ext4_group_desc_csum_verify(sb, g, gdp)) {
ext4_msg(sb, KERN_ERR,
"ext4_remount: Checksum for group %u failed (%u!=%u)",
g, le16_to_cpu(ext4_group_desc_csum(sbi, g, gdp)),
le16_to_cpu(gdp->bg_checksum));
err = -EINVAL;
goto restore_opts;
}
}
/*
* If we have an unprocessed orphan list hanging
* around from a previously readonly bdev mount,
* require a full umount/remount for now.
*/
if (es->s_last_orphan) {
ext4_msg(sb, KERN_WARNING, "Couldn't "
"remount RDWR because of unprocessed "
"orphan inode list. Please "
"umount/remount instead");
err = -EINVAL;
goto restore_opts;
}
/*
* Mounting a RDONLY partition read-write, so reread
* and store the current valid flag. (It may have
* been changed by e2fsck since we originally mounted
* the partition.)
*/
if (sbi->s_journal)
ext4_clear_journal_err(sb, es);
sbi->s_mount_state = le16_to_cpu(es->s_state);
if (!ext4_setup_super(sb, es, 0))
sb->s_flags &= ~MS_RDONLY;
if (EXT4_HAS_INCOMPAT_FEATURE(sb,
EXT4_FEATURE_INCOMPAT_MMP))
if (ext4_multi_mount_protect(sb,
le64_to_cpu(es->s_mmp_block))) {
err = -EROFS;
goto restore_opts;
}
enable_quota = 1;
}
}
/*
* Reinitialize lazy itable initialization thread based on
* current settings
*/
if ((sb->s_flags & MS_RDONLY) || !test_opt(sb, INIT_INODE_TABLE))
ext4_unregister_li_request(sb);
else {
ext4_group_t first_not_zeroed;
first_not_zeroed = ext4_has_uninit_itable(sb);
ext4_register_li_request(sb, first_not_zeroed);
}
ext4_setup_system_zone(sb);
if (sbi->s_journal == NULL && !(old_sb_flags & MS_RDONLY))
ext4_commit_super(sb, 1);
#ifdef CONFIG_QUOTA
/* Release old quota file names */
for (i = 0; i < EXT4_MAXQUOTAS; i++)
kfree(old_opts.s_qf_names[i]);
if (enable_quota) {
if (sb_any_quota_suspended(sb))
dquot_resume(sb, -1);
else if (EXT4_HAS_RO_COMPAT_FEATURE(sb,
EXT4_FEATURE_RO_COMPAT_QUOTA)) {
err = ext4_enable_quotas(sb);
if (err)
goto restore_opts;
}
}
#endif
ext4_msg(sb, KERN_INFO, "re-mounted. Opts: %s", orig_data);
kfree(orig_data);
return 0;
restore_opts:
sb->s_flags = old_sb_flags;
sbi->s_mount_opt = old_opts.s_mount_opt;
sbi->s_mount_opt2 = old_opts.s_mount_opt2;
sbi->s_resuid = old_opts.s_resuid;
sbi->s_resgid = old_opts.s_resgid;
sbi->s_commit_interval = old_opts.s_commit_interval;
sbi->s_min_batch_time = old_opts.s_min_batch_time;
sbi->s_max_batch_time = old_opts.s_max_batch_time;
#ifdef CONFIG_QUOTA
sbi->s_jquota_fmt = old_opts.s_jquota_fmt;
for (i = 0; i < EXT4_MAXQUOTAS; i++) {
kfree(sbi->s_qf_names[i]);
sbi->s_qf_names[i] = old_opts.s_qf_names[i];
}
#endif
kfree(orig_data);
return err;
}
static int ext4_statfs(struct dentry *dentry, struct kstatfs *buf)
{
struct super_block *sb = dentry->d_sb;
struct ext4_sb_info *sbi = EXT4_SB(sb);
struct ext4_super_block *es = sbi->s_es;
ext4_fsblk_t overhead = 0, resv_blocks;
u64 fsid;
s64 bfree;
resv_blocks = EXT4_C2B(sbi, atomic64_read(&sbi->s_resv_clusters));
if (!test_opt(sb, MINIX_DF))
overhead = sbi->s_overhead;
buf->f_type = EXT4_SUPER_MAGIC;
buf->f_bsize = sb->s_blocksize;
buf->f_blocks = ext4_blocks_count(es) - EXT4_C2B(sbi, overhead);
bfree = percpu_counter_sum_positive(&sbi->s_freeclusters_counter) -
percpu_counter_sum_positive(&sbi->s_dirtyclusters_counter);
/* prevent underflow in case that few free space is available */
buf->f_bfree = EXT4_C2B(sbi, max_t(s64, bfree, 0));
buf->f_bavail = buf->f_bfree -
(ext4_r_blocks_count(es) + resv_blocks);
if (buf->f_bfree < (ext4_r_blocks_count(es) + resv_blocks))
buf->f_bavail = 0;
buf->f_files = le32_to_cpu(es->s_inodes_count);
buf->f_ffree = percpu_counter_sum_positive(&sbi->s_freeinodes_counter);
buf->f_namelen = EXT4_NAME_LEN;
fsid = le64_to_cpup((void *)es->s_uuid) ^
le64_to_cpup((void *)es->s_uuid + sizeof(u64));
buf->f_fsid.val[0] = fsid & 0xFFFFFFFFUL;
buf->f_fsid.val[1] = (fsid >> 32) & 0xFFFFFFFFUL;
return 0;
}
/* Helper function for writing quotas on sync - we need to start transaction
* before quota file is locked for write. Otherwise the are possible deadlocks:
* Process 1 Process 2
* ext4_create() quota_sync()
* jbd2_journal_start() write_dquot()
* dquot_initialize() down(dqio_mutex)
* down(dqio_mutex) jbd2_journal_start()
*
*/
#ifdef CONFIG_QUOTA
static inline struct inode *dquot_to_inode(struct dquot *dquot)
{
return sb_dqopt(dquot->dq_sb)->files[dquot->dq_id.type];
}
static int ext4_write_dquot(struct dquot *dquot)
{
int ret, err;
handle_t *handle;
struct inode *inode;
inode = dquot_to_inode(dquot);
handle = ext4_journal_start(inode, EXT4_HT_QUOTA,
EXT4_QUOTA_TRANS_BLOCKS(dquot->dq_sb));
if (IS_ERR(handle))
return PTR_ERR(handle);
ret = dquot_commit(dquot);
err = ext4_journal_stop(handle);
if (!ret)
ret = err;
return ret;
}
static int ext4_acquire_dquot(struct dquot *dquot)
{
int ret, err;
handle_t *handle;
handle = ext4_journal_start(dquot_to_inode(dquot), EXT4_HT_QUOTA,
EXT4_QUOTA_INIT_BLOCKS(dquot->dq_sb));
if (IS_ERR(handle))
return PTR_ERR(handle);
ret = dquot_acquire(dquot);
err = ext4_journal_stop(handle);
if (!ret)
ret = err;
return ret;
}
static int ext4_release_dquot(struct dquot *dquot)
{
int ret, err;
handle_t *handle;
handle = ext4_journal_start(dquot_to_inode(dquot), EXT4_HT_QUOTA,
EXT4_QUOTA_DEL_BLOCKS(dquot->dq_sb));
if (IS_ERR(handle)) {
/* Release dquot anyway to avoid endless cycle in dqput() */
dquot_release(dquot);
return PTR_ERR(handle);
}
ret = dquot_release(dquot);
err = ext4_journal_stop(handle);
if (!ret)
ret = err;
return ret;
}
static int ext4_mark_dquot_dirty(struct dquot *dquot)
{
struct super_block *sb = dquot->dq_sb;
struct ext4_sb_info *sbi = EXT4_SB(sb);
/* Are we journaling quotas? */
if (EXT4_HAS_RO_COMPAT_FEATURE(sb, EXT4_FEATURE_RO_COMPAT_QUOTA) ||
sbi->s_qf_names[USRQUOTA] || sbi->s_qf_names[GRPQUOTA]) {
dquot_mark_dquot_dirty(dquot);
return ext4_write_dquot(dquot);
} else {
return dquot_mark_dquot_dirty(dquot);
}
}
static int ext4_write_info(struct super_block *sb, int type)
{
int ret, err;
handle_t *handle;
/* Data block + inode block */
handle = ext4_journal_start(sb->s_root->d_inode, EXT4_HT_QUOTA, 2);
if (IS_ERR(handle))
return PTR_ERR(handle);
ret = dquot_commit_info(sb, type);
err = ext4_journal_stop(handle);
if (!ret)
ret = err;
return ret;
}
/*
* Turn on quotas during mount time - we need to find
* the quota file and such...
*/
static int ext4_quota_on_mount(struct super_block *sb, int type)
{
return dquot_quota_on_mount(sb, EXT4_SB(sb)->s_qf_names[type],
EXT4_SB(sb)->s_jquota_fmt, type);
}
/*
* Standard function to be called on quota_on
*/
static int ext4_quota_on(struct super_block *sb, int type, int format_id,
struct path *path)
{
int err;
if (!test_opt(sb, QUOTA))
return -EINVAL;
/* Quotafile not on the same filesystem? */
if (path->dentry->d_sb != sb)
return -EXDEV;
/* Journaling quota? */
if (EXT4_SB(sb)->s_qf_names[type]) {
/* Quotafile not in fs root? */
if (path->dentry->d_parent != sb->s_root)
ext4_msg(sb, KERN_WARNING,
"Quota file not on filesystem root. "
"Journaled quota will not work");
}
/*
* When we journal data on quota file, we have to flush journal to see
* all updates to the file when we bypass pagecache...
*/
if (EXT4_SB(sb)->s_journal &&
ext4_should_journal_data(path->dentry->d_inode)) {
/*
* We don't need to lock updates but journal_flush() could
* otherwise be livelocked...
*/
jbd2_journal_lock_updates(EXT4_SB(sb)->s_journal);
err = jbd2_journal_flush(EXT4_SB(sb)->s_journal);
jbd2_journal_unlock_updates(EXT4_SB(sb)->s_journal);
if (err)
return err;
}
return dquot_quota_on(sb, type, format_id, path);
}
static int ext4_quota_enable(struct super_block *sb, int type, int format_id,
unsigned int flags)
{
int err;
struct inode *qf_inode;
unsigned long qf_inums[EXT4_MAXQUOTAS] = {
le32_to_cpu(EXT4_SB(sb)->s_es->s_usr_quota_inum),
le32_to_cpu(EXT4_SB(sb)->s_es->s_grp_quota_inum)
};
BUG_ON(!EXT4_HAS_RO_COMPAT_FEATURE(sb, EXT4_FEATURE_RO_COMPAT_QUOTA));
if (!qf_inums[type])
return -EPERM;
qf_inode = ext4_iget(sb, qf_inums[type]);
if (IS_ERR(qf_inode)) {
ext4_error(sb, "Bad quota inode # %lu", qf_inums[type]);
return PTR_ERR(qf_inode);
}
/* Don't account quota for quota files to avoid recursion */
qf_inode->i_flags |= S_NOQUOTA;
err = dquot_enable(qf_inode, type, format_id, flags);
iput(qf_inode);
return err;
}
/* Enable usage tracking for all quota types. */
static int ext4_enable_quotas(struct super_block *sb)
{
int type, err = 0;
unsigned long qf_inums[EXT4_MAXQUOTAS] = {
le32_to_cpu(EXT4_SB(sb)->s_es->s_usr_quota_inum),
le32_to_cpu(EXT4_SB(sb)->s_es->s_grp_quota_inum)
};
sb_dqopt(sb)->flags |= DQUOT_QUOTA_SYS_FILE;
for (type = 0; type < EXT4_MAXQUOTAS; type++) {
if (qf_inums[type]) {
err = ext4_quota_enable(sb, type, QFMT_VFS_V1,
DQUOT_USAGE_ENABLED);
if (err) {
ext4_warning(sb,
"Failed to enable quota tracking "
"(type=%d, err=%d). Please run "
"e2fsck to fix.", type, err);
return err;
}
}
}
return 0;
}
/*
* quota_on function that is used when QUOTA feature is set.
*/
static int ext4_quota_on_sysfile(struct super_block *sb, int type,
int format_id)
{
if (!EXT4_HAS_RO_COMPAT_FEATURE(sb, EXT4_FEATURE_RO_COMPAT_QUOTA))
return -EINVAL;
/*
* USAGE was enabled at mount time. Only need to enable LIMITS now.
*/
return ext4_quota_enable(sb, type, format_id, DQUOT_LIMITS_ENABLED);
}
static int ext4_quota_off(struct super_block *sb, int type)
{
struct inode *inode = sb_dqopt(sb)->files[type];
handle_t *handle;
/* Force all delayed allocation blocks to be allocated.
* Caller already holds s_umount sem */
if (test_opt(sb, DELALLOC))
sync_filesystem(sb);
if (!inode)
goto out;
/* Update modification times of quota files when userspace can
* start looking at them */
handle = ext4_journal_start(inode, EXT4_HT_QUOTA, 1);
if (IS_ERR(handle))
goto out;
inode->i_mtime = inode->i_ctime = CURRENT_TIME;
ext4_mark_inode_dirty(handle, inode);
ext4_journal_stop(handle);
out:
return dquot_quota_off(sb, type);
}
/*
* quota_off function that is used when QUOTA feature is set.
*/
static int ext4_quota_off_sysfile(struct super_block *sb, int type)
{
if (!EXT4_HAS_RO_COMPAT_FEATURE(sb, EXT4_FEATURE_RO_COMPAT_QUOTA))
return -EINVAL;
/* Disable only the limits. */
return dquot_disable(sb, type, DQUOT_LIMITS_ENABLED);
}
/* Read data from quotafile - avoid pagecache and such because we cannot afford
* acquiring the locks... As quota files are never truncated and quota code
* itself serializes the operations (and no one else should touch the files)
* we don't have to be afraid of races */
static ssize_t ext4_quota_read(struct super_block *sb, int type, char *data,
size_t len, loff_t off)
{
struct inode *inode = sb_dqopt(sb)->files[type];
ext4_lblk_t blk = off >> EXT4_BLOCK_SIZE_BITS(sb);
int offset = off & (sb->s_blocksize - 1);
int tocopy;
size_t toread;
struct buffer_head *bh;
loff_t i_size = i_size_read(inode);
if (off > i_size)
return 0;
if (off+len > i_size)
len = i_size-off;
toread = len;
while (toread > 0) {
tocopy = sb->s_blocksize - offset < toread ?
sb->s_blocksize - offset : toread;
bh = ext4_bread(NULL, inode, blk, 0);
if (IS_ERR(bh))
return PTR_ERR(bh);
if (!bh) /* A hole? */
memset(data, 0, tocopy);
else
memcpy(data, bh->b_data+offset, tocopy);
brelse(bh);
offset = 0;
toread -= tocopy;
data += tocopy;
blk++;
}
return len;
}
/* Write to quotafile (we know the transaction is already started and has
* enough credits) */
static ssize_t ext4_quota_write(struct super_block *sb, int type,
const char *data, size_t len, loff_t off)
{
struct inode *inode = sb_dqopt(sb)->files[type];
ext4_lblk_t blk = off >> EXT4_BLOCK_SIZE_BITS(sb);
int err, offset = off & (sb->s_blocksize - 1);
struct buffer_head *bh;
handle_t *handle = journal_current_handle();
if (EXT4_SB(sb)->s_journal && !handle) {
ext4_msg(sb, KERN_WARNING, "Quota write (off=%llu, len=%llu)"
" cancelled because transaction is not started",
(unsigned long long)off, (unsigned long long)len);
return -EIO;
}
/*
* Since we account only one data block in transaction credits,
* then it is impossible to cross a block boundary.
*/
if (sb->s_blocksize - offset < len) {
ext4_msg(sb, KERN_WARNING, "Quota write (off=%llu, len=%llu)"
" cancelled because not block aligned",
(unsigned long long)off, (unsigned long long)len);
return -EIO;
}
bh = ext4_bread(handle, inode, blk, 1);
if (IS_ERR(bh))
return PTR_ERR(bh);
if (!bh)
goto out;
BUFFER_TRACE(bh, "get write access");
err = ext4_journal_get_write_access(handle, bh);
if (err) {
brelse(bh);
return err;
}
lock_buffer(bh);
memcpy(bh->b_data+offset, data, len);
flush_dcache_page(bh->b_page);
unlock_buffer(bh);
err = ext4_handle_dirty_metadata(handle, NULL, bh);
brelse(bh);
out:
if (inode->i_size < off + len) {
i_size_write(inode, off + len);
EXT4_I(inode)->i_disksize = inode->i_size;
ext4_mark_inode_dirty(handle, inode);
}
return len;
}
#endif
static struct dentry *ext4_mount(struct file_system_type *fs_type, int flags,
const char *dev_name, void *data)
{
return mount_bdev(fs_type, flags, dev_name, data, ext4_fill_super);
}
#if !defined(CONFIG_EXT2_FS) && !defined(CONFIG_EXT2_FS_MODULE) && defined(CONFIG_EXT4_USE_FOR_EXT23)
static inline void register_as_ext2(void)
{
int err = register_filesystem(&ext2_fs_type);
if (err)
printk(KERN_WARNING
"EXT4-fs: Unable to register as ext2 (%d)\n", err);
}
static inline void unregister_as_ext2(void)
{
unregister_filesystem(&ext2_fs_type);
}
static inline int ext2_feature_set_ok(struct super_block *sb)
{
if (EXT4_HAS_INCOMPAT_FEATURE(sb, ~EXT2_FEATURE_INCOMPAT_SUPP))
return 0;
if (sb->s_flags & MS_RDONLY)
return 1;
if (EXT4_HAS_RO_COMPAT_FEATURE(sb, ~EXT2_FEATURE_RO_COMPAT_SUPP))
return 0;
return 1;
}
#else
static inline void register_as_ext2(void) { }
static inline void unregister_as_ext2(void) { }
static inline int ext2_feature_set_ok(struct super_block *sb) { return 0; }
#endif
#if !defined(CONFIG_EXT3_FS) && !defined(CONFIG_EXT3_FS_MODULE) && defined(CONFIG_EXT4_USE_FOR_EXT23)
static inline void register_as_ext3(void)
{
int err = register_filesystem(&ext3_fs_type);
if (err)
printk(KERN_WARNING
"EXT4-fs: Unable to register as ext3 (%d)\n", err);
}
static inline void unregister_as_ext3(void)
{
unregister_filesystem(&ext3_fs_type);
}
static inline int ext3_feature_set_ok(struct super_block *sb)
{
if (EXT4_HAS_INCOMPAT_FEATURE(sb, ~EXT3_FEATURE_INCOMPAT_SUPP))
return 0;
if (!EXT4_HAS_COMPAT_FEATURE(sb, EXT4_FEATURE_COMPAT_HAS_JOURNAL))
return 0;
if (sb->s_flags & MS_RDONLY)
return 1;
if (EXT4_HAS_RO_COMPAT_FEATURE(sb, ~EXT3_FEATURE_RO_COMPAT_SUPP))
return 0;
return 1;
}
#else
static inline void register_as_ext3(void) { }
static inline void unregister_as_ext3(void) { }
static inline int ext3_feature_set_ok(struct super_block *sb) { return 0; }
#endif
static struct file_system_type ext4_fs_type = {
.owner = THIS_MODULE,
.name = "ext4",
.mount = ext4_mount,
.kill_sb = kill_block_super,
.fs_flags = FS_REQUIRES_DEV,
};
MODULE_ALIAS_FS("ext4");
static int __init ext4_init_feat_adverts(void)
{
struct ext4_features *ef;
int ret = -ENOMEM;
ef = kzalloc(sizeof(struct ext4_features), GFP_KERNEL);
if (!ef)
goto out;
ef->f_kobj.kset = ext4_kset;
init_completion(&ef->f_kobj_unregister);
ret = kobject_init_and_add(&ef->f_kobj, &ext4_feat_ktype, NULL,
"features");
if (ret) {
kfree(ef);
goto out;
}
ext4_feat = ef;
ret = 0;
out:
return ret;
}
static void ext4_exit_feat_adverts(void)
{
kobject_put(&ext4_feat->f_kobj);
wait_for_completion(&ext4_feat->f_kobj_unregister);
kfree(ext4_feat);
}
/* Shared across all ext4 file systems */
wait_queue_head_t ext4__ioend_wq[EXT4_WQ_HASH_SZ];
struct mutex ext4__aio_mutex[EXT4_WQ_HASH_SZ];
static int __init ext4_init_fs(void)
{
int i, err;
ext4_li_info = NULL;
mutex_init(&ext4_li_mtx);
/* Build-time check for flags consistency */
ext4_check_flag_values();
for (i = 0; i < EXT4_WQ_HASH_SZ; i++) {
mutex_init(&ext4__aio_mutex[i]);
init_waitqueue_head(&ext4__ioend_wq[i]);
}
err = ext4_init_es();
if (err)
return err;
err = ext4_init_pageio();
if (err)
goto out7;
err = ext4_init_system_zone();
if (err)
goto out6;
ext4_kset = kset_create_and_add("ext4", NULL, fs_kobj);
if (!ext4_kset) {
err = -ENOMEM;
goto out5;
}
ext4_proc_root = proc_mkdir("fs/ext4", NULL);
err = ext4_init_feat_adverts();
if (err)
goto out4;
err = ext4_init_mballoc();
if (err)
goto out2;
else
ext4_mballoc_ready = 1;
err = init_inodecache();
if (err)
goto out1;
register_as_ext3();
register_as_ext2();
err = register_filesystem(&ext4_fs_type);
if (err)
goto out;
return 0;
out:
unregister_as_ext2();
unregister_as_ext3();
destroy_inodecache();
out1:
ext4_mballoc_ready = 0;
ext4_exit_mballoc();
out2:
ext4_exit_feat_adverts();
out4:
if (ext4_proc_root)
remove_proc_entry("fs/ext4", NULL);
kset_unregister(ext4_kset);
out5:
ext4_exit_system_zone();
out6:
ext4_exit_pageio();
out7:
ext4_exit_es();
return err;
}
static void __exit ext4_exit_fs(void)
{
ext4_exit_crypto();
ext4_destroy_lazyinit_thread();
unregister_as_ext2();
unregister_as_ext3();
unregister_filesystem(&ext4_fs_type);
destroy_inodecache();
ext4_exit_mballoc();
ext4_exit_feat_adverts();
remove_proc_entry("fs/ext4", NULL);
kset_unregister(ext4_kset);
ext4_exit_system_zone();
ext4_exit_pageio();
ext4_exit_es();
}
MODULE_AUTHOR("Remy Card, Stephen Tweedie, Andrew Morton, Andreas Dilger, Theodore Ts'o and others");
MODULE_DESCRIPTION("Fourth Extended Filesystem");
MODULE_LICENSE("GPL");
module_init(ext4_init_fs)
module_exit(ext4_exit_fs)
|
# CPUfreq core
obj-$(CONFIG_CPU_FREQ) += cpufreq.o
# CPUfreq stats
obj-$(CONFIG_CPU_FREQ_STAT) += cpufreq_stats.o
# CPUfreq governors
obj-$(CONFIG_CPU_FREQ_GOV_PERFORMANCE) += cpufreq_performance.o
obj-$(CONFIG_CPU_FREQ_GOV_POWERSAVE) += cpufreq_powersave.o
obj-$(CONFIG_CPU_FREQ_GOV_USERSPACE) += cpufreq_userspace.o
obj-$(CONFIG_CPU_FREQ_GOV_ONDEMAND) += cpufreq_ondemand.o
obj-$(CONFIG_CPU_FREQ_GOV_CONSERVATIVE) += cpufreq_conservative.o
obj-$(CONFIG_CPU_FREQ_GOV_INTERACTIVE) += cpufreq_interactive.o
obj-$(CONFIG_CPU_FREQ_GOV_SMARTASS2) += cpufreq_smartass2.o
# CPUfreq cross-arch helpers
obj-$(CONFIG_CPU_FREQ_TABLE) += freq_table.o
|
<?php
/**
* File containing the Services controller class
*
* @copyright Copyright (C) eZ Systems AS. All rights reserved.
* @license For full copyright and license information view LICENSE file distributed with this source code.
* @version //autogentag//
*/
namespace eZ\Publish\Core\REST\Server\Controller;
use eZ\Publish\Core\REST\Server\Controller as RestController;
use eZ\Publish\Core\REST\Server\Values;
/**
* Services controller
*/
class Services extends RestController
{
/**
* @var array
*/
protected $countriesInfo;
public function __construct( array $countriesInfo )
{
$this->countriesInfo = $countriesInfo;
}
/**
* Loads Country List
*
*/
public function loadCountryList()
{
return new Values\CountryList( $this->countriesInfo );
}
}
|
/*
* A driver for the ARM PL022 PrimeCell SSP/SPI bus master.
*
* Copyright (C) 2008-2009 ST-Ericsson AB
* Copyright (C) 2006 STMicroelectronics Pvt. Ltd.
*
* Author: Linus Walleij <linus.walleij@stericsson.com>
*
* Initial version inspired by:
* linux-2.6.17-rc3-mm1/drivers/spi/pxa2xx_spi.c
* Initial adoption to PL022 by:
* Sachin Verma <sachin.verma@st.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#include <linux/init.h>
#include <linux/module.h>
#include <linux/device.h>
#include <linux/ioport.h>
#include <linux/errno.h>
#include <linux/interrupt.h>
#include <linux/spi/spi.h>
#include <linux/delay.h>
#include <linux/clk.h>
#include <linux/err.h>
#include <linux/amba/bus.h>
#include <linux/amba/pl022.h>
#include <linux/io.h>
#include <linux/slab.h>
#include <linux/dmaengine.h>
#include <linux/dma-mapping.h>
#include <linux/scatterlist.h>
#include <linux/pm_runtime.h>
/*
* This macro is used to define some register default values.
* reg is masked with mask, the OR:ed with an (again masked)
* val shifted sb steps to the left.
*/
#define SSP_WRITE_BITS(reg, val, mask, sb) \
((reg) = (((reg) & ~(mask)) | (((val)<<(sb)) & (mask))))
/*
* This macro is also used to define some default values.
* It will just shift val by sb steps to the left and mask
* the result with mask.
*/
#define GEN_MASK_BITS(val, mask, sb) \
(((val)<<(sb)) & (mask))
#define DRIVE_TX 0
#define DO_NOT_DRIVE_TX 1
#define DO_NOT_QUEUE_DMA 0
#define QUEUE_DMA 1
#define RX_TRANSFER 1
#define TX_TRANSFER 2
/*
* Macros to access SSP Registers with their offsets
*/
#define SSP_CR0(r) (r + 0x000)
#define SSP_CR1(r) (r + 0x004)
#define SSP_DR(r) (r + 0x008)
#define SSP_SR(r) (r + 0x00C)
#define SSP_CPSR(r) (r + 0x010)
#define SSP_IMSC(r) (r + 0x014)
#define SSP_RIS(r) (r + 0x018)
#define SSP_MIS(r) (r + 0x01C)
#define SSP_ICR(r) (r + 0x020)
#define SSP_DMACR(r) (r + 0x024)
#define SSP_ITCR(r) (r + 0x080)
#define SSP_ITIP(r) (r + 0x084)
#define SSP_ITOP(r) (r + 0x088)
#define SSP_TDR(r) (r + 0x08C)
#define SSP_PID0(r) (r + 0xFE0)
#define SSP_PID1(r) (r + 0xFE4)
#define SSP_PID2(r) (r + 0xFE8)
#define SSP_PID3(r) (r + 0xFEC)
#define SSP_CID0(r) (r + 0xFF0)
#define SSP_CID1(r) (r + 0xFF4)
#define SSP_CID2(r) (r + 0xFF8)
#define SSP_CID3(r) (r + 0xFFC)
/*
* SSP Control Register 0 - SSP_CR0
*/
#define SSP_CR0_MASK_DSS (0x0FUL << 0)
#define SSP_CR0_MASK_FRF (0x3UL << 4)
#define SSP_CR0_MASK_SPO (0x1UL << 6)
#define SSP_CR0_MASK_SPH (0x1UL << 7)
#define SSP_CR0_MASK_SCR (0xFFUL << 8)
/*
* The ST version of this block moves som bits
* in SSP_CR0 and extends it to 32 bits
*/
#define SSP_CR0_MASK_DSS_ST (0x1FUL << 0)
#define SSP_CR0_MASK_HALFDUP_ST (0x1UL << 5)
#define SSP_CR0_MASK_CSS_ST (0x1FUL << 16)
#define SSP_CR0_MASK_FRF_ST (0x3UL << 21)
/*
* SSP Control Register 0 - SSP_CR1
*/
#define SSP_CR1_MASK_LBM (0x1UL << 0)
#define SSP_CR1_MASK_SSE (0x1UL << 1)
#define SSP_CR1_MASK_MS (0x1UL << 2)
#define SSP_CR1_MASK_SOD (0x1UL << 3)
/*
* The ST version of this block adds some bits
* in SSP_CR1
*/
#define SSP_CR1_MASK_RENDN_ST (0x1UL << 4)
#define SSP_CR1_MASK_TENDN_ST (0x1UL << 5)
#define SSP_CR1_MASK_MWAIT_ST (0x1UL << 6)
#define SSP_CR1_MASK_RXIFLSEL_ST (0x7UL << 7)
#define SSP_CR1_MASK_TXIFLSEL_ST (0x7UL << 10)
/* This one is only in the PL023 variant */
#define SSP_CR1_MASK_FBCLKDEL_ST (0x7UL << 13)
/*
* SSP Status Register - SSP_SR
*/
#define SSP_SR_MASK_TFE (0x1UL << 0) /* Transmit FIFO empty */
#define SSP_SR_MASK_TNF (0x1UL << 1) /* Transmit FIFO not full */
#define SSP_SR_MASK_RNE (0x1UL << 2) /* Receive FIFO not empty */
#define SSP_SR_MASK_RFF (0x1UL << 3) /* Receive FIFO full */
#define SSP_SR_MASK_BSY (0x1UL << 4) /* Busy Flag */
/*
* SSP Clock Prescale Register - SSP_CPSR
*/
#define SSP_CPSR_MASK_CPSDVSR (0xFFUL << 0)
/*
* SSP Interrupt Mask Set/Clear Register - SSP_IMSC
*/
#define SSP_IMSC_MASK_RORIM (0x1UL << 0) /* Receive Overrun Interrupt mask */
#define SSP_IMSC_MASK_RTIM (0x1UL << 1) /* Receive timeout Interrupt mask */
#define SSP_IMSC_MASK_RXIM (0x1UL << 2) /* Receive FIFO Interrupt mask */
#define SSP_IMSC_MASK_TXIM (0x1UL << 3) /* Transmit FIFO Interrupt mask */
/*
* SSP Raw Interrupt Status Register - SSP_RIS
*/
/* Receive Overrun Raw Interrupt status */
#define SSP_RIS_MASK_RORRIS (0x1UL << 0)
/* Receive Timeout Raw Interrupt status */
#define SSP_RIS_MASK_RTRIS (0x1UL << 1)
/* Receive FIFO Raw Interrupt status */
#define SSP_RIS_MASK_RXRIS (0x1UL << 2)
/* Transmit FIFO Raw Interrupt status */
#define SSP_RIS_MASK_TXRIS (0x1UL << 3)
/*
* SSP Masked Interrupt Status Register - SSP_MIS
*/
/* Receive Overrun Masked Interrupt status */
#define SSP_MIS_MASK_RORMIS (0x1UL << 0)
/* Receive Timeout Masked Interrupt status */
#define SSP_MIS_MASK_RTMIS (0x1UL << 1)
/* Receive FIFO Masked Interrupt status */
#define SSP_MIS_MASK_RXMIS (0x1UL << 2)
/* Transmit FIFO Masked Interrupt status */
#define SSP_MIS_MASK_TXMIS (0x1UL << 3)
/*
* SSP Interrupt Clear Register - SSP_ICR
*/
/* Receive Overrun Raw Clear Interrupt bit */
#define SSP_ICR_MASK_RORIC (0x1UL << 0)
/* Receive Timeout Clear Interrupt bit */
#define SSP_ICR_MASK_RTIC (0x1UL << 1)
/*
* SSP DMA Control Register - SSP_DMACR
*/
/* Receive DMA Enable bit */
#define SSP_DMACR_MASK_RXDMAE (0x1UL << 0)
/* Transmit DMA Enable bit */
#define SSP_DMACR_MASK_TXDMAE (0x1UL << 1)
/*
* SSP Integration Test control Register - SSP_ITCR
*/
#define SSP_ITCR_MASK_ITEN (0x1UL << 0)
#define SSP_ITCR_MASK_TESTFIFO (0x1UL << 1)
/*
* SSP Integration Test Input Register - SSP_ITIP
*/
#define ITIP_MASK_SSPRXD (0x1UL << 0)
#define ITIP_MASK_SSPFSSIN (0x1UL << 1)
#define ITIP_MASK_SSPCLKIN (0x1UL << 2)
#define ITIP_MASK_RXDMAC (0x1UL << 3)
#define ITIP_MASK_TXDMAC (0x1UL << 4)
#define ITIP_MASK_SSPTXDIN (0x1UL << 5)
/*
* SSP Integration Test output Register - SSP_ITOP
*/
#define ITOP_MASK_SSPTXD (0x1UL << 0)
#define ITOP_MASK_SSPFSSOUT (0x1UL << 1)
#define ITOP_MASK_SSPCLKOUT (0x1UL << 2)
#define ITOP_MASK_SSPOEn (0x1UL << 3)
#define ITOP_MASK_SSPCTLOEn (0x1UL << 4)
#define ITOP_MASK_RORINTR (0x1UL << 5)
#define ITOP_MASK_RTINTR (0x1UL << 6)
#define ITOP_MASK_RXINTR (0x1UL << 7)
#define ITOP_MASK_TXINTR (0x1UL << 8)
#define ITOP_MASK_INTR (0x1UL << 9)
#define ITOP_MASK_RXDMABREQ (0x1UL << 10)
#define ITOP_MASK_RXDMASREQ (0x1UL << 11)
#define ITOP_MASK_TXDMABREQ (0x1UL << 12)
#define ITOP_MASK_TXDMASREQ (0x1UL << 13)
/*
* SSP Test Data Register - SSP_TDR
*/
#define TDR_MASK_TESTDATA (0xFFFFFFFF)
/*
* Message State
* we use the spi_message.state (void *) pointer to
* hold a single state value, that's why all this
* (void *) casting is done here.
*/
#define STATE_START ((void *) 0)
#define STATE_RUNNING ((void *) 1)
#define STATE_DONE ((void *) 2)
#define STATE_ERROR ((void *) -1)
/*
* SSP State - Whether Enabled or Disabled
*/
#define SSP_DISABLED (0)
#define SSP_ENABLED (1)
/*
* SSP DMA State - Whether DMA Enabled or Disabled
*/
#define SSP_DMA_DISABLED (0)
#define SSP_DMA_ENABLED (1)
/*
* SSP Clock Defaults
*/
#define SSP_DEFAULT_CLKRATE 0x2
#define SSP_DEFAULT_PRESCALE 0x40
/*
* SSP Clock Parameter ranges
*/
#define CPSDVR_MIN 0x02
#define CPSDVR_MAX 0xFE
#define SCR_MIN 0x00
#define SCR_MAX 0xFF
/*
* SSP Interrupt related Macros
*/
#define DEFAULT_SSP_REG_IMSC 0x0UL
#define DISABLE_ALL_INTERRUPTS DEFAULT_SSP_REG_IMSC
#define ENABLE_ALL_INTERRUPTS (~DEFAULT_SSP_REG_IMSC)
#define CLEAR_ALL_INTERRUPTS 0x3
#define SPI_POLLING_TIMEOUT 1000
/*
* The type of reading going on on this chip
*/
enum ssp_reading {
READING_NULL,
READING_U8,
READING_U16,
READING_U32
};
/**
* The type of writing going on on this chip
*/
enum ssp_writing {
WRITING_NULL,
WRITING_U8,
WRITING_U16,
WRITING_U32
};
/**
* struct vendor_data - vendor-specific config parameters
* for PL022 derivates
* @fifodepth: depth of FIFOs (both)
* @max_bpw: maximum number of bits per word
* @unidir: supports unidirection transfers
* @extended_cr: 32 bit wide control register 0 with extra
* features and extra features in CR1 as found in the ST variants
* @pl023: supports a subset of the ST extensions called "PL023"
*/
struct vendor_data {
int fifodepth;
int max_bpw;
bool unidir;
bool extended_cr;
bool pl023;
bool loopback;
};
/**
* struct pl022 - This is the private SSP driver data structure
* @adev: AMBA device model hookup
* @vendor: vendor data for the IP block
* @phybase: the physical memory where the SSP device resides
* @virtbase: the virtual memory where the SSP is mapped
* @clk: outgoing clock "SPICLK" for the SPI bus
* @master: SPI framework hookup
* @master_info: controller-specific data from machine setup
* @kworker: thread struct for message pump
* @kworker_task: pointer to task for message pump kworker thread
* @pump_messages: work struct for scheduling work to the message pump
* @queue_lock: spinlock to syncronise access to message queue
* @queue: message queue
* @busy: message pump is busy
* @running: message pump is running
* @pump_transfers: Tasklet used in Interrupt Transfer mode
* @cur_msg: Pointer to current spi_message being processed
* @cur_transfer: Pointer to current spi_transfer
* @cur_chip: pointer to current clients chip(assigned from controller_state)
* @next_msg_cs_active: the next message in the queue has been examined
* and it was found that it uses the same chip select as the previous
* message, so we left it active after the previous transfer, and it's
* active already.
* @tx: current position in TX buffer to be read
* @tx_end: end position in TX buffer to be read
* @rx: current position in RX buffer to be written
* @rx_end: end position in RX buffer to be written
* @read: the type of read currently going on
* @write: the type of write currently going on
* @exp_fifo_level: expected FIFO level
* @dma_rx_channel: optional channel for RX DMA
* @dma_tx_channel: optional channel for TX DMA
* @sgt_rx: scattertable for the RX transfer
* @sgt_tx: scattertable for the TX transfer
* @dummypage: a dummy page used for driving data on the bus with DMA
*/
struct pl022 {
struct amba_device *adev;
struct vendor_data *vendor;
resource_size_t phybase;
void __iomem *virtbase;
struct clk *clk;
struct spi_master *master;
struct pl022_ssp_controller *master_info;
/* Message per-transfer pump */
struct tasklet_struct pump_transfers;
struct spi_message *cur_msg;
struct spi_transfer *cur_transfer;
struct chip_data *cur_chip;
bool next_msg_cs_active;
void *tx;
void *tx_end;
void *rx;
void *rx_end;
enum ssp_reading read;
enum ssp_writing write;
u32 exp_fifo_level;
enum ssp_rx_level_trig rx_lev_trig;
enum ssp_tx_level_trig tx_lev_trig;
/* DMA settings */
#ifdef CONFIG_DMA_ENGINE
struct dma_chan *dma_rx_channel;
struct dma_chan *dma_tx_channel;
struct sg_table sgt_rx;
struct sg_table sgt_tx;
char *dummypage;
bool dma_running;
#endif
};
/**
* struct chip_data - To maintain runtime state of SSP for each client chip
* @cr0: Value of control register CR0 of SSP - on later ST variants this
* register is 32 bits wide rather than just 16
* @cr1: Value of control register CR1 of SSP
* @dmacr: Value of DMA control Register of SSP
* @cpsr: Value of Clock prescale register
* @n_bytes: how many bytes(power of 2) reqd for a given data width of client
* @enable_dma: Whether to enable DMA or not
* @read: function ptr to be used to read when doing xfer for this chip
* @write: function ptr to be used to write when doing xfer for this chip
* @cs_control: chip select callback provided by chip
* @xfer_type: polling/interrupt/DMA
*
* Runtime state of the SSP controller, maintained per chip,
* This would be set according to the current message that would be served
*/
struct chip_data {
u32 cr0;
u16 cr1;
u16 dmacr;
u16 cpsr;
u8 n_bytes;
bool enable_dma;
enum ssp_reading read;
enum ssp_writing write;
void (*cs_control) (u32 command);
int xfer_type;
};
/**
* null_cs_control - Dummy chip select function
* @command: select/delect the chip
*
* If no chip select function is provided by client this is used as dummy
* chip select
*/
static void null_cs_control(u32 command)
{
pr_debug("pl022: dummy chip select control, CS=0x%x\n", command);
}
/**
* giveback - current spi_message is over, schedule next message and call
* callback of this message. Assumes that caller already
* set message->status; dma and pio irqs are blocked
* @pl022: SSP driver private data structure
*/
static void giveback(struct pl022 *pl022)
{
struct spi_transfer *last_transfer;
pl022->next_msg_cs_active = false;
last_transfer = list_entry(pl022->cur_msg->transfers.prev,
struct spi_transfer,
transfer_list);
/* Delay if requested before any change in chip select */
if (last_transfer->delay_usecs)
/*
* FIXME: This runs in interrupt context.
* Is this really smart?
*/
udelay(last_transfer->delay_usecs);
if (!last_transfer->cs_change) {
struct spi_message *next_msg;
/*
* cs_change was not set. We can keep the chip select
* enabled if there is message in the queue and it is
* for the same spi device.
*
* We cannot postpone this until pump_messages, because
* after calling msg->complete (below) the driver that
* sent the current message could be unloaded, which
* could invalidate the cs_control() callback...
*/
/* get a pointer to the next message, if any */
next_msg = spi_get_next_queued_message(pl022->master);
/*
* see if the next and current messages point
* to the same spi device.
*/
if (next_msg && next_msg->spi != pl022->cur_msg->spi)
next_msg = NULL;
if (!next_msg || pl022->cur_msg->state == STATE_ERROR)
pl022->cur_chip->cs_control(SSP_CHIP_DESELECT);
else
pl022->next_msg_cs_active = true;
}
pl022->cur_msg = NULL;
pl022->cur_transfer = NULL;
pl022->cur_chip = NULL;
spi_finalize_current_message(pl022->master);
}
/**
* flush - flush the FIFO to reach a clean state
* @pl022: SSP driver private data structure
*/
static int flush(struct pl022 *pl022)
{
unsigned long limit = loops_per_jiffy << 1;
dev_dbg(&pl022->adev->dev, "flush\n");
do {
while (readw(SSP_SR(pl022->virtbase)) & SSP_SR_MASK_RNE)
readw(SSP_DR(pl022->virtbase));
} while ((readw(SSP_SR(pl022->virtbase)) & SSP_SR_MASK_BSY) && limit--);
pl022->exp_fifo_level = 0;
return limit;
}
/**
* restore_state - Load configuration of current chip
* @pl022: SSP driver private data structure
*/
static void restore_state(struct pl022 *pl022)
{
struct chip_data *chip = pl022->cur_chip;
if (pl022->vendor->extended_cr)
writel(chip->cr0, SSP_CR0(pl022->virtbase));
else
writew(chip->cr0, SSP_CR0(pl022->virtbase));
writew(chip->cr1, SSP_CR1(pl022->virtbase));
writew(chip->dmacr, SSP_DMACR(pl022->virtbase));
writew(chip->cpsr, SSP_CPSR(pl022->virtbase));
writew(DISABLE_ALL_INTERRUPTS, SSP_IMSC(pl022->virtbase));
writew(CLEAR_ALL_INTERRUPTS, SSP_ICR(pl022->virtbase));
}
/*
* Default SSP Register Values
*/
#define DEFAULT_SSP_REG_CR0 ( \
GEN_MASK_BITS(SSP_DATA_BITS_12, SSP_CR0_MASK_DSS, 0) | \
GEN_MASK_BITS(SSP_INTERFACE_MOTOROLA_SPI, SSP_CR0_MASK_FRF, 4) | \
GEN_MASK_BITS(SSP_CLK_POL_IDLE_LOW, SSP_CR0_MASK_SPO, 6) | \
GEN_MASK_BITS(SSP_CLK_SECOND_EDGE, SSP_CR0_MASK_SPH, 7) | \
GEN_MASK_BITS(SSP_DEFAULT_CLKRATE, SSP_CR0_MASK_SCR, 8) \
)
/* ST versions have slightly different bit layout */
#define DEFAULT_SSP_REG_CR0_ST ( \
GEN_MASK_BITS(SSP_DATA_BITS_12, SSP_CR0_MASK_DSS_ST, 0) | \
GEN_MASK_BITS(SSP_MICROWIRE_CHANNEL_FULL_DUPLEX, SSP_CR0_MASK_HALFDUP_ST, 5) | \
GEN_MASK_BITS(SSP_CLK_POL_IDLE_LOW, SSP_CR0_MASK_SPO, 6) | \
GEN_MASK_BITS(SSP_CLK_SECOND_EDGE, SSP_CR0_MASK_SPH, 7) | \
GEN_MASK_BITS(SSP_DEFAULT_CLKRATE, SSP_CR0_MASK_SCR, 8) | \
GEN_MASK_BITS(SSP_BITS_8, SSP_CR0_MASK_CSS_ST, 16) | \
GEN_MASK_BITS(SSP_INTERFACE_MOTOROLA_SPI, SSP_CR0_MASK_FRF_ST, 21) \
)
/* The PL023 version is slightly different again */
#define DEFAULT_SSP_REG_CR0_ST_PL023 ( \
GEN_MASK_BITS(SSP_DATA_BITS_12, SSP_CR0_MASK_DSS_ST, 0) | \
GEN_MASK_BITS(SSP_CLK_POL_IDLE_LOW, SSP_CR0_MASK_SPO, 6) | \
GEN_MASK_BITS(SSP_CLK_SECOND_EDGE, SSP_CR0_MASK_SPH, 7) | \
GEN_MASK_BITS(SSP_DEFAULT_CLKRATE, SSP_CR0_MASK_SCR, 8) \
)
#define DEFAULT_SSP_REG_CR1 ( \
GEN_MASK_BITS(LOOPBACK_DISABLED, SSP_CR1_MASK_LBM, 0) | \
GEN_MASK_BITS(SSP_DISABLED, SSP_CR1_MASK_SSE, 1) | \
GEN_MASK_BITS(SSP_MASTER, SSP_CR1_MASK_MS, 2) | \
GEN_MASK_BITS(DO_NOT_DRIVE_TX, SSP_CR1_MASK_SOD, 3) \
)
/* ST versions extend this register to use all 16 bits */
#define DEFAULT_SSP_REG_CR1_ST ( \
DEFAULT_SSP_REG_CR1 | \
GEN_MASK_BITS(SSP_RX_MSB, SSP_CR1_MASK_RENDN_ST, 4) | \
GEN_MASK_BITS(SSP_TX_MSB, SSP_CR1_MASK_TENDN_ST, 5) | \
GEN_MASK_BITS(SSP_MWIRE_WAIT_ZERO, SSP_CR1_MASK_MWAIT_ST, 6) |\
GEN_MASK_BITS(SSP_RX_1_OR_MORE_ELEM, SSP_CR1_MASK_RXIFLSEL_ST, 7) | \
GEN_MASK_BITS(SSP_TX_1_OR_MORE_EMPTY_LOC, SSP_CR1_MASK_TXIFLSEL_ST, 10) \
)
/*
* The PL023 variant has further differences: no loopback mode, no microwire
* support, and a new clock feedback delay setting.
*/
#define DEFAULT_SSP_REG_CR1_ST_PL023 ( \
GEN_MASK_BITS(SSP_DISABLED, SSP_CR1_MASK_SSE, 1) | \
GEN_MASK_BITS(SSP_MASTER, SSP_CR1_MASK_MS, 2) | \
GEN_MASK_BITS(DO_NOT_DRIVE_TX, SSP_CR1_MASK_SOD, 3) | \
GEN_MASK_BITS(SSP_RX_MSB, SSP_CR1_MASK_RENDN_ST, 4) | \
GEN_MASK_BITS(SSP_TX_MSB, SSP_CR1_MASK_TENDN_ST, 5) | \
GEN_MASK_BITS(SSP_RX_1_OR_MORE_ELEM, SSP_CR1_MASK_RXIFLSEL_ST, 7) | \
GEN_MASK_BITS(SSP_TX_1_OR_MORE_EMPTY_LOC, SSP_CR1_MASK_TXIFLSEL_ST, 10) | \
GEN_MASK_BITS(SSP_FEEDBACK_CLK_DELAY_NONE, SSP_CR1_MASK_FBCLKDEL_ST, 13) \
)
#define DEFAULT_SSP_REG_CPSR ( \
GEN_MASK_BITS(SSP_DEFAULT_PRESCALE, SSP_CPSR_MASK_CPSDVSR, 0) \
)
#define DEFAULT_SSP_REG_DMACR (\
GEN_MASK_BITS(SSP_DMA_DISABLED, SSP_DMACR_MASK_RXDMAE, 0) | \
GEN_MASK_BITS(SSP_DMA_DISABLED, SSP_DMACR_MASK_TXDMAE, 1) \
)
/**
* load_ssp_default_config - Load default configuration for SSP
* @pl022: SSP driver private data structure
*/
static void load_ssp_default_config(struct pl022 *pl022)
{
if (pl022->vendor->pl023) {
writel(DEFAULT_SSP_REG_CR0_ST_PL023, SSP_CR0(pl022->virtbase));
writew(DEFAULT_SSP_REG_CR1_ST_PL023, SSP_CR1(pl022->virtbase));
} else if (pl022->vendor->extended_cr) {
writel(DEFAULT_SSP_REG_CR0_ST, SSP_CR0(pl022->virtbase));
writew(DEFAULT_SSP_REG_CR1_ST, SSP_CR1(pl022->virtbase));
} else {
writew(DEFAULT_SSP_REG_CR0, SSP_CR0(pl022->virtbase));
writew(DEFAULT_SSP_REG_CR1, SSP_CR1(pl022->virtbase));
}
writew(DEFAULT_SSP_REG_DMACR, SSP_DMACR(pl022->virtbase));
writew(DEFAULT_SSP_REG_CPSR, SSP_CPSR(pl022->virtbase));
writew(DISABLE_ALL_INTERRUPTS, SSP_IMSC(pl022->virtbase));
writew(CLEAR_ALL_INTERRUPTS, SSP_ICR(pl022->virtbase));
}
/**
* This will write to TX and read from RX according to the parameters
* set in pl022.
*/
static void readwriter(struct pl022 *pl022)
{
/*
* The FIFO depth is different between primecell variants.
* I believe filling in too much in the FIFO might cause
* errons in 8bit wide transfers on ARM variants (just 8 words
* FIFO, means only 8x8 = 64 bits in FIFO) at least.
*
* To prevent this issue, the TX FIFO is only filled to the
* unused RX FIFO fill length, regardless of what the TX
* FIFO status flag indicates.
*/
dev_dbg(&pl022->adev->dev,
"%s, rx: %p, rxend: %p, tx: %p, txend: %p\n",
__func__, pl022->rx, pl022->rx_end, pl022->tx, pl022->tx_end);
/* Read as much as you can */
while ((readw(SSP_SR(pl022->virtbase)) & SSP_SR_MASK_RNE)
&& (pl022->rx < pl022->rx_end)) {
switch (pl022->read) {
case READING_NULL:
readw(SSP_DR(pl022->virtbase));
break;
case READING_U8:
*(u8 *) (pl022->rx) =
readw(SSP_DR(pl022->virtbase)) & 0xFFU;
break;
case READING_U16:
*(u16 *) (pl022->rx) =
(u16) readw(SSP_DR(pl022->virtbase));
break;
case READING_U32:
*(u32 *) (pl022->rx) =
readl(SSP_DR(pl022->virtbase));
break;
}
pl022->rx += (pl022->cur_chip->n_bytes);
pl022->exp_fifo_level--;
}
/*
* Write as much as possible up to the RX FIFO size
*/
while ((pl022->exp_fifo_level < pl022->vendor->fifodepth)
&& (pl022->tx < pl022->tx_end)) {
switch (pl022->write) {
case WRITING_NULL:
writew(0x0, SSP_DR(pl022->virtbase));
break;
case WRITING_U8:
writew(*(u8 *) (pl022->tx), SSP_DR(pl022->virtbase));
break;
case WRITING_U16:
writew((*(u16 *) (pl022->tx)), SSP_DR(pl022->virtbase));
break;
case WRITING_U32:
writel(*(u32 *) (pl022->tx), SSP_DR(pl022->virtbase));
break;
}
pl022->tx += (pl022->cur_chip->n_bytes);
pl022->exp_fifo_level++;
/*
* This inner reader takes care of things appearing in the RX
* FIFO as we're transmitting. This will happen a lot since the
* clock starts running when you put things into the TX FIFO,
* and then things are continuously clocked into the RX FIFO.
*/
while ((readw(SSP_SR(pl022->virtbase)) & SSP_SR_MASK_RNE)
&& (pl022->rx < pl022->rx_end)) {
switch (pl022->read) {
case READING_NULL:
readw(SSP_DR(pl022->virtbase));
break;
case READING_U8:
*(u8 *) (pl022->rx) =
readw(SSP_DR(pl022->virtbase)) & 0xFFU;
break;
case READING_U16:
*(u16 *) (pl022->rx) =
(u16) readw(SSP_DR(pl022->virtbase));
break;
case READING_U32:
*(u32 *) (pl022->rx) =
readl(SSP_DR(pl022->virtbase));
break;
}
pl022->rx += (pl022->cur_chip->n_bytes);
pl022->exp_fifo_level--;
}
}
/*
* When we exit here the TX FIFO should be full and the RX FIFO
* should be empty
*/
}
/**
* next_transfer - Move to the Next transfer in the current spi message
* @pl022: SSP driver private data structure
*
* This function moves though the linked list of spi transfers in the
* current spi message and returns with the state of current spi
* message i.e whether its last transfer is done(STATE_DONE) or
* Next transfer is ready(STATE_RUNNING)
*/
static void *next_transfer(struct pl022 *pl022)
{
struct spi_message *msg = pl022->cur_msg;
struct spi_transfer *trans = pl022->cur_transfer;
/* Move to next transfer */
if (trans->transfer_list.next != &msg->transfers) {
pl022->cur_transfer =
list_entry(trans->transfer_list.next,
struct spi_transfer, transfer_list);
return STATE_RUNNING;
}
return STATE_DONE;
}
/*
* This DMA functionality is only compiled in if we have
* access to the generic DMA devices/DMA engine.
*/
#ifdef CONFIG_DMA_ENGINE
static void unmap_free_dma_scatter(struct pl022 *pl022)
{
/* Unmap and free the SG tables */
dma_unmap_sg(pl022->dma_tx_channel->device->dev, pl022->sgt_tx.sgl,
pl022->sgt_tx.nents, DMA_TO_DEVICE);
dma_unmap_sg(pl022->dma_rx_channel->device->dev, pl022->sgt_rx.sgl,
pl022->sgt_rx.nents, DMA_FROM_DEVICE);
sg_free_table(&pl022->sgt_rx);
sg_free_table(&pl022->sgt_tx);
}
static void dma_callback(void *data)
{
struct pl022 *pl022 = data;
struct spi_message *msg = pl022->cur_msg;
BUG_ON(!pl022->sgt_rx.sgl);
#ifdef VERBOSE_DEBUG
/*
* Optionally dump out buffers to inspect contents, this is
* good if you want to convince yourself that the loopback
* read/write contents are the same, when adopting to a new
* DMA engine.
*/
{
struct scatterlist *sg;
unsigned int i;
dma_sync_sg_for_cpu(&pl022->adev->dev,
pl022->sgt_rx.sgl,
pl022->sgt_rx.nents,
DMA_FROM_DEVICE);
for_each_sg(pl022->sgt_rx.sgl, sg, pl022->sgt_rx.nents, i) {
dev_dbg(&pl022->adev->dev, "SPI RX SG ENTRY: %d", i);
print_hex_dump(KERN_ERR, "SPI RX: ",
DUMP_PREFIX_OFFSET,
16,
1,
sg_virt(sg),
sg_dma_len(sg),
1);
}
for_each_sg(pl022->sgt_tx.sgl, sg, pl022->sgt_tx.nents, i) {
dev_dbg(&pl022->adev->dev, "SPI TX SG ENTRY: %d", i);
print_hex_dump(KERN_ERR, "SPI TX: ",
DUMP_PREFIX_OFFSET,
16,
1,
sg_virt(sg),
sg_dma_len(sg),
1);
}
}
#endif
unmap_free_dma_scatter(pl022);
/* Update total bytes transferred */
msg->actual_length += pl022->cur_transfer->len;
if (pl022->cur_transfer->cs_change)
pl022->cur_chip->
cs_control(SSP_CHIP_DESELECT);
/* Move to next transfer */
msg->state = next_transfer(pl022);
tasklet_schedule(&pl022->pump_transfers);
}
static void setup_dma_scatter(struct pl022 *pl022,
void *buffer,
unsigned int length,
struct sg_table *sgtab)
{
struct scatterlist *sg;
int bytesleft = length;
void *bufp = buffer;
int mapbytes;
int i;
if (buffer) {
for_each_sg(sgtab->sgl, sg, sgtab->nents, i) {
/*
* If there are less bytes left than what fits
* in the current page (plus page alignment offset)
* we just feed in this, else we stuff in as much
* as we can.
*/
if (bytesleft < (PAGE_SIZE - offset_in_page(bufp)))
mapbytes = bytesleft;
else
mapbytes = PAGE_SIZE - offset_in_page(bufp);
sg_set_page(sg, virt_to_page(bufp),
mapbytes, offset_in_page(bufp));
bufp += mapbytes;
bytesleft -= mapbytes;
dev_dbg(&pl022->adev->dev,
"set RX/TX target page @ %p, %d bytes, %d left\n",
bufp, mapbytes, bytesleft);
}
} else {
/* Map the dummy buffer on every page */
for_each_sg(sgtab->sgl, sg, sgtab->nents, i) {
if (bytesleft < PAGE_SIZE)
mapbytes = bytesleft;
else
mapbytes = PAGE_SIZE;
sg_set_page(sg, virt_to_page(pl022->dummypage),
mapbytes, 0);
bytesleft -= mapbytes;
dev_dbg(&pl022->adev->dev,
"set RX/TX to dummy page %d bytes, %d left\n",
mapbytes, bytesleft);
}
}
BUG_ON(bytesleft);
}
/**
* configure_dma - configures the channels for the next transfer
* @pl022: SSP driver's private data structure
*/
static int configure_dma(struct pl022 *pl022)
{
struct dma_slave_config rx_conf = {
.src_addr = SSP_DR(pl022->phybase),
.direction = DMA_DEV_TO_MEM,
.device_fc = false,
};
struct dma_slave_config tx_conf = {
.dst_addr = SSP_DR(pl022->phybase),
.direction = DMA_MEM_TO_DEV,
.device_fc = false,
};
unsigned int pages;
int ret;
int rx_sglen, tx_sglen;
struct dma_chan *rxchan = pl022->dma_rx_channel;
struct dma_chan *txchan = pl022->dma_tx_channel;
struct dma_async_tx_descriptor *rxdesc;
struct dma_async_tx_descriptor *txdesc;
/* Check that the channels are available */
if (!rxchan || !txchan)
return -ENODEV;
/*
* If supplied, the DMA burstsize should equal the FIFO trigger level.
* Notice that the DMA engine uses one-to-one mapping. Since we can
* not trigger on 2 elements this needs explicit mapping rather than
* calculation.
*/
switch (pl022->rx_lev_trig) {
case SSP_RX_1_OR_MORE_ELEM:
rx_conf.src_maxburst = 1;
break;
case SSP_RX_4_OR_MORE_ELEM:
rx_conf.src_maxburst = 4;
break;
case SSP_RX_8_OR_MORE_ELEM:
rx_conf.src_maxburst = 8;
break;
case SSP_RX_16_OR_MORE_ELEM:
rx_conf.src_maxburst = 16;
break;
case SSP_RX_32_OR_MORE_ELEM:
rx_conf.src_maxburst = 32;
break;
default:
rx_conf.src_maxburst = pl022->vendor->fifodepth >> 1;
break;
}
switch (pl022->tx_lev_trig) {
case SSP_TX_1_OR_MORE_EMPTY_LOC:
tx_conf.dst_maxburst = 1;
break;
case SSP_TX_4_OR_MORE_EMPTY_LOC:
tx_conf.dst_maxburst = 4;
break;
case SSP_TX_8_OR_MORE_EMPTY_LOC:
tx_conf.dst_maxburst = 8;
break;
case SSP_TX_16_OR_MORE_EMPTY_LOC:
tx_conf.dst_maxburst = 16;
break;
case SSP_TX_32_OR_MORE_EMPTY_LOC:
tx_conf.dst_maxburst = 32;
break;
default:
tx_conf.dst_maxburst = pl022->vendor->fifodepth >> 1;
break;
}
switch (pl022->read) {
case READING_NULL:
/* Use the same as for writing */
rx_conf.src_addr_width = DMA_SLAVE_BUSWIDTH_UNDEFINED;
break;
case READING_U8:
rx_conf.src_addr_width = DMA_SLAVE_BUSWIDTH_1_BYTE;
break;
case READING_U16:
rx_conf.src_addr_width = DMA_SLAVE_BUSWIDTH_2_BYTES;
break;
case READING_U32:
rx_conf.src_addr_width = DMA_SLAVE_BUSWIDTH_4_BYTES;
break;
}
switch (pl022->write) {
case WRITING_NULL:
/* Use the same as for reading */
tx_conf.dst_addr_width = DMA_SLAVE_BUSWIDTH_UNDEFINED;
break;
case WRITING_U8:
tx_conf.dst_addr_width = DMA_SLAVE_BUSWIDTH_1_BYTE;
break;
case WRITING_U16:
tx_conf.dst_addr_width = DMA_SLAVE_BUSWIDTH_2_BYTES;
break;
case WRITING_U32:
tx_conf.dst_addr_width = DMA_SLAVE_BUSWIDTH_4_BYTES;
break;
}
/* SPI pecularity: we need to read and write the same width */
if (rx_conf.src_addr_width == DMA_SLAVE_BUSWIDTH_UNDEFINED)
rx_conf.src_addr_width = tx_conf.dst_addr_width;
if (tx_conf.dst_addr_width == DMA_SLAVE_BUSWIDTH_UNDEFINED)
tx_conf.dst_addr_width = rx_conf.src_addr_width;
BUG_ON(rx_conf.src_addr_width != tx_conf.dst_addr_width);
dmaengine_slave_config(rxchan, &rx_conf);
dmaengine_slave_config(txchan, &tx_conf);
/* Create sglists for the transfers */
pages = DIV_ROUND_UP(pl022->cur_transfer->len, PAGE_SIZE);
dev_dbg(&pl022->adev->dev, "using %d pages for transfer\n", pages);
ret = sg_alloc_table(&pl022->sgt_rx, pages, GFP_ATOMIC);
if (ret)
goto err_alloc_rx_sg;
ret = sg_alloc_table(&pl022->sgt_tx, pages, GFP_ATOMIC);
if (ret)
goto err_alloc_tx_sg;
/* Fill in the scatterlists for the RX+TX buffers */
setup_dma_scatter(pl022, pl022->rx,
pl022->cur_transfer->len, &pl022->sgt_rx);
setup_dma_scatter(pl022, pl022->tx,
pl022->cur_transfer->len, &pl022->sgt_tx);
/* Map DMA buffers */
rx_sglen = dma_map_sg(rxchan->device->dev, pl022->sgt_rx.sgl,
pl022->sgt_rx.nents, DMA_FROM_DEVICE);
if (!rx_sglen)
goto err_rx_sgmap;
tx_sglen = dma_map_sg(txchan->device->dev, pl022->sgt_tx.sgl,
pl022->sgt_tx.nents, DMA_TO_DEVICE);
if (!tx_sglen)
goto err_tx_sgmap;
/* Send both scatterlists */
rxdesc = dmaengine_prep_slave_sg(rxchan,
pl022->sgt_rx.sgl,
rx_sglen,
DMA_DEV_TO_MEM,
DMA_PREP_INTERRUPT | DMA_CTRL_ACK);
if (!rxdesc)
goto err_rxdesc;
txdesc = dmaengine_prep_slave_sg(txchan,
pl022->sgt_tx.sgl,
tx_sglen,
DMA_MEM_TO_DEV,
DMA_PREP_INTERRUPT | DMA_CTRL_ACK);
if (!txdesc)
goto err_txdesc;
/* Put the callback on the RX transfer only, that should finish last */
rxdesc->callback = dma_callback;
rxdesc->callback_param = pl022;
/* Submit and fire RX and TX with TX last so we're ready to read! */
dmaengine_submit(rxdesc);
dmaengine_submit(txdesc);
dma_async_issue_pending(rxchan);
dma_async_issue_pending(txchan);
pl022->dma_running = true;
return 0;
err_txdesc:
dmaengine_terminate_all(txchan);
err_rxdesc:
dmaengine_terminate_all(rxchan);
dma_unmap_sg(txchan->device->dev, pl022->sgt_tx.sgl,
pl022->sgt_tx.nents, DMA_TO_DEVICE);
err_tx_sgmap:
dma_unmap_sg(rxchan->device->dev, pl022->sgt_rx.sgl,
pl022->sgt_tx.nents, DMA_FROM_DEVICE);
err_rx_sgmap:
sg_free_table(&pl022->sgt_tx);
err_alloc_tx_sg:
sg_free_table(&pl022->sgt_rx);
err_alloc_rx_sg:
return -ENOMEM;
}
static int __devinit pl022_dma_probe(struct pl022 *pl022)
{
dma_cap_mask_t mask;
/* Try to acquire a generic DMA engine slave channel */
dma_cap_zero(mask);
dma_cap_set(DMA_SLAVE, mask);
/*
* We need both RX and TX channels to do DMA, else do none
* of them.
*/
pl022->dma_rx_channel = dma_request_channel(mask,
pl022->master_info->dma_filter,
pl022->master_info->dma_rx_param);
if (!pl022->dma_rx_channel) {
dev_dbg(&pl022->adev->dev, "no RX DMA channel!\n");
goto err_no_rxchan;
}
pl022->dma_tx_channel = dma_request_channel(mask,
pl022->master_info->dma_filter,
pl022->master_info->dma_tx_param);
if (!pl022->dma_tx_channel) {
dev_dbg(&pl022->adev->dev, "no TX DMA channel!\n");
goto err_no_txchan;
}
pl022->dummypage = kmalloc(PAGE_SIZE, GFP_KERNEL);
if (!pl022->dummypage) {
dev_dbg(&pl022->adev->dev, "no DMA dummypage!\n");
goto err_no_dummypage;
}
dev_info(&pl022->adev->dev, "setup for DMA on RX %s, TX %s\n",
dma_chan_name(pl022->dma_rx_channel),
dma_chan_name(pl022->dma_tx_channel));
return 0;
err_no_dummypage:
dma_release_channel(pl022->dma_tx_channel);
err_no_txchan:
dma_release_channel(pl022->dma_rx_channel);
pl022->dma_rx_channel = NULL;
err_no_rxchan:
dev_err(&pl022->adev->dev,
"Failed to work in dma mode, work without dma!\n");
return -ENODEV;
}
static void terminate_dma(struct pl022 *pl022)
{
struct dma_chan *rxchan = pl022->dma_rx_channel;
struct dma_chan *txchan = pl022->dma_tx_channel;
dmaengine_terminate_all(rxchan);
dmaengine_terminate_all(txchan);
unmap_free_dma_scatter(pl022);
pl022->dma_running = false;
}
static void pl022_dma_remove(struct pl022 *pl022)
{
if (pl022->dma_running)
terminate_dma(pl022);
if (pl022->dma_tx_channel)
dma_release_channel(pl022->dma_tx_channel);
if (pl022->dma_rx_channel)
dma_release_channel(pl022->dma_rx_channel);
kfree(pl022->dummypage);
}
#else
static inline int configure_dma(struct pl022 *pl022)
{
return -ENODEV;
}
static inline int pl022_dma_probe(struct pl022 *pl022)
{
return 0;
}
static inline void pl022_dma_remove(struct pl022 *pl022)
{
}
#endif
/**
* pl022_interrupt_handler - Interrupt handler for SSP controller
*
* This function handles interrupts generated for an interrupt based transfer.
* If a receive overrun (ROR) interrupt is there then we disable SSP, flag the
* current message's state as STATE_ERROR and schedule the tasklet
* pump_transfers which will do the postprocessing of the current message by
* calling giveback(). Otherwise it reads data from RX FIFO till there is no
* more data, and writes data in TX FIFO till it is not full. If we complete
* the transfer we move to the next transfer and schedule the tasklet.
*/
static irqreturn_t pl022_interrupt_handler(int irq, void *dev_id)
{
struct pl022 *pl022 = dev_id;
struct spi_message *msg = pl022->cur_msg;
u16 irq_status = 0;
u16 flag = 0;
if (unlikely(!msg)) {
dev_err(&pl022->adev->dev,
"bad message state in interrupt handler");
/* Never fail */
return IRQ_HANDLED;
}
/* Read the Interrupt Status Register */
irq_status = readw(SSP_MIS(pl022->virtbase));
if (unlikely(!irq_status))
return IRQ_NONE;
/*
* This handles the FIFO interrupts, the timeout
* interrupts are flatly ignored, they cannot be
* trusted.
*/
if (unlikely(irq_status & SSP_MIS_MASK_RORMIS)) {
/*
* Overrun interrupt - bail out since our Data has been
* corrupted
*/
dev_err(&pl022->adev->dev, "FIFO overrun\n");
if (readw(SSP_SR(pl022->virtbase)) & SSP_SR_MASK_RFF)
dev_err(&pl022->adev->dev,
"RXFIFO is full\n");
if (readw(SSP_SR(pl022->virtbase)) & SSP_SR_MASK_TNF)
dev_err(&pl022->adev->dev,
"TXFIFO is full\n");
/*
* Disable and clear interrupts, disable SSP,
* mark message with bad status so it can be
* retried.
*/
writew(DISABLE_ALL_INTERRUPTS,
SSP_IMSC(pl022->virtbase));
writew(CLEAR_ALL_INTERRUPTS, SSP_ICR(pl022->virtbase));
writew((readw(SSP_CR1(pl022->virtbase)) &
(~SSP_CR1_MASK_SSE)), SSP_CR1(pl022->virtbase));
msg->state = STATE_ERROR;
/* Schedule message queue handler */
tasklet_schedule(&pl022->pump_transfers);
return IRQ_HANDLED;
}
readwriter(pl022);
if ((pl022->tx == pl022->tx_end) && (flag == 0)) {
flag = 1;
/* Disable Transmit interrupt, enable receive interrupt */
writew((readw(SSP_IMSC(pl022->virtbase)) &
~SSP_IMSC_MASK_TXIM) | SSP_IMSC_MASK_RXIM,
SSP_IMSC(pl022->virtbase));
}
/*
* Since all transactions must write as much as shall be read,
* we can conclude the entire transaction once RX is complete.
* At this point, all TX will always be finished.
*/
if (pl022->rx >= pl022->rx_end) {
writew(DISABLE_ALL_INTERRUPTS,
SSP_IMSC(pl022->virtbase));
writew(CLEAR_ALL_INTERRUPTS, SSP_ICR(pl022->virtbase));
if (unlikely(pl022->rx > pl022->rx_end)) {
dev_warn(&pl022->adev->dev, "read %u surplus "
"bytes (did you request an odd "
"number of bytes on a 16bit bus?)\n",
(u32) (pl022->rx - pl022->rx_end));
}
/* Update total bytes transferred */
msg->actual_length += pl022->cur_transfer->len;
if (pl022->cur_transfer->cs_change)
pl022->cur_chip->
cs_control(SSP_CHIP_DESELECT);
/* Move to next transfer */
msg->state = next_transfer(pl022);
tasklet_schedule(&pl022->pump_transfers);
return IRQ_HANDLED;
}
return IRQ_HANDLED;
}
/**
* This sets up the pointers to memory for the next message to
* send out on the SPI bus.
*/
static int set_up_next_transfer(struct pl022 *pl022,
struct spi_transfer *transfer)
{
int residue;
/* Sanity check the message for this bus width */
residue = pl022->cur_transfer->len % pl022->cur_chip->n_bytes;
if (unlikely(residue != 0)) {
dev_err(&pl022->adev->dev,
"message of %u bytes to transmit but the current "
"chip bus has a data width of %u bytes!\n",
pl022->cur_transfer->len,
pl022->cur_chip->n_bytes);
dev_err(&pl022->adev->dev, "skipping this message\n");
return -EIO;
}
pl022->tx = (void *)transfer->tx_buf;
pl022->tx_end = pl022->tx + pl022->cur_transfer->len;
pl022->rx = (void *)transfer->rx_buf;
pl022->rx_end = pl022->rx + pl022->cur_transfer->len;
pl022->write =
pl022->tx ? pl022->cur_chip->write : WRITING_NULL;
pl022->read = pl022->rx ? pl022->cur_chip->read : READING_NULL;
return 0;
}
/**
* pump_transfers - Tasklet function which schedules next transfer
* when running in interrupt or DMA transfer mode.
* @data: SSP driver private data structure
*
*/
static void pump_transfers(unsigned long data)
{
struct pl022 *pl022 = (struct pl022 *) data;
struct spi_message *message = NULL;
struct spi_transfer *transfer = NULL;
struct spi_transfer *previous = NULL;
/* Get current state information */
message = pl022->cur_msg;
transfer = pl022->cur_transfer;
/* Handle for abort */
if (message->state == STATE_ERROR) {
message->status = -EIO;
giveback(pl022);
return;
}
/* Handle end of message */
if (message->state == STATE_DONE) {
message->status = 0;
giveback(pl022);
return;
}
/* Delay if requested at end of transfer before CS change */
if (message->state == STATE_RUNNING) {
previous = list_entry(transfer->transfer_list.prev,
struct spi_transfer,
transfer_list);
if (previous->delay_usecs)
/*
* FIXME: This runs in interrupt context.
* Is this really smart?
*/
udelay(previous->delay_usecs);
/* Reselect chip select only if cs_change was requested */
if (previous->cs_change)
pl022->cur_chip->cs_control(SSP_CHIP_SELECT);
} else {
/* STATE_START */
message->state = STATE_RUNNING;
}
if (set_up_next_transfer(pl022, transfer)) {
message->state = STATE_ERROR;
message->status = -EIO;
giveback(pl022);
return;
}
/* Flush the FIFOs and let's go! */
flush(pl022);
if (pl022->cur_chip->enable_dma) {
if (configure_dma(pl022)) {
dev_dbg(&pl022->adev->dev,
"configuration of DMA failed, fall back to interrupt mode\n");
goto err_config_dma;
}
return;
}
err_config_dma:
/* enable all interrupts except RX */
writew(ENABLE_ALL_INTERRUPTS & ~SSP_IMSC_MASK_RXIM, SSP_IMSC(pl022->virtbase));
}
static void do_interrupt_dma_transfer(struct pl022 *pl022)
{
/*
* Default is to enable all interrupts except RX -
* this will be enabled once TX is complete
*/
u32 irqflags = ENABLE_ALL_INTERRUPTS & ~SSP_IMSC_MASK_RXIM;
/* Enable target chip, if not already active */
if (!pl022->next_msg_cs_active)
pl022->cur_chip->cs_control(SSP_CHIP_SELECT);
if (set_up_next_transfer(pl022, pl022->cur_transfer)) {
/* Error path */
pl022->cur_msg->state = STATE_ERROR;
pl022->cur_msg->status = -EIO;
giveback(pl022);
return;
}
/* If we're using DMA, set up DMA here */
if (pl022->cur_chip->enable_dma) {
/* Configure DMA transfer */
if (configure_dma(pl022)) {
dev_dbg(&pl022->adev->dev,
"configuration of DMA failed, fall back to interrupt mode\n");
goto err_config_dma;
}
/* Disable interrupts in DMA mode, IRQ from DMA controller */
irqflags = DISABLE_ALL_INTERRUPTS;
}
err_config_dma:
/* Enable SSP, turn on interrupts */
writew((readw(SSP_CR1(pl022->virtbase)) | SSP_CR1_MASK_SSE),
SSP_CR1(pl022->virtbase));
writew(irqflags, SSP_IMSC(pl022->virtbase));
}
static void do_polling_transfer(struct pl022 *pl022)
{
struct spi_message *message = NULL;
struct spi_transfer *transfer = NULL;
struct spi_transfer *previous = NULL;
struct chip_data *chip;
unsigned long time, timeout;
chip = pl022->cur_chip;
message = pl022->cur_msg;
while (message->state != STATE_DONE) {
/* Handle for abort */
if (message->state == STATE_ERROR)
break;
transfer = pl022->cur_transfer;
/* Delay if requested at end of transfer */
if (message->state == STATE_RUNNING) {
previous =
list_entry(transfer->transfer_list.prev,
struct spi_transfer, transfer_list);
if (previous->delay_usecs)
udelay(previous->delay_usecs);
if (previous->cs_change)
pl022->cur_chip->cs_control(SSP_CHIP_SELECT);
} else {
/* STATE_START */
message->state = STATE_RUNNING;
if (!pl022->next_msg_cs_active)
pl022->cur_chip->cs_control(SSP_CHIP_SELECT);
}
/* Configuration Changing Per Transfer */
if (set_up_next_transfer(pl022, transfer)) {
/* Error path */
message->state = STATE_ERROR;
break;
}
/* Flush FIFOs and enable SSP */
flush(pl022);
writew((readw(SSP_CR1(pl022->virtbase)) | SSP_CR1_MASK_SSE),
SSP_CR1(pl022->virtbase));
dev_dbg(&pl022->adev->dev, "polling transfer ongoing ...\n");
timeout = jiffies + msecs_to_jiffies(SPI_POLLING_TIMEOUT);
while (pl022->tx < pl022->tx_end || pl022->rx < pl022->rx_end) {
time = jiffies;
readwriter(pl022);
if (time_after(time, timeout)) {
dev_warn(&pl022->adev->dev,
"%s: timeout!\n", __func__);
message->state = STATE_ERROR;
goto out;
}
cpu_relax();
}
/* Update total byte transferred */
message->actual_length += pl022->cur_transfer->len;
if (pl022->cur_transfer->cs_change)
pl022->cur_chip->cs_control(SSP_CHIP_DESELECT);
/* Move to next transfer */
message->state = next_transfer(pl022);
}
out:
/* Handle end of message */
if (message->state == STATE_DONE)
message->status = 0;
else
message->status = -EIO;
giveback(pl022);
return;
}
static int pl022_transfer_one_message(struct spi_master *master,
struct spi_message *msg)
{
struct pl022 *pl022 = spi_master_get_devdata(master);
/* Initial message state */
pl022->cur_msg = msg;
msg->state = STATE_START;
pl022->cur_transfer = list_entry(msg->transfers.next,
struct spi_transfer, transfer_list);
/* Setup the SPI using the per chip configuration */
pl022->cur_chip = spi_get_ctldata(msg->spi);
restore_state(pl022);
flush(pl022);
if (pl022->cur_chip->xfer_type == POLLING_TRANSFER)
do_polling_transfer(pl022);
else
do_interrupt_dma_transfer(pl022);
return 0;
}
static int pl022_prepare_transfer_hardware(struct spi_master *master)
{
struct pl022 *pl022 = spi_master_get_devdata(master);
/*
* Just make sure we have all we need to run the transfer by syncing
* with the runtime PM framework.
*/
pm_runtime_get_sync(&pl022->adev->dev);
return 0;
}
static int pl022_unprepare_transfer_hardware(struct spi_master *master)
{
struct pl022 *pl022 = spi_master_get_devdata(master);
/* nothing more to do - disable spi/ssp and power off */
writew((readw(SSP_CR1(pl022->virtbase)) &
(~SSP_CR1_MASK_SSE)), SSP_CR1(pl022->virtbase));
if (pl022->master_info->autosuspend_delay > 0) {
pm_runtime_mark_last_busy(&pl022->adev->dev);
pm_runtime_put_autosuspend(&pl022->adev->dev);
} else {
pm_runtime_put(&pl022->adev->dev);
}
return 0;
}
static int verify_controller_parameters(struct pl022 *pl022,
struct pl022_config_chip const *chip_info)
{
if ((chip_info->iface < SSP_INTERFACE_MOTOROLA_SPI)
|| (chip_info->iface > SSP_INTERFACE_UNIDIRECTIONAL)) {
dev_err(&pl022->adev->dev,
"interface is configured incorrectly\n");
return -EINVAL;
}
if ((chip_info->iface == SSP_INTERFACE_UNIDIRECTIONAL) &&
(!pl022->vendor->unidir)) {
dev_err(&pl022->adev->dev,
"unidirectional mode not supported in this "
"hardware version\n");
return -EINVAL;
}
if ((chip_info->hierarchy != SSP_MASTER)
&& (chip_info->hierarchy != SSP_SLAVE)) {
dev_err(&pl022->adev->dev,
"hierarchy is configured incorrectly\n");
return -EINVAL;
}
if ((chip_info->com_mode != INTERRUPT_TRANSFER)
&& (chip_info->com_mode != DMA_TRANSFER)
&& (chip_info->com_mode != POLLING_TRANSFER)) {
dev_err(&pl022->adev->dev,
"Communication mode is configured incorrectly\n");
return -EINVAL;
}
switch (chip_info->rx_lev_trig) {
case SSP_RX_1_OR_MORE_ELEM:
case SSP_RX_4_OR_MORE_ELEM:
case SSP_RX_8_OR_MORE_ELEM:
/* These are always OK, all variants can handle this */
break;
case SSP_RX_16_OR_MORE_ELEM:
if (pl022->vendor->fifodepth < 16) {
dev_err(&pl022->adev->dev,
"RX FIFO Trigger Level is configured incorrectly\n");
return -EINVAL;
}
break;
case SSP_RX_32_OR_MORE_ELEM:
if (pl022->vendor->fifodepth < 32) {
dev_err(&pl022->adev->dev,
"RX FIFO Trigger Level is configured incorrectly\n");
return -EINVAL;
}
break;
default:
dev_err(&pl022->adev->dev,
"RX FIFO Trigger Level is configured incorrectly\n");
return -EINVAL;
break;
}
switch (chip_info->tx_lev_trig) {
case SSP_TX_1_OR_MORE_EMPTY_LOC:
case SSP_TX_4_OR_MORE_EMPTY_LOC:
case SSP_TX_8_OR_MORE_EMPTY_LOC:
/* These are always OK, all variants can handle this */
break;
case SSP_TX_16_OR_MORE_EMPTY_LOC:
if (pl022->vendor->fifodepth < 16) {
dev_err(&pl022->adev->dev,
"TX FIFO Trigger Level is configured incorrectly\n");
return -EINVAL;
}
break;
case SSP_TX_32_OR_MORE_EMPTY_LOC:
if (pl022->vendor->fifodepth < 32) {
dev_err(&pl022->adev->dev,
"TX FIFO Trigger Level is configured incorrectly\n");
return -EINVAL;
}
break;
default:
dev_err(&pl022->adev->dev,
"TX FIFO Trigger Level is configured incorrectly\n");
return -EINVAL;
break;
}
if (chip_info->iface == SSP_INTERFACE_NATIONAL_MICROWIRE) {
if ((chip_info->ctrl_len < SSP_BITS_4)
|| (chip_info->ctrl_len > SSP_BITS_32)) {
dev_err(&pl022->adev->dev,
"CTRL LEN is configured incorrectly\n");
return -EINVAL;
}
if ((chip_info->wait_state != SSP_MWIRE_WAIT_ZERO)
&& (chip_info->wait_state != SSP_MWIRE_WAIT_ONE)) {
dev_err(&pl022->adev->dev,
"Wait State is configured incorrectly\n");
return -EINVAL;
}
/* Half duplex is only available in the ST Micro version */
if (pl022->vendor->extended_cr) {
if ((chip_info->duplex !=
SSP_MICROWIRE_CHANNEL_FULL_DUPLEX)
&& (chip_info->duplex !=
SSP_MICROWIRE_CHANNEL_HALF_DUPLEX)) {
dev_err(&pl022->adev->dev,
"Microwire duplex mode is configured incorrectly\n");
return -EINVAL;
}
} else {
if (chip_info->duplex != SSP_MICROWIRE_CHANNEL_FULL_DUPLEX)
dev_err(&pl022->adev->dev,
"Microwire half duplex mode requested,"
" but this is only available in the"
" ST version of PL022\n");
return -EINVAL;
}
}
return 0;
}
static inline u32 spi_rate(u32 rate, u16 cpsdvsr, u16 scr)
{
return rate / (cpsdvsr * (1 + scr));
}
static int calculate_effective_freq(struct pl022 *pl022, int freq, struct
ssp_clock_params * clk_freq)
{
/* Lets calculate the frequency parameters */
u16 cpsdvsr = CPSDVR_MIN, scr = SCR_MIN;
u32 rate, max_tclk, min_tclk, best_freq = 0, best_cpsdvsr = 0,
best_scr = 0, tmp, found = 0;
rate = clk_get_rate(pl022->clk);
/* cpsdvscr = 2 & scr 0 */
max_tclk = spi_rate(rate, CPSDVR_MIN, SCR_MIN);
/* cpsdvsr = 254 & scr = 255 */
min_tclk = spi_rate(rate, CPSDVR_MAX, SCR_MAX);
if (!((freq <= max_tclk) && (freq >= min_tclk))) {
dev_err(&pl022->adev->dev,
"controller data is incorrect: out of range frequency");
return -EINVAL;
}
/*
* best_freq will give closest possible available rate (<= requested
* freq) for all values of scr & cpsdvsr.
*/
while ((cpsdvsr <= CPSDVR_MAX) && !found) {
while (scr <= SCR_MAX) {
tmp = spi_rate(rate, cpsdvsr, scr);
if (tmp > freq)
scr++;
/*
* If found exact value, update and break.
* If found more closer value, update and continue.
*/
else if ((tmp == freq) || (tmp > best_freq)) {
best_freq = tmp;
best_cpsdvsr = cpsdvsr;
best_scr = scr;
if (tmp == freq)
break;
}
scr++;
}
cpsdvsr += 2;
scr = SCR_MIN;
}
clk_freq->cpsdvsr = (u8) (best_cpsdvsr & 0xFF);
clk_freq->scr = (u8) (best_scr & 0xFF);
dev_dbg(&pl022->adev->dev,
"SSP Target Frequency is: %u, Effective Frequency is %u\n",
freq, best_freq);
dev_dbg(&pl022->adev->dev, "SSP cpsdvsr = %d, scr = %d\n",
clk_freq->cpsdvsr, clk_freq->scr);
return 0;
}
/*
* A piece of default chip info unless the platform
* supplies it.
*/
static const struct pl022_config_chip pl022_default_chip_info = {
.com_mode = POLLING_TRANSFER,
.iface = SSP_INTERFACE_MOTOROLA_SPI,
.hierarchy = SSP_SLAVE,
.slave_tx_disable = DO_NOT_DRIVE_TX,
.rx_lev_trig = SSP_RX_1_OR_MORE_ELEM,
.tx_lev_trig = SSP_TX_1_OR_MORE_EMPTY_LOC,
.ctrl_len = SSP_BITS_8,
.wait_state = SSP_MWIRE_WAIT_ZERO,
.duplex = SSP_MICROWIRE_CHANNEL_FULL_DUPLEX,
.cs_control = null_cs_control,
};
/**
* pl022_setup - setup function registered to SPI master framework
* @spi: spi device which is requesting setup
*
* This function is registered to the SPI framework for this SPI master
* controller. If it is the first time when setup is called by this device,
* this function will initialize the runtime state for this chip and save
* the same in the device structure. Else it will update the runtime info
* with the updated chip info. Nothing is really being written to the
* controller hardware here, that is not done until the actual transfer
* commence.
*/
static int pl022_setup(struct spi_device *spi)
{
struct pl022_config_chip const *chip_info;
struct chip_data *chip;
struct ssp_clock_params clk_freq = { .cpsdvsr = 0, .scr = 0};
int status = 0;
struct pl022 *pl022 = spi_master_get_devdata(spi->master);
unsigned int bits = spi->bits_per_word;
u32 tmp;
if (!spi->max_speed_hz)
return -EINVAL;
/* Get controller_state if one is supplied */
chip = spi_get_ctldata(spi);
if (chip == NULL) {
chip = kzalloc(sizeof(struct chip_data), GFP_KERNEL);
if (!chip) {
dev_err(&spi->dev,
"cannot allocate controller state\n");
return -ENOMEM;
}
dev_dbg(&spi->dev,
"allocated memory for controller's runtime state\n");
}
/* Get controller data if one is supplied */
chip_info = spi->controller_data;
if (chip_info == NULL) {
chip_info = &pl022_default_chip_info;
/* spi_board_info.controller_data not is supplied */
dev_dbg(&spi->dev,
"using default controller_data settings\n");
} else
dev_dbg(&spi->dev,
"using user supplied controller_data settings\n");
/*
* We can override with custom divisors, else we use the board
* frequency setting
*/
if ((0 == chip_info->clk_freq.cpsdvsr)
&& (0 == chip_info->clk_freq.scr)) {
status = calculate_effective_freq(pl022,
spi->max_speed_hz,
&clk_freq);
if (status < 0)
goto err_config_params;
} else {
memcpy(&clk_freq, &chip_info->clk_freq, sizeof(clk_freq));
if ((clk_freq.cpsdvsr % 2) != 0)
clk_freq.cpsdvsr =
clk_freq.cpsdvsr - 1;
}
if ((clk_freq.cpsdvsr < CPSDVR_MIN)
|| (clk_freq.cpsdvsr > CPSDVR_MAX)) {
status = -EINVAL;
dev_err(&spi->dev,
"cpsdvsr is configured incorrectly\n");
goto err_config_params;
}
status = verify_controller_parameters(pl022, chip_info);
if (status) {
dev_err(&spi->dev, "controller data is incorrect");
goto err_config_params;
}
pl022->rx_lev_trig = chip_info->rx_lev_trig;
pl022->tx_lev_trig = chip_info->tx_lev_trig;
/* Now set controller state based on controller data */
chip->xfer_type = chip_info->com_mode;
if (!chip_info->cs_control) {
chip->cs_control = null_cs_control;
dev_warn(&spi->dev,
"chip select function is NULL for this chip\n");
} else
chip->cs_control = chip_info->cs_control;
if (bits <= 3) {
/* PL022 doesn't support less than 4-bits */
status = -ENOTSUPP;
goto err_config_params;
} else if (bits <= 8) {
dev_dbg(&spi->dev, "4 <= n <=8 bits per word\n");
chip->n_bytes = 1;
chip->read = READING_U8;
chip->write = WRITING_U8;
} else if (bits <= 16) {
dev_dbg(&spi->dev, "9 <= n <= 16 bits per word\n");
chip->n_bytes = 2;
chip->read = READING_U16;
chip->write = WRITING_U16;
} else {
if (pl022->vendor->max_bpw >= 32) {
dev_dbg(&spi->dev, "17 <= n <= 32 bits per word\n");
chip->n_bytes = 4;
chip->read = READING_U32;
chip->write = WRITING_U32;
} else {
dev_err(&spi->dev,
"illegal data size for this controller!\n");
dev_err(&spi->dev,
"a standard pl022 can only handle "
"1 <= n <= 16 bit words\n");
status = -ENOTSUPP;
goto err_config_params;
}
}
/* Now Initialize all register settings required for this chip */
chip->cr0 = 0;
chip->cr1 = 0;
chip->dmacr = 0;
chip->cpsr = 0;
if ((chip_info->com_mode == DMA_TRANSFER)
&& ((pl022->master_info)->enable_dma)) {
chip->enable_dma = true;
dev_dbg(&spi->dev, "DMA mode set in controller state\n");
SSP_WRITE_BITS(chip->dmacr, SSP_DMA_ENABLED,
SSP_DMACR_MASK_RXDMAE, 0);
SSP_WRITE_BITS(chip->dmacr, SSP_DMA_ENABLED,
SSP_DMACR_MASK_TXDMAE, 1);
} else {
chip->enable_dma = false;
dev_dbg(&spi->dev, "DMA mode NOT set in controller state\n");
SSP_WRITE_BITS(chip->dmacr, SSP_DMA_DISABLED,
SSP_DMACR_MASK_RXDMAE, 0);
SSP_WRITE_BITS(chip->dmacr, SSP_DMA_DISABLED,
SSP_DMACR_MASK_TXDMAE, 1);
}
chip->cpsr = clk_freq.cpsdvsr;
/* Special setup for the ST micro extended control registers */
if (pl022->vendor->extended_cr) {
u32 etx;
if (pl022->vendor->pl023) {
/* These bits are only in the PL023 */
SSP_WRITE_BITS(chip->cr1, chip_info->clkdelay,
SSP_CR1_MASK_FBCLKDEL_ST, 13);
} else {
/* These bits are in the PL022 but not PL023 */
SSP_WRITE_BITS(chip->cr0, chip_info->duplex,
SSP_CR0_MASK_HALFDUP_ST, 5);
SSP_WRITE_BITS(chip->cr0, chip_info->ctrl_len,
SSP_CR0_MASK_CSS_ST, 16);
SSP_WRITE_BITS(chip->cr0, chip_info->iface,
SSP_CR0_MASK_FRF_ST, 21);
SSP_WRITE_BITS(chip->cr1, chip_info->wait_state,
SSP_CR1_MASK_MWAIT_ST, 6);
}
SSP_WRITE_BITS(chip->cr0, bits - 1,
SSP_CR0_MASK_DSS_ST, 0);
if (spi->mode & SPI_LSB_FIRST) {
tmp = SSP_RX_LSB;
etx = SSP_TX_LSB;
} else {
tmp = SSP_RX_MSB;
etx = SSP_TX_MSB;
}
SSP_WRITE_BITS(chip->cr1, tmp, SSP_CR1_MASK_RENDN_ST, 4);
SSP_WRITE_BITS(chip->cr1, etx, SSP_CR1_MASK_TENDN_ST, 5);
SSP_WRITE_BITS(chip->cr1, chip_info->rx_lev_trig,
SSP_CR1_MASK_RXIFLSEL_ST, 7);
SSP_WRITE_BITS(chip->cr1, chip_info->tx_lev_trig,
SSP_CR1_MASK_TXIFLSEL_ST, 10);
} else {
SSP_WRITE_BITS(chip->cr0, bits - 1,
SSP_CR0_MASK_DSS, 0);
SSP_WRITE_BITS(chip->cr0, chip_info->iface,
SSP_CR0_MASK_FRF, 4);
}
/* Stuff that is common for all versions */
if (spi->mode & SPI_CPOL)
tmp = SSP_CLK_POL_IDLE_HIGH;
else
tmp = SSP_CLK_POL_IDLE_LOW;
SSP_WRITE_BITS(chip->cr0, tmp, SSP_CR0_MASK_SPO, 6);
if (spi->mode & SPI_CPHA)
tmp = SSP_CLK_SECOND_EDGE;
else
tmp = SSP_CLK_FIRST_EDGE;
SSP_WRITE_BITS(chip->cr0, tmp, SSP_CR0_MASK_SPH, 7);
SSP_WRITE_BITS(chip->cr0, clk_freq.scr, SSP_CR0_MASK_SCR, 8);
/* Loopback is available on all versions except PL023 */
if (pl022->vendor->loopback) {
if (spi->mode & SPI_LOOP)
tmp = LOOPBACK_ENABLED;
else
tmp = LOOPBACK_DISABLED;
SSP_WRITE_BITS(chip->cr1, tmp, SSP_CR1_MASK_LBM, 0);
}
SSP_WRITE_BITS(chip->cr1, SSP_DISABLED, SSP_CR1_MASK_SSE, 1);
SSP_WRITE_BITS(chip->cr1, chip_info->hierarchy, SSP_CR1_MASK_MS, 2);
SSP_WRITE_BITS(chip->cr1, chip_info->slave_tx_disable, SSP_CR1_MASK_SOD,
3);
/* Save controller_state */
spi_set_ctldata(spi, chip);
return status;
err_config_params:
spi_set_ctldata(spi, NULL);
kfree(chip);
return status;
}
/**
* pl022_cleanup - cleanup function registered to SPI master framework
* @spi: spi device which is requesting cleanup
*
* This function is registered to the SPI framework for this SPI master
* controller. It will free the runtime state of chip.
*/
static void pl022_cleanup(struct spi_device *spi)
{
struct chip_data *chip = spi_get_ctldata(spi);
spi_set_ctldata(spi, NULL);
kfree(chip);
}
static int __devinit
pl022_probe(struct amba_device *adev, const struct amba_id *id)
{
struct device *dev = &adev->dev;
struct pl022_ssp_controller *platform_info = adev->dev.platform_data;
struct spi_master *master;
struct pl022 *pl022 = NULL; /*Data for this driver */
int status = 0;
dev_info(&adev->dev,
"ARM PL022 driver, device ID: 0x%08x\n", adev->periphid);
if (platform_info == NULL) {
dev_err(&adev->dev, "probe - no platform data supplied\n");
status = -ENODEV;
goto err_no_pdata;
}
/* Allocate master with space for data */
master = spi_alloc_master(dev, sizeof(struct pl022));
if (master == NULL) {
dev_err(&adev->dev, "probe - cannot alloc SPI master\n");
status = -ENOMEM;
goto err_no_master;
}
pl022 = spi_master_get_devdata(master);
pl022->master = master;
pl022->master_info = platform_info;
pl022->adev = adev;
pl022->vendor = id->data;
/*
* Bus Number Which has been Assigned to this SSP controller
* on this board
*/
master->bus_num = platform_info->bus_id;
master->num_chipselect = platform_info->num_chipselect;
master->cleanup = pl022_cleanup;
master->setup = pl022_setup;
master->prepare_transfer_hardware = pl022_prepare_transfer_hardware;
master->transfer_one_message = pl022_transfer_one_message;
master->unprepare_transfer_hardware = pl022_unprepare_transfer_hardware;
master->rt = platform_info->rt;
/*
* Supports mode 0-3, loopback, and active low CS. Transfers are
* always MS bit first on the original pl022.
*/
master->mode_bits = SPI_CPOL | SPI_CPHA | SPI_CS_HIGH | SPI_LOOP;
if (pl022->vendor->extended_cr)
master->mode_bits |= SPI_LSB_FIRST;
dev_dbg(&adev->dev, "BUSNO: %d\n", master->bus_num);
status = amba_request_regions(adev, NULL);
if (status)
goto err_no_ioregion;
pl022->phybase = adev->res.start;
pl022->virtbase = ioremap(adev->res.start, resource_size(&adev->res));
if (pl022->virtbase == NULL) {
status = -ENOMEM;
goto err_no_ioremap;
}
printk(KERN_INFO "pl022: mapped registers from 0x%08x to %p\n",
adev->res.start, pl022->virtbase);
pl022->clk = clk_get(&adev->dev, NULL);
if (IS_ERR(pl022->clk)) {
status = PTR_ERR(pl022->clk);
dev_err(&adev->dev, "could not retrieve SSP/SPI bus clock\n");
goto err_no_clk;
}
status = clk_prepare(pl022->clk);
if (status) {
dev_err(&adev->dev, "could not prepare SSP/SPI bus clock\n");
goto err_clk_prep;
}
status = clk_enable(pl022->clk);
if (status) {
dev_err(&adev->dev, "could not enable SSP/SPI bus clock\n");
goto err_no_clk_en;
}
/* Initialize transfer pump */
tasklet_init(&pl022->pump_transfers, pump_transfers,
(unsigned long)pl022);
/* Disable SSP */
writew((readw(SSP_CR1(pl022->virtbase)) & (~SSP_CR1_MASK_SSE)),
SSP_CR1(pl022->virtbase));
load_ssp_default_config(pl022);
status = request_irq(adev->irq[0], pl022_interrupt_handler, 0, "pl022",
pl022);
if (status < 0) {
dev_err(&adev->dev, "probe - cannot get IRQ (%d)\n", status);
goto err_no_irq;
}
/* Get DMA channels */
if (platform_info->enable_dma) {
status = pl022_dma_probe(pl022);
if (status != 0)
platform_info->enable_dma = 0;
}
/* Register with the SPI framework */
amba_set_drvdata(adev, pl022);
status = spi_register_master(master);
if (status != 0) {
dev_err(&adev->dev,
"probe - problem registering spi master\n");
goto err_spi_register;
}
dev_dbg(dev, "probe succeeded\n");
/* let runtime pm put suspend */
if (platform_info->autosuspend_delay > 0) {
dev_info(&adev->dev,
"will use autosuspend for runtime pm, delay %dms\n",
platform_info->autosuspend_delay);
pm_runtime_set_autosuspend_delay(dev,
platform_info->autosuspend_delay);
pm_runtime_use_autosuspend(dev);
pm_runtime_put_autosuspend(dev);
} else {
pm_runtime_put(dev);
}
return 0;
err_spi_register:
if (platform_info->enable_dma)
pl022_dma_remove(pl022);
free_irq(adev->irq[0], pl022);
err_no_irq:
clk_disable(pl022->clk);
err_no_clk_en:
clk_unprepare(pl022->clk);
err_clk_prep:
clk_put(pl022->clk);
err_no_clk:
iounmap(pl022->virtbase);
err_no_ioremap:
amba_release_regions(adev);
err_no_ioregion:
spi_master_put(master);
err_no_master:
err_no_pdata:
return status;
}
static int __devexit
pl022_remove(struct amba_device *adev)
{
struct pl022 *pl022 = amba_get_drvdata(adev);
if (!pl022)
return 0;
/*
* undo pm_runtime_put() in probe. I assume that we're not
* accessing the primecell here.
*/
pm_runtime_get_noresume(&adev->dev);
load_ssp_default_config(pl022);
if (pl022->master_info->enable_dma)
pl022_dma_remove(pl022);
free_irq(adev->irq[0], pl022);
clk_disable(pl022->clk);
clk_unprepare(pl022->clk);
clk_put(pl022->clk);
iounmap(pl022->virtbase);
amba_release_regions(adev);
tasklet_disable(&pl022->pump_transfers);
spi_unregister_master(pl022->master);
spi_master_put(pl022->master);
amba_set_drvdata(adev, NULL);
return 0;
}
#ifdef CONFIG_SUSPEND
static int pl022_suspend(struct device *dev)
{
struct pl022 *pl022 = dev_get_drvdata(dev);
int ret;
ret = spi_master_suspend(pl022->master);
if (ret) {
dev_warn(dev, "cannot suspend master\n");
return ret;
}
dev_dbg(dev, "suspended\n");
return 0;
}
static int pl022_resume(struct device *dev)
{
struct pl022 *pl022 = dev_get_drvdata(dev);
int ret;
/* Start the queue running */
ret = spi_master_resume(pl022->master);
if (ret)
dev_err(dev, "problem starting queue (%d)\n", ret);
else
dev_dbg(dev, "resumed\n");
return ret;
}
#endif /* CONFIG_PM */
#ifdef CONFIG_PM_RUNTIME
static int pl022_runtime_suspend(struct device *dev)
{
struct pl022 *pl022 = dev_get_drvdata(dev);
clk_disable(pl022->clk);
amba_vcore_disable(pl022->adev);
return 0;
}
static int pl022_runtime_resume(struct device *dev)
{
struct pl022 *pl022 = dev_get_drvdata(dev);
amba_vcore_enable(pl022->adev);
clk_enable(pl022->clk);
return 0;
}
#endif
static const struct dev_pm_ops pl022_dev_pm_ops = {
SET_SYSTEM_SLEEP_PM_OPS(pl022_suspend, pl022_resume)
SET_RUNTIME_PM_OPS(pl022_runtime_suspend, pl022_runtime_resume, NULL)
};
static struct vendor_data vendor_arm = {
.fifodepth = 8,
.max_bpw = 16,
.unidir = false,
.extended_cr = false,
.pl023 = false,
.loopback = true,
};
static struct vendor_data vendor_st = {
.fifodepth = 32,
.max_bpw = 32,
.unidir = false,
.extended_cr = true,
.pl023 = false,
.loopback = true,
};
static struct vendor_data vendor_st_pl023 = {
.fifodepth = 32,
.max_bpw = 32,
.unidir = false,
.extended_cr = true,
.pl023 = true,
.loopback = false,
};
static struct vendor_data vendor_db5500_pl023 = {
.fifodepth = 32,
.max_bpw = 32,
.unidir = false,
.extended_cr = true,
.pl023 = true,
.loopback = true,
};
static struct amba_id pl022_ids[] = {
{
/*
* ARM PL022 variant, this has a 16bit wide
* and 8 locations deep TX/RX FIFO
*/
.id = 0x00041022,
.mask = 0x000fffff,
.data = &vendor_arm,
},
{
/*
* ST Micro derivative, this has 32bit wide
* and 32 locations deep TX/RX FIFO
*/
.id = 0x01080022,
.mask = 0xffffffff,
.data = &vendor_st,
},
{
/*
* ST-Ericsson derivative "PL023" (this is not
* an official ARM number), this is a PL022 SSP block
* stripped to SPI mode only, it has 32bit wide
* and 32 locations deep TX/RX FIFO but no extended
* CR0/CR1 register
*/
.id = 0x00080023,
.mask = 0xffffffff,
.data = &vendor_st_pl023,
},
{
.id = 0x10080023,
.mask = 0xffffffff,
.data = &vendor_db5500_pl023,
},
{ 0, 0 },
};
MODULE_DEVICE_TABLE(amba, pl022_ids);
static struct amba_driver pl022_driver = {
.drv = {
.name = "ssp-pl022",
.pm = &pl022_dev_pm_ops,
},
.id_table = pl022_ids,
.probe = pl022_probe,
.remove = __devexit_p(pl022_remove),
};
static int __init pl022_init(void)
{
return amba_driver_register(&pl022_driver);
}
subsys_initcall(pl022_init);
static void __exit pl022_exit(void)
{
amba_driver_unregister(&pl022_driver);
}
module_exit(pl022_exit);
MODULE_AUTHOR("Linus Walleij <linus.walleij@stericsson.com>");
MODULE_DESCRIPTION("PL022 SSP Controller Driver");
MODULE_LICENSE("GPL");
|
/*
* Copyright (c) 2013, 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.
*/
/**
* A JVM with JDP on should send multicast JDP packets regularly.
* Look at JdpOnTestCase.java and JdpOffTestCase.java
*/
import sun.management.jdp.JdpJmxPacket;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.DatagramPacket;
import java.net.MulticastSocket;
import java.net.SocketTimeoutException;
import java.util.Arrays;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
public abstract class JdpTestCase {
final Logger log = Logger.getLogger("sun.management.jdp");
final int MAGIC = 0xC0FFEE42; // Jdp magic number.
private static final int BUFFER_LENGTH = 64 * 1024; // max UDP size, except for IPv6 jumbograms.
private final int TIME_OUT_FACTOR = 10; // Socket times out after 10 times the jdp pause.
protected int timeOut;
private long startTime;
protected ClientConnection connection;
public JdpTestCase(ClientConnection connection) {
this.connection = connection;
JdpTestUtil.enableConsoleLogging(log, Level.ALL);
}
public void run() throws Exception {
log.fine("Test started.");
log.fine("Listening for multicast packets at " + connection.address.getHostAddress()
+ ":" + String.valueOf(connection.port));
log.fine(initialLogMessage());
log.fine("Pause in between packets is: " + connection.pauseInSeconds + " seconds.");
startTime = System.currentTimeMillis();
timeOut = connection.pauseInSeconds * TIME_OUT_FACTOR;
log.fine("Timeout set to " + String.valueOf(timeOut) + " seconds.");
MulticastSocket socket = connection.connectWithTimeout(timeOut * 1000);
byte[] buffer = new byte[BUFFER_LENGTH];
DatagramPacket datagram = new DatagramPacket(buffer, buffer.length);
do {
try {
socket.receive(datagram);
onReceived(extractUDPpayload(datagram));
} catch (SocketTimeoutException e) {
onSocketTimeOut(e);
}
if (hasTestLivedLongEnough()) {
shutdown();
}
} while (shouldContinue());
log.fine("Test ended successfully.");
}
/**
* Subclasses: JdpOnTestCase and JdpOffTestCase have different messages.
*/
protected abstract String initialLogMessage();
/**
* Executed when the socket receives a UDP packet.
*/
private void onReceived(byte[] packet) throws Exception {
if (isJDP(packet)) {
Map<String, String> payload = checkStructure(packet);
jdpPacketReceived(payload);
} else {
log.fine("Non JDP packet received, ignoring it.");
}
}
/**
* Determine whether the test should end.
*
* @return
*/
abstract protected boolean shouldContinue();
/**
* This method is executed when the socket has not received any packet for timeOut seconds.
*/
abstract protected void onSocketTimeOut(SocketTimeoutException e) throws Exception;
/**
* This method is executed after a correct Jdp packet has been received.
*
* @param payload A dictionary containing the data if the received Jdp packet.
*/
private void jdpPacketReceived(Map<String, String> payload) throws Exception {
final String instanceName = payload.get("INSTANCE_NAME");
if (instanceName != null && instanceName.equals(connection.instanceName)) {
packetFromThisVMReceived(payload);
} else {
packetFromOtherVMReceived(payload);
}
}
/**
* This method is executed after a correct Jdp packet, coming from this VM has been received.
*
* @param payload A dictionary containing the data if the received Jdp packet.
*/
protected abstract void packetFromThisVMReceived(Map<String, String> payload) throws Exception;
/**
* This method is executed after a correct Jdp packet, coming from another VM has been received.
*
* @param payload A dictionary containing the data if the received Jdp packet.
*/
protected void packetFromOtherVMReceived(Map<String, String> payload) {
final String jdpName = payload.get("INSTANCE_NAME");
log.fine("Ignoring JDP packet sent by other VM, jdp.name=" + jdpName);
}
/**
* The test should stop if it has been 12 times the jdp.pause.
* jdp.pause is how many seconds in between packets.
* <p/>
* This timeout (12 times)is slightly longer than the socket timeout (10 times) on purpose.
* In the off test case, the socket should time out first.
*
* @return
*/
protected boolean hasTestLivedLongEnough() {
long now = System.currentTimeMillis();
boolean haslivedLongEnough = (now - startTime) > (timeOut * 1.2 * 1000);
return haslivedLongEnough;
}
/**
* This exit condition arises when we receive UDP packets but they are not valid Jdp.
*/
protected void shutdown() throws Exception {
log.severe("Shutting down the test.");
throw new Exception("Not enough JDP packets received before timeout!");
}
/**
* Assert that this Jdp packet contains the required two keys.
* <p/>
* We expect zero packet corruption and thus fail on the first corrupted packet.
* This might need revision.
*/
protected Map<String, String> checkStructure(byte[] packet) throws UnsupportedEncodingException {
Map<String, String> payload = JdpTestUtil.readPayload(packet);
assertTrue(payload.size() >= 2, "JDP should have minimun 2 entries.");
assertTrue(payload.get(JdpJmxPacket.UUID_KEY).length() > 0);
assertTrue(payload.get(JdpJmxPacket.JMX_SERVICE_URL_KEY).length() > 0);
return payload;
}
/**
* Check if packet has correct JDP magic number.
*
* @param packet
* @return
* @throws IOException
*/
private boolean isJDP(byte[] packet) throws IOException {
int magic = JdpTestUtil.decode4ByteInt(packet, 0);
return (magic == MAGIC);
}
private byte[] extractUDPpayload(DatagramPacket datagram) {
byte[] data = Arrays.copyOf(datagram.getData(), datagram.getLength());
return data;
}
/**
* Hack until I find a way to use TestNG's assertions.
*/
private void assertTrue(boolean assertion, String message) {
if (assertion == false) {
log.severe(message);
assert (false);
}
}
private void assertTrue(boolean assertion) {
assertTrue(assertion, "");
}
}
|
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Validate
* @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: LessThan.php 8064 2008-02-16 10:58:39Z thomas $
*/
/**
* @see Zend_Validate_Abstract
*/
require_once 'external/Zend/Validate/Abstract.php';
/**
* @category Zend
* @package Zend_Validate
* @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Validate_LessThan extends Zend_Validate_Abstract {
const NOT_LESS = 'notLessThan';
/**
* @var array
*/
protected $_messageTemplates = array(self::NOT_LESS => "'%value%' is not less than '%max%'");
/**
* @var array
*/
protected $_messageVariables = array('max' => '_max');
/**
* Maximum value
*
* @var mixed
*/
protected $_max;
/**
* Sets validator options
*
* @param mixed $max
* @return void
*/
public function __construct($max) {
$this->setMax($max);
}
/**
* Returns the max option
*
* @return mixed
*/
public function getMax() {
return $this->_max;
}
/**
* Sets the max option
*
* @param mixed $max
* @return Zend_Validate_LessThan Provides a fluent interface
*/
public function setMax($max) {
$this->_max = $max;
return $this;
}
/**
* Defined by Zend_Validate_Interface
*
* Returns true if and only if $value is less than max option
*
* @param mixed $value
* @return boolean
*/
public function isValid($value) {
$this->_setValue($value);
if ($this->_max <= $value) {
$this->_error();
return false;
}
return true;
}
}
|
#ifndef __EXTDISP_DRV_PLATFORM_H__
#define __EXTDISP_DRV_PLATFORM_H__
#include <linux/dma-mapping.h>
#include <mach/mt_typedefs.h>
#include <mach/mt_gpio.h>
#include <mach/m4u.h>
//#include <mach/mt6585_pwm.h>
#include <mach/mt_reg_base.h>
#include <mach/mt_clkmgr.h>
#include <mach/mt_irq.h>
//#include <mach/boot.h>
#include <board-custom.h>
#include <linux/disp_assert_layer.h>
#include "ddp_hal.h"
#if 0
#include "ddp_drv.h"
#include "ddp_path.h"
#include "ddp_rdma.h"
#include <mach/sync_write.h>
#ifdef OUTREG32
#undef OUTREG32
#define OUTREG32(x, y) mt65xx_reg_sync_writel(y, x)
#endif
#ifndef OUTREGBIT
#define OUTREGBIT(TYPE,REG,bit,value) \
do { \
TYPE r = *((TYPE*)&INREG32(®)); \
r.bit = value; \
OUTREG32(®, AS_UINT32(&r)); \
} while (0)
#endif
#endif
#define MAX_SESSION_COUNT 5
//#define MTK_LCD_HW_3D_SUPPORT
#define ALIGN_TO(x, n) \
(((x) + ((n) - 1)) & ~((n) - 1))
#define MTK_EXT_DISP_ALIGNMENT 32
#define MTK_EXT_DISP_START_DSI_ISR
#define MTK_EXT_DISP_OVERLAY_SUPPORT
#define MTK_EXT_DISP_SYNC_SUPPORT
#define MTK_EXT_DISP_ION_SUPPORT
#define MTK_AUDIO_MULTI_CHANNEL_SUPPORT
///#define EXTD_DBG_USE_INNER_BUF
#define HW_OVERLAY_COUNT (4)
#endif //__DISP_DRV_PLATFORM_H__
|
<?php
$base = array(
0x00 => '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
0x10 => '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
0x20 => '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
0x30 => '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
0x40 => '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', NULL,
0x50 => NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
0x60 => '', '', '', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
0x70 => NULL, NULL, NULL, NULL, '\'', ',', NULL, NULL, NULL, NULL, '', NULL, NULL, NULL, '?', NULL,
0x80 => NULL, NULL, NULL, NULL, '', '', 'A', ';', 'E', 'I', 'I', NULL, 'O', NULL, 'U', 'O',
0x90 => 'I', 'A', 'V', 'G', 'D', 'E', 'Z', 'I', 'Th', 'I', 'K', 'L', 'M', 'N', 'X', 'O',
0xA0 => 'P', 'R', NULL, 'S', 'T', 'Y', 'F', 'H', 'Ps', 'O', 'I', 'Y', 'a', 'e', 'i', 'i',
0xB0 => 'y', 'a', 'v', 'g', 'd', 'e', 'z', 'i', 'th', 'i', 'k', 'l', 'm', 'n', 'x', 'o',
0xC0 => 'p', 'r', 's', 's', 't', 'y', 'f', 'h', 'ps', 'o', 'i', 'y', 'o', 'y', 'o', NULL,
0xD0 => 'b', 'th', 'U', 'U', 'U', 'ph', 'p', '&', NULL, NULL, 'St', 'st', 'W', 'w', 'Q', 'q',
0xE0 => 'Sp', 'sp', 'Sh', 'sh', 'F', 'f', 'Kh', 'kh', 'H', 'h', 'G', 'g', 'CH', 'ch', 'Ti', 'ti',
0xF0 => 'k', 'r', 'c', 'j', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
);
|
/* Shared general utility routines for GDB, the GNU debugger.
Copyright (C) 1986-2015 Free Software Foundation, Inc.
This file is part of GDB.
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/>. */
#ifndef COMMON_UTILS_H
#define COMMON_UTILS_H
/* If possible, define FUNCTION_NAME, a macro containing the name of
the function being defined. Since this macro may not always be
defined, all uses must be protected by appropriate macro definition
checks (Eg: "#ifdef FUNCTION_NAME").
Version 2.4 and later of GCC define a magical variable `__PRETTY_FUNCTION__'
which contains the name of the function currently being defined.
This is broken in G++ before version 2.6.
C9x has a similar variable called __func__, but prefer the GCC one since
it demangles C++ function names. */
#if (GCC_VERSION >= 2004)
#define FUNCTION_NAME __PRETTY_FUNCTION__
#else
#if defined __STDC_VERSION__ && __STDC_VERSION__ >= 199901L
#define FUNCTION_NAME __func__ /* ARI: func */
#endif
#endif
/* xmalloc(), xrealloc() and xcalloc() have already been declared in
"libiberty.h". */
/* Like xmalloc, but zero the memory. */
void *xzalloc (size_t);
void xfree (void *);
/* Like asprintf and vasprintf, but return the string, throw an error
if no memory. */
char *xstrprintf (const char *format, ...) ATTRIBUTE_PRINTF (1, 2);
char *xstrvprintf (const char *format, va_list ap)
ATTRIBUTE_PRINTF (1, 0);
/* Like snprintf, but throw an error if the output buffer is too small. */
int xsnprintf (char *str, size_t size, const char *format, ...)
ATTRIBUTE_PRINTF (3, 4);
/* Make a copy of the string at PTR with LEN characters
(and add a null character at the end in the copy).
Uses malloc to get the space. Returns the address of the copy. */
char *savestring (const char *ptr, size_t len);
/* The strerror() function can return NULL for errno values that are
out of range. Provide a "safe" version that always returns a
printable string. */
extern char *safe_strerror (int);
/* Return non-zero if the start of STRING matches PATTERN, zero
otherwise. */
static inline int
startswith (const char *string, const char *pattern)
{
return strncmp (string, pattern, strlen (pattern)) == 0;
}
#endif
|
/******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution *
* Copyright (C) 1999-2007 ComPiere, Inc. All Rights Reserved. *
* This program is free software, you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY, without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program, if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.model;
import java.math.BigDecimal;
import java.sql.Timestamp;
import org.compiere.util.KeyNamePair;
/** Generated Interface for C_Phase
* @author Adempiere (generated)
* @version Release 3.8.0
*/
public interface I_C_Phase
{
/** TableName=C_Phase */
public static final String Table_Name = "C_Phase";
/** AD_Table_ID=577 */
public static final int Table_ID = MTable.getTable_ID(Table_Name);
KeyNamePair Model = new KeyNamePair(Table_ID, Table_Name);
/** AccessLevel = 3 - Client - Org
*/
BigDecimal accessLevel = BigDecimal.valueOf(3);
/** Load Meta Data */
/** Column name AD_Client_ID */
public static final String COLUMNNAME_AD_Client_ID = "AD_Client_ID";
/** Get Client.
* Client/Tenant for this installation.
*/
public int getAD_Client_ID();
/** Column name AD_Org_ID */
public static final String COLUMNNAME_AD_Org_ID = "AD_Org_ID";
/** Set Organization.
* Organizational entity within client
*/
public void setAD_Org_ID (int AD_Org_ID);
/** Get Organization.
* Organizational entity within client
*/
public int getAD_Org_ID();
/** Column name C_Phase_ID */
public static final String COLUMNNAME_C_Phase_ID = "C_Phase_ID";
/** Set Standard Phase.
* Standard Phase of the Project Type
*/
public void setC_Phase_ID (int C_Phase_ID);
/** Get Standard Phase.
* Standard Phase of the Project Type
*/
public int getC_Phase_ID();
/** Column name C_ProjectType_ID */
public static final String COLUMNNAME_C_ProjectType_ID = "C_ProjectType_ID";
/** Set Project Type.
* Type of the project
*/
public void setC_ProjectType_ID (int C_ProjectType_ID);
/** Get Project Type.
* Type of the project
*/
public int getC_ProjectType_ID();
public org.compiere.model.I_C_ProjectType getC_ProjectType() throws RuntimeException;
/** Column name Created */
public static final String COLUMNNAME_Created = "Created";
/** Get Created.
* Date this record was created
*/
public Timestamp getCreated();
/** Column name CreatedBy */
public static final String COLUMNNAME_CreatedBy = "CreatedBy";
/** Get Created By.
* User who created this records
*/
public int getCreatedBy();
/** Column name Description */
public static final String COLUMNNAME_Description = "Description";
/** Set Description.
* Optional short description of the record
*/
public void setDescription (String Description);
/** Get Description.
* Optional short description of the record
*/
public String getDescription();
/** Column name Help */
public static final String COLUMNNAME_Help = "Help";
/** Set Comment/Help.
* Comment or Hint
*/
public void setHelp (String Help);
/** Get Comment/Help.
* Comment or Hint
*/
public String getHelp();
/** Column name IsActive */
public static final String COLUMNNAME_IsActive = "IsActive";
/** Set Active.
* The record is active in the system
*/
public void setIsActive (boolean IsActive);
/** Get Active.
* The record is active in the system
*/
public boolean isActive();
/** Column name M_Product_ID */
public static final String COLUMNNAME_M_Product_ID = "M_Product_ID";
/** Set Product.
* Product, Service, Item
*/
public void setM_Product_ID (int M_Product_ID);
/** Get Product.
* Product, Service, Item
*/
public int getM_Product_ID();
public org.compiere.model.I_M_Product getM_Product() throws RuntimeException;
/** Column name Name */
public static final String COLUMNNAME_Name = "Name";
/** Set Name.
* Alphanumeric identifier of the entity
*/
public void setName (String Name);
/** Get Name.
* Alphanumeric identifier of the entity
*/
public String getName();
/** Column name SeqNo */
public static final String COLUMNNAME_SeqNo = "SeqNo";
/** Set Sequence.
* Method of ordering records;
lowest number comes first
*/
public void setSeqNo (int SeqNo);
/** Get Sequence.
* Method of ordering records;
lowest number comes first
*/
public int getSeqNo();
/** Column name StandardQty */
public static final String COLUMNNAME_StandardQty = "StandardQty";
/** Set Standard Quantity.
* Standard Quantity
*/
public void setStandardQty (BigDecimal StandardQty);
/** Get Standard Quantity.
* Standard Quantity
*/
public BigDecimal getStandardQty();
/** Column name Updated */
public static final String COLUMNNAME_Updated = "Updated";
/** Get Updated.
* Date this record was updated
*/
public Timestamp getUpdated();
/** Column name UpdatedBy */
public static final String COLUMNNAME_UpdatedBy = "UpdatedBy";
/** Get Updated By.
* User who updated this records
*/
public int getUpdatedBy();
}
|
/* 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 "kyra/engine/kyra_lok.h"
#include "kyra/sequence/seqplayer_lok.h"
#include "kyra/resource/resource.h"
#include "kyra/engine/sprites.h"
#include "kyra/graphics/wsamovie.h"
#include "kyra/graphics/animator_lok.h"
#include "kyra/engine/timer.h"
#include "kyra/sound/sound.h"
#include "common/system.h"
#include "common/savefile.h"
#include "common/list.h"
namespace Kyra {
void KyraEngine_LoK::seq_demo() {
snd_playTheme(0, 2);
_screen->loadBitmap("START.CPS", 7, 7, &_screen->getPalette(0));
_screen->copyRegion(0, 0, 0, 0, 320, 200, 6, 0, Screen::CR_NO_P_CHECK);
_screen->updateScreen();
_screen->fadeFromBlack();
delay(60 * _tickLength);
_screen->fadeToBlack();
_screen->clearPage(0);
_screen->loadBitmap("TOP.CPS", 7, 7, 0);
_screen->loadBitmap("BOTTOM.CPS", 5, 5, &_screen->getPalette(0));
_screen->copyRegion(0, 91, 0, 8, 320, 103, 6, 0);
_screen->copyRegion(0, 0, 0, 111, 320, 64, 6, 0);
_screen->updateScreen();
_screen->fadeFromBlack();
_seq->playSequence(_seq_WestwoodLogo, true);
delay(60 * _tickLength);
_seq->playSequence(_seq_KyrandiaLogo, true);
_screen->fadeToBlack();
_screen->clearPage(2);
_screen->clearPage(0);
_seq->playSequence(_seq_Demo1, true);
_screen->clearPage(0);
_seq->playSequence(_seq_Demo2, true);
_screen->clearPage(0);
_seq->playSequence(_seq_Demo3, true);
_screen->clearPage(0);
_seq->playSequence(_seq_Demo4, true);
_screen->clearPage(0);
_screen->loadBitmap("FINAL.CPS", 7, 7, &_screen->getPalette(0));
_screen->_curPage = 0;
_screen->copyRegion(0, 0, 0, 0, 320, 200, 6, 0);
_screen->updateScreen();
_screen->fadeFromBlack();
delay(60 * _tickLength);
_screen->fadeToBlack();
_sound->haltTrack();
}
void KyraEngine_LoK::seq_intro() {
if (_flags.isTalkie)
_res->loadPakFile("INTRO.VRM");
static const IntroProc introProcTable[] = {
&KyraEngine_LoK::seq_introPublisherLogos,
&KyraEngine_LoK::seq_introLogos,
&KyraEngine_LoK::seq_introStory,
&KyraEngine_LoK::seq_introMalcolmTree,
&KyraEngine_LoK::seq_introKallakWriting,
&KyraEngine_LoK::seq_introKallakMalcolm
};
Common::InSaveFile *in;
if ((in = _saveFileMan->openForLoading(getSavegameFilename(0)))) {
delete in;
_skipIntroFlag = true;
} else {
_skipIntroFlag = !_flags.isDemo;
}
_seq->setCopyViewOffs(true);
_screen->setFont(_flags.lang == Common::JA_JPN ? Screen::FID_SJIS_FNT : Screen::FID_8_FNT);
if (_flags.platform != Common::kPlatformFMTowns && _flags.platform != Common::kPlatformPC98 && _flags.platform != Common::kPlatformAmiga)
snd_playTheme(0, 2);
_text->setTalkCoords(144);
for (int i = 0; i < ARRAYSIZE(introProcTable) && !seq_skipSequence(); ++i) {
if ((this->*introProcTable[i])() && !shouldQuit()) {
resetSkipFlag();
_screen->fadeToBlack();
_screen->clearPage(0);
}
}
_text->setTalkCoords(136);
delay(30 * _tickLength);
_seq->setCopyViewOffs(false);
_sound->haltTrack();
_sound->voiceStop();
if (_flags.isTalkie)
_res->unloadPakFile("INTRO.VRM");
}
bool KyraEngine_LoK::seq_introPublisherLogos() {
if (_flags.platform == Common::kPlatformFMTowns || _flags.platform == Common::kPlatformPC98) {
_screen->loadBitmap("LOGO.CPS", 3, 3, &_screen->getPalette(0));
_screen->copyRegion(0, 0, 0, 0, 320, 200, 2, 0);
_screen->updateScreen();
_screen->fadeFromBlack();
delay(90 * _tickLength);
if (!_abortIntroFlag) {
_screen->fadeToBlack();
snd_playWanderScoreViaMap(_flags.platform == Common::kPlatformFMTowns ? 57 : 2, 0);
}
} else if (_flags.platform == Common::kPlatformMacintosh && _res->exists("MP_GOLD.CPS")) {
_screen->loadPalette("MP_GOLD.COL", _screen->getPalette(0));
_screen->loadBitmap("MP_GOLD.CPS", 3, 3, 0);
_screen->copyRegion(0, 0, 0, 0, 320, 200, 2, 0);
_screen->updateScreen();
_screen->fadeFromBlack();
delay(120 * _tickLength);
if (!_abortIntroFlag)
_screen->fadeToBlack();
}
return _abortIntroFlag;
}
bool KyraEngine_LoK::seq_introLogos() {
_screen->clearPage(0);
if (_flags.platform == Common::kPlatformAmiga) {
_screen->loadPaletteTable("INTRO.PAL", 0);
_screen->loadBitmap("BOTTOM.CPS", 3, 5, 0);
_screen->loadBitmap("TOP.CPS", 3, 3, 0);
_screen->copyRegion(0, 0, 0, 111, 320, 64, 2, 0);
_screen->copyRegion(0, 91, 0, 8, 320, 109, 2, 0);
_screen->copyRegion(0, 0, 0, 0, 320, 190, 0, 2);
} else {
_screen->loadBitmap("TOP.CPS", 7, 7, 0);
_screen->loadBitmap("BOTTOM.CPS", 5, 5, &_screen->getPalette(0));
_screen->copyRegion(0, 91, 0, 8, 320, 103, 6, 0);
_screen->copyRegion(0, 0, 0, 111, 320, 64, 6, 0);
}
_screen->_curPage = 0;
_screen->updateScreen();
_screen->fadeFromBlack();
if (_seq->playSequence(_seq_WestwoodLogo, skipFlag()) || shouldQuit())
return true;
delay(60 * _tickLength);
if (_flags.platform == Common::kPlatformAmiga) {
_screen->copyPalette(0, 1);
_screen->setScreenPalette(_screen->getPalette(0));
}
Screen::FontId of = _screen->setFont(Screen::FID_8_FNT);
if (_seq->playSequence(_seq_KyrandiaLogo, skipFlag()) || shouldQuit())
return true;
_screen->setFont(of);
_screen->fillRect(0, 179, 319, 199, 0);
if (shouldQuit())
return false;
if (_flags.platform == Common::kPlatformAmiga) {
_screen->copyPalette(0, 2);
_screen->fadeToBlack();
_screen->copyRegion(0, 0, 0, 0, 320, 200, 4, 0);
_screen->fadeFromBlack();
} else {
_screen->copyRegion(0, 91, 0, 8, 320, 104, 6, 2);
_screen->copyRegion(0, 0, 0, 112, 320, 64, 6, 2);
uint32 start = _system->getMillis();
bool doneFlag = false;
int oldDistance = 0;
do {
uint32 now = _system->getMillis();
// The smallest y2 we ever draw the screen for is 65.
int distance = (now - start) / _tickLength;
if (distance > 112) {
distance = 112;
doneFlag = true;
}
if (distance > oldDistance) {
int y1 = 8 + distance;
int h1 = 168 - distance;
int y2 = 176 - distance;
int h2 = distance;
_screen->copyRegion(0, y1, 0, 8, 320, h1, 2, 0);
if (h2 > 0)
_screen->copyRegion(0, 64, 0, y2, 320, h2, 4, 0);
_screen->updateScreen();
}
oldDistance = distance;
delay(10);
} while (!doneFlag && !shouldQuit() && !_abortIntroFlag);
}
if (_abortIntroFlag || shouldQuit())
return true;
return _seq->playSequence(_seq_Forest, true);
}
bool KyraEngine_LoK::seq_introStory() {
_screen->clearPage(3);
_screen->clearPage(0);
// HACK: The Italian fan translation uses an special text screen here
// so we show it even when text is disabled
if (!textEnabled() && speechEnabled() && _flags.lang != Common::IT_ITA)
return false;
if (((_flags.lang == Common::EN_ANY || _flags.lang == Common::RU_RUS) && !_flags.isTalkie && _flags.platform == Common::kPlatformDOS) || _flags.platform == Common::kPlatformAmiga)
_screen->loadBitmap("TEXT.CPS", 3, 3, &_screen->getPalette(0));
else if (_flags.lang == Common::EN_ANY || _flags.lang == Common::JA_JPN)
_screen->loadBitmap("TEXT_ENG.CPS", 3, 3, &_screen->getPalette(0));
else if (_flags.lang == Common::DE_DEU)
_screen->loadBitmap("TEXT_GER.CPS", 3, 3, &_screen->getPalette(0));
else if (_flags.lang == Common::FR_FRA || (_flags.lang == Common::ES_ESP && _flags.isTalkie) /* Spanish fan made over French CD version */ )
_screen->loadBitmap("TEXT_FRE.CPS", 3, 3, &_screen->getPalette(0));
else if (_flags.lang == Common::ES_ESP)
_screen->loadBitmap("TEXT_SPA.CPS", 3, 3, &_screen->getPalette(0));
else if (_flags.lang == Common::IT_ITA && !_flags.isTalkie)
_screen->loadBitmap("TEXT_ITA.CPS", 3, 3, &_screen->getPalette(0));
else if (_flags.lang == Common::IT_ITA && _flags.isTalkie)
_screen->loadBitmap("TEXT_ENG.CPS", 3, 3, &_screen->getPalette(0));
else if (_flags.lang == Common::RU_RUS && _flags.isTalkie)
_screen->loadBitmap("TEXT_ENG.CPS", 3, 3, &_screen->getPalette(0));
else if (_flags.lang == Common::HE_ISR)
_screen->loadBitmap("TEXT_HEB.CPS", 3, 3, &_screen->getPalette(0));
else
warning("no story graphics file found");
if (_flags.platform == Common::kPlatformAmiga)
_screen->setScreenPalette(_screen->getPalette(4));
else
_screen->setScreenPalette(_screen->getPalette(0));
_screen->copyPage(3, 0);
if (_flags.lang == Common::JA_JPN) {
const int y1 = 175;
int x1, x2, y2, col1;
const char *s1, *s2;
if (_flags.platform == Common::kPlatformFMTowns) {
s1 = _seq_textsTable[18];
s2 = _seq_textsTable[19];
x1 = (Screen::SCREEN_W - _screen->getTextWidth(s1)) / 2;
x2 = (Screen::SCREEN_W - _screen->getTextWidth(s2)) / 2;
uint8 colorMap[] = { 0, 15, 12, 12 };
_screen->setTextColor(colorMap, 0, 3);
y2 = 184;
col1 = 5;
} else {
s1 = _storyStrings[0];
s2 = _storyStrings[1];
x1 = x2 = 54;
y2 = 185;
col1 = 15;
}
_screen->printText(s1, x1, y1, col1, 8);
_screen->printText(s2, x2, y2, col1, 8);
}
_screen->updateScreen();
delay(360 * _tickLength);
return _abortIntroFlag;
}
bool KyraEngine_LoK::seq_introMalcolmTree() {
_screen->_curPage = 0;
_screen->clearPage(3);
return _seq->playSequence(_seq_MalcolmTree, true);
}
bool KyraEngine_LoK::seq_introKallakWriting() {
_seq->makeHandShapes();
_screen->setAnimBlockPtr(5060);
_screen->_charSpacing = -2;
_screen->clearPage(3);
const bool skipped = _seq->playSequence(_seq_KallakWriting, true);
_seq->freeHandShapes();
return skipped;
}
bool KyraEngine_LoK::seq_introKallakMalcolm() {
_screen->clearPage(3);
return _seq->playSequence(_seq_KallakMalcolm, true);
}
void KyraEngine_LoK::seq_createAmuletJewel(int jewel, int page, int noSound, int drawOnly) {
static const uint16 specialJewelTable[] = {
0x167, 0x162, 0x15D, 0x158, 0x153, 0xFFFF
};
static const uint16 specialJewelTable1[] = {
0x14F, 0x154, 0x159, 0x15E, 0x163, 0xFFFF
};
static const uint16 specialJewelTable2[] = {
0x150, 0x155, 0x15A, 0x15F, 0x164, 0xFFFF
};
static const uint16 specialJewelTable3[] = {
0x151, 0x156, 0x15B, 0x160, 0x165, 0xFFFF
};
static const uint16 specialJewelTable4[] = {
0x152, 0x157, 0x15C, 0x161, 0x166, 0xFFFF
};
if (!noSound)
snd_playSoundEffect(0x5F);
_screen->hideMouse();
if (!drawOnly) {
for (int i = 0; specialJewelTable[i] != 0xFFFF; ++i) {
_screen->drawShape(page, _shapes[specialJewelTable[i]], _amuletX2[jewel], _amuletY2[jewel], 0, 0);
_screen->updateScreen();
delayWithTicks(3);
}
const uint16 *opcodes = 0;
switch (jewel - 1) {
case 0:
opcodes = specialJewelTable1;
break;
case 1:
opcodes = specialJewelTable2;
break;
case 2:
opcodes = specialJewelTable3;
break;
case 3:
opcodes = specialJewelTable4;
break;
default:
break;
}
if (opcodes) {
for (int i = 0; opcodes[i] != 0xFFFF; ++i) {
_screen->drawShape(page, _shapes[opcodes[i]], _amuletX2[jewel], _amuletY2[jewel], 0, 0);
_screen->updateScreen();
delayWithTicks(3);
}
}
}
_screen->drawShape(page, _shapes[323 + jewel], _amuletX2[jewel], _amuletY2[jewel], 0, 0);
_screen->updateScreen();
_screen->showMouse();
setGameFlag(0x55 + jewel);
}
void KyraEngine_LoK::seq_brandonHealing() {
if (!(_deathHandler & 8))
return;
if (_currentCharacter->sceneId == 210) {
if (_beadStateVar == 4 || _beadStateVar == 6)
return;
}
_screen->hideMouse();
checkAmuletAnimFlags();
assert(_healingShapeTable);
setupShapes123(_healingShapeTable, 22, 0);
_animator->setBrandonAnimSeqSize(3, 48);
snd_playSoundEffect(0x53);
for (int i = 123; i <= 144; ++i) {
_currentCharacter->currentAnimFrame = i;
_animator->animRefreshNPC(0);
delayWithTicks(8);
}
for (int i = 125; i >= 123; --i) {
_currentCharacter->currentAnimFrame = i;
_animator->animRefreshNPC(0);
delayWithTicks(8);
}
_animator->resetBrandonAnimSeqSize();
_currentCharacter->currentAnimFrame = 7;
_animator->animRefreshNPC(0);
freeShapes123();
_screen->showMouse();
}
void KyraEngine_LoK::seq_brandonHealing2() {
_screen->hideMouse();
checkAmuletAnimFlags();
assert(_healingShape2Table);
setupShapes123(_healingShape2Table, 30, 0);
resetBrandonPoisonFlags();
_animator->setBrandonAnimSeqSize(3, 48);
snd_playSoundEffect(0x50);
for (int i = 123; i <= 152; ++i) {
_currentCharacter->currentAnimFrame = i;
_animator->animRefreshNPC(0);
delayWithTicks(8);
}
_animator->resetBrandonAnimSeqSize();
_currentCharacter->currentAnimFrame = 7;
_animator->animRefreshNPC(0);
freeShapes123();
_screen->showMouse();
assert(_poisonGone);
characterSays(2010, _poisonGone[0], 0, -2);
characterSays(2011, _poisonGone[1], 0, -2);
}
void KyraEngine_LoK::seq_poisonDeathNow(int now) {
if (!(_brandonStatusBit & 1))
return;
++_poisonDeathCounter;
if (now)
_poisonDeathCounter = 2;
if (_poisonDeathCounter >= 2) {
snd_playWanderScoreViaMap(1, 1);
assert(_thePoison);
characterSays(7000, _thePoison[0], 0, -2);
characterSays(7001, _thePoison[1], 0, -2);
seq_poisonDeathNowAnim();
_deathHandler = 3;
} else {
assert(_thePoison);
characterSays(7002, _thePoison[2], 0, -2);
characterSays(7004, _thePoison[3], 0, -2);
}
}
void KyraEngine_LoK::seq_poisonDeathNowAnim() {
_screen->hideMouse();
checkAmuletAnimFlags();
assert(_posionDeathShapeTable);
setupShapes123(_posionDeathShapeTable, 20, 0);
_animator->setBrandonAnimSeqSize(8, 48);
_currentCharacter->currentAnimFrame = 124;
_animator->animRefreshNPC(0);
delayWithTicks(30);
_currentCharacter->currentAnimFrame = 123;
_animator->animRefreshNPC(0);
delayWithTicks(30);
for (int i = 125; i <= 139; ++i) {
_currentCharacter->currentAnimFrame = i;
_animator->animRefreshNPC(0);
delayWithTicks(8);
}
delayWithTicks(60);
for (int i = 140; i <= 142; ++i) {
_currentCharacter->currentAnimFrame = i;
_animator->animRefreshNPC(0);
delayWithTicks(8);
}
delayWithTicks(60);
_animator->resetBrandonAnimSeqSize();
freeShapes123();
_animator->restoreAllObjectBackgrounds();
_currentCharacter->x1 = _currentCharacter->x2 = -1;
_currentCharacter->y1 = _currentCharacter->y2 = -1;
_animator->preserveAllBackgrounds();
_screen->showMouse();
}
void KyraEngine_LoK::seq_playFluteAnimation() {
_screen->hideMouse();
checkAmuletAnimFlags();
setupShapes123(_fluteAnimShapeTable, 36, 0);
_animator->setBrandonAnimSeqSize(3, 75);
for (int i = 123; i <= 130; ++i) {
_currentCharacter->currentAnimFrame = i;
_animator->animRefreshNPC(0);
delayWithTicks(2);
}
int delayTime = 0, soundType = 0;
if (queryGameFlag(0x85)) {
snd_playSoundEffect(0x63);
delayTime = 9;
soundType = 3;
} else if (!queryGameFlag(0x86)) {
snd_playSoundEffect(0x61);
delayTime = 2;
soundType = 1;
setGameFlag(0x86);
} else {
snd_playSoundEffect(0x62);
delayTime = 2;
soundType = 2;
}
for (int i = 131; i <= 158; ++i) {
_currentCharacter->currentAnimFrame = i;
_animator->animRefreshNPC(0);
delayWithTicks(delayTime);
}
for (int i = 126; i >= 123; --i) {
_currentCharacter->currentAnimFrame = i;
_animator->animRefreshNPC(0);
delayWithTicks(delayTime);
}
_animator->resetBrandonAnimSeqSize();
_currentCharacter->currentAnimFrame = 7;
_animator->animRefreshNPC(0);
freeShapes123();
_screen->showMouse();
if (soundType == 1) {
assert(_fluteString);
characterSays(1000, _fluteString[0], 0, -2);
} else if (soundType == 2) {
assert(_fluteString);
characterSays(1001, _fluteString[1], 0, -2);
}
}
void KyraEngine_LoK::seq_winterScroll1() {
_screen->hideMouse();
checkAmuletAnimFlags();
assert(_winterScrollTable);
assert(_winterScroll1Table);
assert(_winterScroll2Table);
setupShapes123(_winterScrollTable, 7, 0);
_animator->setBrandonAnimSeqSize(5, 66);
for (int i = 123; i <= 129; ++i) {
_currentCharacter->currentAnimFrame = i;
_animator->animRefreshNPC(0);
delayWithTicks(8);
}
freeShapes123();
snd_playSoundEffect(0x20);
uint8 numFrames, midpoint;
if (_flags.isTalkie) {
numFrames = 18;
midpoint = 136;
} else {
numFrames = 35;
midpoint = 147;
}
setupShapes123(_winterScroll1Table, numFrames, 0);
for (int i = 123; i < midpoint; ++i) {
_currentCharacter->currentAnimFrame = i;
_animator->animRefreshNPC(0);
delayWithTicks(8);
}
if (_currentCharacter->sceneId == 41 && !queryGameFlag(0xA2)) {
snd_playSoundEffect(0x20);
_sprites->_anims[0].play = false;
_animator->sprites()[0].active = 0;
_sprites->_anims[1].play = true;
_animator->sprites()[1].active = 1;
if (_flags.platform != Common::kPlatformAmiga)
setGameFlag(0xA2);
}
for (int i = midpoint; i < 123 + numFrames; ++i) {
_currentCharacter->currentAnimFrame = i;
_animator->animRefreshNPC(0);
delayWithTicks(8);
}
if (_currentCharacter->sceneId == 117 && !queryGameFlag(0xB3)) {
for (int i = 0; i <= 7; ++i) {
_sprites->_anims[i].play = false;
_animator->sprites()[i].active = 0;
}
if (_flags.platform == Common::kPlatformAmiga) {
_screen->copyPalette(0, 11);
} else {
_screen->getPalette(0).copy(palTable2()[0], 0, 20, 228);
_screen->fadePalette(_screen->getPalette(0), 72);
_screen->setScreenPalette(_screen->getPalette(0));
setGameFlag(0xB3);
}
} else {
delayWithTicks(120);
}
freeShapes123();
setupShapes123(_winterScroll2Table, 4, 0);
for (int i = 123; i <= 126; ++i) {
_currentCharacter->currentAnimFrame = i;
_animator->animRefreshNPC(0);
delayWithTicks(8);
}
_animator->resetBrandonAnimSeqSize();
_currentCharacter->currentAnimFrame = 7;
_animator->animRefreshNPC(0);
freeShapes123();
_screen->showMouse();
}
void KyraEngine_LoK::seq_winterScroll2() {
_screen->hideMouse();
checkAmuletAnimFlags();
assert(_winterScrollTable);
setupShapes123(_winterScrollTable, 7, 0);
_animator->setBrandonAnimSeqSize(5, 66);
for (int i = 123; i <= 128; ++i) {
_currentCharacter->currentAnimFrame = i;
_animator->animRefreshNPC(0);
delayWithTicks(8);
}
delayWithTicks(120);
for (int i = 127; i >= 123; --i) {
_currentCharacter->currentAnimFrame = i;
_animator->animRefreshNPC(0);
delayWithTicks(8);
}
_animator->resetBrandonAnimSeqSize();
_currentCharacter->currentAnimFrame = 7;
_animator->animRefreshNPC(0);
freeShapes123();
_screen->showMouse();
}
void KyraEngine_LoK::seq_makeBrandonInv() {
if (_deathHandler == 8)
return;
if (_currentCharacter->sceneId == 210) {
if (_beadStateVar == 4 || _beadStateVar == 6)
return;
}
_screen->hideMouse();
checkAmuletAnimFlags();
_brandonStatusBit |= 0x20;
_timer->setCountdown(18, 2700);
_brandonStatusBit |= 0x40;
snd_playSoundEffect(0x77);
_brandonInvFlag = 0;
while (_brandonInvFlag <= 0x100) {
_animator->animRefreshNPC(0);
delayWithTicks(10);
_brandonInvFlag += 0x10;
}
_brandonStatusBit &= 0xFFBF;
_screen->showMouse();
}
void KyraEngine_LoK::seq_makeBrandonNormal() {
_screen->hideMouse();
_brandonStatusBit |= 0x40;
snd_playSoundEffect(0x77);
_brandonInvFlag = 0x100;
while (_brandonInvFlag >= 0) {
_animator->animRefreshNPC(0);
delayWithTicks(10);
_brandonInvFlag -= 0x10;
}
_brandonInvFlag = 0;
_brandonStatusBit &= 0xFF9F;
_screen->showMouse();
}
void KyraEngine_LoK::seq_makeBrandonNormal2() {
_screen->hideMouse();
assert(_brandonToWispTable);
setupShapes123(_brandonToWispTable, 26, 0);
_animator->setBrandonAnimSeqSize(5, 48);
_brandonStatusBit &= 0xFFFD;
snd_playSoundEffect(0x6C);
for (int i = 138; i >= 123; --i) {
_currentCharacter->currentAnimFrame = i;
_animator->animRefreshNPC(0);
delayWithTicks(8);
}
_animator->setBrandonAnimSeqSize(3, 48);
_currentCharacter->currentAnimFrame = 7;
_animator->animRefreshNPC(0);
if (_currentCharacter->sceneId >= 229 && _currentCharacter->sceneId <= 245)
_screen->fadeSpecialPalette(31, 234, 13, 4);
else if (_currentCharacter->sceneId >= 118 && _currentCharacter->sceneId <= 186)
_screen->fadeSpecialPalette(14, 228, 15, 4);
freeShapes123();
_screen->showMouse();
}
void KyraEngine_LoK::seq_makeBrandonWisp() {
if (_deathHandler == 8)
return;
if (_currentCharacter->sceneId == 210) {
if (_beadStateVar == 4 || _beadStateVar == 6)
return;
}
_screen->hideMouse();
checkAmuletAnimFlags();
assert(_brandonToWispTable);
setupShapes123(_brandonToWispTable, 26, 0);
_animator->setBrandonAnimSeqSize(5, 48);
snd_playSoundEffect(0x6C);
for (int i = 123; i <= 138; ++i) {
_currentCharacter->currentAnimFrame = i;
_animator->animRefreshNPC(0);
delayWithTicks(8);
}
_brandonStatusBit |= 2;
if (_currentCharacter->sceneId >= 109 && _currentCharacter->sceneId <= 198)
_timer->setCountdown(14, 18000);
else
_timer->setCountdown(14, 7200);
_animator->_brandonDrawFrame = 113;
_brandonStatusBit0x02Flag = 1;
_currentCharacter->currentAnimFrame = 113;
_animator->animRefreshNPC(0);
_animator->updateAllObjectShapes();
if (_flags.platform == Common::kPlatformAmiga) {
if ((_currentCharacter->sceneId >= 229 && _currentCharacter->sceneId <= 245) ||
(_currentCharacter->sceneId >= 118 && _currentCharacter->sceneId <= 186))
_screen->fadePalette(_screen->getPalette(10), 0x54);
} else {
if (_currentCharacter->sceneId >= 229 && _currentCharacter->sceneId <= 245)
_screen->fadeSpecialPalette(30, 234, 13, 4);
else if (_currentCharacter->sceneId >= 118 && _currentCharacter->sceneId <= 186)
_screen->fadeSpecialPalette(14, 228, 15, 4);
}
freeShapes123();
_screen->showMouse();
}
void KyraEngine_LoK::seq_dispelMagicAnimation() {
if (_deathHandler == 8)
return;
if (_currentCharacter->sceneId == 210) {
if (_beadStateVar == 4 || _beadStateVar == 6)
return;
}
_screen->hideMouse();
// TODO
#if 0
// FIXME: This condition is always false. Is this a typo or a bug in the original?
if (_currentCharacter->sceneId == 210 && _currentCharacter->sceneId < 160) {
_currentCharacter->facing = 3;
}
#endif
if (_malcolmFlag == 7 && _beadStateVar == 3) {
_beadStateVar = 6;
_unkEndSeqVar5 = 2;
_malcolmFlag = 10;
}
checkAmuletAnimFlags();
setGameFlag(0xEE);
assert(_magicAnimationTable);
setupShapes123(_magicAnimationTable, 5, 0);
_animator->setBrandonAnimSeqSize(8, 49);
snd_playSoundEffect(0x15);
for (int i = 123; i <= 127; ++i) {
_currentCharacter->currentAnimFrame = i;
_animator->animRefreshNPC(0);
delayWithTicks(8);
}
delayWithTicks(120);
for (int i = 127; i >= 123; --i) {
_currentCharacter->currentAnimFrame = i;
_animator->animRefreshNPC(0);
delayWithTicks(10);
}
_animator->resetBrandonAnimSeqSize();
_currentCharacter->currentAnimFrame = 7;
_animator->animRefreshNPC(0);
freeShapes123();
_screen->showMouse();
}
void KyraEngine_LoK::seq_fillFlaskWithWater(int item, int type) {
int newItem = -1;
static const uint8 flaskTable1[] = { 0x46, 0x48, 0x4A, 0x4C };
static const uint8 flaskTable2[] = { 0x47, 0x49, 0x4B, 0x4D };
if (item >= 60 && item <= 77) {
assert(_flaskFull);
characterSays(8006, _flaskFull[0], 0, -2);
} else if (item == 78) {
assert(type >= 0 && type < ARRAYSIZE(flaskTable1));
newItem = flaskTable1[type];
} else if (item == 79) {
assert(type >= 0 && type < ARRAYSIZE(flaskTable2));
newItem = flaskTable2[type];
}
if (newItem == -1)
return;
setMouseItem(newItem);
_itemInHand = newItem;
assert(_fullFlask);
assert(type < _fullFlask_Size && type >= 0);
static const uint16 voiceEntries[] = {
0x1F40, 0x1F41, 0x1F42, 0x1F45
};
assert(type < ARRAYSIZE(voiceEntries));
characterSays(voiceEntries[type], _fullFlask[type], 0, -2);
}
void KyraEngine_LoK::seq_playDrinkPotionAnim(int item, int makeFlaskEmpty, int flags) {
if (_flags.platform == Common::kPlatformAmiga) {
uint8 r, g, b;
switch (item) {
case 60: case 61:
// 0xC22
r = 50;
g = 8;
b = 8;
break;
case 62: case 63: case 76:
case 77:
// 0x00E
r = 0;
g = 0;
b = 58;
break;
case 64: case 65:
// 0xFF5
r = 63;
g = 63;
b = 21;
break;
case 66:
// 0x090
r = 0;
g = 37;
b = 0;
break;
case 67:
// 0xC61
r = 50;
g = 25;
b = 4;
break;
case 68:
// 0xE2E
r = 58;
g = 8;
b = 58;
break;
case 69:
// 0xBBB
r = 46;
g = 46;
b = 46;
break;
default:
// 0xFFF
r = 63;
g = 63;
b = 63;
}
_screen->setPaletteIndex(16, r, g, b);
} else {
uint8 red, green, blue;
switch (item) {
case 60: case 61:
red = 63;
green = blue = 6;
break;
case 62: case 63:
red = green = 0;
blue = 67;
break;
case 64: case 65:
red = 84;
green = 78;
blue = 14;
break;
case 66:
red = blue = 0;
green = 48;
break;
case 67:
red = 100;
green = 48;
blue = 23;
break;
case 68:
red = 73;
green = 0;
blue = 89;
break;
case 69:
red = green = 73;
blue = 86;
break;
default:
red = 33;
green = 66;
blue = 100;
}
red = red * 0x3F / 100;
green = green * 0x3F / 100;
blue = blue * 0x3F / 100;
_screen->setPaletteIndex(0xFE, red, green, blue);
}
_screen->hideMouse();
checkAmuletAnimFlags();
_currentCharacter->facing = 5;
_animator->animRefreshNPC(0);
assert(_drinkAnimationTable);
setupShapes123(_drinkAnimationTable, 9, flags);
_animator->setBrandonAnimSeqSize(5, 54);
for (int i = 123; i <= 131; ++i) {
_currentCharacter->currentAnimFrame = i;
_animator->animRefreshNPC(0);
delayWithTicks(5);
}
snd_playSoundEffect(0x34);
for (int i = 0; i < 2; ++i) {
_currentCharacter->currentAnimFrame = 130;
_animator->animRefreshNPC(0);
delayWithTicks(7);
_currentCharacter->currentAnimFrame = 131;
_animator->animRefreshNPC(0);
delayWithTicks(7);
}
if (makeFlaskEmpty)
_screen->setPaletteIndex(0xFE, 30, 30, 30);
for (int i = 131; i >= 123; --i) {
_currentCharacter->currentAnimFrame = i;
_animator->animRefreshNPC(0);
delayWithTicks(5);
}
_animator->resetBrandonAnimSeqSize();
_currentCharacter->currentAnimFrame = 7;
_animator->animRefreshNPC(0);
freeShapes123();
if (_flags.platform != Common::kPlatformAmiga)
_screen->setPaletteIndex(0xFE, 30, 30, 30);
_screen->showMouse();
}
int KyraEngine_LoK::seq_playEnd() {
if (_endSequenceSkipFlag)
return 0;
if (_deathHandler == 8)
return 0;
_screen->_curPage = 2;
if (_endSequenceNeedLoading) {
snd_playWanderScoreViaMap(50, 1);
setupPanPages();
if (_flags.platform == Common::kPlatformAmiga) {
_sound->loadSoundFile(kMusicFinale);
// The original started song 0 directly here. Since our player
// uses 0, 1 for stop and fade we start song 0 with 2
_sound->playTrack(2);
}
_finalA = createWSAMovie();
assert(_finalA);
_finalA->open("finala.wsa", 1, 0);
_finalB = createWSAMovie();
assert(_finalB);
_finalB->open("finalb.wsa", 1, 0);
_finalC = createWSAMovie();
assert(_finalC);
_endSequenceNeedLoading = 0;
_finalC->open("finalc.wsa", 1, 0);
_screen->_curPage = 0;
_beadStateVar = 0;
_malcolmFlag = 0;
_unkEndSeqVar2 = _system->getMillis() + 600 * _tickLength;
_screen->copyRegion(312, 0, 312, 0, 8, 136, 0, 2);
}
// TODO: better handling. This timer shouldn't count when the menu is open or something.
if (_unkEndSeqVar2 != -1) {
if (_system->getMillis() > (uint32)_unkEndSeqVar2) {
_unkEndSeqVar2 = -1;
if (!_malcolmFlag)
_malcolmFlag = 1;
}
}
if (handleMalcolmFlag()) {
_beadStateVar = 0;
_malcolmFlag = 12;
handleMalcolmFlag();
handleBeadState();
closeFinalWsa();
if (_deathHandler == 8) {
_screen->_curPage = 0;
checkAmuletAnimFlags();
seq_brandonToStone();
delay(60 * _tickLength);
return 1;
} else {
_endSequenceSkipFlag = 1;
if (_text->printed())
_text->restoreTalkTextMessageBkgd(2, 0);
_screen->_curPage = 0;
_screen->hideMouse();
if (_flags.platform != Common::kPlatformAmiga)
_screen->fadeSpecialPalette(32, 228, 20, 60);
delay(60 * _tickLength);
_screen->loadBitmap("GEMHEAL.CPS", 3, 3, &_screen->getPalette(0));
_screen->setScreenPalette(_screen->getPalette(0));
_screen->shuffleScreen(8, 8, 304, 128, 2, 0, 1, 0);
uint32 nextTime = _system->getMillis() + 120 * _tickLength;
_finalA = createWSAMovie();
assert(_finalA);
_finalA->open("finald.wsa", 1, 0);
delayUntil(nextTime);
snd_playSoundEffect(0x40);
for (int i = 0; i < 22; ++i) {
delayUntil(nextTime);
if (i == 4)
snd_playSoundEffect(0x3E);
else if (i == 20)
snd_playSoundEffect(_flags.platform == Common::kPlatformPC98 ? 0x13 : 0x0E);
nextTime = _system->getMillis() + 8 * _tickLength;
_finalA->displayFrame(i, 0, 8, 8, 0, 0, 0);
_screen->updateScreen();
}
nextTime = _system->getMillis() + 300 * _tickLength;
delete _finalA;
_finalA = 0;
delayUntil(nextTime);
seq_playEnding();
return 1;
}
} else {
handleBeadState();
_screen->bitBlitRects();
_screen->updateScreen();
_screen->_curPage = 0;
}
return 0;
}
void KyraEngine_LoK::seq_brandonToStone() {
_screen->hideMouse();
assert(_brandonStoneTable);
setupShapes123(_brandonStoneTable, 14, 0);
_animator->setBrandonAnimSeqSize(5, 51);
for (int i = 123; i <= 136; ++i) {
_currentCharacter->currentAnimFrame = i;
_animator->animRefreshNPC(0);
delayWithTicks(8);
}
_animator->resetBrandonAnimSeqSize();
freeShapes123();
_screen->showMouse();
}
void KyraEngine_LoK::seq_playEnding() {
if (shouldQuit())
return;
_screen->hideMouse();
_screen->_curPage = 0;
_screen->fadeToBlack();
if (_flags.platform == Common::kPlatformAmiga) {
_screen->loadBitmap("GEMCUT.CPS", 3, 3, &_screen->getPalette(0));
_screen->copyRegion(232, 136, 176, 56, 56, 56, 2, 2);
_screen->copyRegion(8, 8, 8, 8, 304, 128, 2, 0);
_screen->copyRegion(0, 0, 0, 0, 320, 200, 0, 2, Screen::CR_NO_P_CHECK);
} else {
_screen->loadBitmap("REUNION.CPS", 3, 3, &_screen->getPalette(0));
_screen->copyRegion(8, 8, 8, 8, 304, 128, 2, 0);
}
_screen->_curPage = 0;
// XXX
assert(_homeString);
drawSentenceCommand(_homeString[0], 179);
_screen->getPalette(2).clear();
_screen->setScreenPalette(_screen->getPalette(2));
_seqPlayerFlag = true;
_seq->playSequence(_seq_Reunion, false);
_screen->fadeToBlack();
_seqPlayerFlag = false;
_screen->showMouse();
// To avoid any remaining input events, we remove the queue
// over here.
_eventList.clear();
if (_flags.platform == Common::kPlatformAmiga) {
_screen->_charSpacing = -2;
_screen->setCurPage(2);
_screen->getPalette(2).clear();
_screen->setScreenPalette(_screen->getPalette(2));
while (!shouldQuit()) {
seq_playCreditsAmiga();
delayUntil(_system->getMillis() + 300 * _tickLength);
}
} else {
seq_playCredits();
}
}
namespace {
struct CreditsLine {
int16 x, y;
Screen::FontId font;
uint8 *str;
};
} // end of anonymous namespace
void KyraEngine_LoK::seq_playCredits() {
static const uint8 colorMap[] = { 0, 0, 0xC, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
static const char stringTerms[] = { 0x5, 0xD, 0x0};
typedef Common::List<CreditsLine> CreditsLineList;
CreditsLineList lines;
_screen->disableDualPaletteMode();
_screen->hideMouse();
if (!_flags.isTalkie) {
_screen->loadFont(Screen::FID_CRED6_FNT, "CREDIT6.FNT");
_screen->loadFont(Screen::FID_CRED8_FNT, "CREDIT8.FNT");
_screen->setFont(Screen::FID_CRED8_FNT);
} else
_screen->setFont(Screen::FID_8_FNT);
_screen->loadBitmap("CHALET.CPS", 4, 4, &_screen->getPalette(0));
_screen->setCurPage(0);
_screen->clearCurPage();
_screen->setTextColorMap(colorMap);
_screen->_charSpacing = -1;
// we only need this for the FM-TOWNS version
if (_flags.platform == Common::kPlatformFMTowns && _configMusic == 1)
snd_playWanderScoreViaMap(53, 1);
uint8 *buffer = 0;
uint32 size = 0;
if (_flags.platform == Common::kPlatformFMTowns || _flags.platform == Common::kPlatformPC98) {
int sizeTmp = 0;
const uint8 *bufferTmp = _staticres->loadRawData(k1CreditsStrings, sizeTmp);
buffer = new uint8[sizeTmp];
assert(buffer);
memcpy(buffer, bufferTmp, sizeTmp);
size = sizeTmp;
_staticres->unloadId(k1CreditsStrings);
} else {
buffer = _res->fileData("CREDITS.TXT", &size);
assert(buffer);
}
uint8 *nextString = buffer;
uint8 *currentString = buffer;
int currentY = 200;
do {
currentString = nextString;
nextString = (uint8 *)strpbrk((char *)currentString, stringTerms);
if (!nextString)
nextString = (uint8 *)strchr((char *)currentString, 0);
CreditsLine line;
int lineEndCode = nextString[0];
*nextString = 0;
if (lineEndCode != 0)
nextString++;
int alignment = 0;
if (*currentString == 3 || *currentString == 4) {
alignment = *currentString;
currentString++;
}
if (*currentString == 1) {
currentString++;
if (!_flags.isTalkie)
_screen->setFont(Screen::FID_CRED6_FNT);
} else if (*currentString == 2) {
currentString++;
if (!_flags.isTalkie)
_screen->setFont(Screen::FID_CRED8_FNT);
}
line.font = _screen->_currentFont;
if (alignment == 3)
line.x = 157 - _screen->getTextWidth((const char *)currentString);
else if (alignment == 4)
line.x = 161;
else
line.x = (320 - _screen->getTextWidth((const char *)currentString)) / 2 + 1;
line.y = currentY;
if (lineEndCode != 5)
currentY += 10;
line.str = currentString;
lines.push_back(line);
} while (*nextString);
_screen->setCurPage(2);
_screen->getPalette(2).clear();
_screen->setScreenPalette(_screen->getPalette(2));
_screen->copyRegion(0, 32, 0, 32, 320, 128, 4, 0, Screen::CR_NO_P_CHECK);
_screen->fadePalette(_screen->getPalette(0), 0x5A);
bool finished = false;
int bottom = 201;
while (!finished && !shouldQuit()) {
uint32 startLoop = _system->getMillis();
if (bottom > 175) {
_screen->copyRegion(0, 32, 0, 32, 320, 128, 4, 2, Screen::CR_NO_P_CHECK);
bottom = 0;
for (CreditsLineList::iterator it = lines.begin(); it != lines.end();) {
if (it->y < 0) {
it = lines.erase(it);
continue;
}
if (it->y < 200) {
if (it->font != _screen->_currentFont)
_screen->setFont(it->font);
_screen->printText((const char *)it->str, it->x, it->y, 15, 0);
}
it->y--;
if (it->y > bottom)
bottom = it->y;
++it;
}
_screen->copyRegion(0, 32, 0, 32, 320, 128, 2, 0, Screen::CR_NO_P_CHECK);
_screen->updateScreen();
}
if (checkInput(0, false)) {
removeInputTop();
finished = true;
}
uint32 now = _system->getMillis();
uint32 nextLoop = startLoop + _tickLength * 5;
if (nextLoop > now)
_system->delayMillis(nextLoop - now);
}
delete[] buffer;
_screen->fadeToBlack();
_screen->clearCurPage();
_screen->showMouse();
}
void KyraEngine_LoK::seq_playCreditsAmiga() {
_screen->setFont(Screen::FID_8_FNT);
_screen->loadBitmap("CHALET.CPS", 4, 2, &_screen->getPalette(0));
_screen->copyPage(2, 0);
_screen->getPalette(0).fill(16, 1, 63);
_screen->fadePalette(_screen->getPalette(0), 0x5A);
_screen->updateScreen();
const char *theEnd = "THE END";
const int width = _screen->getTextWidth(theEnd) + 1;
int x = (320 - width) / 2 + 1;
_screen->copyRegion(x, 8, x, 8, width, 56, 0, 2, Screen::CR_NO_P_CHECK);
_screen->copyRegion(x, 8, 0, 8, width, 11, 0, 2, Screen::CR_NO_P_CHECK);
_screen->printText(theEnd, 0, 10, 31, 0);
for (int y = 18, h = 1; y >= 10 && !shouldQuit(); --y, ++h) {
uint32 endTime = _system->getMillis() + 3 * _tickLength;
_screen->copyRegion(0, y, x, 8, width, h, 2, 0, Screen::CR_NO_P_CHECK);
_screen->updateScreen();
delayUntil(endTime);
}
for (int y = 8; y <= 62 && !shouldQuit(); ++y) {
uint32 endTime = _system->getMillis() + 3 * _tickLength;
_screen->copyRegion(x, y, 0, 8, width, 11, 2, 2, Screen::CR_NO_P_CHECK);
_screen->printText(theEnd, 0, 9, 31, 0);
_screen->copyRegion(0, 8, x, y, width, 11, 2, 0, Screen::CR_NO_P_CHECK);
_screen->updateScreen();
delayUntil(endTime);
}
int size = 0;
const char *creditsData = (const char *)_staticres->loadRawData(k1CreditsStrings, size);
char stringBuffer[81];
memset(stringBuffer, 0, sizeof(stringBuffer));
const char *cur = creditsData;
char *specialString = stringBuffer;
bool fillRectFlag = false, subWidth = false, centerFlag = false;
x = 0;
int specialX = 0;
const int fontHeight = _screen->getFontHeight();
do {
char code = *cur;
if (code == 3) {
fillRectFlag = subWidth = true;
} else if (code == 5) {
centerFlag = true;
} else if (code == 4) {
if (fillRectFlag) {
_screen->fillRect(0, 0, 319, 20, 0);
if (subWidth)
specialX = 157 - _screen->getTextWidth(stringBuffer);
_screen->printText(stringBuffer, specialX + 8, 0, 31, 0);
}
specialString = stringBuffer;
*specialString = 0;
x = 161;
} else if (code == 13) {
if (!fillRectFlag)
_screen->fillRect(0, 0, 319, 20, 0);
uint32 nextTime = _system->getMillis() + 8 * _tickLength;
if (centerFlag)
x = (320 - _screen->getTextWidth(stringBuffer)) / 2 - 8;
_screen->printText(stringBuffer, x + 8, 0, 31, 0);
for (int i = 0; i < fontHeight && !shouldQuit(); ++i) {
_screen->copyRegion(0, 141, 0, 140, 320, 59, 0, 0, Screen::CR_NO_P_CHECK);
_screen->copyRegion(0, i, 0, 198, 320, 3, 2, 0, Screen::CR_NO_P_CHECK);
_screen->updateScreen();
delayUntil(nextTime);
nextTime = _system->getMillis() + 8 * _tickLength;
}
specialString = stringBuffer;
*specialString = 0;
centerFlag = fillRectFlag = false;
} else {
*specialString++ = code;
*specialString = 0;
}
if (checkInput(0, false)) {
removeInputTop();
break;
}
} while (++cur != (creditsData + size) && !shouldQuit());
}
bool KyraEngine_LoK::seq_skipSequence() const {
return shouldQuit() || _abortIntroFlag;
}
int KyraEngine_LoK::handleMalcolmFlag() {
switch (_malcolmFlag) {
case 1:
_malcolmFrame = 0;
_malcolmFlag = 2;
_malcolmTimer2 = 0;
// fall through
case 2:
if (_system->getMillis() >= _malcolmTimer2) {
_finalA->displayFrame(_malcolmFrame, 0, 8, 46, 0, 0, 0);
_screen->updateScreen();
_malcolmTimer2 = _system->getMillis() + 8 * _tickLength;
++_malcolmFrame;
if (_malcolmFrame > 13) {
_malcolmFlag = 3;
_malcolmTimer1 = _system->getMillis() + 180 * _tickLength;
}
}
break;
case 3:
if (_system->getMillis() < _malcolmTimer1) {
if (_system->getMillis() >= _malcolmTimer2) {
_malcolmFrame = _rnd.getRandomNumberRng(14, 17);
_finalA->displayFrame(_malcolmFrame, 0, 8, 46, 0, 0, 0);
_screen->updateScreen();
_malcolmTimer2 = _system->getMillis() + 8 * _tickLength;
}
} else {
_malcolmFlag = 4;
_malcolmFrame = 18;
}
break;
case 4:
if (_system->getMillis() >= _malcolmTimer2) {
_finalA->displayFrame(_malcolmFrame, 0, 8, 46, 0, 0, 0);
_screen->updateScreen();
_malcolmTimer2 = _system->getMillis() + 8 * _tickLength;
++_malcolmFrame;
if (_malcolmFrame > 25) {
_malcolmFrame = 26;
_malcolmFlag = 5;
_beadStateVar = 1;
}
}
break;
case 5:
if (_system->getMillis() >= _malcolmTimer2) {
_finalA->displayFrame(_malcolmFrame, 0, 8, 46, 0, 0, 0);
_screen->updateScreen();
_malcolmTimer2 = _system->getMillis() + 8 * _tickLength;
++_malcolmFrame;
if (_malcolmFrame > 31) {
_malcolmFrame = 32;
_malcolmFlag = 6;
}
}
break;
case 6:
if (_unkEndSeqVar4) {
if (_malcolmFrame <= 33 && _system->getMillis() >= _malcolmTimer2) {
_finalA->displayFrame(_malcolmFrame, 0, 8, 46, 0, 0, 0);
_screen->updateScreen();
_malcolmTimer2 = _system->getMillis() + 8 * _tickLength;
++_malcolmFrame;
if (_malcolmFrame > 33) {
_malcolmFlag = 7;
_malcolmFrame = 32;
_unkEndSeqVar5 = 0;
}
}
}
break;
case 7:
if (_unkEndSeqVar5 == 1) {
_malcolmFlag = 8;
_malcolmFrame = 34;
} else if (_unkEndSeqVar5 == 2) {
_malcolmFlag = 3;
_malcolmTimer1 = _system->getMillis() + 180 * _tickLength;
}
break;
case 8:
if (_system->getMillis() >= _malcolmTimer2) {
_finalA->displayFrame(_malcolmFrame, 0, 8, 46, 0, 0, 0);
_screen->updateScreen();
_malcolmTimer2 = _system->getMillis() + 8 * _tickLength;
++_malcolmFrame;
if (_malcolmFrame > 37) {
_malcolmFlag = 0;
_deathHandler = 8;
return 1;
}
}
break;
case 9:
snd_playSoundEffect(12);
snd_playSoundEffect(12);
for (int i = 0; i < 18; ++i) {
_malcolmTimer2 = _system->getMillis() + 4 * _tickLength;
_finalC->displayFrame(i, 0, 16, 50, 0, 0, 0);
_screen->updateScreen();
delayUntil(_malcolmTimer2);
}
snd_playWanderScoreViaMap(51, 1);
delay(60 * _tickLength);
_malcolmFlag = 0;
return 1;
case 10:
if (!_beadStateVar) {
handleBeadState();
_screen->bitBlitRects();
assert(_veryClever);
_text->printTalkTextMessage(_veryClever[0], 60, 31, 5, 0, 2);
_malcolmTimer2 = _system->getMillis() + 180 * _tickLength;
_malcolmFlag = 11;
}
break;
case 11:
if (_system->getMillis() >= _malcolmTimer2) {
_text->restoreTalkTextMessageBkgd(2, 0);
_malcolmFlag = 3;
_malcolmTimer1 = _system->getMillis() + 180 * _tickLength;
}
break;
default:
break;
}
return 0;
}
int KyraEngine_LoK::handleBeadState() {
static const int table1[] = {
-1, -2, -4, -5, -6, -7, -6, -5,
-4, -2, -1, 0, 1, 2, 4, 5,
6, 7, 6, 5, 4, 2, 1, 0, 0
};
static const int table2[] = {
0, 0, 1, 1, 2, 2, 3, 3,
4, 4, 5, 5, 5, 5, 4, 4,
3, 3, 2, 2, 1, 1, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0
};
switch (_beadStateVar) {
case 0:
if (_beadState1.x != -1 && _endSequenceBackUpRect) {
_screen->copyBlockToPage(_screen->_curPage, _beadState1.x, _beadState1.y, _beadState1.width << 3, _beadState1.height, _endSequenceBackUpRect);
_screen->addBitBlitRect(_beadState1.x, _beadState1.y, _beadState1.width2, _beadState1.height);
}
_beadState1.x = -1;
_beadState1.tableIndex = 0;
_beadStateTimer1 = 0;
_beadStateTimer2 = 0;
_lastDisplayedPanPage = 0;
return 1;
case 1:
if (_beadState1.x != -1) {
if (_endSequenceBackUpRect) {
_screen->copyBlockToPage(_screen->_curPage, _beadState1.x, _beadState1.y, _beadState1.width << 3, _beadState1.height, _endSequenceBackUpRect);
_screen->addBitBlitRect(_beadState1.x, _beadState1.y, _beadState1.width2, _beadState1.height);
}
_beadState1.x = -1;
_beadState1.tableIndex = 0;
}
_beadStateVar = 2;
break;
case 2:
if (_system->getMillis() >= _beadStateTimer1) {
int x = 0, y = 0;
_beadStateTimer1 = _system->getMillis() + 4 * _tickLength;
if (_beadState1.x == -1) {
assert(_panPagesTable);
_beadState1.width2 = _animator->fetchAnimWidth(_panPagesTable[19], 256);
_beadState1.width = ((_beadState1.width2 + 7) >> 3) + 1;
_beadState1.height = _animator->fetchAnimHeight(_panPagesTable[19], 256);
if (!_endSequenceBackUpRect) {
_endSequenceBackUpRect = new uint8[(_beadState1.width * _beadState1.height) << 3];
assert(_endSequenceBackUpRect);
memset(_endSequenceBackUpRect, 0, ((_beadState1.width * _beadState1.height) << 3) * sizeof(uint8));
}
x = _beadState1.x = 60;
y = _beadState1.y = 40;
initBeadState(x, y, x, 25, 8, &_beadState2);
} else {
if (processBead(_beadState1.x, _beadState1.y, x, y, &_beadState2)) {
_beadStateVar = 3;
_beadStateTimer2 = _system->getMillis() + 240 * _tickLength;
_unkEndSeqVar4 = 0;
_beadState1.dstX = _beadState1.x;
_beadState1.dstY = _beadState1.y;
return 0;
} else {
_screen->copyBlockToPage(_screen->_curPage, _beadState1.x, _beadState1.y, _beadState1.width << 3, _beadState1.height, _endSequenceBackUpRect);
_screen->addBitBlitRect(_beadState1.x, _beadState1.y, _beadState1.width2, _beadState1.height);
_beadState1.x = x;
_beadState1.y = y;
}
}
_screen->copyRegionToBuffer(_screen->_curPage, x, y, _beadState1.width << 3, _beadState1.height, _endSequenceBackUpRect);
_screen->drawShape(2, _panPagesTable[_lastDisplayedPanPage++], x, y, 0, 0);
if (_lastDisplayedPanPage > 17)
_lastDisplayedPanPage = 0;
_screen->addBitBlitRect(x, y, _beadState1.width2, _beadState1.height);
}
break;
case 3:
if (_system->getMillis() >= _beadStateTimer1) {
_beadStateTimer1 = _system->getMillis() + 4 * _tickLength;
_screen->copyBlockToPage(_screen->_curPage, _beadState1.x, _beadState1.y, _beadState1.width << 3, _beadState1.height, _endSequenceBackUpRect);
_screen->addBitBlitRect(_beadState1.x, _beadState1.y, _beadState1.width2, _beadState1.height);
_beadState1.x = _beadState1.dstX + table1[_beadState1.tableIndex];
_beadState1.y = _beadState1.dstY + table2[_beadState1.tableIndex];
_screen->copyRegionToBuffer(_screen->_curPage, _beadState1.x, _beadState1.y, _beadState1.width << 3, _beadState1.height, _endSequenceBackUpRect);
_screen->drawShape(2, _panPagesTable[_lastDisplayedPanPage++], _beadState1.x, _beadState1.y, 0, 0);
if (_lastDisplayedPanPage >= 17)
_lastDisplayedPanPage = 0;
_screen->addBitBlitRect(_beadState1.x, _beadState1.y, _beadState1.width2, _beadState1.height);
++_beadState1.tableIndex;
if (_beadState1.tableIndex > 24) {
_beadState1.tableIndex = 0;
_unkEndSeqVar4 = 1;
}
if (_system->getMillis() > _beadStateTimer2 && _malcolmFlag == 7 && !_unkAmuletVar && !_text->printed()) {
snd_playSoundEffect(0x0B);
if (_currentCharacter->x1 > 233 && _currentCharacter->x1 < 305 && _currentCharacter->y1 > 85 && _currentCharacter->y1 < 105 &&
(_brandonStatusBit & 0x20)) {
_beadState1.unk8 = 290;
_beadState1.unk9 = 40;
_beadStateVar = 5;
} else {
_beadStateVar = 4;
_beadState1.unk8 = _currentCharacter->x1 - 4;
_beadState1.unk9 = _currentCharacter->y1 - 30;
}
if (_text->printed())
_text->restoreTalkTextMessageBkgd(2, 0);
initBeadState(_beadState1.x, _beadState1.y, _beadState1.unk8, _beadState1.unk9, 12, &_beadState2);
_lastDisplayedPanPage = 18;
}
}
break;
case 4:
if (_system->getMillis() >= _beadStateTimer1) {
int x = 0, y = 0;
_beadStateTimer1 = _system->getMillis() + _tickLength;
if (processBead(_beadState1.x, _beadState1.y, x, y, &_beadState2)) {
if (_brandonStatusBit & 20) {
_unkEndSeqVar5 = 2;
_beadStateVar = 6;
} else {
snd_playWanderScoreViaMap(52, 1);
snd_playSoundEffect(0x0C);
_unkEndSeqVar5 = 1;
_beadStateVar = 0;
}
} else {
_screen->copyBlockToPage(_screen->_curPage, _beadState1.x, _beadState1.y, _beadState1.width << 3, _beadState1.height, _endSequenceBackUpRect);
_screen->addBitBlitRect(_beadState1.x, _beadState1.y, _beadState1.width2, _beadState1.height);
_beadState1.x = x;
_beadState1.y = y;
_screen->copyRegionToBuffer(_screen->_curPage, _beadState1.x, _beadState1.y, _beadState1.width << 3, _beadState1.height, _endSequenceBackUpRect);
_screen->drawShape(2, _panPagesTable[_lastDisplayedPanPage++], x, y, 0, 0);
if (_lastDisplayedPanPage > 17) {
_lastDisplayedPanPage = 0;
}
_screen->addBitBlitRect(_beadState1.x, _beadState1.y, _beadState1.width2, _beadState1.height);
}
}
break;
case 5:
if (_system->getMillis() >= _beadStateTimer1) {
_beadStateTimer1 = _system->getMillis() + _tickLength;
int x = 0, y = 0;
if (processBead(_beadState1.x, _beadState1.y, x, y, &_beadState2)) {
if (_beadState2.dstX == 290) {
_screen->copyBlockToPage(_screen->_curPage, _beadState1.x, _beadState1.y, _beadState1.width << 3, _beadState1.height, _endSequenceBackUpRect);
uint32 nextRun = 0;
for (int i = 0; i < 8; ++i) {
nextRun = _system->getMillis() + _tickLength;
_finalB->displayFrame(i, 0, 224, 8, 0, 0, 0);
_screen->updateScreen();
delayUntil(nextRun);
}
snd_playSoundEffect(0x0D);
for (int i = 7; i >= 0; --i) {
nextRun = _system->getMillis() + _tickLength;
_finalB->displayFrame(i, 0, 224, 8, 0, 0, 0);
_screen->updateScreen();
delayUntil(nextRun);
}
initBeadState(_beadState1.x, _beadState1.y, 63, 60, 12, &_beadState2);
} else {
_screen->copyBlockToPage(_screen->_curPage, _beadState1.x, _beadState1.y, _beadState1.width << 3, _beadState1.height, _endSequenceBackUpRect);
_screen->addBitBlitRect(_beadState1.x, _beadState1.y, _beadState1.width2, _beadState1.height);
_beadState1.x = -1;
_beadState1.tableIndex = 0;
_beadStateVar = 0;
_malcolmFlag = 9;
}
} else {
_screen->copyBlockToPage(_screen->_curPage, _beadState1.x, _beadState1.y, _beadState1.width << 3, _beadState1.height, _endSequenceBackUpRect);
_screen->addBitBlitRect(_beadState1.x, _beadState1.y, _beadState1.width2, _beadState1.height);
_beadState1.x = x;
_beadState1.y = y;
_screen->copyRegionToBuffer(_screen->_curPage, _beadState1.x, _beadState1.y, _beadState1.width << 3, _beadState1.height, _endSequenceBackUpRect);
_screen->drawShape(2, _panPagesTable[_lastDisplayedPanPage++], x, y, 0, 0);
if (_lastDisplayedPanPage > 17)
_lastDisplayedPanPage = 0;
_screen->addBitBlitRect(_beadState1.x, _beadState1.y, _beadState1.width2, _beadState1.height);
}
}
break;
case 6:
_screen->drawShape(2, _panPagesTable[19], _beadState1.x, _beadState1.y, 0, 0);
_screen->addBitBlitRect(_beadState1.x, _beadState1.y, _beadState1.width2, _beadState1.height);
_beadStateVar = 0;
break;
default:
break;
}
return 0;
}
void KyraEngine_LoK::initBeadState(int x, int y, int x2, int y2, int unk, BeadState *ptr) {
ptr->unk9 = unk;
int xDiff = x2 - x;
int yDiff = y2 - y;
int unk1 = 0, unk2 = 0;
if (xDiff > 0)
unk1 = 1;
else if (xDiff == 0)
unk1 = 0;
else
unk1 = -1;
if (yDiff > 0)
unk2 = 1;
else if (yDiff == 0)
unk2 = 0;
else
unk2 = -1;
xDiff = ABS(xDiff);
yDiff = ABS(yDiff);
ptr->y = 0;
ptr->x = 0;
ptr->width = xDiff;
ptr->height = yDiff;
ptr->dstX = x2;
ptr->dstY = y2;
ptr->width2 = unk1;
ptr->unk8 = unk2;
}
int KyraEngine_LoK::processBead(int x, int y, int &x2, int &y2, BeadState *ptr) {
if (x == ptr->dstX && y == ptr->dstY)
return 1;
int xPos = x, yPos = y;
if (ptr->width >= ptr->height) {
for (int i = 0; i < ptr->unk9; ++i) {
ptr->y += ptr->height;
if (ptr->y >= ptr->width) {
ptr->y -= ptr->width;
yPos += ptr->unk8;
}
xPos += ptr->width2;
}
} else {
for (int i = 0; i < ptr->unk9; ++i) {
ptr->x += ptr->width;
if (ptr->x >= ptr->height) {
ptr->x -= ptr->height;
xPos += ptr->width2;
}
yPos += ptr->unk8;
}
}
int temp = ABS(x - ptr->dstX);
if (ptr->unk9 > temp)
xPos = ptr->dstX;
temp = ABS(y - ptr->dstY);
if (ptr->unk9 > temp)
yPos = ptr->dstY;
x2 = xPos;
y2 = yPos;
return 0;
}
void KyraEngine_LoK::setupPanPages() {
_screen->savePageToDisk("BKGD.PG", 2);
_screen->loadBitmap("BEAD.CPS", 3, 3, 0);
if (_flags.platform == Common::kPlatformMacintosh || _flags.platform == Common::kPlatformAmiga) {
int pageBackUp = _screen->_curPage;
_screen->_curPage = 2;
delete[] _panPagesTable[19];
_panPagesTable[19] = _screen->encodeShape(0, 0, 16, 9, 0);
assert(_panPagesTable[19]);
int curX = 16;
for (int i = 0; i < 19; ++i) {
delete[] _panPagesTable[i];
_panPagesTable[i] = _screen->encodeShape(curX, 0, 8, 5, 0);
assert(_panPagesTable[i]);
curX += 8;
}
_screen->_curPage = pageBackUp;
} else {
for (int i = 0; i <= 19; ++i) {
delete[] _panPagesTable[i];
_panPagesTable[i] = _seq->setPanPages(3, i);
assert(_panPagesTable[i]);
}
}
_screen->loadPageFromDisk("BKGD.PG", 2);
}
void KyraEngine_LoK::freePanPages() {
delete[] _endSequenceBackUpRect;
_endSequenceBackUpRect = 0;
for (int i = 0; i <= 19; ++i) {
delete[] _panPagesTable[i];
_panPagesTable[i] = 0;
}
}
void KyraEngine_LoK::closeFinalWsa() {
delete _finalA;
_finalA = 0;
delete _finalB;
_finalB = 0;
delete _finalC;
_finalC = 0;
freePanPages();
_endSequenceNeedLoading = 1;
}
void KyraEngine_LoK::updateKyragemFading() {
if (_flags.platform == Common::kPlatformAmiga) {
// The AMIGA version seems to have no fading for the Kyragem. The code does not
// alter the screen palette.
//
// TODO: Check this in the original.
return;
}
static const uint8 kyraGemPalette[0x28] = {
0x3F, 0x3B, 0x38, 0x34, 0x32, 0x2F, 0x2C, 0x29, 0x25, 0x22,
0x1F, 0x1C, 0x19, 0x16, 0x12, 0x0F, 0x0C, 0x0A, 0x06, 0x03,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
};
if (_system->getMillis() < _kyragemFadingState.timerCount)
return;
_kyragemFadingState.timerCount = _system->getMillis() + 4 * _tickLength;
int palPos = 684;
for (int i = 0; i < 20; ++i) {
_screen->getPalette(0)[palPos++] = kyraGemPalette[i + _kyragemFadingState.rOffset];
_screen->getPalette(0)[palPos++] = kyraGemPalette[i + _kyragemFadingState.gOffset];
_screen->getPalette(0)[palPos++] = kyraGemPalette[i + _kyragemFadingState.bOffset];
}
_screen->setScreenPalette(_screen->getPalette(0));
switch (_kyragemFadingState.nextOperation) {
case 0:
--_kyragemFadingState.bOffset;
if (_kyragemFadingState.bOffset >= 1)
return;
_kyragemFadingState.nextOperation = 1;
break;
case 1:
++_kyragemFadingState.rOffset;
if (_kyragemFadingState.rOffset < 19)
return;
_kyragemFadingState.nextOperation = 2;
break;
case 2:
--_kyragemFadingState.gOffset;
if (_kyragemFadingState.gOffset >= 1)
return;
_kyragemFadingState.nextOperation = 3;
break;
case 3:
++_kyragemFadingState.bOffset;
if (_kyragemFadingState.bOffset < 19)
return;
_kyragemFadingState.nextOperation = 4;
break;
case 4:
--_kyragemFadingState.rOffset;
if (_kyragemFadingState.rOffset >= 1)
return;
_kyragemFadingState.nextOperation = 5;
break;
case 5:
++_kyragemFadingState.gOffset;
if (_kyragemFadingState.gOffset < 19)
return;
_kyragemFadingState.nextOperation = 0;
break;
default:
break;
}
_kyragemFadingState.timerCount = _system->getMillis() + 120 * _tickLength;
}
void KyraEngine_LoK::drawJewelPress(int jewel, int drawSpecial) {
_screen->hideMouse();
int shape = 0;
if (drawSpecial)
shape = 0x14E;
else
shape = jewel + 0x149;
snd_playSoundEffect(0x45);
_screen->drawShape(0, _shapes[shape], _amuletX2[jewel], _amuletY2[jewel], 0, 0);
_screen->updateScreen();
delayWithTicks(2);
if (drawSpecial)
shape = 0x148;
else
shape = jewel + 0x143;
_screen->drawShape(0, _shapes[shape], _amuletX2[jewel], _amuletY2[jewel], 0, 0);
_screen->updateScreen();
_screen->showMouse();
}
void KyraEngine_LoK::drawJewelsFadeOutStart() {
static const uint16 jewelTable1[] = { 0x164, 0x15F, 0x15A, 0x155, 0x150, 0xFFFF };
static const uint16 jewelTable2[] = { 0x163, 0x15E, 0x159, 0x154, 0x14F, 0xFFFF };
static const uint16 jewelTable3[] = { 0x166, 0x160, 0x15C, 0x157, 0x152, 0xFFFF };
static const uint16 jewelTable4[] = { 0x165, 0x161, 0x15B, 0x156, 0x151, 0xFFFF };
for (int i = 0; jewelTable1[i] != 0xFFFF; ++i) {
if (queryGameFlag(0x57))
_screen->drawShape(0, _shapes[jewelTable1[i]], _amuletX2[2], _amuletY2[2], 0, 0);
if (queryGameFlag(0x59))
_screen->drawShape(0, _shapes[jewelTable3[i]], _amuletX2[4], _amuletY2[4], 0, 0);
if (queryGameFlag(0x56))
_screen->drawShape(0, _shapes[jewelTable2[i]], _amuletX2[1], _amuletY2[1], 0, 0);
if (queryGameFlag(0x58))
_screen->drawShape(0, _shapes[jewelTable4[i]], _amuletX2[3], _amuletY2[3], 0, 0);
_screen->updateScreen();
delayWithTicks(3);
}
}
void KyraEngine_LoK::drawJewelsFadeOutEnd(int jewel) {
static const uint16 jewelTable[] = { 0x153, 0x158, 0x15D, 0x162, 0x148, 0xFFFF };
int newDelay = 0;
switch (jewel - 1) {
case 2:
if (_currentCharacter->sceneId >= 109 && _currentCharacter->sceneId <= 198)
newDelay = 18900;
else
newDelay = 8100;
break;
default:
newDelay = 3600;
}
setGameFlag(0xF1);
_timer->setCountdown(19, newDelay);
_screen->hideMouse();
for (int i = 0; jewelTable[i] != 0xFFFF; ++i) {
uint16 shape = jewelTable[i];
if (queryGameFlag(0x57))
_screen->drawShape(0, _shapes[shape], _amuletX2[2], _amuletY2[2], 0, 0);
if (queryGameFlag(0x59))
_screen->drawShape(0, _shapes[shape], _amuletX2[4], _amuletY2[4], 0, 0);
if (queryGameFlag(0x56))
_screen->drawShape(0, _shapes[shape], _amuletX2[1], _amuletY2[1], 0, 0);
if (queryGameFlag(0x58))
_screen->drawShape(0, _shapes[shape], _amuletX2[3], _amuletY2[3], 0, 0);
_screen->updateScreen();
delayWithTicks(3);
}
_screen->showMouse();
}
} // End of namespace Kyra
|
/*
* This file is part of the coreboot project.
*
* Copyright (C) 2012 The ChromiumOS Authors. 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; version 2 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* 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.
*/
#include <arch/io.h>
#include <arch/acpi.h>
#include <console/console.h>
#include <device/device.h>
#include <device/pci.h>
#include <device/pci_ops.h>
#include <stdint.h>
#include <string.h>
#include <elog.h>
#include "pch.h"
static void pch_log_standard_gpe(u32 gpe0_sts_reg, u32 gpe0_en_reg)
{
u32 gpe0_en = inl(get_pmbase() + gpe0_en_reg);
u32 gpe0_sts = inl(get_pmbase() + gpe0_sts_reg) & gpe0_en;
/* PME (TODO: determine wake device) */
if (gpe0_sts & (1 << 11))
elog_add_event_wake(ELOG_WAKE_SOURCE_PME, 0);
/* Internal PME (TODO: determine wake device) */
if (gpe0_sts & (1 << 13))
elog_add_event_wake(ELOG_WAKE_SOURCE_PME_INTERNAL, 0);
/* SMBUS Wake */
if (gpe0_sts & (1 << 7))
elog_add_event_wake(ELOG_WAKE_SOURCE_SMBUS, 0);
}
static void pch_log_gpio_gpe(u32 gpe0_sts_reg, u32 gpe0_en_reg, int start)
{
/* GPE Bank 1 is GPIO 0-31 */
u32 gpe0_en = inl(get_pmbase() + gpe0_en_reg);
u32 gpe0_sts = inl(get_pmbase() + gpe0_sts_reg) & gpe0_en;
int i;
for (i = 0; i <= 31; i++) {
if (gpe0_sts & (1 << i))
elog_add_event_wake(ELOG_WAKE_SOURCE_GPIO, i + start);
}
}
static void pch_log_gpe(void)
{
int i;
u16 pmbase = get_pmbase();
u32 gpe0_sts, gpe0_en;
int gpe0_high_gpios[] = {
[0] = 27,
[24] = 17,
[25] = 19,
[26] = 21,
[27] = 22,
[28] = 43,
[29] = 56,
[30] = 57,
[31] = 60
};
pch_log_standard_gpe(GPE0_EN, GPE0_STS);
/* GPIO 0-15 */
gpe0_en = inw(pmbase + GPE0_EN + 2);
gpe0_sts = inw(pmbase + GPE0_STS + 2) & gpe0_en;
for (i = 0; i <= 15; i++) {
if (gpe0_sts & (1 << i))
elog_add_event_wake(ELOG_WAKE_SOURCE_GPIO, i);
}
/*
* Now check and log upper status bits
*/
gpe0_en = inl(pmbase + GPE0_EN_2);
gpe0_sts = inl(pmbase + GPE0_STS_2) & gpe0_en;
for (i = 0; i <= 31; i++) {
if (!gpe0_high_gpios[i])
continue;
if (gpe0_sts & (1 << i))
elog_add_event_wake(ELOG_WAKE_SOURCE_GPIO,
gpe0_high_gpios[i]);
}
}
static void pch_lp_log_gpe(void)
{
/* Standard GPE are in GPE set 4 */
pch_log_standard_gpe(LP_GPE0_STS_4, LP_GPE0_EN_4);
/* Log GPIO events in set 1-3 */
pch_log_gpio_gpe(LP_GPE0_STS_1, LP_GPE0_EN_1, 0);
pch_log_gpio_gpe(LP_GPE0_STS_2, LP_GPE0_EN_2, 32);
pch_log_gpio_gpe(LP_GPE0_STS_3, LP_GPE0_EN_3, 64);
}
void pch_log_state(void)
{
u16 pm1_sts, gen_pmcon_3, tco2_sts;
u8 gen_pmcon_2;
struct device *lpc = dev_find_slot(0, PCI_DEVFN(0x1f, 0));
if (!lpc)
return;
pm1_sts = inw(get_pmbase() + PM1_STS);
tco2_sts = inw(get_pmbase() + TCO2_STS);
gen_pmcon_2 = pci_read_config8(lpc, GEN_PMCON_2);
gen_pmcon_3 = pci_read_config16(lpc, GEN_PMCON_3);
/* PWR_FLR Power Failure */
if (gen_pmcon_2 & (1 << 0))
elog_add_event(ELOG_TYPE_POWER_FAIL);
/* SUS Well Power Failure */
if (gen_pmcon_3 & (1 << 14))
elog_add_event(ELOG_TYPE_SUS_POWER_FAIL);
/* SYS_PWROK Failure */
if (gen_pmcon_2 & (1 << 1))
elog_add_event(ELOG_TYPE_SYS_PWROK_FAIL);
/* PWROK Failure */
if (gen_pmcon_2 & (1 << 0))
elog_add_event(ELOG_TYPE_PWROK_FAIL);
/* Second TCO Timeout */
if (tco2_sts & (1 << 1))
elog_add_event(ELOG_TYPE_TCO_RESET);
/* Power Button Override */
if (pm1_sts & (1 << 11))
elog_add_event(ELOG_TYPE_POWER_BUTTON_OVERRIDE);
/* System Reset Status (reset button pushed) */
if (gen_pmcon_2 & (1 << 4))
elog_add_event(ELOG_TYPE_RESET_BUTTON);
/* General Reset Status */
if (gen_pmcon_3 & (1 << 9))
elog_add_event(ELOG_TYPE_SYSTEM_RESET);
/* ACPI Wake */
if (pm1_sts & (1 << 15))
elog_add_event_byte(ELOG_TYPE_ACPI_WAKE,
acpi_is_wakeup_s3() ? 3 : 5);
/*
* Wake sources
*/
/* Power Button */
if (pm1_sts & (1 << 8))
elog_add_event_wake(ELOG_WAKE_SOURCE_PWRBTN, 0);
/* RTC */
if (pm1_sts & (1 << 10))
elog_add_event_wake(ELOG_WAKE_SOURCE_RTC, 0);
/* PCI Express (TODO: determine wake device) */
if (pm1_sts & (1 << 14))
elog_add_event_wake(ELOG_WAKE_SOURCE_PCIE, 0);
/* GPE */
if (pch_is_lp())
pch_lp_log_gpe();
else
pch_log_gpe();
}
|
#!/bin/bash
set -e
# This script is used to parse VCF data for a specific study
# The script requires 1 parameter: the params file to be used
# If the parameter is not given, the user is expected to set
# the parameters from the params file himself.
if [ $# -ge 1 ]
then
source $1
fi
# DATA_LOCATION can be set to the root directory to search the VCF_FILE
# and SUBJECT_SAMPLE_MAPPING_FILE in. If not set, the files must be specified
# as absolute paths
if [ -z "$DATA_LOCATION" ]; then
DATA_LOCATION=""
fi
DIR=`dirname $0`
# Make sure the output directory exists
mkdir -p "$VCF_TEMP_DIR"
perl $DIR/parseVCFintoTextFiles.pl "$DATA_LOCATION/$VCF_FILE" "$VCF_TEMP_DIR" "$DATASOURCE" \
"$DATASET_ID" "$GPL_ID" "$GENOME_BUILD" "$ETL_USER"
perl $DIR/convertMappingIntoSQLFiles.pl "$DATA_LOCATION/$SUBJECT_SAMPLE_MAPPING_FILE" "$VCF_TEMP_DIR" \
"$STUDY_ID" "$DATASET_ID" "$CONCEPT_PATH"
|
// SuperTuxKart - a fun racing game with go-kart
//
// Copyright (C) 2013-2015 Lionel Fuentes
//
// 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, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#include "crash_reporting.hpp"
#include "log.hpp"
#include <string.h>
#if defined(WIN32) && !defined(DEBUG) && !defined(__MINGW32__)
// --------------------- Windows version -----------------
#include <Windows.h>
#include <DbgHelp.h>
#include <stdlib.h>
#include <signal.h>
#include <new.h>
typedef BOOL (__stdcall *tSymCleanup)(
_In_ HANDLE hProcess
);
typedef PVOID (__stdcall *tSymFunctionTableAccess64)(
_In_ HANDLE hProcess,
_In_ DWORD64 AddrBase
);
typedef BOOL (__stdcall *tSymGetLineFromAddr64)(
_In_ HANDLE hProcess,
_In_ DWORD64 qwAddr,
_Out_ PDWORD pdwDisplacement,
_Out_ PIMAGEHLP_LINE64 Line64
);
typedef DWORD64 (__stdcall *tSymGetModuleBase64)(
_In_ HANDLE hProcess,
_In_ DWORD64 qwAddr
);
typedef BOOL (__stdcall *tSymGetSymFromAddr64)(
_In_ HANDLE hProcess,
_In_ DWORD64 qwAddr,
_Out_opt_ PDWORD64 pdwDisplacement,
_Inout_ PIMAGEHLP_SYMBOL64 Symbol
);
typedef BOOL (__stdcall *tSymInitialize)(
_In_ HANDLE hProcess,
_In_opt_ PCSTR UserSearchPath,
_In_ BOOL fInvadeProcess
);
typedef DWORD (__stdcall *tSymSetOptions)(
_In_ DWORD SymOptions
);
typedef BOOL (__stdcall *tStackWalk64)(
_In_ DWORD MachineType,
_In_ HANDLE hProcess,
_In_ HANDLE hThread,
_Inout_ LPSTACKFRAME64 StackFrame,
_Inout_ PVOID ContextRecord,
_In_opt_ PREAD_PROCESS_MEMORY_ROUTINE64 ReadMemoryRoutine,
_In_opt_ PFUNCTION_TABLE_ACCESS_ROUTINE64 FunctionTableAccessRoutine,
_In_opt_ PGET_MODULE_BASE_ROUTINE64 GetModuleBaseRoutine,
_In_opt_ PTRANSLATE_ADDRESS_ROUTINE64 TranslateAddress
);
typedef DWORD (__stdcall *tUnDecorateSymbolName)(
_In_ PCSTR name,
_Out_ PSTR outputString,
_In_ DWORD maxStringLength,
_In_ DWORD flags
);
namespace CrashReporting
{
void getCallStackWithContext(std::string& callstack, PCONTEXT pContext);
void winCrashHandler(PCONTEXT pContext=NULL)
{
std::string callstack;
if(pContext)
getCallStackWithContext(callstack, pContext);
else
getCallStack(callstack);
std::string msg = "SuperTuxKart crashed!\n"
"Please hit Ctrl+C to copy to clipboard and signal the problem\n"
"to the developers on our forum: http://forum.freegamedev.net/viewforum.php?f=16\n"
"\n"
"Call stack:\n";
msg += callstack;
MessageBoxA(NULL, msg.c_str(), "SuperTuxKart crashed :/", MB_OK);
}
LONG WINAPI sehHandler(_In_ struct _EXCEPTION_POINTERS *ExceptionInfo)
{
winCrashHandler(ExceptionInfo->ContextRecord);
return EXCEPTION_EXECUTE_HANDLER;
}
void pureCallHandler()
{
winCrashHandler();
}
int newHandler( size_t )
{
winCrashHandler();
return 0;
}
void invalidParameterHandler(const wchar_t *, const wchar_t *, const wchar_t *, unsigned int, uintptr_t)
{
winCrashHandler();
}
void signalHandler(int code)
{
winCrashHandler();
}
void installHandlers()
{
// ----- Per-process handlers -----
SetUnhandledExceptionFilter(sehHandler); // Top-level SEH handler
_set_purecall_handler(pureCallHandler); // Pure virtual function calls handler
// Catch new operator memory allocation exceptions
_set_new_mode(1); // Force malloc() to call new handler too
_set_new_handler(newHandler);
_set_invalid_parameter_handler(invalidParameterHandler); // Catch invalid parameter exceptions.
//_set_security_error_handler(securityHandler); // Catch buffer overrun exceptions
signal(SIGABRT, signalHandler);
signal(SIGINT, signalHandler);
signal(SIGTERM, signalHandler);
// ----- Per-thread handlers -----
// TODO
}
void getCallStackWithContext(std::string& callstack, PCONTEXT pContext)
{
HINSTANCE hImageHlpDll = LoadLibraryA("imagehlp.dll");
if(!hImageHlpDll)
{
Log::warn("CrashReporting", "Failed to load DLL imagehlp.dll");
callstack = "Crash reporting failed to load DLL imagehlp.dll";
return;
}
// Retrieve the DLL functions
#define GET_FUNC_PTR(FuncName) \
t##FuncName _##FuncName = (t##FuncName)GetProcAddress(hImageHlpDll, #FuncName); \
if(!_##FuncName) { \
Log::warn("CrashReporting", "Failed to import symbol " #FuncName " from imagehlp.dll"); \
FreeLibrary(hImageHlpDll); \
return; \
}
GET_FUNC_PTR(SymCleanup )
GET_FUNC_PTR(SymFunctionTableAccess64 )
GET_FUNC_PTR(SymGetLineFromAddr64 )
GET_FUNC_PTR(SymGetModuleBase64 )
GET_FUNC_PTR(SymGetSymFromAddr64 )
GET_FUNC_PTR(SymInitialize )
GET_FUNC_PTR(SymSetOptions )
GET_FUNC_PTR(StackWalk64 )
GET_FUNC_PTR(UnDecorateSymbolName )
#undef GET_FUNC_PTR
const HANDLE hProcess = GetCurrentProcess();
const HANDLE hThread = GetCurrentThread();
// Initialize the symbol hander for the process
{
// Get the file path of the executable
char filepath[512];
GetModuleFileNameA(NULL, filepath, sizeof(filepath));
if(!filepath)
{
Log::warn("CrashReporting", "GetModuleFileNameA failed");
FreeLibrary(hImageHlpDll);
return;
}
// Only keep the directory
char* last_separator = strchr(filepath, '/');
if(!last_separator) last_separator = strchr(filepath, '\\');
if(last_separator)
last_separator[0] = '\0';
// Since the stack trace can also be used for leak checks, don't
// initialise this all the time.
static bool first_time = true;
if (first_time)
{
// Finally initialize the symbol handler.
BOOL bOk = _SymInitialize(hProcess, filepath ? filepath : NULL, TRUE);
if (!bOk)
{
Log::warn("CrashReporting", "SymInitialize() failed");
FreeLibrary(hImageHlpDll);
return;
}
_SymSetOptions(SYMOPT_LOAD_LINES);
first_time = false;
}
}
// Get the stack trace
{
// Initialize the IMAGEHLP_SYMBOL64 structure
const size_t MaxNameLength = 256;
IMAGEHLP_SYMBOL64* sym = (IMAGEHLP_SYMBOL64*)_malloca(sizeof(IMAGEHLP_SYMBOL64) + MaxNameLength);
sym->SizeOfStruct = sizeof(IMAGEHLP_SYMBOL64);
sym->MaxNameLength = MaxNameLength;
// Initialize the STACKFRAME structure so that it
// corresponds to the current function call
STACKFRAME64 stackframe;
memset(&stackframe, 0, sizeof(stackframe));
stackframe.AddrPC.Offset = pContext->Eip;
stackframe.AddrPC.Mode = AddrModeFlat;
stackframe.AddrStack.Offset = pContext->Esp;
stackframe.AddrStack.Mode = AddrModeFlat;
stackframe.AddrFrame.Offset = pContext->Ebp;
stackframe.AddrFrame.Mode = AddrModeFlat;
const DWORD machine_type = IMAGE_FILE_MACHINE_I386;
// Walk the stack
const int max_nb_calls = 32;
for(int i=0 ; i < max_nb_calls ; i++)
{
const BOOL stackframe_ok = _StackWalk64( machine_type,
hProcess,
hThread,
&stackframe,
pContext,
NULL,
_SymFunctionTableAccess64,
_SymGetModuleBase64,
NULL);
if(stackframe_ok)
{
// Decode the symbol and add it to the call stack
DWORD64 sym_displacement;
if(_SymGetSymFromAddr64( hProcess,
stackframe.AddrPC.Offset,
&sym_displacement,
sym))
{
IMAGEHLP_LINE64 line64;
DWORD dwDisplacement = (DWORD)sym_displacement;
if(_SymGetLineFromAddr64(hProcess, stackframe.AddrPC.Offset, &dwDisplacement, &line64))
{
callstack += "\n ";
// Directory + filename -> filename only
const char* filename = line64.FileName;
const char* ptr = line64.FileName;
while(*ptr)
{
if(*ptr == '\\' || *ptr == '/')
filename = ptr+1;
ptr++;
}
callstack += filename;
callstack += ":";
callstack += sym->Name;
char str[128];
_itoa(line64.LineNumber, str, 10);
callstack += ":";
callstack += str;
}
else
{
callstack += "\n ";
callstack += sym->Name;
}
}
else
callstack += "\n <no symbol available>";
}
else
break; // done
}
}
FreeLibrary(hImageHlpDll);
}
void getCallStack(std::string& callstack)
{
// Get the current CONTEXT
// NB: this code is ONLY VALID FOR X86 (32 bit)!
CONTEXT ctx;
memset(&ctx, '\0', sizeof(ctx));
ctx.ContextFlags = CONTEXT_FULL;
__asm call x
__asm x: pop eax // get eip (can't directly use mov)
__asm mov ctx.Eip, eax
__asm mov ctx.Ebp, ebp
__asm mov ctx.Esp, esp
getCallStackWithContext(callstack, &ctx);
}
} // end namespace CrashReporting
#else
// --------------------- Unix version -----------------------
namespace CrashReporting
{
void installHandlers()
{
// TODO!
}
void getCallStack(std::string& callstack)
{
// TODO!
}
} // end namespace CrashReporting
#endif
|
package net.minecraft.util;
import net.minecraft.nbt.NBTTagCompound;
public class WeightedSpawnerEntity extends WeightedRandom.Item
{
private final NBTTagCompound nbt;
public WeightedSpawnerEntity()
{
super(1);
this.nbt = new NBTTagCompound();
this.nbt.setString("id", "Pig");
}
public WeightedSpawnerEntity(NBTTagCompound nbtIn)
{
this(nbtIn.hasKey("Weight", 99) ? nbtIn.getInteger("Weight") : 1, nbtIn.getCompoundTag("Entity"));
}
public WeightedSpawnerEntity(int itemWeightIn, NBTTagCompound nbtIn)
{
super(itemWeightIn);
this.nbt = nbtIn;
}
public NBTTagCompound toCompoundTag()
{
NBTTagCompound nbttagcompound = new NBTTagCompound();
nbttagcompound.setTag("Entity", this.nbt);
nbttagcompound.setInteger("Weight", this.itemWeight);
return nbttagcompound;
}
public NBTTagCompound getNbt()
{
return this.nbt;
}
} |
/* Copyright 2008 (C) Nicira, Inc.
*
* This file is part of NOX.
*
* NOX 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.
*
* NOX 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 NOX. If not, see <http://www.gnu.org/licenses/>.
*/
/*
*/
#include "user_event_log_proxy.hh"
#include "threads/cooperative.hh"
#include "pyrt/pycontext.hh"
#include "swigpyrun.h"
#include "vlog.hh"
#include "pyrt/pyglue.hh"
using namespace std;
using namespace vigil;
using namespace vigil::applications;
namespace {
Vlog_module lg("user_event_log_proxy");
}
namespace vigil {
namespace applications {
/*
* Get a pointer to the runtime context so we can resolve
* user_event_log at configure time.
*/
user_event_log_proxy::user_event_log_proxy(PyObject* ctxt) : uel(0)
{
if (!SWIG_Python_GetSwigThis(ctxt) || !SWIG_Python_GetSwigThis(ctxt)->ptr) {
throw runtime_error("Unable to access Python context.");
}
c = ((PyContext*)SWIG_Python_GetSwigThis(ctxt)->ptr)->c;
}
void user_event_log_proxy::log_simple(const string &app_name, int level,
const string &msg){
uel->log_simple(app_name, (LogEntry::Level) level, msg);
}
void user_event_log_proxy::log(const LogEntry &entry){
uel->log(entry);
}
int user_event_log_proxy::get_max_logid() {
return uel->get_max_logid();
}
int user_event_log_proxy::get_min_logid() {
return uel->get_min_logid();
}
void user_event_log_proxy::set_max_num_entries(int num) {
uel->set_max_num_entries(num);
}
void user_event_log_proxy::python_callback(PyObject *args,
boost::intrusive_ptr<PyObject> cb) {
Co_critical_section c;
PyObject* ret = PyObject_CallObject(cb.get(), args);
if (ret == 0) {
const string exc = pretty_print_python_exception();
lg.err("Python callback invocation failed:\n%s", exc.c_str());
}
Py_DECREF(args);
Py_XDECREF(ret);
}
PyObject *user_event_log_proxy::get_log_entry(int logid, PyObject *cb){
try {
if (!cb || !PyCallable_Check(cb)) { throw "Invalid callback"; }
boost::intrusive_ptr<PyObject> cptr(cb, true);
Log_entry_callback f = boost::bind(
&user_event_log_proxy::get_log_callback,this,_1,_2,_3,_4,_5,_6,_7,cptr);
uel->get_log_entry((int64_t)logid, f);
Py_RETURN_NONE;
}
catch (const char* msg) {
/* Unable to convert the arguments. */
PyErr_SetString(PyExc_TypeError, msg);
return 0;
}
}
void user_event_log_proxy::get_log_callback(int64_t logid, int64_t ts,
const string &app,
int level, const string &msg, const PrincipalList &src_names,
const PrincipalList &dst_names, boost::intrusive_ptr<PyObject> cb) {
Co_critical_section c;
PyObject* args = PyTuple_New(7);
PyTuple_SetItem(args, 0, PyInt_FromLong(logid));
PyTuple_SetItem(args, 1, PyLong_FromLong(ts));
PyTuple_SetItem(args, 2, PyString_FromString(app.c_str()));
PyTuple_SetItem(args, 3, PyInt_FromLong(level));
PyTuple_SetItem(args, 4, PyString_FromString(msg.c_str()));
PyTuple_SetItem(args, 5, to_python_list(src_names));
PyTuple_SetItem(args, 6, to_python_list(dst_names));
python_callback(args,cb);
}
PyObject * user_event_log_proxy::get_logids_for_name(int64_t id,
int64_t type, PyObject* cb) {
try {
if (!cb || !PyCallable_Check(cb)) { throw "Invalid callback"; }
boost::intrusive_ptr<PyObject> cptr(cb, true);
Get_logids_callback f = boost::bind(
&user_event_log_proxy::get_logids_callback,this,_1,cptr);
uel->get_logids_for_name(id, (PrincipalType) type,f);
Py_RETURN_NONE;
}
catch (const char* msg) {
/* Unable to convert the arguments. */
PyErr_SetString(PyExc_TypeError, msg);
return 0;
}
}
void user_event_log_proxy::get_logids_callback(const list<int64_t> &logids,
boost::intrusive_ptr<PyObject> cb) {
Co_critical_section c;
PyObject* logid_tuple = PyTuple_New(logids.size());
list<int64_t>::const_iterator it = logids.begin();
int i = 0;
for( ; it != logids.end(); ++it) {
PyTuple_SetItem(logid_tuple, i, PyLong_FromLong(*it));
++i;
}
PyObject* args = PyTuple_New(1);
PyTuple_SetItem(args,0,logid_tuple);
python_callback(args,cb);
}
PyObject *user_event_log_proxy::clear(PyObject *cb){
try {
if (!cb || !PyCallable_Check(cb)) { throw "Invalid callback"; }
boost::intrusive_ptr<PyObject> cptr(cb, true);
Clear_log_callback f = boost::bind(
&user_event_log_proxy::clear_callback,this,_1, cptr);
uel->clear(f);
Py_RETURN_NONE;
}
catch (const char* msg) {
/* Unable to convert the arguments. */
PyErr_SetString(PyExc_TypeError, msg);
return 0;
}
}
PyObject *user_event_log_proxy::remove(int max_logid, PyObject *cb){
try {
if (!cb || !PyCallable_Check(cb)) { throw "Invalid callback"; }
boost::intrusive_ptr<PyObject> cptr(cb, true);
Clear_log_callback f = boost::bind(
&user_event_log_proxy::clear_callback,this,_1,cptr);
uel->remove(max_logid, f);
Py_RETURN_NONE;
}
catch (const char* msg) {
/* Unable to convert the arguments. */
PyErr_SetString(PyExc_TypeError, msg);
return 0;
}
}
void user_event_log_proxy::clear_callback(const storage::Result &r,
boost::intrusive_ptr<PyObject> cb){
PyObject* args = PyTuple_New(0);
python_callback(args,cb);
}
void
user_event_log_proxy::configure(PyObject* configuration)
{
c->resolve(uel);
}
void
user_event_log_proxy::install(PyObject*)
{
}
} // namespace applications
} // namespace vigil
|
var toArray = require('./toArray');
var find = require('../array/find');
/**
* Return first non void argument
*/
function defaults(var_args){
return find(toArray(arguments), nonVoid);
}
function nonVoid(val){
return val != null;
}
module.exports = defaults;
|
<?php
/*
* Copyright (c) 2011-2015 Lp digital system
*
* This file is part of BackBee.
*
* BackBee 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.
*
* BackBee 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 BackBee. If not, see <http://www.gnu.org/licenses/>.
*
* @author Charles Rouillon <charles.rouillon@lp-digital.fr>
*/
namespace BackBee\Util;
use Symfony\Component\HttpFoundation\File\MimeType\MimeTypeGuesser;
/**
* @category BackBee
*
* @copyright Lp digital system
* @author c.rouillon <charles.rouillon@lp-digital.fr>
*/
class MimeType
{
/**
* The singleton instance.
*
* @var MimeTypeGuesser
*/
private static $instance = null;
private static $guesser = null;
private function __construct()
{
self::$guesser = MimeTypeGuesser::getInstance();
self::$guesser->register(new ExtensionMimeTypeGuesser());
}
public static function getInstance()
{
if (null === self::$instance) {
self::$instance = new self();
}
return self::$instance;
}
/**
* @codeCoverageIgnore
*
* @param type $path
*
* @return type
*/
public function guess($path)
{
return self::$guesser->guess($path);
}
}
|
YUI.add('moodle-core-blocks', function (Y, NAME) {
/**
* Provides drag and drop functionality for blocks.
*
* @module moodle-core-blockdraganddrop
*/
var AJAXURL = '/lib/ajax/blocks.php',
CSS = {
BLOCK : 'block',
BLOCKREGION : 'block-region',
BLOCKADMINBLOCK : 'block_adminblock',
EDITINGMOVE : 'editing_move',
HEADER : 'header',
LIGHTBOX : 'lightbox',
REGIONCONTENT : 'region-content',
SKIPBLOCK : 'skip-block',
SKIPBLOCKTO : 'skip-block-to',
MYINDEX : 'page-my-index',
REGIONMAIN : 'region-main'
};
/**
* Legacy drag and drop manager.
* This drag and drop manager is specifically designed for themes using side-pre and side-post
* that do not make use of the block output methods introduced by MDL-39824.
*
* @namespace M.core.blockdraganddrop
* @class LegacyManager
* @constructor
* @extends M.core.dragdrop
*/
var DRAGBLOCK = function() {
DRAGBLOCK.superclass.constructor.apply(this, arguments);
};
Y.extend(DRAGBLOCK, M.core.dragdrop, {
skipnodetop : null,
skipnodebottom : null,
dragsourceregion : null,
initializer : function() {
// Set group for parent class
this.groups = ['block'];
this.samenodeclass = CSS.BLOCK;
this.parentnodeclass = CSS.REGIONCONTENT;
// Add relevant classes and ID to 'content' block region on My Home page.
var myhomecontent = Y.Node.all('body#'+CSS.MYINDEX+' #'+CSS.REGIONMAIN+' > .'+CSS.REGIONCONTENT);
if (myhomecontent.size() > 0) {
var contentregion = myhomecontent.item(0);
contentregion.addClass(CSS.BLOCKREGION);
contentregion.set('id', CSS.REGIONCONTENT);
contentregion.one('div').addClass(CSS.REGIONCONTENT);
}
// Initialise blocks dragging
// Find all block regions on the page
var blockregionlist = Y.Node.all('div.'+CSS.BLOCKREGION);
if (blockregionlist.size() === 0) {
return false;
}
// See if we are missing either of block regions,
// if yes we need to add an empty one to use as target
if (blockregionlist.size() !== this.get('regions').length) {
var blockregion = Y.Node.create('<div></div>')
.addClass(CSS.BLOCKREGION);
var regioncontent = Y.Node.create('<div></div>')
.addClass(CSS.REGIONCONTENT);
blockregion.appendChild(regioncontent);
var pre = blockregionlist.filter('#region-pre');
var post = blockregionlist.filter('#region-post');
if (pre.size() === 0 && post.size() === 1) {
// pre block is missing, instert it before post
blockregion.setAttrs({id : 'region-pre'});
post.item(0).insert(blockregion, 'before');
blockregionlist.unshift(blockregion);
} else if (post.size() === 0 && pre.size() === 1) {
// post block is missing, instert it after pre
blockregion.setAttrs({id : 'region-post'});
pre.item(0).insert(blockregion, 'after');
blockregionlist.push(blockregion);
}
}
blockregionlist.each(function(blockregionnode) {
// Setting blockregion as droptarget (the case when it is empty)
// The region-post (the right one)
// is very narrow, so add extra padding on the left to drop block on it.
new Y.DD.Drop({
node: blockregionnode.one('div.'+CSS.REGIONCONTENT),
groups: this.groups,
padding: '40 240 40 240'
});
// Make each div element in the list of blocks draggable
var del = new Y.DD.Delegate({
container: blockregionnode,
nodes: '.'+CSS.BLOCK,
target: true,
handles: ['.'+CSS.HEADER],
invalid: '.block-hider-hide, .block-hider-show, .moveto',
dragConfig: {groups: this.groups}
});
del.dd.plug(Y.Plugin.DDProxy, {
// Don't move the node at the end of the drag
moveOnEnd: false
});
del.dd.plug(Y.Plugin.DDWinScroll);
var blocklist = blockregionnode.all('.'+CSS.BLOCK);
blocklist.each(function(blocknode) {
var move = blocknode.one('a.'+CSS.EDITINGMOVE);
if (move) {
move.remove();
blocknode.one('.'+CSS.HEADER).setStyle('cursor', 'move');
}
}, this);
}, this);
},
get_block_id : function(node) {
return Number(node.get('id').replace(/inst/i, ''));
},
get_block_region : function(node) {
var region = node.ancestor('div.'+CSS.BLOCKREGION).get('id').replace(/region-/i, '');
if (Y.Array.indexOf(this.get('regions'), region) === -1) {
// Must be standard side-X
if (right_to_left()) {
if (region === 'post') {
region = 'pre';
} else if (region === 'pre') {
region = 'post';
}
}
return 'side-' + region;
}
// Perhaps custom region
return region;
},
get_region_id : function(node) {
return node.get('id').replace(/region-/i, '');
},
drag_start : function(e) {
// Get our drag object
var drag = e.target;
// Store the parent node of original drag node (block)
// we will need it later for show/hide empty regions
this.dragsourceregion = drag.get('node').ancestor('div.'+CSS.BLOCKREGION);
// Determine skipnodes and store them
if (drag.get('node').previous() && drag.get('node').previous().hasClass(CSS.SKIPBLOCK)) {
this.skipnodetop = drag.get('node').previous();
}
if (drag.get('node').next() && drag.get('node').next().hasClass(CSS.SKIPBLOCKTO)) {
this.skipnodebottom = drag.get('node').next();
}
},
drop_over : function(e) {
// Get a reference to our drag and drop nodes
var drag = e.drag.get('node');
var drop = e.drop.get('node');
// We need to fix the case when parent drop over event has determined
// 'goingup' and appended the drag node after admin-block.
if (drop.hasClass(this.parentnodeclass) && drop.one('.'+CSS.BLOCKADMINBLOCK) && drop.one('.'+CSS.BLOCKADMINBLOCK).next('.'+CSS.BLOCK)) {
drop.prepend(drag);
}
// Block is moved within the same region
// stop here, no need to modify anything.
if (this.dragsourceregion.contains(drop)) {
return false;
}
// TODO: Hiding-displaying block region only works for base theme blocks
// (region-pre, region-post) at the moment. It should be improved
// to work with custom block regions as well.
// TODO: Fix this for the case when user drag block towards empty section,
// then the section appears, then user chnages his mind and moving back to
// original section. The opposite section remains opened and empty.
var documentbody = Y.one('body');
// Moving block towards hidden region-content, display it
var regionname = this.get_region_id(this.dragsourceregion);
if (documentbody.hasClass('side-'+regionname+'-only')) {
documentbody.removeClass('side-'+regionname+'-only');
}
// Moving from empty region-content towards the opposite one,
// hide empty one (only for region-pre, region-post areas at the moment).
regionname = this.get_region_id(drop.ancestor('div.'+CSS.BLOCKREGION));
if (this.dragsourceregion.all('.'+CSS.BLOCK).size() === 0 && this.dragsourceregion.get('id').match(/(region-pre|region-post)/i)) {
if (!documentbody.hasClass('side-'+regionname+'-only')) {
documentbody.addClass('side-'+regionname+'-only');
}
}
},
drop_end : function() {
// clear variables
this.skipnodetop = null;
this.skipnodebottom = null;
this.dragsourceregion = null;
},
drag_dropmiss : function(e) {
// Missed the target, but we assume the user intended to drop it
// on the last last ghost node location, e.drag and e.drop should be
// prepared by global_drag_dropmiss parent so simulate drop_hit(e).
this.drop_hit(e);
},
drop_hit : function(e) {
var drag = e.drag;
// Get a reference to our drag node
var dragnode = drag.get('node');
var dropnode = e.drop.get('node');
// Amend existing skipnodes
if (dragnode.previous() && dragnode.previous().hasClass(CSS.SKIPBLOCK)) {
// the one that belongs to block below move below
dragnode.insert(dragnode.previous(), 'after');
}
// Move original skipnodes
if (this.skipnodetop) {
dragnode.insert(this.skipnodetop, 'before');
}
if (this.skipnodebottom) {
dragnode.insert(this.skipnodebottom, 'after');
}
// Add lightbox if it not there
var lightbox = M.util.add_lightbox(Y, dragnode);
// Prepare request parameters
var params = {
sesskey : M.cfg.sesskey,
courseid : this.get('courseid'),
pagelayout : this.get('pagelayout'),
pagetype : this.get('pagetype'),
subpage : this.get('subpage'),
contextid : this.get('contextid'),
action : 'move',
bui_moveid : this.get_block_id(dragnode),
bui_newregion : this.get_block_region(dropnode)
};
if (this.get('cmid')) {
params.cmid = this.get('cmid');
}
if (dragnode.next('.'+this.samenodeclass) && !dragnode.next('.'+this.samenodeclass).hasClass(CSS.BLOCKADMINBLOCK)) {
params.bui_beforeid = this.get_block_id(dragnode.next('.'+this.samenodeclass));
}
// Do AJAX request
Y.io(M.cfg.wwwroot+AJAXURL, {
method: 'POST',
data: params,
on: {
start : function() {
lightbox.show();
},
success: function(tid, response) {
window.setTimeout(function() {
lightbox.hide();
}, 250);
try {
var responsetext = Y.JSON.parse(response.responseText);
if (responsetext.error) {
new M.core.ajaxException(responsetext);
}
} catch (e) {}
},
failure: function(tid, response) {
this.ajax_failure(response);
lightbox.hide();
}
},
context:this
});
}
}, {
NAME : 'core-blocks-dragdrop',
ATTRS : {
courseid : {
value : null
},
cmid : {
value : null
},
contextid : {
value : null
},
pagelayout : {
value : null
},
pagetype : {
value : null
},
subpage : {
value : null
},
regions : {
value : null
}
}
});
/**
* Core namespace.
* @static
* @class core
*/
M.core = M.core || {};
/**
* Block drag and drop static class.
* @namespace M.core
* @class blockdraganddrop
* @static
*/
M.core.blockdraganddrop = M.core.blockdraganddrop || {};
/**
* True if the page is using the new blocks methods.
* @private
* @static
* @property _isusingnewblocksmethod
* @type Boolean
* @default null
*/
M.core.blockdraganddrop._isusingnewblocksmethod = null;
/**
* Returns true if the page is using the new blocks methods.
* @static
* @method is_using_blocks_render_method
* @return Boolean
*/
M.core.blockdraganddrop.is_using_blocks_render_method = function() {
if (this._isusingnewblocksmethod === null) {
var goodregions = Y.all('.block-region[data-blockregion]').size();
var allregions = Y.all('.block-region').size();
this._isusingnewblocksmethod = (allregions === goodregions);
}
return this._isusingnewblocksmethod;
};
/**
* Initialises a drag and drop manager.
* This should only ever be called once for a page.
* @static
* @method init
* @param {Object} params
* @return Manager
*/
M.core.blockdraganddrop.init = function(params) {
if (this.is_using_blocks_render_method()) {
new MANAGER(params);
} else {
new DRAGBLOCK(params);
}
};
/**
* Legacy code to keep things working.
*/
M.core_blocks = M.core_blocks || {};
M.core_blocks.init_dragdrop = function(params) {
M.core.blockdraganddrop.init(params);
};
/**
* This file contains the drag and drop manager class.
*
* Provides drag and drop functionality for blocks.
*
* @module moodle-core-blockdraganddrop
*/
/**
* Constructs a new Block drag and drop manager.
*
* @namespace M.core.blockdraganddrop
* @class Manager
* @constructor
* @extends M.core.dragdrop
*/
var MANAGER = function() {
MANAGER.superclass.constructor.apply(this, arguments);
};
MANAGER.prototype = {
/**
* The skip block link from above the block being dragged while a drag is in progress.
* Required by the M.core.dragdrop from whom this class extends.
* @private
* @property skipnodetop
* @type Node
* @default null
*/
skipnodetop : null,
/**
* The skip block link from below the block being dragged while a drag is in progress.
* Required by the M.core.dragdrop from whom this class extends.
* @private
* @property skipnodebottom
* @type Node
* @default null
*/
skipnodebottom : null,
/**
* An associative object of regions and the
* @property regionobjects
* @type {Object} Primitive object mocking an associative array.
* @type {BLOCKREGION} [regionname]* Each item uses the region name as the key with the value being
* an instance of the BLOCKREGION class.
*/
regionobjects : {},
/**
* Called during the initialisation process of the object.
* @method initializer
*/
initializer : function() {
Y.log('Initialising drag and drop for blocks.', 'info');
var regionnames = this.get('regions'),
i = 0,
region,
regionname,
droptarget,
dragdelegation;
// Evil required by M.core.dragdrop.
this.groups = ['block'];
this.samenodeclass = CSS.BLOCK;
this.parentnodeclass = CSS.BLOCKREGION;
// Add relevant classes and ID to 'content' block region on My Home page.
var myhomecontent = Y.Node.all('body#'+CSS.MYINDEX+' #'+CSS.REGIONMAIN+' > .'+CSS.REGIONCONTENT);
if (myhomecontent.size() > 0) {
var contentregion = myhomecontent.item(0);
contentregion.addClass(CSS.BLOCKREGION);
contentregion.set('id', CSS.REGIONCONTENT);
contentregion.one('div').addClass(CSS.REGIONCONTENT);
}
for (i in regionnames) {
regionname = regionnames[i];
region = new BLOCKREGION({
manager : this,
region : regionname,
node : Y.one('#block-region-'+regionname)
});
this.regionobjects[regionname] = region;
// Setting blockregion as droptarget (the case when it is empty)
// The region-post (the right one)
// is very narrow, so add extra padding on the left to drop block on it.
droptarget = new Y.DD.Drop({
node: region.get_droptarget(),
groups: this.groups,
padding: '40 240 40 240'
});
// Make each div element in the list of blocks draggable
dragdelegation = new Y.DD.Delegate({
container: region.get_droptarget(),
nodes: '.'+CSS.BLOCK,
target: true,
handles: ['.'+CSS.HEADER],
invalid: '.block-hider-hide, .block-hider-show, .moveto',
dragConfig: {groups: this.groups}
});
dragdelegation.dd.plug(Y.Plugin.DDProxy, {
// Don't move the node at the end of the drag
moveOnEnd: false
});
dragdelegation.dd.plug(Y.Plugin.DDWinScroll);
// On the mouse down event we will enable all block regions so that they can be dragged to.
// This is VERY important as without it dnd won't work for empty block regions.
dragdelegation.on('drag:mouseDown', this.enable_all_regions, this);
region.remove_block_move_icons();
}
Y.log('Initialisation of drag and drop for blocks complete.', 'info');
},
/**
* Returns the ID of the block the given node represents.
* @method get_block_id
* @param {Node} node
* @returns {int} The blocks ID in the database.
*/
get_block_id : function(node) {
return Number(node.get('id').replace(/inst/i, ''));
},
/**
* Returns the block region that the node is part of or belonging to.
* @method get_block_region
* @param {Y.Node} node
* @returns {string} The region name.
*/
get_block_region : function(node) {
if (!node.test('[data-blockregion]')) {
node = node.ancestor('[data-blockregion]');
}
return node.getData('blockregion');
},
/**
* Returns the BLOCKREGION instance that represents the block region the given node is part of.
* @method get_region_object
* @param {Y.Node} node
* @returns {BLOCKREGION}
*/
get_region_object : function(node) {
return this.regionobjects[this.get_block_region(node)];
},
/**
* Enables all fo the regions so that they are all visible while dragging is occuring.
* @method enable_all_regions
* @returns {undefined}
*/
enable_all_regions : function() {
var i = 0;
for (i in this.regionobjects) {
this.regionobjects[i].enable();
}
},
/**
* Disables enabled regions if they contain no blocks.
* @method disable_regions_if_required
* @returns {undefined}
*/
disable_regions_if_required : function() {
var i = 0;
for (i in this.regionobjects) {
this.regionobjects[i].disable_if_required();
}
},
/**
* Called by M.core.dragdrop.global_drag_start when dragging starts.
* @method drag_start
* @param {Event} e
* @returns {undefined}
*/
drag_start : function(e) {
// Get our drag object
var drag = e.target;
// Store the parent node of original drag node (block)
// we will need it later for show/hide empty regions
// Determine skipnodes and store them
if (drag.get('node').previous() && drag.get('node').previous().hasClass(CSS.SKIPBLOCK)) {
this.skipnodetop = drag.get('node').previous();
}
if (drag.get('node').next() && drag.get('node').next().hasClass(CSS.SKIPBLOCKTO)) {
this.skipnodebottom = drag.get('node').next();
}
},
/**
* Called by M.core.dragdrop.global_drop_over when something is dragged over a drop target.
* @method drop_over
* @param {Event} e
* @returns {undefined}
*/
drop_over : function(e) {
// Get a reference to our drag and drop nodes
var drag = e.drag.get('node');
var drop = e.drop.get('node');
// We need to fix the case when parent drop over event has determined
// 'goingup' and appended the drag node after admin-block.
if (drop.hasClass(CSS.REGIONCONTENT) && drop.one('.'+CSS.BLOCKADMINBLOCK) && drop.one('.'+CSS.BLOCKADMINBLOCK).next('.'+CSS.BLOCK)) {
drop.prepend(drag);
}
},
/**
* Called by M.core.dragdrop.global_drop_end when a drop has been completed.
* @method drop_end
* @returns {undefined}
*/
drop_end : function() {
// Clear variables.
this.skipnodetop = null;
this.skipnodebottom = null;
this.disable_regions_if_required();
},
/**
* Called by M.core.dragdrop.global_drag_dropmiss when something has been dropped on a node that isn't contained by a drop target.
* @method drag_dropmiss
* @param {Event} e
* @returns {undefined}
*/
drag_dropmiss : function(e) {
// Missed the target, but we assume the user intended to drop it
// on the last ghost node location, e.drag and e.drop should be
// prepared by global_drag_dropmiss parent so simulate drop_hit(e).
this.drop_hit(e);
},
/**
* Called by M.core.dragdrop.global_drag_hit when something has been dropped on a drop target.
* @method drop_hit
* @param {Event} e
* @returns {undefined}
*/
drop_hit : function(e) {
// Get a reference to our drag node
var dragnode = e.drag.get('node');
var dropnode = e.drop.get('node');
// Amend existing skipnodes
if (dragnode.previous() && dragnode.previous().hasClass(CSS.SKIPBLOCK)) {
// the one that belongs to block below move below
dragnode.insert(dragnode.previous(), 'after');
}
// Move original skipnodes
if (this.skipnodetop) {
dragnode.insert(this.skipnodetop, 'before');
}
if (this.skipnodebottom) {
dragnode.insert(this.skipnodebottom, 'after');
}
// Add lightbox if it not there
var lightbox = M.util.add_lightbox(Y, dragnode);
// Prepare request parameters
var params = {
sesskey : M.cfg.sesskey,
courseid : this.get('courseid'),
pagelayout : this.get('pagelayout'),
pagetype : this.get('pagetype'),
subpage : this.get('subpage'),
contextid : this.get('contextid'),
action : 'move',
bui_moveid : this.get_block_id(dragnode),
bui_newregion : this.get_block_region(dropnode)
};
if (this.get('cmid')) {
params.cmid = this.get('cmid');
}
if (dragnode.next('.'+CSS.BLOCK) && !dragnode.next('.'+CSS.BLOCK).hasClass(CSS.BLOCKADMINBLOCK)) {
params.bui_beforeid = this.get_block_id(dragnode.next('.'+CSS.BLOCK));
}
// Do AJAX request
Y.io(M.cfg.wwwroot+AJAXURL, {
method: 'POST',
data: params,
on: {
start : function() {
lightbox.show();
},
success: function(tid, response) {
window.setTimeout(function() {
lightbox.hide();
}, 250);
try {
var responsetext = Y.JSON.parse(response.responseText);
if (responsetext.error) {
new M.core.ajaxException(responsetext);
}
} catch (e) {}
},
failure: function(tid, response) {
this.ajax_failure(response);
lightbox.hide();
},
complete : function() {
this.disable_regions_if_required();
}
},
context:this
});
}
};
Y.extend(MANAGER, M.core.dragdrop, MANAGER.prototype, {
NAME : 'core-blocks-dragdrop-manager',
ATTRS : {
/**
* The Course ID if there is one.
* @attribute courseid
* @type int|null
* @default null
*/
courseid : {
value : null
},
/**
* The Course Module ID if there is one.
* @attribute cmid
* @type int|null
* @default null
*/
cmid : {
value : null
},
/**
* The Context ID.
* @attribute contextid
* @type int|null
* @default null
*/
contextid : {
value : null
},
/**
* The current page layout.
* @attribute pagelayout
* @type string|null
* @default null
*/
pagelayout : {
value : null
},
/**
* The page type string, should be used as the id for the body tag in the theme.
* @attribute pagetype
* @type string|null
* @default null
*/
pagetype : {
value : null
},
/**
* The subpage identifier, if any.
* @attribute subpage
* @type string|null
* @default null
*/
subpage : {
value : null
},
/**
* An array of block regions that are present on the page.
* @attribute regions
* @type array|null
* @default Array[]
*/
regions : {
value : []
}
}
});/**
* This file contains the Block Region class used by the drag and drop manager.
*
* Provides drag and drop functionality for blocks.
*
* @module moodle-core-blockdraganddrop
*/
/**
* Constructs a new block region object.
*
* @namespace M.core.blockdraganddrop
* @class BlockRegion
* @constructor
* @extends Y.Base
*/
var BLOCKREGION = function() {
BLOCKREGION.superclass.constructor.apply(this, arguments);
};
BLOCKREGION.prototype = {
/**
* Called during the initialisation process of the object.
* @method initializer
*/
initializer : function() {
var node = this.get('node');
Y.log('Block region `'+this.get('region')+'` initialising', 'info');
if (!node) {
Y.log('block region known about but no HTML structure found for it. Guessing structure.', 'warn');
node = this.create_and_add_node();
}
var body = Y.one('body'),
hasblocks = node.all('.'+CSS.BLOCK).size() > 0,
hasregionclass = this.get_has_region_class();
this.set('hasblocks', hasblocks);
if (!body.hasClass(hasregionclass)) {
body.addClass(hasregionclass);
}
body.addClass((hasblocks) ? this.get_used_region_class() : this.get_empty_region_class());
body.removeClass((hasblocks) ? this.get_empty_region_class() : this.get_used_region_class());
},
/**
* Creates a generic block region node and adds it to the DOM at the best guess location.
* Any calling of this method is an unfortunate circumstance.
* @method create_and_add_node
* @return Node The newly created Node
*/
create_and_add_node : function() {
var c = Y.Node.create,
region = this.get('region'),
node = c('<div id="block-region-'+region+'" data-droptarget="1"></div>')
.addClass(CSS.BLOCKREGION)
.setData('blockregion', region),
regions = this.get('manager').get('regions'),
i,
haspre = false,
haspost = false,
added = false,
pre,
post;
for (i in regions) {
if (regions[i].match(/(pre|left)/)) {
haspre = regions[i];
} else if (regions[i].match(/(post|right)/)) {
haspost = regions[i];
}
}
if (haspre !== false && haspost !== false) {
if (region === haspre) {
post = Y.one('#block-region-'+haspost);
if (post) {
post.insert(node, 'before');
added = true;
}
} else {
pre = Y.one('#block-region-'+haspre);
if (pre) {
pre.insert(node, 'after');
added = true;
}
}
}
if (added === false) {
Y.one('body').append(node);
}
this.set('node', node);
return node;
},
/**
* Removes the move icons and changes the cursor to a move icon when over the header.
* @method remove_block_move_icons
*/
remove_block_move_icons : function() {
this.get('node').all('.'+CSS.BLOCK+' a.'+CSS.EDITINGMOVE).each(function(moveicon){
moveicon.ancestor('.'+CSS.BLOCK).one('.'+CSS.HEADER).setStyle('cursor', 'move');
moveicon.remove();
});
},
/**
* Returns the class name on the body that signifies the document knows about this region.
* @method get_has_region_class
* @return String
*/
get_has_region_class : function() {
return 'has-region-'+this.get('region');
},
/**
* Returns the class name to use on the body if the region contains no blocks.
* @method get_empty_region_class
* @return String
*/
get_empty_region_class : function() {
return 'empty-region-'+this.get('region');
},
/**
* Returns the class name to use on the body if the region contains blocks.
* @method get_used_region_class
* @return String
*/
get_used_region_class : function() {
return 'used-region-'+this.get('region');
},
/**
* Returns the node to use as the drop target for this region.
* @method get_droptarget
* @return Node
*/
get_droptarget : function() {
var node = this.get('node');
if (node.test('[data-droptarget="1"]')) {
return node;
}
return node.one('[data-droptarget="1"]');
},
/**
* Enables the block region so that we can be sure the user can see it.
* This is done even if it is empty.
* @method enable
*/
enable : function() {
Y.one('body').addClass(this.get_used_region_class()).removeClass(this.get_empty_region_class());
},
/**
* Disables the region if it contains no blocks, essentially hiding it from the user.
* @method disable_if_required
*/
disable_if_required : function() {
if (this.get('node').all('.'+CSS.BLOCK).size() === 0) {
Y.one('body').addClass(this.get_empty_region_class()).removeClass(this.get_used_region_class());
}
}
};
Y.extend(BLOCKREGION, Y.Base, BLOCKREGION.prototype, {
NAME : 'core-blocks-dragdrop-blockregion',
ATTRS : {
/**
* The drag and drop manager that created this block region instance.
* @attribute manager
* @type M.core.blockdraganddrop.Manager
* @writeOnce
*/
manager : {
// Can only be set during initialisation and must be set then.
writeOnce : 'initOnly',
validator : function (value) {
return Y.Lang.isObject(value) && value instanceof MANAGER;
}
},
/**
* The name of the block region this object represents.
* @attribute region
* @type String
* @writeOnce
*/
region : {
// Can only be set during initialisation and must be set then.
writeOnce : 'initOnly',
validator : function (value) {
return Y.Lang.isString(value);
}
},
/**
* The node the block region HTML starts at.s
* @attribute region
* @type Y.Node
*/
node : {
validator : function (value) {
return Y.Lang.isObject(value) || Y.Lang.isNull(value);
}
},
/**
* True if the block region currently contains blocks.
* @attribute hasblocks
* @type Boolean
* @default false
*/
hasblocks : {
value : false,
validator : function (value) {
return Y.Lang.isBoolean(value);
}
}
}
});
}, '@VERSION@', {
"requires": [
"base",
"node",
"io",
"dom",
"dd",
"dd-scroll",
"moodle-core-dragdrop",
"moodle-core-notification"
]
});
|
#!/usr/bin/env python
"""
The LibVMI Library is an introspection library that simplifies access to
memory in a target virtual machine or in a file containing a dump of
a system's physical memory. LibVMI is based on the XenAccess Library.
Copyright 2011 Sandia Corporation. Under the terms of Contract
DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government
retains certain rights in this software.
Author: Bryan D. Payne (bdpayne@acm.org)
This file is part of LibVMI.
LibVMI is free software: you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the
Free Software Foundation, either version 3 of the License, or (at your
option) any later version.
LibVMI 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 LibVMI. If not, see <http://www.gnu.org/licenses/>.
"""
import pyvmi
import sys
def get_processes(vmi):
tasks_offset = vmi.get_offset("win_tasks")
name_offset = vmi.get_offset("win_pname") - tasks_offset
pid_offset = vmi.get_offset("win_pid") - tasks_offset
list_head = vmi.read_addr_ksym("PsInitialSystemProcess")
next_process = vmi.read_addr_va(list_head + tasks_offset, 0)
list_head = next_process
while True:
procname = vmi.read_str_va(next_process + name_offset, 0)
pid = vmi.read_32_va(next_process + pid_offset, 0)
next_process = vmi.read_addr_va(next_process, 0)
if (pid < 1<<16):
yield pid, procname
if (list_head == next_process):
break
def main(argv):
vmi = pyvmi.init(argv[1], "complete")
for pid, procname in get_processes(vmi):
print "[%5d] %s" % (pid, procname)
if __name__ == "__main__":
main(sys.argv)
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2019, Anusha Hegde <anushah@vmware.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = '''
---
module: vmware_guest_serial_port
short_description: Manage serial ports on an existing VM
version_added: "2.10"
description:
- "This module can be used to manage serial ports on an existing VM"
options:
name:
description:
- Name of the virtual machine.
- This is a required parameter, if parameter C(uuid) or C(moid) is not supplied.
type: str
uuid:
description:
- UUID of the instance to manage the serial ports, this is VMware's unique identifier.
- This is a required parameter, if parameter C(name) or C(moid) is not supplied.
type: str
moid:
description:
- Managed Object ID of the instance to manage if known, this is a unique identifier only within a single vCenter instance.
- This is required if C(name) or C(uuid) is not supplied.
type: str
use_instance_uuid:
description:
- Whether to use the VMware instance UUID rather than the BIOS UUID.
default: no
type: bool
backings:
type: list
description:
- A list of backings for serial ports.
- 'C(backing_type) (str): is required to add or reconfigure or remove an existing serial port.'
- 'Valid attributes are:'
- ' - C(backing_type) (str): Backing type is required for the serial ports to be added or reconfigured or removed.'
- ' - C(state) (str): is required to identify whether we are adding, modifying or removing the serial port.
- choices:
- C(present): modify an existing serial port. C(backing_type) is required to determine the port.
The first matching C(backing_type) and either of C(service_uri) or C(pipe_name) or C(device_name) or C(file_path) will be modified.
If there is only one device with a backing type, the secondary details are not needed.
We will match the last such device with the given backing type.
- C(absent): remove an existing serial port. C(backing_type) is required to determine the port.
The first matching C(backing_type) and either of C(service_uri) or C(pipe_name) or C(device_name) or C(file_path) will be removed.
If there is only one device with a backing type, the secondary details are not needed.
We will match the last such device with the given backing type.'
- ' - C(yield_on_poll) (bool): Enables CPU yield behavior. Default value is true.'
- ' - C(direction) (str): Required when I(backing_type=network).
The direction of the connection.
- choices:
- client
- server'
- ' - C(service_uri) (str): Required when I(backing_type=network).
Identifies the local host or a system on the network, depending on the value of I(direction).
If you use the virtual machine as a server, the URI identifies the host on which the virtual machine runs.
In this case, the host name part of the URI should be empty, or it should specify the address of the local host.
If you use the virtual machine as a client, the URI identifies the remote system on the network.'
- ' - C(endpoint) (str): Required when I(backing_type=pipe).
When you use serial port pipe backing to connect a virtual machine to another process, you must define the endpoints.'
- ' - C(no_rx_loss) (bool): Required when I(backing_type=pipe).
Enables optimized data transfer over the pipe.
- choices:
- client
- server'
- ' - C(pipe_name) (str): Required when I(backing_type=pipe).'
- ' - C(device_name) (str): Required when I(backing_type=device).'
- ' - C(file_path) (str): Required when I(backing_type=file).
File path for the host file used in this backing. Fully qualified path is required, like <datastore_name>/<file_name>'
extends_documentation_fragment:
- vmware.documentation
author:
- Anusha Hegde (@anusha94)
'''
EXAMPLES = '''
# Create serial ports
- name: Create multiple serial ports with Backing type - network, pipe, device and file
vmware_guest_serial_port:
hostname: "{{ vcenter_hostname }}"
username: "{{ vcenter_username }}"
password: "{{ vcenter_password }}"
validate_certs: no
name: "test_vm1"
backings:
- type: 'network'
direction: 'client'
service_uri: 'tcp://6000'
yield_on_poll: True
- type: 'pipe'
pipe_name: 'serial_pipe'
endpoint: 'client'
- type: 'device'
device_name: '/dev/char/serial/uart0'
- type: 'file'
file_path: '[datastore1]/file1'
yield_on_poll: True
register: create_multiple_ports
# Modify existing serial port
- name: Modify Network backing type
vmware_guest_serial_port:
hostname: '{{ vcenter_hostname }}'
username: '{{ vcenter_username }}'
password: '{{ vcenter_password }}'
name: '{{ name }}'
backings:
- type: 'network'
state: 'present'
direction: 'server'
service_uri: 'tcp://6000'
delegate_to: localhost
# Remove serial port
- name: Remove pipe backing type
vmware_guest_serial_port:
hostname: '{{ vcenter_hostname }}'
username: '{{ vcenter_username }}'
password: '{{ vcenter_password }}'
name: '{{ name }}'
backings:
- type: 'pipe'
state: 'absent'
delegate_to: localhost
'''
RETURN = r'''
serial_port_data:
description: metadata about the virtual machine's serial ports after managing them
returned: always
type: dict
sample: [
{
"backing_type": "network",
"direction": "client",
"service_uri": "tcp://6000"
},
{
"backing_type": "pipe",
"direction": "server",
"pipe_name": "serial pipe"
},
]
'''
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.vmware import PyVmomi, vmware_argument_spec, wait_for_task
from ansible.module_utils._text import to_native
try:
from pyVmomi import vim
except ImportError:
pass
class PyVmomiHelper(PyVmomi):
""" This class is a helper to create easily VMware Spec for PyVmomiHelper """
def __init__(self, module):
super(PyVmomiHelper, self).__init__(module)
self.change_applied = False # a change was applied meaning at least one task succeeded
self.config_spec = vim.vm.ConfigSpec()
self.config_spec.deviceChange = []
self.serial_ports = []
def check_vm_state(self, vm_obj):
"""
To add serial port, the VM must be in powered off state
Input:
- vm: Virtual Machine
Output:
- True if vm is in poweredOff state
- module fails otherwise
"""
if vm_obj.runtime.powerState == vim.VirtualMachinePowerState.poweredOff:
return True
else:
self.module.fail_json(msg="A serial device cannot be added to a VM in the current state(" + vm_obj.runtime.powerState + ")."
+ "Please use the vmware_guest_powerstate module to power off the VM")
def get_serial_port_config_spec(self, vm_obj):
"""
Variables changed:
- self.config_spec
- self.change_applied
"""
# create serial config spec for adding, editing, removing
for backing in self.params.get('backings'):
backing_keys = backing.keys()
serial_port = get_serial_port(vm_obj, backing)
if serial_port is None and 'state' not in backing_keys:
# if serial port is None and state is not mentioned
# create a new serial port
serial_port_spec = self.create_serial_port(backing)
serial_port_spec.operation = vim.vm.device.VirtualDeviceSpec.Operation.add
self.serial_ports.append(serial_port_spec)
self.change_applied = True
else:
if serial_port is not None and 'state' in backing_keys:
serial_spec = vim.vm.device.VirtualDeviceSpec()
serial_spec.device = serial_port
if backing['state'].lower() == 'present':
# modify existing serial port
serial_spec.operation = vim.vm.device.VirtualDeviceSpec.Operation.edit
serial_spec.device.backing = self.get_backing_info(serial_port, backing, backing['type'])
self.change_applied = True
self.config_spec.deviceChange.append(serial_spec)
elif backing['state'].lower() == 'absent':
# remove serial port
serial_spec.operation = vim.vm.device.VirtualDeviceSpec.Operation.remove
self.change_applied = True
self.config_spec.deviceChange.append(serial_spec)
else:
self.module.fail_json(msg='Unable to find the specified serial port: %s' % backing)
def reconfigure_vm_serial_port(self, vm_obj):
"""
Reconfigure vm with new or modified serial port config spec
"""
self.get_serial_port_config_spec(vm_obj)
try:
# configure create tasks first
if self.serial_ports:
for serial_port in self.serial_ports:
# each type of serial port is of config_spec.device = vim.vm.device.VirtualSerialPort() object type
# because serial ports differ in the backing types and config_spec.device has to be unique,
# we are creating a new spec for every create port configuration
spec = vim.vm.ConfigSpec()
spec.deviceChange.append(serial_port)
task = vm_obj.ReconfigVM_Task(spec=spec)
wait_for_task(task)
task = vm_obj.ReconfigVM_Task(spec=self.config_spec)
wait_for_task(task)
except vim.fault.InvalidDatastorePath as e:
self.module.fail_json(msg="Failed to configure serial port on given virtual machine due to invalid path: %s" % to_native(e.msg))
except vim.fault.RestrictedVersion as e:
self.module.fail_json(msg="Failed to reconfigure virtual machine due to product versioning restrictions: %s" % to_native(e.msg))
if task.info.state == 'error':
results = {'changed': self.change_applied, 'failed': True, 'msg': task.info.error.msg}
else:
serial_port_info = get_serial_port_info(vm_obj)
results = {'changed': self.change_applied, 'failed': False, 'serial_port_info': serial_port_info}
return results
def set_network_backing(self, serial_port, backing_info):
"""
Set the networking backing params
"""
required_params = ['service_uri', 'direction']
if set(required_params).issubset(backing_info.keys()):
backing = serial_port.URIBackingInfo()
backing.serviceURI = backing_info['service_uri']
backing.direction = backing_info['direction']
else:
self.module.fail_json(msg="Failed to create a new serial port of network backing type due to insufficient parameters."
+ "The required parameters are service_uri and direction")
return backing
def set_pipe_backing(self, serial_port, backing_info):
"""
Set the pipe backing params
"""
required_params = ['pipe_name', 'endpoint']
if set(required_params).issubset(backing_info.keys()):
backing = serial_port.PipeBackingInfo()
backing.pipeName = backing_info['pipe_name']
backing.endpoint = backing_info['endpoint']
else:
self.module.fail_json(msg="Failed to create a new serial port of pipe backing type due to insufficient parameters."
+ "The required parameters are pipe_name and endpoint")
# since no_rx_loss is an optional argument, so check if the key is present
if 'no_rx_loss' in backing_info.keys() and backing_info['no_rx_loss']:
backing.noRxLoss = backing_info['no_rx_loss']
return backing
def set_device_backing(self, serial_port, backing_info):
"""
Set the device backing params
"""
required_params = ['device_name']
if set(required_params).issubset(backing_info.keys()):
backing = serial_port.DeviceBackingInfo()
backing.deviceName = backing_info['device_name']
else:
self.module.fail_json(msg="Failed to create a new serial port of device backing type due to insufficient parameters."
+ "The required parameters are device_name")
return backing
def set_file_backing(self, serial_port, backing_info):
"""
Set the file backing params
"""
required_params = ['file_path']
if set(required_params).issubset(backing_info.keys()):
backing = serial_port.FileBackingInfo()
backing.fileName = backing_info['file_path']
else:
self.module.fail_json(msg="Failed to create a new serial port of file backing type due to insufficient parameters."
+ "The required parameters are file_path")
return backing
def get_backing_info(self, serial_port, backing, backing_type):
"""
Returns the call to the appropriate backing function based on the backing type
"""
switcher = {
"network": self.set_network_backing,
"pipe": self.set_pipe_backing,
"device": self.set_device_backing,
"file": self.set_file_backing
}
backing_func = switcher.get(backing_type, "Invalid Backing Info")
return backing_func(serial_port, backing)
def create_serial_port(self, backing):
"""
Create a new serial port
"""
serial_spec = vim.vm.device.VirtualDeviceSpec()
serial_port = vim.vm.device.VirtualSerialPort()
serial_port.yieldOnPoll = backing['yield_on_poll'] if 'yield_on_poll' in backing.keys() else True
serial_port.backing = self.get_backing_info(serial_port, backing, backing['type'])
serial_spec.device = serial_port
return serial_spec
def get_serial_port(vm_obj, backing):
"""
Return the serial port of specified backing type
"""
serial_port = None
backing_type_mapping = {
'network': vim.vm.device.VirtualSerialPort.URIBackingInfo,
'pipe': vim.vm.device.VirtualSerialPort.PipeBackingInfo,
'device': vim.vm.device.VirtualSerialPort.DeviceBackingInfo,
'file': vim.vm.device.VirtualSerialPort.FileBackingInfo
}
valid_params = backing.keys()
for device in vm_obj.config.hardware.device:
if isinstance(device, vim.vm.device.VirtualSerialPort):
if isinstance(device.backing, backing_type_mapping[backing['type']]):
if 'service_uri' in valid_params:
# network backing type
if device.backing.serviceURI == backing['service_uri']:
serial_port = device
break
elif 'pipe_name' in valid_params:
# named pipe backing type
if device.backing.pipeName == backing['pipe_name']:
serial_port = device
break
elif 'device_name' in valid_params:
# physical serial device backing type
if device.backing.deviceName == backing['device_name']:
serial_port = device
break
elif 'file_path' in valid_params:
# file backing type
if device.backing.fileName == backing['file_path']:
serial_port = device
break
# if there is a backing of only one type, user need not provide secondary details like service_uri, pipe_name, device_name or file_path
# we will match the serial port with backing type only
# in this case, the last matching serial port will be returned
serial_port = device
return serial_port
def get_serial_port_info(vm_obj):
"""
Get the serial port info
"""
serial_port_info = []
if vm_obj is None:
return serial_port_info
for port in vm_obj.config.hardware.device:
backing = dict()
if isinstance(port, vim.vm.device.VirtualSerialPort):
if isinstance(port.backing, vim.vm.device.VirtualSerialPort.URIBackingInfo):
backing['backing_type'] = 'network'
backing['direction'] = port.backing.direction
backing['service_uri'] = port.backing.serviceURI
elif isinstance(port.backing, vim.vm.device.VirtualSerialPort.PipeBackingInfo):
backing['backing_type'] = 'pipe'
backing['pipe_name'] = port.backing.pipeName
backing['endpoint'] = port.backing.endpoint
backing['no_rx_loss'] = port.backing.noRxLoss
elif isinstance(port.backing, vim.vm.device.VirtualSerialPort.DeviceBackingInfo):
backing['backing_type'] = 'device'
backing['device_name'] = port.backing.deviceName
elif isinstance(port.backing, vim.vm.device.VirtualSerialPort.FileBackingInfo):
backing['backing_type'] = 'file'
backing['file_path'] = port.backing.fileName
else:
continue
serial_port_info.append(backing)
return serial_port_info
def main():
"""
Main method
"""
argument_spec = vmware_argument_spec()
argument_spec.update(
name=dict(type='str'),
uuid=dict(type='str'),
moid=dict(type='str'),
use_instance_uuid=dict(type='bool', default=False),
backings=dict(type='list', default=[])
)
module = AnsibleModule(
argument_spec=argument_spec,
required_one_of=[
['name', 'uuid', 'moid']
],
mutually_exclusive=[
['name', 'uuid', 'moid']
],
)
result = {'failed': False, 'changed': False}
pyv = PyVmomiHelper(module)
# Check if the VM exists before continuing
vm_obj = pyv.get_vm()
if vm_obj:
proceed = pyv.check_vm_state(vm_obj)
if proceed:
result = pyv.reconfigure_vm_serial_port(vm_obj)
else:
# We are unable to find the virtual machine user specified
# Bail out
vm_id = (module.params.get('name') or module.params.get('uuid') or module.params.get('vm_id'))
module.fail_json(msg="Unable to manage serial ports for non-existing"
" virtual machine '%s'." % vm_id)
if result['failed']:
module.fail_json(**result)
else:
module.exit_json(**result)
if __name__ == '__main__':
main()
|
/*
* Copyright (C) 2004 Michael Niedermayer <michaelni@gmx.at>
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "libavutil/intmath.h"
#include "libavutil/log.h"
#include "libavutil/opt.h"
#include "avcodec.h"
#include "dsputil.h"
#include "dwt.h"
#include "snow.h"
#include "snowdata.h"
#include "rangecoder.h"
#include "mathops.h"
#include "h263.h"
#undef NDEBUG
#include <assert.h>
void ff_snow_inner_add_yblock(const uint8_t *obmc, const int obmc_stride, uint8_t * * block, int b_w, int b_h,
int src_x, int src_y, int src_stride, slice_buffer * sb, int add, uint8_t * dst8){
int y, x;
IDWTELEM * dst;
for(y=0; y<b_h; y++){
//FIXME ugly misuse of obmc_stride
const uint8_t *obmc1= obmc + y*obmc_stride;
const uint8_t *obmc2= obmc1+ (obmc_stride>>1);
const uint8_t *obmc3= obmc1+ obmc_stride*(obmc_stride>>1);
const uint8_t *obmc4= obmc3+ (obmc_stride>>1);
dst = slice_buffer_get_line(sb, src_y + y);
for(x=0; x<b_w; x++){
int v= obmc1[x] * block[3][x + y*src_stride]
+obmc2[x] * block[2][x + y*src_stride]
+obmc3[x] * block[1][x + y*src_stride]
+obmc4[x] * block[0][x + y*src_stride];
v <<= 8 - LOG2_OBMC_MAX;
if(FRAC_BITS != 8){
v >>= 8 - FRAC_BITS;
}
if(add){
v += dst[x + src_x];
v = (v + (1<<(FRAC_BITS-1))) >> FRAC_BITS;
if(v&(~255)) v= ~(v>>31);
dst8[x + y*src_stride] = v;
}else{
dst[x + src_x] -= v;
}
}
}
}
void ff_snow_reset_contexts(SnowContext *s){ //FIXME better initial contexts
int plane_index, level, orientation;
for(plane_index=0; plane_index<3; plane_index++){
for(level=0; level<MAX_DECOMPOSITIONS; level++){
for(orientation=level ? 1:0; orientation<4; orientation++){
memset(s->plane[plane_index].band[level][orientation].state, MID_STATE, sizeof(s->plane[plane_index].band[level][orientation].state));
}
}
}
memset(s->header_state, MID_STATE, sizeof(s->header_state));
memset(s->block_state, MID_STATE, sizeof(s->block_state));
}
int ff_snow_alloc_blocks(SnowContext *s){
int w= -((-s->avctx->width )>>LOG2_MB_SIZE);
int h= -((-s->avctx->height)>>LOG2_MB_SIZE);
s->b_width = w;
s->b_height= h;
av_free(s->block);
s->block= av_mallocz(w * h * sizeof(BlockNode) << (s->block_max_depth*2));
return 0;
}
static void init_qexp(void){
int i;
double v=128;
for(i=0; i<QROOT; i++){
ff_qexp[i]= lrintf(v);
v *= pow(2, 1.0 / QROOT);
}
}
static void mc_block(Plane *p, uint8_t *dst, const uint8_t *src, int stride, int b_w, int b_h, int dx, int dy){
static const uint8_t weight[64]={
8,7,6,5,4,3,2,1,
7,7,0,0,0,0,0,1,
6,0,6,0,0,0,2,0,
5,0,0,5,0,3,0,0,
4,0,0,0,4,0,0,0,
3,0,0,5,0,3,0,0,
2,0,6,0,0,0,2,0,
1,7,0,0,0,0,0,1,
};
static const uint8_t brane[256]={
0x00,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x11,0x12,0x12,0x12,0x12,0x12,0x12,0x12,
0x04,0x05,0xcc,0xcc,0xcc,0xcc,0xcc,0x41,0x15,0x16,0xcc,0xcc,0xcc,0xcc,0xcc,0x52,
0x04,0xcc,0x05,0xcc,0xcc,0xcc,0x41,0xcc,0x15,0xcc,0x16,0xcc,0xcc,0xcc,0x52,0xcc,
0x04,0xcc,0xcc,0x05,0xcc,0x41,0xcc,0xcc,0x15,0xcc,0xcc,0x16,0xcc,0x52,0xcc,0xcc,
0x04,0xcc,0xcc,0xcc,0x41,0xcc,0xcc,0xcc,0x15,0xcc,0xcc,0xcc,0x16,0xcc,0xcc,0xcc,
0x04,0xcc,0xcc,0x41,0xcc,0x05,0xcc,0xcc,0x15,0xcc,0xcc,0x52,0xcc,0x16,0xcc,0xcc,
0x04,0xcc,0x41,0xcc,0xcc,0xcc,0x05,0xcc,0x15,0xcc,0x52,0xcc,0xcc,0xcc,0x16,0xcc,
0x04,0x41,0xcc,0xcc,0xcc,0xcc,0xcc,0x05,0x15,0x52,0xcc,0xcc,0xcc,0xcc,0xcc,0x16,
0x44,0x45,0x45,0x45,0x45,0x45,0x45,0x45,0x55,0x56,0x56,0x56,0x56,0x56,0x56,0x56,
0x48,0x49,0xcc,0xcc,0xcc,0xcc,0xcc,0x85,0x59,0x5A,0xcc,0xcc,0xcc,0xcc,0xcc,0x96,
0x48,0xcc,0x49,0xcc,0xcc,0xcc,0x85,0xcc,0x59,0xcc,0x5A,0xcc,0xcc,0xcc,0x96,0xcc,
0x48,0xcc,0xcc,0x49,0xcc,0x85,0xcc,0xcc,0x59,0xcc,0xcc,0x5A,0xcc,0x96,0xcc,0xcc,
0x48,0xcc,0xcc,0xcc,0x49,0xcc,0xcc,0xcc,0x59,0xcc,0xcc,0xcc,0x96,0xcc,0xcc,0xcc,
0x48,0xcc,0xcc,0x85,0xcc,0x49,0xcc,0xcc,0x59,0xcc,0xcc,0x96,0xcc,0x5A,0xcc,0xcc,
0x48,0xcc,0x85,0xcc,0xcc,0xcc,0x49,0xcc,0x59,0xcc,0x96,0xcc,0xcc,0xcc,0x5A,0xcc,
0x48,0x85,0xcc,0xcc,0xcc,0xcc,0xcc,0x49,0x59,0x96,0xcc,0xcc,0xcc,0xcc,0xcc,0x5A,
};
static const uint8_t needs[16]={
0,1,0,0,
2,4,2,0,
0,1,0,0,
15
};
int x, y, b, r, l;
int16_t tmpIt [64*(32+HTAPS_MAX)];
uint8_t tmp2t[3][stride*(32+HTAPS_MAX)];
int16_t *tmpI= tmpIt;
uint8_t *tmp2= tmp2t[0];
const uint8_t *hpel[11];
assert(dx<16 && dy<16);
r= brane[dx + 16*dy]&15;
l= brane[dx + 16*dy]>>4;
b= needs[l] | needs[r];
if(p && !p->diag_mc)
b= 15;
if(b&5){
for(y=0; y < b_h+HTAPS_MAX-1; y++){
for(x=0; x < b_w; x++){
int a_1=src[x + HTAPS_MAX/2-4];
int a0= src[x + HTAPS_MAX/2-3];
int a1= src[x + HTAPS_MAX/2-2];
int a2= src[x + HTAPS_MAX/2-1];
int a3= src[x + HTAPS_MAX/2+0];
int a4= src[x + HTAPS_MAX/2+1];
int a5= src[x + HTAPS_MAX/2+2];
int a6= src[x + HTAPS_MAX/2+3];
int am=0;
if(!p || p->fast_mc){
am= 20*(a2+a3) - 5*(a1+a4) + (a0+a5);
tmpI[x]= am;
am= (am+16)>>5;
}else{
am= p->hcoeff[0]*(a2+a3) + p->hcoeff[1]*(a1+a4) + p->hcoeff[2]*(a0+a5) + p->hcoeff[3]*(a_1+a6);
tmpI[x]= am;
am= (am+32)>>6;
}
if(am&(~255)) am= ~(am>>31);
tmp2[x]= am;
}
tmpI+= 64;
tmp2+= stride;
src += stride;
}
src -= stride*y;
}
src += HTAPS_MAX/2 - 1;
tmp2= tmp2t[1];
if(b&2){
for(y=0; y < b_h; y++){
for(x=0; x < b_w+1; x++){
int a_1=src[x + (HTAPS_MAX/2-4)*stride];
int a0= src[x + (HTAPS_MAX/2-3)*stride];
int a1= src[x + (HTAPS_MAX/2-2)*stride];
int a2= src[x + (HTAPS_MAX/2-1)*stride];
int a3= src[x + (HTAPS_MAX/2+0)*stride];
int a4= src[x + (HTAPS_MAX/2+1)*stride];
int a5= src[x + (HTAPS_MAX/2+2)*stride];
int a6= src[x + (HTAPS_MAX/2+3)*stride];
int am=0;
if(!p || p->fast_mc)
am= (20*(a2+a3) - 5*(a1+a4) + (a0+a5) + 16)>>5;
else
am= (p->hcoeff[0]*(a2+a3) + p->hcoeff[1]*(a1+a4) + p->hcoeff[2]*(a0+a5) + p->hcoeff[3]*(a_1+a6) + 32)>>6;
if(am&(~255)) am= ~(am>>31);
tmp2[x]= am;
}
src += stride;
tmp2+= stride;
}
src -= stride*y;
}
src += stride*(HTAPS_MAX/2 - 1);
tmp2= tmp2t[2];
tmpI= tmpIt;
if(b&4){
for(y=0; y < b_h; y++){
for(x=0; x < b_w; x++){
int a_1=tmpI[x + (HTAPS_MAX/2-4)*64];
int a0= tmpI[x + (HTAPS_MAX/2-3)*64];
int a1= tmpI[x + (HTAPS_MAX/2-2)*64];
int a2= tmpI[x + (HTAPS_MAX/2-1)*64];
int a3= tmpI[x + (HTAPS_MAX/2+0)*64];
int a4= tmpI[x + (HTAPS_MAX/2+1)*64];
int a5= tmpI[x + (HTAPS_MAX/2+2)*64];
int a6= tmpI[x + (HTAPS_MAX/2+3)*64];
int am=0;
if(!p || p->fast_mc)
am= (20*(a2+a3) - 5*(a1+a4) + (a0+a5) + 512)>>10;
else
am= (p->hcoeff[0]*(a2+a3) + p->hcoeff[1]*(a1+a4) + p->hcoeff[2]*(a0+a5) + p->hcoeff[3]*(a_1+a6) + 2048)>>12;
if(am&(~255)) am= ~(am>>31);
tmp2[x]= am;
}
tmpI+= 64;
tmp2+= stride;
}
}
hpel[ 0]= src;
hpel[ 1]= tmp2t[0] + stride*(HTAPS_MAX/2-1);
hpel[ 2]= src + 1;
hpel[ 4]= tmp2t[1];
hpel[ 5]= tmp2t[2];
hpel[ 6]= tmp2t[1] + 1;
hpel[ 8]= src + stride;
hpel[ 9]= hpel[1] + stride;
hpel[10]= hpel[8] + 1;
if(b==15){
const uint8_t *src1= hpel[dx/8 + dy/8*4 ];
const uint8_t *src2= hpel[dx/8 + dy/8*4+1];
const uint8_t *src3= hpel[dx/8 + dy/8*4+4];
const uint8_t *src4= hpel[dx/8 + dy/8*4+5];
dx&=7;
dy&=7;
for(y=0; y < b_h; y++){
for(x=0; x < b_w; x++){
dst[x]= ((8-dx)*(8-dy)*src1[x] + dx*(8-dy)*src2[x]+
(8-dx)* dy *src3[x] + dx* dy *src4[x]+32)>>6;
}
src1+=stride;
src2+=stride;
src3+=stride;
src4+=stride;
dst +=stride;
}
}else{
const uint8_t *src1= hpel[l];
const uint8_t *src2= hpel[r];
int a= weight[((dx&7) + (8*(dy&7)))];
int b= 8-a;
for(y=0; y < b_h; y++){
for(x=0; x < b_w; x++){
dst[x]= (a*src1[x] + b*src2[x] + 4)>>3;
}
src1+=stride;
src2+=stride;
dst +=stride;
}
}
}
void ff_snow_pred_block(SnowContext *s, uint8_t *dst, uint8_t *tmp, int stride, int sx, int sy, int b_w, int b_h, BlockNode *block, int plane_index, int w, int h){
if(block->type & BLOCK_INTRA){
int x, y;
const unsigned color = block->color[plane_index];
const unsigned color4 = color*0x01010101;
if(b_w==32){
for(y=0; y < b_h; y++){
*(uint32_t*)&dst[0 + y*stride]= color4;
*(uint32_t*)&dst[4 + y*stride]= color4;
*(uint32_t*)&dst[8 + y*stride]= color4;
*(uint32_t*)&dst[12+ y*stride]= color4;
*(uint32_t*)&dst[16+ y*stride]= color4;
*(uint32_t*)&dst[20+ y*stride]= color4;
*(uint32_t*)&dst[24+ y*stride]= color4;
*(uint32_t*)&dst[28+ y*stride]= color4;
}
}else if(b_w==16){
for(y=0; y < b_h; y++){
*(uint32_t*)&dst[0 + y*stride]= color4;
*(uint32_t*)&dst[4 + y*stride]= color4;
*(uint32_t*)&dst[8 + y*stride]= color4;
*(uint32_t*)&dst[12+ y*stride]= color4;
}
}else if(b_w==8){
for(y=0; y < b_h; y++){
*(uint32_t*)&dst[0 + y*stride]= color4;
*(uint32_t*)&dst[4 + y*stride]= color4;
}
}else if(b_w==4){
for(y=0; y < b_h; y++){
*(uint32_t*)&dst[0 + y*stride]= color4;
}
}else{
for(y=0; y < b_h; y++){
for(x=0; x < b_w; x++){
dst[x + y*stride]= color;
}
}
}
}else{
uint8_t *src= s->last_picture[block->ref].data[plane_index];
const int scale= plane_index ? s->mv_scale : 2*s->mv_scale;
int mx= block->mx*scale;
int my= block->my*scale;
const int dx= mx&15;
const int dy= my&15;
const int tab_index= 3 - (b_w>>2) + (b_w>>4);
sx += (mx>>4) - (HTAPS_MAX/2-1);
sy += (my>>4) - (HTAPS_MAX/2-1);
src += sx + sy*stride;
if( (unsigned)sx >= w - b_w - (HTAPS_MAX-2)
|| (unsigned)sy >= h - b_h - (HTAPS_MAX-2)){
s->dsp.emulated_edge_mc(tmp + MB_SIZE, src, stride, b_w+HTAPS_MAX-1, b_h+HTAPS_MAX-1, sx, sy, w, h);
src= tmp + MB_SIZE;
}
// assert(b_w == b_h || 2*b_w == b_h || b_w == 2*b_h);
// assert(!(b_w&(b_w-1)));
assert(b_w>1 && b_h>1);
assert((tab_index>=0 && tab_index<4) || b_w==32);
if((dx&3) || (dy&3) || !(b_w == b_h || 2*b_w == b_h || b_w == 2*b_h) || (b_w&(b_w-1)) || !s->plane[plane_index].fast_mc )
mc_block(&s->plane[plane_index], dst, src, stride, b_w, b_h, dx, dy);
else if(b_w==32){
int y;
for(y=0; y<b_h; y+=16){
s->dsp.put_h264_qpel_pixels_tab[0][dy+(dx>>2)](dst + y*stride, src + 3 + (y+3)*stride,stride);
s->dsp.put_h264_qpel_pixels_tab[0][dy+(dx>>2)](dst + 16 + y*stride, src + 19 + (y+3)*stride,stride);
}
}else if(b_w==b_h)
s->dsp.put_h264_qpel_pixels_tab[tab_index ][dy+(dx>>2)](dst,src + 3 + 3*stride,stride);
else if(b_w==2*b_h){
s->dsp.put_h264_qpel_pixels_tab[tab_index+1][dy+(dx>>2)](dst ,src + 3 + 3*stride,stride);
s->dsp.put_h264_qpel_pixels_tab[tab_index+1][dy+(dx>>2)](dst+b_h,src + 3 + b_h + 3*stride,stride);
}else{
assert(2*b_w==b_h);
s->dsp.put_h264_qpel_pixels_tab[tab_index ][dy+(dx>>2)](dst ,src + 3 + 3*stride ,stride);
s->dsp.put_h264_qpel_pixels_tab[tab_index ][dy+(dx>>2)](dst+b_w*stride,src + 3 + 3*stride+b_w*stride,stride);
}
}
}
#define mca(dx,dy,b_w)\
static void mc_block_hpel ## dx ## dy ## b_w(uint8_t *dst, const uint8_t *src, int stride, int h){\
assert(h==b_w);\
mc_block(NULL, dst, src-(HTAPS_MAX/2-1)-(HTAPS_MAX/2-1)*stride, stride, b_w, b_w, dx, dy);\
}
mca( 0, 0,16)
mca( 8, 0,16)
mca( 0, 8,16)
mca( 8, 8,16)
mca( 0, 0,8)
mca( 8, 0,8)
mca( 0, 8,8)
mca( 8, 8,8)
av_cold int ff_snow_common_init(AVCodecContext *avctx){
SnowContext *s = avctx->priv_data;
int width, height;
int i, j;
s->avctx= avctx;
s->max_ref_frames=1; //just make sure its not an invalid value in case of no initial keyframe
ff_dsputil_init(&s->dsp, avctx);
ff_dwt_init(&s->dwt);
#define mcf(dx,dy)\
s->dsp.put_qpel_pixels_tab [0][dy+dx/4]=\
s->dsp.put_no_rnd_qpel_pixels_tab[0][dy+dx/4]=\
s->dsp.put_h264_qpel_pixels_tab[0][dy+dx/4];\
s->dsp.put_qpel_pixels_tab [1][dy+dx/4]=\
s->dsp.put_no_rnd_qpel_pixels_tab[1][dy+dx/4]=\
s->dsp.put_h264_qpel_pixels_tab[1][dy+dx/4];
mcf( 0, 0)
mcf( 4, 0)
mcf( 8, 0)
mcf(12, 0)
mcf( 0, 4)
mcf( 4, 4)
mcf( 8, 4)
mcf(12, 4)
mcf( 0, 8)
mcf( 4, 8)
mcf( 8, 8)
mcf(12, 8)
mcf( 0,12)
mcf( 4,12)
mcf( 8,12)
mcf(12,12)
#define mcfh(dx,dy)\
s->dsp.put_pixels_tab [0][dy/4+dx/8]=\
s->dsp.put_no_rnd_pixels_tab[0][dy/4+dx/8]=\
mc_block_hpel ## dx ## dy ## 16;\
s->dsp.put_pixels_tab [1][dy/4+dx/8]=\
s->dsp.put_no_rnd_pixels_tab[1][dy/4+dx/8]=\
mc_block_hpel ## dx ## dy ## 8;
mcfh(0, 0)
mcfh(8, 0)
mcfh(0, 8)
mcfh(8, 8)
init_qexp();
// dec += FFMAX(s->chroma_h_shift, s->chroma_v_shift);
width= s->avctx->width;
height= s->avctx->height;
s->spatial_idwt_buffer= av_mallocz(width*height*sizeof(IDWTELEM));
s->spatial_dwt_buffer= av_mallocz(width*height*sizeof(DWTELEM)); //FIXME this does not belong here
for(i=0; i<MAX_REF_FRAMES; i++)
for(j=0; j<MAX_REF_FRAMES; j++)
ff_scale_mv_ref[i][j] = 256*(i+1)/(j+1);
s->avctx->get_buffer(s->avctx, &s->mconly_picture);
s->scratchbuf = av_mallocz(s->mconly_picture.linesize[0]*7*MB_SIZE);
return 0;
}
int ff_snow_common_init_after_header(AVCodecContext *avctx) {
SnowContext *s = avctx->priv_data;
int plane_index, level, orientation;
for(plane_index=0; plane_index<3; plane_index++){
int w= s->avctx->width;
int h= s->avctx->height;
if(plane_index){
w>>= s->chroma_h_shift;
h>>= s->chroma_v_shift;
}
s->plane[plane_index].width = w;
s->plane[plane_index].height= h;
for(level=s->spatial_decomposition_count-1; level>=0; level--){
for(orientation=level ? 1 : 0; orientation<4; orientation++){
SubBand *b= &s->plane[plane_index].band[level][orientation];
b->buf= s->spatial_dwt_buffer;
b->level= level;
b->stride= s->plane[plane_index].width << (s->spatial_decomposition_count - level);
b->width = (w + !(orientation&1))>>1;
b->height= (h + !(orientation>1))>>1;
b->stride_line = 1 << (s->spatial_decomposition_count - level);
b->buf_x_offset = 0;
b->buf_y_offset = 0;
if(orientation&1){
b->buf += (w+1)>>1;
b->buf_x_offset = (w+1)>>1;
}
if(orientation>1){
b->buf += b->stride>>1;
b->buf_y_offset = b->stride_line >> 1;
}
b->ibuf= s->spatial_idwt_buffer + (b->buf - s->spatial_dwt_buffer);
if(level)
b->parent= &s->plane[plane_index].band[level-1][orientation];
//FIXME avoid this realloc
av_freep(&b->x_coeff);
b->x_coeff=av_mallocz(((b->width+1) * b->height+1)*sizeof(x_and_coeff));
}
w= (w+1)>>1;
h= (h+1)>>1;
}
}
return 0;
}
#define USE_HALFPEL_PLANE 0
static void halfpel_interpol(SnowContext *s, uint8_t *halfpel[4][4], AVFrame *frame){
int p,x,y;
for(p=0; p<3; p++){
int is_chroma= !!p;
int w= s->avctx->width >>is_chroma;
int h= s->avctx->height >>is_chroma;
int ls= frame->linesize[p];
uint8_t *src= frame->data[p];
halfpel[1][p] = (uint8_t*) av_malloc(ls * (h + 2 * EDGE_WIDTH)) + EDGE_WIDTH * (1 + ls);
halfpel[2][p] = (uint8_t*) av_malloc(ls * (h + 2 * EDGE_WIDTH)) + EDGE_WIDTH * (1 + ls);
halfpel[3][p] = (uint8_t*) av_malloc(ls * (h + 2 * EDGE_WIDTH)) + EDGE_WIDTH * (1 + ls);
halfpel[0][p]= src;
for(y=0; y<h; y++){
for(x=0; x<w; x++){
int i= y*ls + x;
halfpel[1][p][i]= (20*(src[i] + src[i+1]) - 5*(src[i-1] + src[i+2]) + (src[i-2] + src[i+3]) + 16 )>>5;
}
}
for(y=0; y<h; y++){
for(x=0; x<w; x++){
int i= y*ls + x;
halfpel[2][p][i]= (20*(src[i] + src[i+ls]) - 5*(src[i-ls] + src[i+2*ls]) + (src[i-2*ls] + src[i+3*ls]) + 16 )>>5;
}
}
src= halfpel[1][p];
for(y=0; y<h; y++){
for(x=0; x<w; x++){
int i= y*ls + x;
halfpel[3][p][i]= (20*(src[i] + src[i+ls]) - 5*(src[i-ls] + src[i+2*ls]) + (src[i-2*ls] + src[i+3*ls]) + 16 )>>5;
}
}
//FIXME border!
}
}
void ff_snow_release_buffer(AVCodecContext *avctx)
{
SnowContext *s = avctx->priv_data;
int i;
if(s->last_picture[s->max_ref_frames-1].data[0]){
avctx->release_buffer(avctx, &s->last_picture[s->max_ref_frames-1]);
for(i=0; i<9; i++)
if(s->halfpel_plane[s->max_ref_frames-1][1+i/3][i%3])
av_free(s->halfpel_plane[s->max_ref_frames-1][1+i/3][i%3] - EDGE_WIDTH*(1+s->current_picture.linesize[i%3]));
}
}
int ff_snow_frame_start(SnowContext *s){
AVFrame tmp;
int w= s->avctx->width; //FIXME round up to x16 ?
int h= s->avctx->height;
if (s->current_picture.data[0] && !(s->avctx->flags&CODEC_FLAG_EMU_EDGE)) {
s->dsp.draw_edges(s->current_picture.data[0],
s->current_picture.linesize[0], w , h ,
EDGE_WIDTH , EDGE_WIDTH , EDGE_TOP | EDGE_BOTTOM);
s->dsp.draw_edges(s->current_picture.data[1],
s->current_picture.linesize[1], w>>1, h>>1,
EDGE_WIDTH/2, EDGE_WIDTH/2, EDGE_TOP | EDGE_BOTTOM);
s->dsp.draw_edges(s->current_picture.data[2],
s->current_picture.linesize[2], w>>1, h>>1,
EDGE_WIDTH/2, EDGE_WIDTH/2, EDGE_TOP | EDGE_BOTTOM);
}
ff_snow_release_buffer(s->avctx);
tmp= s->last_picture[s->max_ref_frames-1];
memmove(s->last_picture+1, s->last_picture, (s->max_ref_frames-1)*sizeof(AVFrame));
memmove(s->halfpel_plane+1, s->halfpel_plane, (s->max_ref_frames-1)*sizeof(void*)*4*4);
if(USE_HALFPEL_PLANE && s->current_picture.data[0])
halfpel_interpol(s, s->halfpel_plane[0], &s->current_picture);
s->last_picture[0]= s->current_picture;
s->current_picture= tmp;
if(s->keyframe){
s->ref_frames= 0;
}else{
int i;
for(i=0; i<s->max_ref_frames && s->last_picture[i].data[0]; i++)
if(i && s->last_picture[i-1].key_frame)
break;
s->ref_frames= i;
if(s->ref_frames==0){
av_log(s->avctx,AV_LOG_ERROR, "No reference frames\n");
return -1;
}
}
s->current_picture.reference= 3;
if(s->avctx->get_buffer(s->avctx, &s->current_picture) < 0){
av_log(s->avctx, AV_LOG_ERROR, "get_buffer() failed\n");
return -1;
}
s->current_picture.key_frame= s->keyframe;
return 0;
}
av_cold void ff_snow_common_end(SnowContext *s)
{
int plane_index, level, orientation, i;
av_freep(&s->spatial_dwt_buffer);
av_freep(&s->spatial_idwt_buffer);
s->m.me.temp= NULL;
av_freep(&s->m.me.scratchpad);
av_freep(&s->m.me.map);
av_freep(&s->m.me.score_map);
av_freep(&s->m.obmc_scratchpad);
av_freep(&s->block);
av_freep(&s->scratchbuf);
for(i=0; i<MAX_REF_FRAMES; i++){
av_freep(&s->ref_mvs[i]);
av_freep(&s->ref_scores[i]);
if(s->last_picture[i].data[0])
s->avctx->release_buffer(s->avctx, &s->last_picture[i]);
}
for(plane_index=0; plane_index<3; plane_index++){
for(level=s->spatial_decomposition_count-1; level>=0; level--){
for(orientation=level ? 1 : 0; orientation<4; orientation++){
SubBand *b= &s->plane[plane_index].band[level][orientation];
av_freep(&b->x_coeff);
}
}
}
if (s->mconly_picture.data[0])
s->avctx->release_buffer(s->avctx, &s->mconly_picture);
if (s->current_picture.data[0])
s->avctx->release_buffer(s->avctx, &s->current_picture);
}
|
// ReSharper disable All
using System;
using System.Collections.Generic;
using System.Dynamic;
using PetaPoco;
using MixERP.Net.Entities.Core;
namespace MixERP.Net.Schemas.Core.Data
{
public interface IGetStateIdByStateNameRepository
{
string PgArg0 { get; set; }
/// <summary>
/// Prepares and executes IGetStateIdByStateNameRepository.
/// </summary>
int Execute();
}
} |
// ReSharper disable All
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using MixERP.Net.Api.Framework;
using MixERP.Net.ApplicationState.Cache;
using MixERP.Net.Common.Extensions;
using MixERP.Net.EntityParser;
using MixERP.Net.Framework;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using PetaPoco;
using MixERP.Net.Schemas.Core.Data;
namespace MixERP.Net.Api.Core
{
/// <summary>
/// Provides a direct HTTP access to perform various tasks such as adding, editing, and removing Item Selling Price Scrud Views.
/// </summary>
[RoutePrefix("api/v1.5/core/item-selling-price-scrud-view")]
public class ItemSellingPriceScrudViewController : ApiController
{
/// <summary>
/// The ItemSellingPriceScrudView repository.
/// </summary>
private readonly IItemSellingPriceScrudViewRepository ItemSellingPriceScrudViewRepository;
public ItemSellingPriceScrudViewController()
{
this._LoginId = AppUsers.GetCurrent().View.LoginId.ToLong();
this._UserId = AppUsers.GetCurrent().View.UserId.ToInt();
this._OfficeId = AppUsers.GetCurrent().View.OfficeId.ToInt();
this._Catalog = AppUsers.GetCurrentUserDB();
this.ItemSellingPriceScrudViewRepository = new MixERP.Net.Schemas.Core.Data.ItemSellingPriceScrudView
{
_Catalog = this._Catalog,
_LoginId = this._LoginId,
_UserId = this._UserId
};
}
public ItemSellingPriceScrudViewController(IItemSellingPriceScrudViewRepository repository, string catalog, LoginView view)
{
this._LoginId = view.LoginId.ToLong();
this._UserId = view.UserId.ToInt();
this._OfficeId = view.OfficeId.ToInt();
this._Catalog = catalog;
this.ItemSellingPriceScrudViewRepository = repository;
}
public long _LoginId { get; }
public int _UserId { get; private set; }
public int _OfficeId { get; private set; }
public string _Catalog { get; }
/// <summary>
/// Counts the number of item selling price scrud views.
/// </summary>
/// <returns>Returns the count of the item selling price scrud views.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("count")]
[Route("~/api/core/item-selling-price-scrud-view/count")]
public long Count()
{
try
{
return this.ItemSellingPriceScrudViewRepository.Count();
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (MixERPException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
}
/// <summary>
/// Returns collection of item selling price scrud view for export.
/// </summary>
/// <returns></returns>
[AcceptVerbs("GET", "HEAD")]
[Route("export")]
[Route("all")]
[Route("~/api/core/item-selling-price-scrud-view/export")]
[Route("~/api/core/item-selling-price-scrud-view/all")]
public IEnumerable<MixERP.Net.Entities.Core.ItemSellingPriceScrudView> Get()
{
try
{
return this.ItemSellingPriceScrudViewRepository.Get();
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (MixERPException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
}
/// <summary>
/// Creates a paginated collection containing 10 item selling price scrud views on each page, sorted by the property .
/// </summary>
/// <returns>Returns the first page from the collection.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("")]
[Route("~/api/core/item-selling-price-scrud-view")]
public IEnumerable<MixERP.Net.Entities.Core.ItemSellingPriceScrudView> GetPaginatedResult()
{
try
{
return this.ItemSellingPriceScrudViewRepository.GetPaginatedResult();
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (MixERPException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
}
/// <summary>
/// Creates a paginated collection containing 10 item selling price scrud views on each page, sorted by the property .
/// </summary>
/// <param name="pageNumber">Enter the page number to produce the resultset.</param>
/// <returns>Returns the requested page from the collection.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("page/{pageNumber}")]
[Route("~/api/core/item-selling-price-scrud-view/page/{pageNumber}")]
public IEnumerable<MixERP.Net.Entities.Core.ItemSellingPriceScrudView> GetPaginatedResult(long pageNumber)
{
try
{
return this.ItemSellingPriceScrudViewRepository.GetPaginatedResult(pageNumber);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (MixERPException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
}
/// <summary>
/// Displayfield is a lightweight key/value collection of item selling price scrud views.
/// </summary>
/// <returns>Returns an enumerable key/value collection of item selling price scrud views.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("display-fields")]
[Route("~/api/core/item-selling-price-scrud-view/display-fields")]
public IEnumerable<DisplayField> GetDisplayFields()
{
try
{
return this.ItemSellingPriceScrudViewRepository.GetDisplayFields();
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (MixERPException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
}
/// <summary>
/// Counts the number of item selling price scrud views using the supplied filter(s).
/// </summary>
/// <param name="filters">The list of filter conditions.</param>
/// <returns>Returns the count of filtered item selling price scrud views.</returns>
[AcceptVerbs("POST")]
[Route("count-where")]
[Route("~/api/core/item-selling-price-scrud-view/count-where")]
public long CountWhere([FromBody]JArray filters)
{
try
{
List<EntityParser.Filter> f = filters.ToObject<List<EntityParser.Filter>>(JsonHelper.GetJsonSerializer());
return this.ItemSellingPriceScrudViewRepository.CountWhere(f);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (MixERPException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
}
/// <summary>
/// Creates a filtered and paginated collection containing 10 item selling price scrud views on each page, sorted by the property .
/// </summary>
/// <param name="pageNumber">Enter the page number to produce the resultset.</param>
/// <param name="filters">The list of filter conditions.</param>
/// <returns>Returns the requested page from the collection using the supplied filters.</returns>
[AcceptVerbs("POST")]
[Route("get-where/{pageNumber}")]
[Route("~/api/core/item-selling-price-scrud-view/get-where/{pageNumber}")]
public IEnumerable<MixERP.Net.Entities.Core.ItemSellingPriceScrudView> GetWhere(long pageNumber, [FromBody]JArray filters)
{
try
{
List<EntityParser.Filter> f = filters.ToObject<List<EntityParser.Filter>>(JsonHelper.GetJsonSerializer());
return this.ItemSellingPriceScrudViewRepository.GetWhere(pageNumber, f);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (MixERPException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
}
/// <summary>
/// Counts the number of item selling price scrud views using the supplied filter name.
/// </summary>
/// <param name="filterName">The named filter.</param>
/// <returns>Returns the count of filtered item selling price scrud views.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("count-filtered/{filterName}")]
[Route("~/api/core/item-selling-price-scrud-view/count-filtered/{filterName}")]
public long CountFiltered(string filterName)
{
try
{
return this.ItemSellingPriceScrudViewRepository.CountFiltered(filterName);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (MixERPException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
}
/// <summary>
/// Creates a filtered and paginated collection containing 10 item selling price scrud views on each page, sorted by the property .
/// </summary>
/// <param name="pageNumber">Enter the page number to produce the resultset.</param>
/// <param name="filterName">The named filter.</param>
/// <returns>Returns the requested page from the collection using the supplied filters.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("get-filtered/{pageNumber}/{filterName}")]
[Route("~/api/core/item-selling-price-scrud-view/get-filtered/{pageNumber}/{filterName}")]
public IEnumerable<MixERP.Net.Entities.Core.ItemSellingPriceScrudView> GetFiltered(long pageNumber, string filterName)
{
try
{
return this.ItemSellingPriceScrudViewRepository.GetFiltered(pageNumber, filterName);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (MixERPException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
}
}
} |
# Copyright (C) 2010-2014 GRNET S.A.
#
# 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/>.
from django.core import urlresolvers
from django.views.decorators import csrf
from django.conf.urls import patterns
def _patch_pattern(regex_pattern):
"""
Patch pattern callback using csrf_exempt. Enforce
RegexURLPattern callback to get resolved if required.
"""
regex_pattern._callback = \
csrf.csrf_exempt(regex_pattern.callback)
def _patch_resolver(r):
"""
Patch all patterns found in resolver with _patch_pattern
"""
if hasattr(r, 'url_patterns'):
entries = r.url_patterns
else:
# first level view in patterns ?
entries = [r]
for entry in entries:
if isinstance(entry, urlresolvers.RegexURLResolver):
_patch_resolver(entry)
#if isinstance(entry, urlresolvers.RegexURLPattern):
# let it break...
else:
_patch_pattern(entry)
def api_patterns(*args, **kwargs):
"""
Protect all url patterns from csrf attacks.
"""
_patterns = patterns(*args, **kwargs)
for entry in _patterns:
_patch_resolver(entry)
return _patterns
|
#region License
// Copyright (c) 2013, ClearCanvas Inc.
// All rights reserved.
// http://www.clearcanvas.ca
//
// This file is part of the ClearCanvas RIS/PACS open source project.
//
// The ClearCanvas RIS/PACS open source project is free software: you can
// redistribute it and/or modify it under the terms of the GNU General Public
// License as published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// The ClearCanvas RIS/PACS open source project is distributed in the hope that it
// will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
// Public License for more details.
//
// You should have received a copy of the GNU General Public License along with
// the ClearCanvas RIS/PACS open source project. If not, see
// <http://www.gnu.org/licenses/>.
#endregion
using System;
using System.Windows.Forms;
using ClearCanvas.Desktop.View.WinForms;
using ClearCanvas.Ris.Client.View.WinForms;
namespace ClearCanvas.Ris.Client.Workflow.View.WinForms
{
/// <summary>
/// Provides a Windows Forms user-interface for <see cref="CheckInOrderComponent"/>
/// </summary>
public partial class MppsDocumentationComponentControl : ApplicationComponentUserControl
{
private readonly MppsDocumentationComponent _component;
private CannedTextSupport _cannedTextSupport;
/// <summary>
/// Constructor
/// </summary>
public MppsDocumentationComponentControl(MppsDocumentationComponent component)
: base(component)
{
InitializeComponent();
_component = component;
_label.DataBindings.Add("Text", _component, "CommentsLabel", true, DataSourceUpdateMode.OnPropertyChanged);
_comments.DataBindings.Add("Text", _component, "Comments", true, DataSourceUpdateMode.OnPropertyChanged);
_comments.DataBindings.Add("Enabled", _component, "CommentsEnabled", true, DataSourceUpdateMode.OnPropertyChanged);
_cannedTextSupport = new CannedTextSupport(_comments, _component.CannedTextLookupHandler);
}
}
}
|
<!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"/>
<title>iniparser: iniparser documentation</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<link href="doxygen.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<!-- Generated by Doxygen 1.6.3 -->
<div class="contents">
<h1>iniparser documentation </h1><h3 class="version">3.0 </h3><h2><a class="anchor" id="welcome">
Introduction</a></h2>
<p>iniParser is a simple C library offering ini file parsing services. The library is pretty small (less than 1500 lines of C) and robust, and does not depend on any other external library to compile. It is written in ANSI C and should compile on most platforms without difficulty.</p>
<h2><a class="anchor" id="inidef">
What is an ini file?</a></h2>
<p>An ini file is an ASCII file describing simple parameters (character strings, integers, floating-point values or booleans) in an explicit format, easy to use and modify for users.</p>
<p>An ini file is segmented into Sections, declared by the following syntax:</p>
<div class="fragment"><pre class="fragment">
[Section Name]
</pre></div><p>i.e. the section name enclosed in square brackets, alone on a line. Sections names are allowed to contain any character but square brackets or linefeeds.</p>
<p>In any section are zero or more variables, declared with the following syntax:</p>
<div class="fragment"><pre class="fragment">
Key = value ; comment
</pre></div><p>The key is any string (possibly containing blanks). The value is any character on the right side of the equal sign. Values can be given enclosed with quotes. If no quotes are present, the value is understood as containing all characters between the first and the last non-blank characters before the comment. The following declarations are identical:</p>
<div class="fragment"><pre class="fragment">
Hello = "this is a long string value" ; comment
Hello = this is a long string value ; comment
</pre></div><p>The semicolon and comment at the end of the line are optional. If there is a comment, it starts from the first character after the semicolon up to the end of the line.</p>
<p>Multi-line values can be provided by ending the line with a backslash (\).</p>
<div class="fragment"><pre class="fragment">
Multiple = Line 1 \
Line 2 \
Line 3 \
Line 4 ; comment
</pre></div><p>This would yield: "multiple" <- "Line1 Line2 Line3 Line4"</p>
<p>Comments in an ini file are:</p>
<ul>
<li>Lines starting with a hash sign</li>
<li>Blank lines (only blanks or tabs)</li>
<li>Comments given on value lines after the semicolon (if present)</li>
</ul>
<h2><a class="anchor" id="install">
Compiling/installing the library</a></h2>
<p>Edit the Makefile to indicate the C compiler you want to use, the options to provide to compile ANSI C, and possibly the options to pass to the ar program on your machine to build a library (.a) from a set of object (.o) files.</p>
<p>Defaults are set for the gcc compiler and the standard ar library builder.</p>
<p>Type 'make', that should do it.</p>
<p>To use the library in your programs, add the following line on top of your module:</p>
<div class="fragment"><pre class="fragment"><span class="preprocessor"> #include "<a class="code" href="iniparser_8h.html" title="Parser for ini files.">iniparser.h</a>"</span>
</pre></div><p>And link your program with the iniparser library by adding <code>-liniparser.a</code> to the compile line.</p>
<p>See the file test/initest.c for an example.</p>
<p>iniparser is an ANSI C library. If you want to compile it with a C++ compiler you will likely run into compatibility issues. Headers probably have to include the extern "C" hack and function prototypes will want to add some const here and there to keep the compiler happy. This job is left to the reader as there are too many C++ compilers around, each with its own requirements as to what represents acceptable C code in a C++ environment. You have been warned.</p>
<h2><a class="anchor" id="reference">
Library reference</a></h2>
<p>The library is completely documented in its header file. On-line documentation has been generated and can be consulted here:</p>
<ul>
<li><a class="el" href="iniparser_8h.html" title="Parser for ini files.">iniparser.h</a></li>
</ul>
<h2><a class="anchor" id="usage">
Using the parser</a></h2>
<p>Comments are discarded by the parser. Then sections are identified, and in each section a new entry is created for every keyword found. The keywords are stored with the following syntax:</p>
<div class="fragment"><pre class="fragment">
[Section]
Keyword = value ; comment
</pre></div><p>is converted to the following key pair:</p>
<div class="fragment"><pre class="fragment">
("section:keyword", "value")
</pre></div><p>This means that if you want to retrieve the value that was stored in the section called <code>Pizza</code>, in the keyword <code>Cheese</code>, you would make a request to the dictionary for <code>"pizza:cheese"</code>. All section and keyword names are converted to lowercase before storage in the structure. The value side is conserved as it has been parsed, though.</p>
<p>Section names are also stored in the structure. They are stored using as key the section name, and a NULL associated value. They can be queried through <a class="el" href="iniparser_8h.html#a3d67c98bbc0cb5239f024ad54bdc63f1" title="Finds out if a given entry exists in a dictionary.">iniparser_find_entry()</a>.</p>
<p>To launch the parser, use the function called <a class="el" href="iniparser_8h.html#a45d87791d4d2593781bfdfe2991c3a2d" title="Parse an ini file and return an allocated dictionary object.">iniparser_load()</a>, which takes an input file name and returns a newly allocated <em>dictionary</em> structure. This latter object should remain opaque to the user and only accessed through the following accessor functions:</p>
<ul>
<li><a class="el" href="iniparser_8h.html#aec2e5539bc2be063d1323cdf65f162a3" title="Get the string associated to a key.">iniparser_getstring()</a></li>
<li><a class="el" href="iniparser_8h.html#ab813340fa9c9a7fcfe6775d6e5e458c2" title="Get the string associated to a key, convert to an int.">iniparser_getint()</a></li>
<li><a class="el" href="iniparser_8h.html#a480d35322f1252344cf2246ac21ee559" title="Get the string associated to a key, convert to a double.">iniparser_getdouble()</a></li>
<li><a class="el" href="iniparser_8h.html#aa2ea2b34f6f4b3cf93c9d4f8f992811f" title="Get the string associated to a key, convert to a boolean.">iniparser_getboolean()</a></li>
</ul>
<p>Finally, discard this structure using <a class="el" href="iniparser_8h.html#a90549ee518523921886b74454ff872eb" title="Free all memory associated to an ini dictionary.">iniparser_freedict()</a>.</p>
<p>All values parsed from the ini file are stored as strings. The accessors are just converting these strings to the requested type on the fly, but you could basically perform this conversion by yourself after having called the string accessor.</p>
<p>Notice that <a class="el" href="iniparser_8h.html#aa2ea2b34f6f4b3cf93c9d4f8f992811f" title="Get the string associated to a key, convert to a boolean.">iniparser_getboolean()</a> will return an integer (0 or 1), trying to make sense of what was found in the file. Strings starting with "y", "Y", "t", "T" or "1" are considered true values (return 1), strings starting with "n", "N", "f", "F", "0" are considered false (return 0). This allows some flexibility in handling of boolean answers.</p>
<p>If you want to add extra information into the structure that was not present in the ini file, you can use <a class="el" href="iniparser_8h.html#aa5d5787f96d6982a937edb2fd499ba60" title="Set an entry in a dictionary.">iniparser_set()</a> to insert a string.</p>
<p>If you want to add a section to the structure, add a key with a NULL value. Example: </p>
<div class="fragment"><pre class="fragment">
iniparser_set(ini, "section", NULL);
iniparser_set(ini, "section:key1", NULL);
iniparser_set(ini, "section:key2", NULL);
</pre></div><h2><a class="anchor" id="implementation">
A word about the implementation</a></h2>
<p>The dictionary structure is a pretty simple dictionary implementation which might find some uses in other applications. If you are curious, look into the source.</p>
<h2><a class="anchor" id="defects">
Known defects</a></h2>
<p>The dictionary structure is extremely unefficient for searching as keys are sorted in the same order as they are read from the ini file, which is convenient when dumping back to a file. The simplistic first-approach linear search implemented there can become a bottleneck if you have a very large number of keys.</p>
<p>People who need to load large amounts of data from an ini file should definitely turn to more appropriate solutions: sqlite3 or similar. There are otherwise many other dictionary implementations available on the net to replace this one.</p>
<h2><a class="anchor" id="authors">
Authors</a></h2>
<p>Nicolas Devillard (ndevilla AT free DOT fr). </p>
</div>
<hr class="footer"/><address style="text-align: right;"><small>Generated on Wed Mar 2 22:04:58 2011 for iniparser by
<a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.6.3 </small></address>
</body>
</html>
|
package org.jboss.as.test.integration.jaxrs.decorator;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
/**
* @author Stuart Douglas
*/
@Path("decorator")
@Produces({"text/plain"})
public interface ResourceInterface {
@GET
String getMessage();
}
|
// 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 1.0.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.KeyVault.Models
{
using Azure;
using KeyVault;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// A Storage account bundle consists of key vault storage account details
/// plus its attributes.
/// </summary>
public partial class StorageBundle
{
/// <summary>
/// Initializes a new instance of the StorageBundle class.
/// </summary>
public StorageBundle() { }
/// <summary>
/// Initializes a new instance of the StorageBundle class.
/// </summary>
/// <param name="id">The storage account id.</param>
/// <param name="resourceId">The storage account resource id.</param>
/// <param name="activeKeyName">The current active storage account key
/// name.</param>
/// <param name="autoRegenerateKey">whether keyvault should manage the
/// storage account for the user.</param>
/// <param name="regenerationPeriod">The key regeneration time duration
/// specified in ISO-8601 format.</param>
/// <param name="attributes">The storage account attributes.</param>
/// <param name="tags">Application specific metadata in the form of
/// key-value pairs</param>
public StorageBundle(string id = default(string), string resourceId = default(string), string activeKeyName = default(string), bool? autoRegenerateKey = default(bool?), string regenerationPeriod = default(string), StorageAccountAttributes attributes = default(StorageAccountAttributes), IDictionary<string, string> tags = default(IDictionary<string, string>))
{
Id = id;
ResourceId = resourceId;
ActiveKeyName = activeKeyName;
AutoRegenerateKey = autoRegenerateKey;
RegenerationPeriod = regenerationPeriod;
Attributes = attributes;
Tags = tags;
}
/// <summary>
/// Gets the storage account id.
/// </summary>
[JsonProperty(PropertyName = "id")]
public string Id { get; protected set; }
/// <summary>
/// Gets the storage account resource id.
/// </summary>
[JsonProperty(PropertyName = "resourceId")]
public string ResourceId { get; protected set; }
/// <summary>
/// Gets the current active storage account key name.
/// </summary>
[JsonProperty(PropertyName = "activeKeyName")]
public string ActiveKeyName { get; protected set; }
/// <summary>
/// Gets whether keyvault should manage the storage account for the
/// user.
/// </summary>
[JsonProperty(PropertyName = "autoRegenerateKey")]
public bool? AutoRegenerateKey { get; protected set; }
/// <summary>
/// Gets the key regeneration time duration specified in ISO-8601
/// format.
/// </summary>
[JsonProperty(PropertyName = "regenerationPeriod")]
public string RegenerationPeriod { get; protected set; }
/// <summary>
/// Gets the storage account attributes.
/// </summary>
[JsonProperty(PropertyName = "attributes")]
public StorageAccountAttributes Attributes { get; protected set; }
/// <summary>
/// Gets application specific metadata in the form of key-value pairs
/// </summary>
[JsonProperty(PropertyName = "tags")]
public IDictionary<string, string> Tags { get; protected set; }
}
}
|
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the ec2-2014-10-01.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.EC2.Model
{
/// <summary>
/// Describes a static route for a VPN connection.
/// </summary>
public partial class VpnStaticRoute
{
private string _destinationCidrBlock;
private VpnStaticRouteSource _source;
private VpnState _state;
/// <summary>
/// Gets and sets the property DestinationCidrBlock.
/// <para>
/// The CIDR block associated with the local subnet of the customer data center.
/// </para>
/// </summary>
public string DestinationCidrBlock
{
get { return this._destinationCidrBlock; }
set { this._destinationCidrBlock = value; }
}
// Check to see if DestinationCidrBlock property is set
internal bool IsSetDestinationCidrBlock()
{
return this._destinationCidrBlock != null;
}
/// <summary>
/// Gets and sets the property Source.
/// <para>
/// Indicates how the routes were provided.
/// </para>
/// </summary>
public VpnStaticRouteSource Source
{
get { return this._source; }
set { this._source = value; }
}
// Check to see if Source property is set
internal bool IsSetSource()
{
return this._source != null;
}
/// <summary>
/// Gets and sets the property State.
/// <para>
/// The current state of the static route.
/// </para>
/// </summary>
public VpnState State
{
get { return this._state; }
set { this._state = value; }
}
// Check to see if State property is set
internal bool IsSetState()
{
return this._state != null;
}
}
} |
/*
* 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 gls.ch06.s05.testClasses;
import groovy.lang.GroovyObjectSupport;
public class Tt1go extends GroovyObjectSupport {
public String x = "field";
public String getX() {
return this.p1;
}
public void setX(final String x) {
this.p1 = x;
}
public String x() {
return "method";
}
public String p1 = "property";
}
|
package v1_test
import (
"reflect"
"testing"
"github.com/GoogleCloudPlatform/kubernetes/pkg/runtime"
kapi "github.com/GoogleCloudPlatform/kubernetes/pkg/api"
deployapi "github.com/openshift/origin/pkg/deploy/api"
current "github.com/openshift/origin/pkg/deploy/api/v1"
)
func roundTrip(t *testing.T, obj runtime.Object) runtime.Object {
data, err := kapi.Codec.Encode(obj)
if err != nil {
t.Errorf("%v\n %#v", err, obj)
return nil
}
obj2, err := kapi.Codec.Decode(data)
if err != nil {
t.Errorf("%v\nData: %s\nSource: %#v", err, string(data), obj)
return nil
}
obj3 := reflect.New(reflect.TypeOf(obj).Elem()).Interface().(runtime.Object)
err = kapi.Scheme.Convert(obj2, obj3)
if err != nil {
t.Errorf("%v\nSource: %#v", err, obj2)
return nil
}
return obj3
}
func TestDefaults_rollingParams(t *testing.T) {
c := ¤t.DeploymentConfig{}
o := roundTrip(t, runtime.Object(c))
config := o.(*current.DeploymentConfig)
strat := config.Spec.Strategy
if e, a := current.DeploymentStrategyTypeRolling, strat.Type; e != a {
t.Errorf("expected strategy type %s, got %s", e, a)
}
if e, a := deployapi.DefaultRollingUpdatePeriodSeconds, *strat.RollingParams.UpdatePeriodSeconds; e != a {
t.Errorf("expected UpdatePeriodSeconds %d, got %d", e, a)
}
if e, a := deployapi.DefaultRollingIntervalSeconds, *strat.RollingParams.IntervalSeconds; e != a {
t.Errorf("expected IntervalSeconds %d, got %d", e, a)
}
if e, a := deployapi.DefaultRollingTimeoutSeconds, *strat.RollingParams.TimeoutSeconds; e != a {
t.Errorf("expected UpdatePeriodSeconds %d, got %d", e, a)
}
}
|
/**
* Copyright 2014 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.mr4c.message;
import com.google.mr4c.util.MR4CLogging;
import java.io.IOException;
import java.net.URI;
import org.slf4j.Logger;
public class DefaultMessageHandler implements MessageHandler {
protected static final Logger s_log = MR4CLogging.getLogger(DefaultMessageHandler.class);
public void setURI(URI uri) {}
public void handleMessage(Message msg) throws IOException {
s_log.info("Message sent to default handler for topic [{}] : [{}]", msg.getTopic(), msg.getContent());
}
}
|
// <auto-generated>
// 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.
// </auto-generated>
namespace Microsoft.Azure.Management.ResourceManager.Models
{
using Microsoft.Rest;
using Newtonsoft.Json;
using System.Linq;
/// <summary>
/// Entity representing the reference to the template.
/// </summary>
public partial class TemplateLink
{
/// <summary>
/// Initializes a new instance of the TemplateLink class.
/// </summary>
public TemplateLink()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the TemplateLink class.
/// </summary>
/// <param name="uri">The URI of the template to deploy.</param>
/// <param name="contentVersion">If included, must match the
/// ContentVersion in the template.</param>
public TemplateLink(string uri, string contentVersion = default(string))
{
Uri = uri;
ContentVersion = contentVersion;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// Gets or sets the URI of the template to deploy.
/// </summary>
[JsonProperty(PropertyName = "uri")]
public string Uri { get; set; }
/// <summary>
/// Gets or sets if included, must match the ContentVersion in the
/// template.
/// </summary>
[JsonProperty(PropertyName = "contentVersion")]
public string ContentVersion { get; set; }
/// <summary>
/// Validate the object.
/// </summary>
/// <exception cref="ValidationException">
/// Thrown if validation fails
/// </exception>
public virtual void Validate()
{
if (Uri == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "Uri");
}
}
}
}
|
# Copyright 2013 Mirantis Inc.
# All Rights Reserved
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
#
# @author: Eugene Nikanorov, Mirantis Inc.
#
import sys
from neutronclient.neutron.v2_0 import servicetype
from neutronclient.tests.unit import test_cli20
class CLITestV20ServiceProvidersJSON(test_cli20.CLITestV20Base):
id_field = "name"
def setUp(self):
super(CLITestV20ServiceProvidersJSON, self).setUp(
plurals={'tags': 'tag'}
)
def test_list_service_providers(self):
resources = "service_providers"
cmd = servicetype.ListServiceProvider(test_cli20.MyApp(sys.stdout),
None)
self._test_list_resources(resources, cmd, True)
def test_list_service_providers_pagination(self):
resources = "service_providers"
cmd = servicetype.ListServiceProvider(test_cli20.MyApp(sys.stdout),
None)
self._test_list_resources_with_pagination(resources, cmd)
def test_list_service_providers_sort(self):
resources = "service_providers"
cmd = servicetype.ListServiceProvider(test_cli20.MyApp(sys.stdout),
None)
self._test_list_resources(resources, cmd,
sort_key=["name"],
sort_dir=["asc", "desc"])
def test_list_service_providers_limit(self):
resources = "service_providers"
cmd = servicetype.ListServiceProvider(test_cli20.MyApp(sys.stdout),
None)
self._test_list_resources(resources, cmd, page_size=1000)
class CLITestV20ServiceProvidersXML(CLITestV20ServiceProvidersJSON):
format = 'xml'
|
<html>
<body>
<font face="verdana" size="-1">This inspection reports unnecessary cast expressions.</font>
</body>
</html>
|
/*
Copyright 2015 Akexorcist
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.akexorcist.roundcornerprogressbar;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.os.Build;
import android.os.Parcel;
import android.os.Parcelable;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.akexorcist.roundcornerprogressbar.common.BaseRoundCornerProgressBar;
import java.text.NumberFormat;
public class TextRoundCornerProgressBar extends BaseRoundCornerProgressBar {
protected final static int DEFAULT_PROGRESS_BAR_HEIGHT = 30;
protected final static int DEFAULT_TEXT_PADDING = 10;
protected final static int DEFAULT_TEXT_SIZE = 18;
protected final static int DEFAULT_TEXT_WIDTH = 100;
protected final static int DEFAULT_TEXT_COLOR = Color.parseColor("#ff333333");
protected TextView textViewValue;
protected String text;
protected String textUnit;
protected boolean autoTextChange;
protected int textSize;
protected int textPadding;
protected int textWidth;
protected int textColor;
@SuppressLint("NewApi")
public TextRoundCornerProgressBar(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected int initProgressBarLayout() {
return R.layout.round_corner_with_text_layout;
}
@Override
protected void setup(TypedArray typedArray, DisplayMetrics metrics) {
autoTextChange = typedArray.getBoolean(R.styleable.RoundCornerProgress_rcAutoTextChange, false);
textSize = (int) typedArray.getDimension(R.styleable.RoundCornerProgress_rcTextProgressSize, DEFAULT_TEXT_SIZE);
textPadding = (int) typedArray.getDimension(R.styleable.RoundCornerProgress_rcTextProgressPadding, DEFAULT_TEXT_PADDING);
text = typedArray.getString(R.styleable.RoundCornerProgress_rcTextProgress);
text = (text == null) ? "" : text;
textUnit = typedArray.getString(R.styleable.RoundCornerProgress_rcTextProgressUnit);
textUnit = (textUnit == null) ? "" : textUnit;
textWidth = (int) typedArray.getDimension(R.styleable.RoundCornerProgress_rcTextProgressWidth, DEFAULT_TEXT_WIDTH);
textViewValue = (TextView) findViewById(R.id.round_corner_progress_text);
textViewValue.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize);
textViewValue.setTextColor(typedArray.getColor(R.styleable.RoundCornerProgress_rcTextProgressColor, DEFAULT_TEXT_COLOR));
textViewValue.setText(text);
textViewValue.setPadding(textPadding, 0, textPadding, 0);
}
@Override
public void setBackgroundLayoutSize(LinearLayout layoutBackground) {
int height, width;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
width = getMeasuredWidth() - textWidth;
height = getMeasuredHeight();
} else {
width = getWidth() - textWidth;
height = getHeight();
}
if(height == 0) {
height = (int) dp2px(DEFAULT_PROGRESS_BAR_HEIGHT);
}
setBackgroundWidth(width);
setBackgroundHeight(height);
}
@Override
protected void setGradientRadius(GradientDrawable gradient) {
int radius = getRadius() - (getPadding() / 2);
gradient.setCornerRadii(new float[]{radius, radius, radius, radius, radius, radius, radius, radius});
}
@Override
protected void onLayoutMeasured() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
setBackgroundWidth(getMeasuredWidth() - textWidth);
} else {
setBackgroundWidth(getWidth() - textWidth);
}
}
@Override
protected float setLayoutProgressWidth(float ratio) {
if (isAutoTextChange()) {
String strProgress = NumberFormat.getInstance().format((progress % 1 == 0) ? (int) progress : progress);
textViewValue.setText(strProgress + " " + textUnit);
}
return (ratio > 0) ? (getBackgroundWidth() - (getPadding() * 2)) / ratio : 0;
}
@Override
protected float setSecondaryLayoutProgressWidth(float ratio) {
return (ratio > 0) ? (getBackgroundWidth() - (getPadding() * 2)) / ratio : 0;
}
public void setTextUnit(String unit) {
textUnit = unit;
setProgress();
}
public String getTextUnit() {
return textUnit;
}
public void setTextProgress(CharSequence text) {
textViewValue.setText(text);
}
public CharSequence getTextProgress() {
return textViewValue.getText();
}
public void setTextColor(int color) {
textColor = color;
textViewValue.setTextColor(color);
}
public int getTextColor() {
return textColor;
}
public void setAutoTextChange(boolean isAuto) {
autoTextChange = isAuto;
}
public boolean isAutoTextChange() {
return autoTextChange;
}
@Override
protected Parcelable onSaveInstanceState() {
Parcelable superState = super.onSaveInstanceState();
SavedState ss = new SavedState(superState);
ss.autoTextChange = this.autoTextChange;
ss.textSize = this.textSize;
ss.textPadding = this.textPadding;
ss.textWidth = this.textWidth;
ss.textColor = this.textColor;
ss.text = this.text;
ss.textUnit = this.textUnit;
return ss;
}
@Override
protected void onRestoreInstanceState(Parcelable state) {
if(!(state instanceof SavedState)) {
super.onRestoreInstanceState(state);
return;
}
SavedState ss = (SavedState)state;
super.onRestoreInstanceState(ss.getSuperState());
this.autoTextChange = ss.autoTextChange;
this.textSize = ss.textSize;
this.textPadding = ss.textPadding;
this.textWidth = ss.textWidth;
this.textColor = ss.textColor;
this.text = ss.text;
this.textUnit = ss.textUnit;
setTextProgress(text + textUnit);
setTextColor(textColor);
}
private static class SavedState extends BaseSavedState {
String text;
String textUnit;
int textSize;
int textPadding;
int textWidth;
int textColor;
boolean autoTextChange;
SavedState(Parcelable superState) {
super(superState);
}
private SavedState(Parcel in) {
super(in);
this.textSize = in.readInt();
this.textPadding = in.readInt();
this.textWidth = in.readInt();
this.textColor = in.readInt();
this.autoTextChange = in.readByte() != 0;
this.text = in.readString();
this.textUnit = in.readString();
}
@Override
public void writeToParcel(Parcel out, int flags) {
super.writeToParcel(out, flags);
out.writeInt(this.textSize);
out.writeInt(this.textPadding);
out.writeInt(this.textWidth);
out.writeInt(this.textColor);
out.writeByte((byte) (this.autoTextChange ? 1 : 0));
out.writeString(this.text);
out.writeString(this.textUnit);
}
public static final Parcelable.Creator<SavedState> CREATOR = new Parcelable.Creator<SavedState>() {
public SavedState createFromParcel(Parcel in) {
return new SavedState(in);
}
public SavedState[] newArray(int size) {
return new SavedState[size];
}
};
}
}
|
/**
src/audio_reader/audio_reader_test.h
This simple test application uses an audio_reader and
content_pipe to read audio data from a file URI
Copyright (C) 2007-2009 STMicroelectronics
Copyright (C) 2007-2009 Nokia Corporation and/or its subsidiary(-ies).
This library is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the Free
Software Foundation; either version 2.1 of the License, or (at your option)
any later version.
This library is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
details.
You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation, Inc.,
51 Franklin St, Fifth Floor, Boston, MA
02110-1301 USA
*/
#ifndef __AUDIO_READER_TEST_H__
#define __AUDIO_READER_TEST_H__
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <string.h>
#include <pthread.h>
#include <unistd.h>
#include <sys/stat.h>
#include <OMX_Types.h>
#include <OMX_Core.h>
#include <OMX_Component.h>
#include <OMX_ContentPipe.h>
#include <OMX_Audio.h>
#include <bellagio/omx_comp_debug_levels.h>
#include <bellagio/tsemaphore.h>
#include "audio_reader.h"
/** Specification version*/
#define VERSIONMAJOR 1
#define VERSIONMINOR 1
#define VERSIONREVISION 0
#define VERSIONSTEP 0
/* Number of buffers used on each component port */
#define BUFFER_COUNT_ACTUAL 2
/* Application's private data */
typedef struct appPrivateType{
/* cmdline options */
int opd;
OMX_S8* szURI;
/* private data */
OMX_HANDLETYPE handle; /* handle for audio_reader */
OMX_HANDLETYPE pipe; /* handle for content_pipe */
tsem_t* eventSem;
tsem_t* eofSem;
} appPrivateType;
#endif
|
using System.Windows;
using System.Windows.Documents;
using Microsoft.VisualStudio.PlatformUI;
using NuGet.VisualStudio;
namespace NuGet.Dialog.PackageManagerUI
{
/// <summary>
/// Interaction logic for LicenseAcceptanceWindow.xaml
/// </summary>
public partial class LicenseAcceptanceWindow : DialogWindow
{
public LicenseAcceptanceWindow()
{
InitializeComponent();
}
private void OnDeclineButtonClick(object sender, RoutedEventArgs e)
{
this.DialogResult = false;
}
private void OnAcceptButtonClick(object sender, RoutedEventArgs e)
{
this.DialogResult = true;
}
private void OnViewLicenseTermsRequestNavigate(object sender, RoutedEventArgs e)
{
Hyperlink hyperlink = (Hyperlink)sender;
var licenseUrl = hyperlink.NavigateUri;
UriHelper.OpenExternalLink(licenseUrl);
}
}
} |
/*
* 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 description. -->
* Demonstrates usage of data streamer.
*/
package org.apache.ignite.examples.java8.streaming;
|
//=======================================================================
// Copyright 2001 Jeremy G. Siek, Andrew Lumsdaine, Lie-Quan Lee,
//
// 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)
//=======================================================================
#include <boost/config.hpp>
#include <iostream>
#include <fstream>
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/depth_first_search.hpp>
#include <boost/graph/graphviz.hpp>
#include <boost/graph/copy.hpp>
int
main(int argc, char *argv[])
{
if (argc < 3) {
std::cerr << "usage: reachable-loop-head.exe <in-file> <out-file>"
<< std::endl;
return -1;
}
using namespace boost;
GraphvizDigraph g;
read_graphviz(argv[1], g);
graph_traits < GraphvizDigraph >::vertex_descriptor loop_head = 1;
typedef color_traits < default_color_type > Color;
std::vector < default_color_type >
reachable_from_head(num_vertices(g), Color::white());
default_color_type c;
depth_first_visit(g, loop_head, default_dfs_visitor(),
make_iterator_property_map(reachable_from_head.begin(),
get(vertex_index, g), c));
property_map<GraphvizDigraph, vertex_attribute_t>::type
vattr_map = get(vertex_attribute, g);
graph_traits < GraphvizDigraph >::vertex_iterator i, i_end;
for (boost::tie(i, i_end) = vertices(g); i != i_end; ++i)
if (reachable_from_head[*i] != Color::white()) {
vattr_map[*i]["color"] = "gray";
vattr_map[*i]["style"] = "filled";
}
std::ofstream loops_out(argv[2]);
#if defined(BOOST_MSVC) && BOOST_MSVC <= 1300
// VC++ has trouble with the get_property() functions
loops_out << "digraph G {\n"
<< "size=\"3,3\"\n"
<< "ratio=\"fill\"\n"
<< "shape=\"box\"\n";
graph_traits<GraphvizDigraph>::vertex_iterator vi, vi_end;
for (boost::tie(vi, vi_end) = vertices(g); vi != vi_end; ++vi) {
loops_out << *vi << "[";
for (std::map<std::string,std::string>::iterator ai = vattr_map[*vi].begin();
ai != vattr_map[*vi].end(); ++ai) {
loops_out << ai->first << "=" << ai->second;
if (next(ai) != vattr_map[*vi].end())
loops_out << ", ";
}
loops_out<< "]";
}
property_map<GraphvizDigraph, edge_attribute_t>::type
eattr_map = get(edge_attribute, g);
graph_traits<GraphvizDigraph>::edge_iterator ei, ei_end;
for (boost::tie(ei, ei_end) = edges(g); ei != ei_end; ++ei) {
loops_out << source(*ei, g) << " -> " << target(*ei, g) << "[";
std::map<std::string,std::string>& attr_map = eattr_map[*ei];
for (std::map<std::string,std::string>::iterator eai = attr_map.begin();
eai != attr_map.end(); ++eai) {
loops_out << eai->first << "=" << eai->second;
if (next(eai) != attr_map.end())
loops_out << ", ";
}
loops_out<< "]";
}
loops_out << "}\n";
#else
get_property(g, graph_graph_attribute)["size"] = "3,3";
get_property(g, graph_graph_attribute)["ratio"] = "fill";
get_property(g, graph_vertex_attribute)["shape"] = "box";
write_graphviz(loops_out, g,
make_vertex_attributes_writer(g),
make_edge_attributes_writer(g),
make_graph_attributes_writer(g));
#endif
return EXIT_SUCCESS;
}
|
/**
* Copyright 2017 The AMP HTML 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.
*/
import {
IframeTransport,
getIframeTransportScriptUrl,
} from '../iframe-transport';
import {addParamsToUrl} from '../../../../src/url';
import {expectPostMessage} from '../../../../testing/iframe.js';
import {urls} from '../../../../src/config';
import {user} from '../../../../src/log';
describes.realWin('amp-analytics.iframe-transport', {amp: true}, env => {
let sandbox;
let iframeTransport;
const frameUrl = 'http://example.com';
beforeEach(() => {
sandbox = env.sandbox;
iframeTransport = new IframeTransport(
env.ampdoc.win,
'some_vendor_type',
{iframe: frameUrl},
frameUrl + '-1'
);
});
afterEach(() => {
IframeTransport.resetCrossDomainIframes();
});
function expectAllUnique(numArray) {
if (!numArray) {
return;
}
expect(numArray).to.have.lengthOf(new Set(numArray).size);
}
it('creates one frame per vendor type', () => {
const createCrossDomainIframeSpy = sandbox.spy(
iframeTransport,
'createCrossDomainIframe'
);
expect(createCrossDomainIframeSpy).to.not.be.called;
expect(IframeTransport.hasCrossDomainIframe(iframeTransport.getType())).to
.be.true;
iframeTransport.processCrossDomainIframe();
expect(createCrossDomainIframeSpy).to.not.be.called;
});
it('enqueues event messages correctly', () => {
const url = 'https://example.com/test';
const config = {iframe: url};
iframeTransport.sendRequest('hello, world!', config);
const {queue} = IframeTransport.getFrameData(iframeTransport.getType());
expect(queue.queueSize()).to.equal(1);
iframeTransport.sendRequest('hello again, world!', config);
expect(queue.queueSize()).to.equal(2);
});
it('does not cause sentinel collisions', () => {
const iframeTransport2 = new IframeTransport(
env.ampdoc.win,
'some_other_vendor_type',
{iframe: 'https://example.com/test2'},
'https://example.com/test2-2'
);
const frame1 = IframeTransport.getFrameData(iframeTransport.getType());
const frame2 = IframeTransport.getFrameData(iframeTransport2.getType());
expectAllUnique([
iframeTransport.getCreativeId(),
iframeTransport2.getCreativeId(),
frame1.frame.sentinel,
frame2.frame.sentinel,
]);
});
it('correctly tracks usageCount and destroys iframes', () => {
const frameUrl2 = 'https://example.com/test2';
const iframeTransport2 = new IframeTransport(
env.ampdoc.win,
'some_other_vendor_type',
{iframe: frameUrl2},
frameUrl2 + '-3'
);
const frame1 = IframeTransport.getFrameData(iframeTransport.getType());
const frame2 = IframeTransport.getFrameData(iframeTransport2.getType());
expect(frame1.usageCount).to.equal(1);
expect(frame2.usageCount).to.equal(1);
expect(env.win.document.getElementsByTagName('IFRAME')).to.have.lengthOf(2);
// Mark the iframes as used multiple times each.
iframeTransport.processCrossDomainIframe();
iframeTransport.processCrossDomainIframe();
iframeTransport2.processCrossDomainIframe();
iframeTransport2.processCrossDomainIframe();
iframeTransport2.processCrossDomainIframe();
expect(frame1.usageCount).to.equal(3);
expect(frame2.usageCount).to.equal(4);
// Stop using the iframes, make sure usage counts go to zero and they are
// removed from the DOM.
IframeTransport.markCrossDomainIframeAsDone(
env.win.document,
iframeTransport.getType()
);
expect(frame1.usageCount).to.equal(2);
IframeTransport.markCrossDomainIframeAsDone(
env.win.document,
iframeTransport.getType()
);
IframeTransport.markCrossDomainIframeAsDone(
env.win.document,
iframeTransport.getType()
);
expect(frame1.usageCount).to.equal(0);
expect(frame2.usageCount).to.equal(4); // (Still)
expect(env.win.document.getElementsByTagName('IFRAME')).to.have.lengthOf(1);
IframeTransport.markCrossDomainIframeAsDone(
env.win.document,
iframeTransport2.getType()
);
IframeTransport.markCrossDomainIframeAsDone(
env.win.document,
iframeTransport2.getType()
);
IframeTransport.markCrossDomainIframeAsDone(
env.win.document,
iframeTransport2.getType()
);
IframeTransport.markCrossDomainIframeAsDone(
env.win.document,
iframeTransport2.getType()
);
expect(frame2.usageCount).to.equal(0);
expect(env.win.document.getElementsByTagName('IFRAME')).to.have.lengthOf(0);
});
it('creates one PerformanceObserver per vendor type', () => {
const createPerformanceObserverSpy = sandbox.spy(
IframeTransport.prototype,
'createPerformanceObserver_'
);
expect(createPerformanceObserverSpy).to.not.be.called;
iframeTransport.processCrossDomainIframe(); // Create 2nd frame for 1st vendor
expect(createPerformanceObserverSpy).to.not.be.called;
// Create frame for a new vendor
const frameUrl2 = 'https://example.com/test2';
new IframeTransport(
env.ampdoc.win,
'some_other_vendor_type',
{iframe: frameUrl2},
frameUrl2 + '-3'
);
expect(createPerformanceObserverSpy).to.be.called;
});
it('gets correct client lib URL in local/test mode', () => {
const url = getIframeTransportScriptUrl(env.ampdoc.win);
expect(url).to.contain(env.win.location.host);
expect(url).to.contain('/dist/iframe-transport-client-lib.js');
});
it('gets correct client lib URL in prod mode', () => {
const url = getIframeTransportScriptUrl(env.ampdoc.win, true);
expect(url).to.contain(urls.thirdParty);
expect(url).to.contain('/iframe-transport-client-v0.js');
expect(url).to.equal(
'https://3p.ampproject.net/$internalRuntimeVersion$/' +
'iframe-transport-client-v0.js'
);
});
});
describes.realWin(
'amp-analytics.iframe-transport',
{amp: true, allowExternalResources: true},
env => {
it('logs poor performance of vendor iframe', () => {
const body =
'<html><head><script>' +
'function busyWait(count, duration, cb) {\n' +
' if (count) {\n' +
' var d = new Date();\n' +
' var d2 = null;\n' +
' do {\n' +
' d2 = new Date();\n' +
' } while (d2-d < duration);\n' + // Note the semicolon!
' setTimeout(function() { ' +
' busyWait(count-1, duration, cb);' +
' },0);\n' +
' } else {\n' +
' cb();\n' +
' }\n' +
'}\n' +
'function begin() {\n' +
' busyWait(5, 200, function() {\n' +
' window.parent.postMessage("doneSleeping", "*");\n' +
' });\n' +
'}' +
'</script></head>' +
'<body onload="javascript:begin()">' +
'Non-Performant Fake Iframe' +
'</body>' +
'</html>';
const frameUrl2 = addParamsToUrl(
'http://ads.localhost:' +
document.location.port +
'/amp4test/compose-doc',
{body}
);
sandbox.stub(env.ampdoc.win.document.body, 'appendChild');
new IframeTransport(
env.ampdoc.win,
'some_other_vendor_type',
{iframe: frameUrl2},
frameUrl2 + '-3'
);
sandbox.restore();
const errorSpy = sandbox.spy(user(), 'error');
const {frame} = IframeTransport.getFrameData('some_other_vendor_type');
frame.setAttribute('style', '');
env.ampdoc.win.document.body.appendChild(frame);
return new Promise((resolve, unused) => {
expectPostMessage(
frame.contentWindow,
env.ampdoc.win,
'doneSleeping'
).then(() => {
expect(errorSpy).to.be.called;
expect(errorSpy.args[0][1]).to.match(
/Long Task: Vendor: "some_other_vendor_type"/
);
resolve();
});
});
}).timeout(10000);
}
);
|
package org.zstack.header.host;
import org.zstack.header.message.NeedReplyMessage;
import org.zstack.header.vm.VmNicInventory;
import java.util.List;
public class AttachNicToVmOnHypervisorMsg extends NeedReplyMessage implements HostMessage {
private String vmInstanceUuid;
private String hostUuid;
private List<VmNicInventory> nics;
public String getVmUuid() {
return vmInstanceUuid;
}
public void setVmUuid(String vmInstanceUuid) {
this.vmInstanceUuid = vmInstanceUuid;
}
public List<VmNicInventory> getNics() {
return nics;
}
public void setNics(List<VmNicInventory> nics) {
this.nics = nics;
}
public void setHostUuid(String hostUuid) {
this.hostUuid = hostUuid;
}
@Override
public String getHostUuid() {
return hostUuid;
}
}
|
/*
Copyright (c) 2014 VMware, Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package ls
import (
"flag"
"fmt"
"io"
"github.com/vmware/govmomi/govc/cli"
"github.com/vmware/govmomi/govc/flags"
"github.com/vmware/govmomi/list"
"github.com/vmware/govmomi/vim25/mo"
"golang.org/x/net/context"
)
type ls struct {
*flags.DatacenterFlag
Long bool
}
func init() {
cli.Register("ls", &ls{})
}
func (cmd *ls) Register(f *flag.FlagSet) {
f.BoolVar(&cmd.Long, "l", false, "Long listing format")
}
func (cmd *ls) Process() error { return nil }
func (cmd *ls) Usage() string {
return "[PATH]..."
}
func (cmd *ls) Run(f *flag.FlagSet) error {
finder, err := cmd.Finder()
if err != nil {
return err
}
lr := listResult{
Elements: nil,
Long: cmd.Long,
}
args := f.Args()
if len(args) == 0 {
args = []string{"."}
}
for _, arg := range args {
es, err := finder.ManagedObjectListChildren(context.TODO(), arg)
if err != nil {
return err
}
lr.Elements = append(lr.Elements, es...)
}
return cmd.WriteResult(lr)
}
type listResult struct {
Elements []list.Element `json:"elements"`
Long bool `json:"-"`
}
func (l listResult) Write(w io.Writer) error {
var err error
for _, e := range l.Elements {
if !l.Long {
fmt.Fprintf(w, "%s\n", e.Path)
continue
}
switch e.Object.(type) {
case mo.Folder:
if _, err = fmt.Fprintf(w, "%s/\n", e.Path); err != nil {
return err
}
default:
if _, err = fmt.Fprintf(w, "%s (%s)\n", e.Path, e.Object.Reference().Type); err != nil {
return err
}
}
}
return nil
}
|
/*
* 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.flink.runtime.concurrent;
/**
* Flink's completable future abstraction. A completable future can be completed with a regular
* value or an exception.
*
* @param <T> type of the future's value
*/
public interface CompletableFuture<T> extends Future<T> {
/**
* Completes the future with the given value. The complete operation only succeeds if the future
* has not been completed before. Whether it is successful or not is returned by the method.
*
* @param value to complete the future with
* @return true if the completion was successful; otherwise false
*/
boolean complete(T value);
/**
* Completes the future with the given exception. The complete operation only succeeds if the
* future has not been completed before. Whether it is successful or not is returned by the
* method.
*
* @param t the exception to complete the future with
* @return true if the completion was successful; otherwise false
*/
boolean completeExceptionally(Throwable t);
}
|
<?php
/**
* Class used internally by Horde_Text_Diff to actually compute the diffs.
*
* This class is implemented using native PHP code.
*
* The algorithm used here is mostly lifted from the perl module
* Algorithm::Diff (version 1.06) by Ned Konz, which is available at:
* http://www.perl.com/CPAN/authors/id/N/NE/NEDKONZ/Algorithm-Diff-1.06.zip
*
* More ideas are taken from: http://www.ics.uci.edu/~eppstein/161/960229.html
*
* Some ideas (and a bit of code) are taken from analyze.c, of GNU
* diffutils-2.7, which can be found at:
* ftp://gnudist.gnu.org/pub/gnu/diffutils/diffutils-2.7.tar.gz
*
* Some ideas (subdivision by NCHUNKS > 2, and some optimizations) are from
* Geoffrey T. Dairiki <dairiki@dairiki.org>. The original PHP version of this
* code was written by him, and is used/adapted with his permission.
*
* Copyright 2004-2011 Horde LLC (http://www.horde.org/)
*
* See the enclosed file COPYING for license information (LGPL). If you did
* not receive this file, see http://www.horde.org/licenses/lgpl21.
*
* @author Geoffrey T. Dairiki <dairiki@dairiki.org>
* @package Text_Diff
*/
// Disallow direct access to this file for security reasons
if(!defined("IN_MYBB"))
{
die("Direct initialization of this file is not allowed.<br /><br />Please make sure IN_MYBB is defined.");
}
class Horde_Text_Diff_Engine_Native
{
public function diff($from_lines, $to_lines)
{
array_walk($from_lines, array('Horde_Text_Diff', 'trimNewlines'));
array_walk($to_lines, array('Horde_Text_Diff', 'trimNewlines'));
$n_from = count($from_lines);
$n_to = count($to_lines);
$this->xchanged = $this->ychanged = array();
$this->xv = $this->yv = array();
$this->xind = $this->yind = array();
unset($this->seq);
unset($this->in_seq);
unset($this->lcs);
// Skip leading common lines.
for ($skip = 0; $skip < $n_from && $skip < $n_to; $skip++) {
if ($from_lines[$skip] !== $to_lines[$skip]) {
break;
}
$this->xchanged[$skip] = $this->ychanged[$skip] = false;
}
// Skip trailing common lines.
$xi = $n_from; $yi = $n_to;
for ($endskip = 0; --$xi > $skip && --$yi > $skip; $endskip++) {
if ($from_lines[$xi] !== $to_lines[$yi]) {
break;
}
$this->xchanged[$xi] = $this->ychanged[$yi] = false;
}
// Ignore lines which do not exist in both files.
for ($xi = $skip; $xi < $n_from - $endskip; $xi++) {
$xhash[$from_lines[$xi]] = 1;
}
for ($yi = $skip; $yi < $n_to - $endskip; $yi++) {
$line = $to_lines[$yi];
if (($this->ychanged[$yi] = empty($xhash[$line]))) {
continue;
}
$yhash[$line] = 1;
$this->yv[] = $line;
$this->yind[] = $yi;
}
for ($xi = $skip; $xi < $n_from - $endskip; $xi++) {
$line = $from_lines[$xi];
if (($this->xchanged[$xi] = empty($yhash[$line]))) {
continue;
}
$this->xv[] = $line;
$this->xind[] = $xi;
}
// Find the LCS.
$this->_compareseq(0, count($this->xv), 0, count($this->yv));
// Merge edits when possible.
$this->_shiftBoundaries($from_lines, $this->xchanged, $this->ychanged);
$this->_shiftBoundaries($to_lines, $this->ychanged, $this->xchanged);
// Compute the edit operations.
$edits = array();
$xi = $yi = 0;
while ($xi < $n_from || $yi < $n_to) {
assert($yi < $n_to || $this->xchanged[$xi]);
assert($xi < $n_from || $this->ychanged[$yi]);
// Skip matching "snake".
$copy = array();
while ($xi < $n_from && $yi < $n_to
&& !$this->xchanged[$xi] && !$this->ychanged[$yi]) {
$copy[] = $from_lines[$xi++];
++$yi;
}
if ($copy) {
$edits[] = new Horde_Text_Diff_Op_Copy($copy);
}
// Find deletes & adds.
$delete = array();
while ($xi < $n_from && $this->xchanged[$xi]) {
$delete[] = $from_lines[$xi++];
}
$add = array();
while ($yi < $n_to && $this->ychanged[$yi]) {
$add[] = $to_lines[$yi++];
}
if ($delete && $add) {
$edits[] = new Horde_Text_Diff_Op_Change($delete, $add);
} elseif ($delete) {
$edits[] = new Horde_Text_Diff_Op_Delete($delete);
} elseif ($add) {
$edits[] = new Horde_Text_Diff_Op_Add($add);
}
}
return $edits;
}
/**
* Divides the Largest Common Subsequence (LCS) of the sequences (XOFF,
* XLIM) and (YOFF, YLIM) into NCHUNKS approximately equally sized
* segments.
*
* Returns (LCS, PTS). LCS is the length of the LCS. PTS is an array of
* NCHUNKS+1 (X, Y) indexes giving the diving points between sub
* sequences. The first sub-sequence is contained in (X0, X1), (Y0, Y1),
* the second in (X1, X2), (Y1, Y2) and so on. Note that (X0, Y0) ==
* (XOFF, YOFF) and (X[NCHUNKS], Y[NCHUNKS]) == (XLIM, YLIM).
*
* This public function assumes that the first lines of the specified portions of
* the two files do not match, and likewise that the last lines do not
* match. The caller must trim matching lines from the beginning and end
* of the portions it is going to specify.
*/
protected function _diag ($xoff, $xlim, $yoff, $ylim, $nchunks)
{
$flip = false;
if ($xlim - $xoff > $ylim - $yoff) {
/* Things seems faster (I'm not sure I understand why) when the
* shortest sequence is in X. */
$flip = true;
list ($xoff, $xlim, $yoff, $ylim)
= array($yoff, $ylim, $xoff, $xlim);
}
if ($flip) {
for ($i = $ylim - 1; $i >= $yoff; $i--) {
$ymatches[$this->xv[$i]][] = $i;
}
} else {
for ($i = $ylim - 1; $i >= $yoff; $i--) {
$ymatches[$this->yv[$i]][] = $i;
}
}
$this->lcs = 0;
$this->seq[0]= $yoff - 1;
$this->in_seq = array();
$ymids[0] = array();
$numer = $xlim - $xoff + $nchunks - 1;
$x = $xoff;
for ($chunk = 0; $chunk < $nchunks; $chunk++) {
if ($chunk > 0) {
for ($i = 0; $i <= $this->lcs; $i++) {
$ymids[$i][$chunk - 1] = $this->seq[$i];
}
}
$x1 = $xoff + (int)(($numer + ($xlim - $xoff) * $chunk) / $nchunks);
for (; $x < $x1; $x++) {
$line = $flip ? $this->yv[$x] : $this->xv[$x];
if (empty($ymatches[$line])) {
continue;
}
$matches = $ymatches[$line];
reset($matches);
while (list(, $y) = each($matches)) {
if (empty($this->in_seq[$y])) {
$k = $this->_lcsPos($y);
assert($k > 0);
$ymids[$k] = $ymids[$k - 1];
break;
}
}
while (list(, $y) = each($matches)) {
if ($y > $this->seq[$k - 1]) {
assert($y <= $this->seq[$k]);
/* Optimization: this is a common case: next match is
* just replacing previous match. */
$this->in_seq[$this->seq[$k]] = false;
$this->seq[$k] = $y;
$this->in_seq[$y] = 1;
} elseif (empty($this->in_seq[$y])) {
$k = $this->_lcsPos($y);
assert($k > 0);
$ymids[$k] = $ymids[$k - 1];
}
}
}
}
$seps[] = $flip ? array($yoff, $xoff) : array($xoff, $yoff);
$ymid = $ymids[$this->lcs];
for ($n = 0; $n < $nchunks - 1; $n++) {
$x1 = $xoff + (int)(($numer + ($xlim - $xoff) * $n) / $nchunks);
$y1 = $ymid[$n] + 1;
$seps[] = $flip ? array($y1, $x1) : array($x1, $y1);
}
$seps[] = $flip ? array($ylim, $xlim) : array($xlim, $ylim);
return array($this->lcs, $seps);
}
protected function _lcsPos($ypos)
{
$end = $this->lcs;
if ($end == 0 || $ypos > $this->seq[$end]) {
$this->seq[++$this->lcs] = $ypos;
$this->in_seq[$ypos] = 1;
return $this->lcs;
}
$beg = 1;
while ($beg < $end) {
$mid = (int)(($beg + $end) / 2);
if ($ypos > $this->seq[$mid]) {
$beg = $mid + 1;
} else {
$end = $mid;
}
}
assert($ypos != $this->seq[$end]);
$this->in_seq[$this->seq[$end]] = false;
$this->seq[$end] = $ypos;
$this->in_seq[$ypos] = 1;
return $end;
}
/**
* Finds LCS of two sequences.
*
* The results are recorded in the vectors $this->{x,y}changed[], by
* storing a 1 in the element for each line that is an insertion or
* deletion (ie. is not in the LCS).
*
* The subsequence of file 0 is (XOFF, XLIM) and likewise for file 1.
*
* Note that XLIM, YLIM are exclusive bounds. All line numbers are
* origin-0 and discarded lines are not counted.
*/
protected function _compareseq ($xoff, $xlim, $yoff, $ylim)
{
/* Slide down the bottom initial diagonal. */
while ($xoff < $xlim && $yoff < $ylim
&& $this->xv[$xoff] == $this->yv[$yoff]) {
++$xoff;
++$yoff;
}
/* Slide up the top initial diagonal. */
while ($xlim > $xoff && $ylim > $yoff
&& $this->xv[$xlim - 1] == $this->yv[$ylim - 1]) {
--$xlim;
--$ylim;
}
if ($xoff == $xlim || $yoff == $ylim) {
$lcs = 0;
} else {
/* This is ad hoc but seems to work well. $nchunks =
* sqrt(min($xlim - $xoff, $ylim - $yoff) / 2.5); $nchunks =
* max(2,min(8,(int)$nchunks)); */
$nchunks = min(7, $xlim - $xoff, $ylim - $yoff) + 1;
list($lcs, $seps)
= $this->_diag($xoff, $xlim, $yoff, $ylim, $nchunks);
}
if ($lcs == 0) {
/* X and Y sequences have no common subsequence: mark all
* changed. */
while ($yoff < $ylim) {
$this->ychanged[$this->yind[$yoff++]] = 1;
}
while ($xoff < $xlim) {
$this->xchanged[$this->xind[$xoff++]] = 1;
}
} else {
/* Use the partitions to split this problem into subproblems. */
reset($seps);
$pt1 = $seps[0];
while ($pt2 = next($seps)) {
$this->_compareseq ($pt1[0], $pt2[0], $pt1[1], $pt2[1]);
$pt1 = $pt2;
}
}
}
/**
* Adjusts inserts/deletes of identical lines to join changes as much as
* possible.
*
* We do something when a run of changed lines include a line at one end
* and has an excluded, identical line at the other. We are free to
* choose which identical line is included. `compareseq' usually chooses
* the one at the beginning, but usually it is cleaner to consider the
* following identical line to be the "change".
*
* This is extracted verbatim from analyze.c (GNU diffutils-2.7).
*/
protected function _shiftBoundaries($lines, &$changed, $other_changed)
{
$i = 0;
$j = 0;
assert('count($lines) == count($changed)');
$len = count($lines);
$other_len = count($other_changed);
while (1) {
/* Scan forward to find the beginning of another run of
* changes. Also keep track of the corresponding point in the
* other file.
*
* Throughout this code, $i and $j are adjusted together so that
* the first $i elements of $changed and the first $j elements of
* $other_changed both contain the same number of zeros (unchanged
* lines).
*
* Furthermore, $j is always kept so that $j == $other_len or
* $other_changed[$j] == false. */
while ($j < $other_len && $other_changed[$j]) {
$j++;
}
while ($i < $len && ! $changed[$i]) {
assert('$j < $other_len && ! $other_changed[$j]');
$i++; $j++;
while ($j < $other_len && $other_changed[$j]) {
$j++;
}
}
if ($i == $len) {
break;
}
$start = $i;
/* Find the end of this run of changes. */
while (++$i < $len && $changed[$i]) {
continue;
}
do {
/* Record the length of this run of changes, so that we can
* later determine whether the run has grown. */
$runlength = $i - $start;
/* Move the changed region back, so long as the previous
* unchanged line matches the last changed one. This merges
* with previous changed regions. */
while ($start > 0 && $lines[$start - 1] == $lines[$i - 1]) {
$changed[--$start] = 1;
$changed[--$i] = false;
while ($start > 0 && $changed[$start - 1]) {
$start--;
}
assert('$j > 0');
while ($other_changed[--$j]) {
continue;
}
assert('$j >= 0 && !$other_changed[$j]');
}
/* Set CORRESPONDING to the end of the changed run, at the
* last point where it corresponds to a changed run in the
* other file. CORRESPONDING == LEN means no such point has
* been found. */
$corresponding = $j < $other_len ? $i : $len;
/* Move the changed region forward, so long as the first
* changed line matches the following unchanged one. This
* merges with following changed regions. Do this second, so
* that if there are no merges, the changed region is moved
* forward as far as possible. */
while ($i < $len && $lines[$start] == $lines[$i]) {
$changed[$start++] = false;
$changed[$i++] = 1;
while ($i < $len && $changed[$i]) {
$i++;
}
assert('$j < $other_len && ! $other_changed[$j]');
$j++;
if ($j < $other_len && $other_changed[$j]) {
$corresponding = $i;
while ($j < $other_len && $other_changed[$j]) {
$j++;
}
}
}
} while ($runlength != $i - $start);
/* If possible, move the fully-merged run of changes back to a
* corresponding run in the other file. */
while ($corresponding < $i) {
$changed[--$start] = 1;
$changed[--$i] = 0;
assert('$j > 0');
while ($other_changed[--$j]) {
continue;
}
assert('$j >= 0 && !$other_changed[$j]');
}
}
}
}
|
// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
#pragma once
// multi producer-multi consumer blocking queue.
// enqueue(..) - will block until room found to put the new message.
// enqueue_nowait(..) - will return immediately with false if no room left in
// the queue.
// dequeue_for(..) - will block until the queue is not empty or timeout have
// passed.
#include <spdlog/details/circular_q.h>
#include <condition_variable>
#include <mutex>
namespace spdlog {
namespace details {
template<typename T>
class mpmc_blocking_queue
{
public:
using item_type = T;
explicit mpmc_blocking_queue(size_t max_items)
: q_(max_items)
{}
#ifndef __MINGW32__
// try to enqueue and block if no room left
void enqueue(T &&item)
{
{
std::unique_lock<std::mutex> lock(queue_mutex_);
pop_cv_.wait(lock, [this] { return !this->q_.full(); });
q_.push_back(std::move(item));
}
push_cv_.notify_one();
}
// enqueue immediately. overrun oldest message in the queue if no room left.
void enqueue_nowait(T &&item)
{
{
std::unique_lock<std::mutex> lock(queue_mutex_);
q_.push_back(std::move(item));
}
push_cv_.notify_one();
}
// try to dequeue item. if no item found. wait upto timeout and try again
// Return true, if succeeded dequeue item, false otherwise
bool dequeue_for(T &popped_item, std::chrono::milliseconds wait_duration)
{
{
std::unique_lock<std::mutex> lock(queue_mutex_);
if (!push_cv_.wait_for(lock, wait_duration, [this] { return !this->q_.empty(); }))
{
return false;
}
popped_item = std::move(q_.front());
q_.pop_front();
}
pop_cv_.notify_one();
return true;
}
#else
// apparently mingw deadlocks if the mutex is released before cv.notify_one(),
// so release the mutex at the very end each function.
// try to enqueue and block if no room left
void enqueue(T &&item)
{
std::unique_lock<std::mutex> lock(queue_mutex_);
pop_cv_.wait(lock, [this] { return !this->q_.full(); });
q_.push_back(std::move(item));
push_cv_.notify_one();
}
// enqueue immediately. overrun oldest message in the queue if no room left.
void enqueue_nowait(T &&item)
{
std::unique_lock<std::mutex> lock(queue_mutex_);
q_.push_back(std::move(item));
push_cv_.notify_one();
}
// try to dequeue item. if no item found. wait upto timeout and try again
// Return true, if succeeded dequeue item, false otherwise
bool dequeue_for(T &popped_item, std::chrono::milliseconds wait_duration)
{
std::unique_lock<std::mutex> lock(queue_mutex_);
if (!push_cv_.wait_for(lock, wait_duration, [this] { return !this->q_.empty(); }))
{
return false;
}
popped_item = std::move(q_.front());
q_.pop_front();
pop_cv_.notify_one();
return true;
}
#endif
size_t overrun_counter()
{
std::unique_lock<std::mutex> lock(queue_mutex_);
return q_.overrun_counter();
}
private:
std::mutex queue_mutex_;
std::condition_variable push_cv_;
std::condition_variable pop_cv_;
spdlog::details::circular_q<T> q_;
};
} // namespace details
} // namespace spdlog
|
// Copyright 2016 Twitter. 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.
package com.twitter.bazel.checkstyle;
import java.io.IOException;
import java.util.Collection;
import java.util.logging.Logger;
import com.google.common.base.Joiner;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.google.common.collect.Collections2;
import com.google.devtools.build.lib.actions.extra.ExtraActionInfo;
import com.google.devtools.build.lib.actions.extra.JavaCompileInfo;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.commons.lang.ArrayUtils;
/**
* Verifies that the java classes styles conform to the styles in the config.
* Usage: java com.twitter.bazel.checkstyle.JavaCheckstyle -f <extra_action_file> -c <checkstyle_config>
* <p>
* To test:
* $ bazel build --config=darwin heron/spi/src/java:heron-spi --experimental_action_listener=tools/java:compile_java
*/
public final class JavaCheckstyle {
public static final Logger LOG = Logger.getLogger(JavaCheckstyle.class.getName());
private static final String CLASSNAME = JavaCheckstyle.class.getCanonicalName();
private JavaCheckstyle() {
}
public static void main(String[] args) throws IOException {
CommandLineParser parser = new DefaultParser();
// create the Options
Options options = new Options();
options.addOption(Option.builder("f")
.required(true).hasArg()
.longOpt("extra_action_file")
.desc("bazel extra action protobuf file")
.build());
options.addOption(Option.builder("hc")
.required(true).hasArg()
.longOpt("heron_checkstyle_config_file")
.desc("checkstyle config file")
.build());
options.addOption(Option.builder("ac")
.required(true).hasArg()
.longOpt("apache_checkstyle_config_file")
.desc("checkstyle config file for imported source files")
.build());
try {
// parse the command line arguments
CommandLine line = parser.parse(options, args);
String extraActionFile = line.getOptionValue("f");
String configFile = line.getOptionValue("hc");
String apacheConfigFile = line.getOptionValue("ac");
// check heron source file style
String[] heronSourceFiles = getHeronSourceFiles(extraActionFile);
checkStyle(heronSourceFiles, configFile);
// check other apache source file style
String[] apacheSourceFiles = getApacheSourceFiles(extraActionFile);
checkStyle(apacheSourceFiles, apacheConfigFile);
} catch (ParseException exp) {
LOG.severe(String.format("Invalid input to %s: %s", CLASSNAME, exp.getMessage()));
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("java " + CLASSNAME, options);
}
}
private static void checkStyle(String[] files, String config) throws IOException {
if (files.length == 0) {
LOG.fine("No java files found by checkstyle");
return;
}
LOG.fine(files.length + " java files found by checkstyle");
String[] checkstyleArgs = (String[]) ArrayUtils.addAll(
new String[]{"-c", config}, files);
LOG.fine("checkstyle args: " + Joiner.on(" ").join(checkstyleArgs));
com.puppycrawl.tools.checkstyle.Main.main(checkstyleArgs);
}
private static String[] getHeronSourceFiles(String extraActionFile) {
return getSourceFiles(extraActionFile, Predicates.not(Predicates.or(
Predicates.containsPattern("heron/storm.src.java"),
Predicates.containsPattern("contrib")
)));
}
private static String[] getApacheSourceFiles(String extraActionFile) {
return getSourceFiles(extraActionFile, Predicates.or(
Predicates.containsPattern("heron/storm.src.java"),
Predicates.containsPattern("contrib")
));
}
private static String[] getSourceFiles(String extraActionFile,
Predicate<CharSequence> predicate) {
ExtraActionInfo info = ExtraActionUtils.getExtraActionInfo(extraActionFile);
JavaCompileInfo jInfo = info.getExtension(JavaCompileInfo.javaCompileInfo);
Collection<String> sourceFiles = Collections2.filter(jInfo.getSourceFileList(), predicate);
return sourceFiles.toArray(new String[sourceFiles.size()]);
}
}
|
//===----------------------------------------------------------------------===//
//
// Peloton
//
// skiplist.h
//
// Identification: src/include/index/skiplist.h
//
// Copyright (c) 2015-17, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//
#pragma once
namespace peloton {
namespace index {
/*
* SKIPLIST_TEMPLATE_ARGUMENTS - Save some key strokes
*/
#define SKIPLIST_TEMPLATE_ARGUMENTS \
template <typename KeyType, typename ValueType, typename KeyComparator, \
typename KeyEqualityChecker, typename ValueEqualityChecker>
template <typename KeyType, typename ValueType, typename KeyComparator,
typename KeyEqualityChecker, typename ValueEqualityChecker>
class SkipList {
// TODO: Add your declarations here
};
} // namespace index
} // namespace peloton
|
/*
* Copyright 2010 The Closure Compiler 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 com.google.javascript.jscomp;
import com.google.common.base.Function;
import com.google.common.base.Preconditions;
import com.google.javascript.jscomp.graph.LatticeElement;
import java.util.List;
/**
* Defines a way join a list of LatticeElements.
*/
interface JoinOp<L extends LatticeElement> extends Function<List<L>, L> {
/**
* An implementation of {@code JoinOp} that makes it easy to join to
* lattice elements at a time.
*/
static abstract class BinaryJoinOp<L extends LatticeElement>
implements JoinOp<L> {
@Override
public final L apply(List<L> values) {
Preconditions.checkArgument(!values.isEmpty());
int size = values.size();
if (size == 1) {
return values.get(0);
} else if (size == 2) {
return apply(values.get(0), values.get(1));
} else {
int mid = computeMidPoint(size);
return apply(
apply(values.subList(0, mid)),
apply(values.subList(mid, size)));
}
}
/**
* Creates a new lattice that will be the join of two input lattices.
*
* @return The join of {@code latticeA} and {@code latticeB}.
*/
abstract L apply(L latticeA, L latticeB);
/**
* Finds the midpoint of a list. The function will favor two lists of
* even length instead of two lists of the same odd length. The list
* must be at least length two.
*
* @param size Size of the list.
*/
static int computeMidPoint(int size) {
int midpoint = size >>> 1;
if (size > 4) {
/* Any list longer than 4 should prefer an even split point
* over the true midpoint, so that [0,6] splits at 2, not 3. */
midpoint &= -2; // (0xfffffffe) clears low bit so midpoint is even
}
return midpoint;
}
}
}
|
/**
src/base/omx_base_filter.c
OpenMAX Base Filter component. This component does not perform any multimedia
processing. It derives from base component and contains two ports. It can be used
as a base class for codec and filter components.
Copyright (C) 2007-2009 STMicroelectronics
Copyright (C) 2007-2009 Nokia Corporation and/or its subsidiary(-ies).
This library is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the Free
Software Foundation; either version 2.1 of the License, or (at your option)
any later version.
This library is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
details.
You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation, Inc.,
51 Franklin St, Fifth Floor, Boston, MA
02110-1301 USA
*/
#include <unistd.h>
#include <asm/unistd.h>
#include <omxcore.h>
#include "omx_base_filter.h"
OMX_ERRORTYPE omx_base_filter_Constructor(OMX_COMPONENTTYPE *openmaxStandComp,OMX_STRING cComponentName) {
OMX_ERRORTYPE err;
omx_base_filter_PrivateType* omx_base_filter_Private;
DEBUG(DEB_LEV_FUNCTION_NAME, "In %s of component %x\n", __func__, (int)openmaxStandComp);
if (openmaxStandComp->pComponentPrivate) {
omx_base_filter_Private = (omx_base_filter_PrivateType*)openmaxStandComp->pComponentPrivate;
} else {
omx_base_filter_Private = calloc(1,sizeof(omx_base_filter_PrivateType));
if (!omx_base_filter_Private) {
DEBUG(DEB_LEV_ERR, "Insufficient memory in %s\n", __func__);
return OMX_ErrorInsufficientResources;
}
openmaxStandComp->pComponentPrivate=omx_base_filter_Private;
}
/* Call the base class constructor */
err = omx_base_component_Constructor(openmaxStandComp,cComponentName);
if (err != OMX_ErrorNone) {
DEBUG(DEB_LEV_ERR, "The base constructor failed in %s\n", __func__);
return err;
}
/* here we can override whatever defaults the base_component constructor set
* e.g. we can override the function pointers in the private struct */
omx_base_filter_Private = openmaxStandComp->pComponentPrivate;
omx_base_filter_Private->BufferMgmtFunction = omx_base_filter_BufferMgmtFunction;
DEBUG(DEB_LEV_FUNCTION_NAME, "Out of %s of component %x\n", __func__, (int)openmaxStandComp);
return OMX_ErrorNone;
}
OMX_ERRORTYPE omx_base_filter_Destructor(OMX_COMPONENTTYPE *openmaxStandComp) {
OMX_ERRORTYPE err;
DEBUG(DEB_LEV_FUNCTION_NAME, "In %s of component %x\n", __func__, (int)openmaxStandComp);
err = omx_base_component_Destructor(openmaxStandComp);
if (err != OMX_ErrorNone) {
DEBUG(DEB_LEV_ERR, "The base component destructor failed\n");
return err;
}
DEBUG(DEB_LEV_FUNCTION_NAME, "Out of %s of component %x\n", __func__, (int)openmaxStandComp);
return OMX_ErrorNone;
}
/** This is the central function for component processing. It
* is executed in a separate thread, is synchronized with
* semaphores at each port, those are released each time a new buffer
* is available on the given port.
*/
void* omx_base_filter_BufferMgmtFunction (void* param) {
OMX_COMPONENTTYPE* openmaxStandComp = (OMX_COMPONENTTYPE*)param;
omx_base_filter_PrivateType* omx_base_filter_Private = (omx_base_filter_PrivateType*)openmaxStandComp->pComponentPrivate;
omx_base_PortType *pInPort=(omx_base_PortType *)omx_base_filter_Private->ports[OMX_BASE_FILTER_INPUTPORT_INDEX];
omx_base_PortType *pOutPort=(omx_base_PortType *)omx_base_filter_Private->ports[OMX_BASE_FILTER_OUTPUTPORT_INDEX];
tsem_t* pInputSem = pInPort->pBufferSem;
tsem_t* pOutputSem = pOutPort->pBufferSem;
queue_t* pInputQueue = pInPort->pBufferQueue;
queue_t* pOutputQueue = pOutPort->pBufferQueue;
OMX_BUFFERHEADERTYPE* pOutputBuffer=NULL;
OMX_BUFFERHEADERTYPE* pInputBuffer=NULL;
OMX_BOOL isInputBufferNeeded=OMX_TRUE,isOutputBufferNeeded=OMX_TRUE;
int inBufExchanged=0,outBufExchanged=0;
omx_base_filter_Private->bellagioThreads->nThreadBufferMngtID = (long int)syscall(__NR_gettid);
DEBUG(DEB_LEV_FUNCTION_NAME, "In %s of component %x\n", __func__, (int)openmaxStandComp);
DEBUG(DEB_LEV_SIMPLE_SEQ, "In %s the thread ID is %i\n", __func__, (int)omx_base_filter_Private->bellagioThreads->nThreadBufferMngtID);
DEBUG(DEB_LEV_FUNCTION_NAME, "In %s\n", __func__);
while(omx_base_filter_Private->state == OMX_StateIdle || omx_base_filter_Private->state == OMX_StateExecuting || omx_base_filter_Private->state == OMX_StatePause ||
omx_base_filter_Private->transientState == OMX_TransStateLoadedToIdle){
/*Wait till the ports are being flushed*/
pthread_mutex_lock(&omx_base_filter_Private->flush_mutex);
while( PORT_IS_BEING_FLUSHED(pInPort) ||
PORT_IS_BEING_FLUSHED(pOutPort)) {
pthread_mutex_unlock(&omx_base_filter_Private->flush_mutex);
DEBUG(DEB_LEV_FULL_SEQ, "In %s 1 signalling flush all cond iE=%d,iF=%d,oE=%d,oF=%d iSemVal=%d,oSemval=%d\n",
__func__,inBufExchanged,isInputBufferNeeded,outBufExchanged,isOutputBufferNeeded,pInputSem->semval,pOutputSem->semval);
if(isOutputBufferNeeded==OMX_FALSE && PORT_IS_BEING_FLUSHED(pOutPort)) {
pOutPort->ReturnBufferFunction(pOutPort,pOutputBuffer);
outBufExchanged--;
pOutputBuffer=NULL;
isOutputBufferNeeded=OMX_TRUE;
DEBUG(DEB_LEV_FULL_SEQ, "Ports are flushing,so returning output buffer\n");
}
if(isInputBufferNeeded==OMX_FALSE && PORT_IS_BEING_FLUSHED(pInPort)) {
pInPort->ReturnBufferFunction(pInPort,pInputBuffer);
inBufExchanged--;
pInputBuffer=NULL;
isInputBufferNeeded=OMX_TRUE;
DEBUG(DEB_LEV_FULL_SEQ, "Ports are flushing,so returning input buffer\n");
}
DEBUG(DEB_LEV_FULL_SEQ, "In %s 2 signalling flush all cond iE=%d,iF=%d,oE=%d,oF=%d iSemVal=%d,oSemval=%d\n",
__func__,inBufExchanged,isInputBufferNeeded,outBufExchanged,isOutputBufferNeeded,pInputSem->semval,pOutputSem->semval);
tsem_up(omx_base_filter_Private->flush_all_condition);
tsem_down(omx_base_filter_Private->flush_condition);
pthread_mutex_lock(&omx_base_filter_Private->flush_mutex);
}
pthread_mutex_unlock(&omx_base_filter_Private->flush_mutex);
/*No buffer to process. So wait here*/
if((isInputBufferNeeded==OMX_TRUE && pInputSem->semval==0) &&
(omx_base_filter_Private->state != OMX_StateLoaded && omx_base_filter_Private->state != OMX_StateInvalid)) {
//Signalled from EmptyThisBuffer or FillThisBuffer or some thing else
DEBUG(DEB_LEV_FULL_SEQ, "Waiting for next input/output buffer\n");
tsem_down(omx_base_filter_Private->bMgmtSem);
}
if(omx_base_filter_Private->state == OMX_StateLoaded || omx_base_filter_Private->state == OMX_StateInvalid) {
DEBUG(DEB_LEV_SIMPLE_SEQ, "In %s Buffer Management Thread is exiting\n",__func__);
break;
}
if((isOutputBufferNeeded==OMX_TRUE && pOutputSem->semval==0) &&
(omx_base_filter_Private->state != OMX_StateLoaded && omx_base_filter_Private->state != OMX_StateInvalid) &&
!(PORT_IS_BEING_FLUSHED(pInPort) || PORT_IS_BEING_FLUSHED(pOutPort))) {
//Signalled from EmptyThisBuffer or FillThisBuffer or some thing else
DEBUG(DEB_LEV_FULL_SEQ, "Waiting for next input/output buffer\n");
tsem_down(omx_base_filter_Private->bMgmtSem);
}
if(omx_base_filter_Private->state == OMX_StateLoaded || omx_base_filter_Private->state == OMX_StateInvalid) {
DEBUG(DEB_LEV_SIMPLE_SEQ, "In %s Buffer Management Thread is exiting\n",__func__);
break;
}
DEBUG(DEB_LEV_FULL_SEQ, "Waiting for input buffer semval=%d \n",pInputSem->semval);
if(pInputSem->semval>0 && isInputBufferNeeded==OMX_TRUE ) {
tsem_down(pInputSem);
if(pInputQueue->nelem>0){
inBufExchanged++;
isInputBufferNeeded=OMX_FALSE;
pInputBuffer = dequeue(pInputQueue);
if(pInputBuffer == NULL){
DEBUG(DEB_LEV_ERR, "Had NULL input buffer!!\n");
break;
}
}
}
/*When we have input buffer to process then get one output buffer*/
if(pOutputSem->semval>0 && isOutputBufferNeeded==OMX_TRUE) {
tsem_down(pOutputSem);
if(pOutputQueue->nelem>0){
outBufExchanged++;
isOutputBufferNeeded=OMX_FALSE;
pOutputBuffer = dequeue(pOutputQueue);
if(pOutputBuffer == NULL){
DEBUG(DEB_LEV_ERR, "Had NULL output buffer!! op is=%d,iq=%d\n",pOutputSem->semval,pOutputQueue->nelem);
break;
}
}
}
if(isInputBufferNeeded==OMX_FALSE) {
if(pInputBuffer->hMarkTargetComponent != NULL){
if((OMX_COMPONENTTYPE*)pInputBuffer->hMarkTargetComponent ==(OMX_COMPONENTTYPE *)openmaxStandComp) {
/*Clear the mark and generate an event*/
(*(omx_base_filter_Private->callbacks->EventHandler))
(openmaxStandComp,
omx_base_filter_Private->callbackData,
OMX_EventMark, /* The command was completed */
1, /* The commands was a OMX_CommandStateSet */
0, /* The state has been changed in message->messageParam2 */
pInputBuffer->pMarkData);
} else {
/*If this is not the target component then pass the mark*/
omx_base_filter_Private->pMark.hMarkTargetComponent = pInputBuffer->hMarkTargetComponent;
omx_base_filter_Private->pMark.pMarkData = pInputBuffer->pMarkData;
}
pInputBuffer->hMarkTargetComponent = NULL;
}
}
if(isInputBufferNeeded==OMX_FALSE && isOutputBufferNeeded==OMX_FALSE) {
if(omx_base_filter_Private->pMark.hMarkTargetComponent != NULL){
pOutputBuffer->hMarkTargetComponent = omx_base_filter_Private->pMark.hMarkTargetComponent;
pOutputBuffer->pMarkData = omx_base_filter_Private->pMark.pMarkData;
omx_base_filter_Private->pMark.hMarkTargetComponent = NULL;
omx_base_filter_Private->pMark.pMarkData = NULL;
}
pOutputBuffer->nTimeStamp = pInputBuffer->nTimeStamp;
if((pInputBuffer->nFlags & OMX_BUFFERFLAG_STARTTIME) == OMX_BUFFERFLAG_STARTTIME) {
DEBUG(DEB_LEV_FULL_SEQ, "Detected START TIME flag in the input buffer filled len=%d\n", (int)pInputBuffer->nFilledLen);
pOutputBuffer->nFlags = pInputBuffer->nFlags;
pInputBuffer->nFlags = 0;
}
if(omx_base_filter_Private->state == OMX_StateExecuting) {
if (omx_base_filter_Private->BufferMgmtCallback && pInputBuffer->nFilledLen > 0) {
(*(omx_base_filter_Private->BufferMgmtCallback))(openmaxStandComp, pInputBuffer, pOutputBuffer);
} else {
/*It no buffer management call back the explicitly consume input buffer*/
pInputBuffer->nFilledLen = 0;
}
} else if(!(PORT_IS_BEING_FLUSHED(pInPort) || PORT_IS_BEING_FLUSHED(pOutPort))) {
DEBUG(DEB_LEV_ERR, "In %s Received Buffer in non-Executing State(%x)\n", __func__, (int)omx_base_filter_Private->state);
} else {
pInputBuffer->nFilledLen = 0;
}
if((pInputBuffer->nFlags & OMX_BUFFERFLAG_EOS) == OMX_BUFFERFLAG_EOS && pInputBuffer->nFilledLen==0) {
DEBUG(DEB_LEV_FULL_SEQ, "Detected EOS flags in input buffer filled len=%d\n", (int)pInputBuffer->nFilledLen);
pOutputBuffer->nFlags=pInputBuffer->nFlags;
pInputBuffer->nFlags=0;
(*(omx_base_filter_Private->callbacks->EventHandler))
(openmaxStandComp,
omx_base_filter_Private->callbackData,
OMX_EventBufferFlag, /* The command was completed */
1, /* The commands was a OMX_CommandStateSet */
pOutputBuffer->nFlags, /* The state has been changed in message->messageParam2 */
NULL);
omx_base_filter_Private->bIsEOSReached = OMX_TRUE;
}
if(omx_base_filter_Private->state==OMX_StatePause && !(PORT_IS_BEING_FLUSHED(pInPort) || PORT_IS_BEING_FLUSHED(pOutPort))) {
/*Waiting at paused state*/
tsem_wait(omx_base_filter_Private->bStateSem);
}
/*If EOS and Input buffer Filled Len Zero then Return output buffer immediately*/
if((pOutputBuffer->nFilledLen != 0) || ((pOutputBuffer->nFlags & OMX_BUFFERFLAG_EOS) == OMX_BUFFERFLAG_EOS) || (omx_base_filter_Private->bIsEOSReached == OMX_TRUE)) {
pOutPort->ReturnBufferFunction(pOutPort,pOutputBuffer);
outBufExchanged--;
pOutputBuffer=NULL;
isOutputBufferNeeded=OMX_TRUE;
}
}
if(omx_base_filter_Private->state==OMX_StatePause && !(PORT_IS_BEING_FLUSHED(pInPort) || PORT_IS_BEING_FLUSHED(pOutPort))) {
/*Waiting at paused state*/
tsem_wait(omx_base_filter_Private->bStateSem);
}
/*Input Buffer has been completely consumed. So, return input buffer*/
if((isInputBufferNeeded == OMX_FALSE) && (pInputBuffer->nFilledLen==0)) {
pInPort->ReturnBufferFunction(pInPort,pInputBuffer);
inBufExchanged--;
pInputBuffer=NULL;
isInputBufferNeeded=OMX_TRUE;
}
}
DEBUG(DEB_LEV_FUNCTION_NAME, "Out of %s of component %x\n", __func__, (int)openmaxStandComp);
return NULL;
}
|
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
package org.elasticsearch.xcontent;
import org.elasticsearch.core.Nullable;
import org.elasticsearch.core.RestApiVersion;
import java.io.IOException;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
import static java.util.Objects.requireNonNull;
import static org.elasticsearch.xcontent.XContentParser.Token.START_ARRAY;
import static org.elasticsearch.xcontent.XContentParser.Token.START_OBJECT;
import static org.elasticsearch.xcontent.XContentParser.Token.VALUE_BOOLEAN;
import static org.elasticsearch.xcontent.XContentParser.Token.VALUE_EMBEDDED_OBJECT;
import static org.elasticsearch.xcontent.XContentParser.Token.VALUE_NULL;
import static org.elasticsearch.xcontent.XContentParser.Token.VALUE_NUMBER;
import static org.elasticsearch.xcontent.XContentParser.Token.VALUE_STRING;
/**
* A declarative, stateless parser that turns XContent into setter calls. A single parser should be defined for each object being parsed,
* nested elements can be added via {@link #declareObject(BiConsumer, ContextParser, ParseField)} which should be satisfied where possible
* by passing another instance of {@link ObjectParser}, this one customized for that Object.
* <p>
* This class works well for object that do have a constructor argument or that can be built using information available from earlier in the
* XContent. For objects that have constructors with required arguments that are specified on the same level as other fields see
* {@link ConstructingObjectParser}.
* </p>
* <p>
* Instances of {@link ObjectParser} should be setup by declaring a constant field for the parsers and declaring all fields in a static
* block just below the creation of the parser. Like this:
* </p>
* <pre>{@code
* private static final ObjectParser<Thing, SomeContext> PARSER = new ObjectParser<>("thing", Thing::new));
* static {
* PARSER.declareInt(Thing::setMineral, new ParseField("mineral"));
* PARSER.declareInt(Thing::setFruit, new ParseField("fruit"));
* }
* }</pre>
* It's highly recommended to use the high level declare methods like {@link #declareString(BiConsumer, ParseField)} instead of
* {@link #declareField} which can be used to implement exceptional parsing operations not covered by the high level methods.
*/
public final class ObjectParser<Value, Context> extends AbstractObjectParser<Value, Context>
implements
BiFunction<XContentParser, Context, Value>,
ContextParser<Context, Value> {
private final List<String[]> requiredFieldSets = new ArrayList<>();
private final List<String[]> exclusiveFieldSets = new ArrayList<>();
/**
* Adapts an array (or varags) setter into a list setter.
*/
public static <Value, ElementValue> BiConsumer<Value, List<ElementValue>> fromList(
Class<ElementValue> c,
BiConsumer<Value, ElementValue[]> consumer
) {
return (Value v, List<ElementValue> l) -> {
@SuppressWarnings("unchecked")
ElementValue[] array = (ElementValue[]) Array.newInstance(c, l.size());
consumer.accept(v, l.toArray(array));
};
}
private interface UnknownFieldParser<Value, Context> {
void acceptUnknownField(
ObjectParser<Value, Context> objectParser,
String field,
XContentLocation location,
XContentParser parser,
Value value,
Context context
) throws IOException;
}
private static <Value, Context> UnknownFieldParser<Value, Context> ignoreUnknown() {
return (op, f, l, p, v, c) -> p.skipChildren();
}
private static <Value, Context> UnknownFieldParser<Value, Context> errorOnUnknown() {
return (op, f, l, p, v, c) -> {
throw new XContentParseException(
l,
ErrorOnUnknown.IMPLEMENTATION.errorMessage(
op.name,
f,
op.fieldParserMap.getOrDefault(p.getRestApiVersion(), Collections.emptyMap()).keySet()
)
);
};
}
/**
* Defines how to consume a parsed undefined field
*/
public interface UnknownFieldConsumer<Value> {
void accept(Value target, String field, Object value);
}
private static <Value, Context> UnknownFieldParser<Value, Context> consumeUnknownField(UnknownFieldConsumer<Value> consumer) {
return (objectParser, field, location, parser, value, context) -> {
XContentParser.Token t = parser.currentToken();
switch (t) {
case VALUE_STRING:
consumer.accept(value, field, parser.text());
break;
case VALUE_NUMBER:
consumer.accept(value, field, parser.numberValue());
break;
case VALUE_BOOLEAN:
consumer.accept(value, field, parser.booleanValue());
break;
case VALUE_NULL:
consumer.accept(value, field, null);
break;
case START_OBJECT:
consumer.accept(value, field, parser.map());
break;
case START_ARRAY:
consumer.accept(value, field, parser.list());
break;
default:
throw new XContentParseException(
parser.getTokenLocation(),
"[" + objectParser.name + "] cannot parse field [" + field + "] with value type [" + t + "]"
);
}
};
}
private static <Value, Category, Context> UnknownFieldParser<Value, Context> unknownIsNamedXContent(
Class<Category> categoryClass,
BiConsumer<Value, ? super Category> consumer
) {
return (objectParser, field, location, parser, value, context) -> {
Category o;
try {
o = parser.namedObject(categoryClass, field, context);
} catch (NamedObjectNotFoundException e) {
Set<String> candidates = new HashSet<>(
objectParser.fieldParserMap.getOrDefault(parser.getRestApiVersion(), Collections.emptyMap()).keySet()
);
e.getCandidates().forEach(candidates::add);
String message = ErrorOnUnknown.IMPLEMENTATION.errorMessage(objectParser.name, field, candidates);
throw new XContentParseException(location, message, e);
}
consumer.accept(value, o);
};
}
private final Map<RestApiVersion, Map<String, FieldParser>> fieldParserMap = new HashMap<>();
private final String name;
private final Function<Context, Value> valueBuilder;
private final UnknownFieldParser<Value, Context> unknownFieldParser;
/**
* Creates a new ObjectParser.
* @param name the parsers name, used to reference the parser in exceptions and messages.
*/
public ObjectParser(String name) {
this(name, errorOnUnknown(), null);
}
/**
* Creates a new ObjectParser.
* @param name the parsers name, used to reference the parser in exceptions and messages.
* @param valueSupplier A supplier that creates a new Value instance. Used when the parser is used as an inner object parser.
*/
public ObjectParser(String name, @Nullable Supplier<Value> valueSupplier) {
this(name, errorOnUnknown(), wrapValueSupplier(valueSupplier));
}
/**
* Creates a new ObjectParser.
* @param name the parsers name, used to reference the parser in exceptions and messages.
* @param valueBuilder A function that creates a new Value from the parse Context. Used
* when the parser is used as an inner object parser.
*/
public static <Value, Context> ObjectParser<Value, Context> fromBuilder(String name, Function<Context, Value> valueBuilder) {
requireNonNull(valueBuilder, "Use the single argument ctor instead");
return new ObjectParser<Value, Context>(name, errorOnUnknown(), valueBuilder);
}
/**
* Creates a new ObjectParser.
* @param name the parsers name, used to reference the parser in exceptions and messages.
* @param ignoreUnknownFields Should this parser ignore unknown fields? This should generally be set to true only when parsing
* responses from external systems, never when parsing requests from users.
* @param valueSupplier a supplier that creates a new Value instance used when the parser is used as an inner object parser.
*/
public ObjectParser(String name, boolean ignoreUnknownFields, @Nullable Supplier<Value> valueSupplier) {
this(name, ignoreUnknownFields ? ignoreUnknown() : errorOnUnknown(), wrapValueSupplier(valueSupplier));
}
private static <C, V> Function<C, V> wrapValueSupplier(@Nullable Supplier<V> valueSupplier) {
return valueSupplier == null ? c -> { throw new NullPointerException(); } : c -> valueSupplier.get();
}
/**
* Creates a new ObjectParser that consumes unknown fields as generic Objects.
* @param name the parsers name, used to reference the parser in exceptions and messages.
* @param unknownFieldConsumer how to consume parsed unknown fields
* @param valueSupplier a supplier that creates a new Value instance used when the parser is used as an inner object parser.
*/
public ObjectParser(String name, UnknownFieldConsumer<Value> unknownFieldConsumer, @Nullable Supplier<Value> valueSupplier) {
this(name, consumeUnknownField(unknownFieldConsumer), wrapValueSupplier(valueSupplier));
}
/**
* Creates a new ObjectParser that attempts to resolve unknown fields as {@link XContentParser#namedObject namedObjects}.
* @param <C> the type of named object that unknown fields are expected to be
* @param name the parsers name, used to reference the parser in exceptions and messages.
* @param categoryClass the type of named object that unknown fields are expected to be
* @param unknownFieldConsumer how to consume parsed unknown fields
* @param valueSupplier a supplier that creates a new Value instance used when the parser is used as an inner object parser.
*/
public <C> ObjectParser(
String name,
Class<C> categoryClass,
BiConsumer<Value, C> unknownFieldConsumer,
@Nullable Supplier<Value> valueSupplier
) {
this(name, unknownIsNamedXContent(categoryClass, unknownFieldConsumer), wrapValueSupplier(valueSupplier));
}
/**
* Creates a new ObjectParser instance with a name.
* @param name the parsers name, used to reference the parser in exceptions and messages.
* @param unknownFieldParser how to parse unknown fields
* @param valueBuilder builds the value from the context. Used when the ObjectParser is not passed a value.
*/
private ObjectParser(
String name,
UnknownFieldParser<Value, Context> unknownFieldParser,
@Nullable Function<Context, Value> valueBuilder
) {
this.name = name;
this.unknownFieldParser = unknownFieldParser;
this.valueBuilder = valueBuilder == null ? c -> { throw new NullPointerException("valueBuilder is not set"); } : valueBuilder;
}
/**
* Parses a Value from the given {@link XContentParser}
* @param parser the parser to build a value from
* @param context context needed for parsing
* @return a new value instance drawn from the provided value supplier on {@link #ObjectParser(String, Supplier)}
* @throws IOException if an IOException occurs.
*/
@Override
public Value parse(XContentParser parser, Context context) throws IOException {
return parse(parser, valueBuilder.apply(context), context);
}
/**
* Parses a Value from the given {@link XContentParser}
* @param parser the parser to build a value from
* @param value the value to fill from the parser
* @param context a context that is passed along to all declared field parsers
* @return the parsed value
* @throws IOException if an IOException occurs.
*/
public Value parse(XContentParser parser, Value value, Context context) throws IOException {
XContentParser.Token token;
if (parser.currentToken() != XContentParser.Token.START_OBJECT) {
token = parser.nextToken();
if (token != XContentParser.Token.START_OBJECT) {
throwExpectedStartObject(parser, token);
}
}
FieldParser fieldParser = null;
String currentFieldName = null;
XContentLocation currentPosition = null;
final List<String[]> requiredFields = this.requiredFieldSets.isEmpty() ? null : new ArrayList<>(this.requiredFieldSets);
final List<List<String>> exclusiveFields;
if (exclusiveFieldSets.isEmpty()) {
exclusiveFields = null;
} else {
exclusiveFields = new ArrayList<>();
for (int i = 0; i < this.exclusiveFieldSets.size(); i++) {
exclusiveFields.add(new ArrayList<>());
}
}
final Map<String, FieldParser> parsers = fieldParserMap.getOrDefault(parser.getRestApiVersion(), Collections.emptyMap());
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) {
currentFieldName = parser.currentName();
currentPosition = parser.getTokenLocation();
fieldParser = parsers.get(currentFieldName);
} else {
if (currentFieldName == null) {
throwNoFieldFound(parser);
}
if (fieldParser == null) {
unknownFieldParser.acceptUnknownField(this, currentFieldName, currentPosition, parser, value, context);
} else {
fieldParser.assertSupports(name, parser, currentFieldName);
if (requiredFields != null) {
// Check to see if this field is a required field, if it is we can
// remove the entry as the requirement is satisfied
maybeMarkRequiredField(currentFieldName, requiredFields);
}
if (exclusiveFields != null) {
// Check if this field is in an exclusive set, if it is then mark
// it as seen.
maybeMarkExclusiveField(currentFieldName, exclusiveFields);
}
parseSub(parser, fieldParser, currentFieldName, value, context);
}
fieldParser = null;
}
}
// Check for a) multiple entries appearing in exclusive field sets and b) empty required field entries
if (exclusiveFields != null) {
ensureExclusiveFields(exclusiveFields);
}
if (requiredFields != null && requiredFields.isEmpty() == false) {
throwMissingRequiredFields(requiredFields);
}
return value;
}
private void throwExpectedStartObject(XContentParser parser, XContentParser.Token token) {
throw new XContentParseException(parser.getTokenLocation(), "[" + name + "] Expected START_OBJECT but was: " + token);
}
private void throwNoFieldFound(XContentParser parser) {
throw new XContentParseException(parser.getTokenLocation(), "[" + name + "] no field found");
}
private void throwMissingRequiredFields(List<String[]> requiredFields) {
final StringBuilder message = new StringBuilder();
for (String[] fields : requiredFields) {
message.append("Required one of fields ").append(Arrays.toString(fields)).append(", but none were specified. ");
}
throw new IllegalArgumentException(message.toString());
}
private void ensureExclusiveFields(List<List<String>> exclusiveFields) {
StringBuilder message = null;
for (List<String> fieldset : exclusiveFields) {
if (fieldset.size() > 1) {
if (message == null) {
message = new StringBuilder();
}
message.append("The following fields are not allowed together: ").append(fieldset).append(" ");
}
}
if (message != null && message.length() > 0) {
throw new IllegalArgumentException(message.toString());
}
}
private void maybeMarkExclusiveField(String currentFieldName, List<List<String>> exclusiveFields) {
for (int i = 0; i < this.exclusiveFieldSets.size(); i++) {
for (String field : this.exclusiveFieldSets.get(i)) {
if (field.equals(currentFieldName)) {
exclusiveFields.get(i).add(currentFieldName);
}
}
}
}
private void maybeMarkRequiredField(String currentFieldName, List<String[]> requiredFields) {
Iterator<String[]> iter = requiredFields.iterator();
while (iter.hasNext()) {
String[] requiredFieldNames = iter.next();
for (String field : requiredFieldNames) {
if (field.equals(currentFieldName)) {
iter.remove();
break;
}
}
}
}
@Override
public Value apply(XContentParser parser, Context context) {
try {
return parse(parser, context);
} catch (IOException e) {
throw new XContentParseException(parser.getTokenLocation(), "[" + name + "] failed to parse object", e);
}
}
public interface Parser<Value, Context> {
void parse(XContentParser parser, Value value, Context context) throws IOException;
}
public void declareField(Parser<Value, Context> p, ParseField parseField, ValueType type) {
if (parseField == null) {
throw new IllegalArgumentException("[parseField] is required");
}
if (type == null) {
throw new IllegalArgumentException("[type] is required");
}
FieldParser fieldParser = new FieldParser(p, type.supportedTokens(), parseField, type);
for (String fieldValue : parseField.getAllNamesIncludedDeprecated()) {
if (RestApiVersion.minimumSupported().matches(parseField.getForRestApiVersion())) {
Map<String, FieldParser> nameToParserMap = fieldParserMap.computeIfAbsent(
RestApiVersion.minimumSupported(),
(v) -> new HashMap<>()
);
FieldParser previousValue = nameToParserMap.putIfAbsent(fieldValue, fieldParser);
if (previousValue != null) {
throw new IllegalArgumentException("Parser already registered for name=[" + fieldValue + "]. " + previousValue);
}
}
if (RestApiVersion.current().matches(parseField.getForRestApiVersion())) {
Map<String, FieldParser> nameToParserMap = fieldParserMap.computeIfAbsent(RestApiVersion.current(), (v) -> new HashMap<>());
FieldParser previousValue = nameToParserMap.putIfAbsent(fieldValue, fieldParser);
if (previousValue != null) {
throw new IllegalArgumentException("Parser already registered for name=[" + fieldValue + "]. " + previousValue);
}
}
}
}
@Override
public <T> void declareField(BiConsumer<Value, T> consumer, ContextParser<Context, T> parser, ParseField parseField, ValueType type) {
if (consumer == null) {
throw new IllegalArgumentException("[consumer] is required");
}
if (parser == null) {
throw new IllegalArgumentException("[parser] is required");
}
declareField((p, v, c) -> consumer.accept(v, parser.parse(p, c)), parseField, type);
}
public <T> void declareObjectOrDefault(
BiConsumer<Value, T> consumer,
BiFunction<XContentParser, Context, T> objectParser,
Supplier<T> defaultValue,
ParseField field
) {
declareField((p, v, c) -> {
if (p.currentToken() == XContentParser.Token.VALUE_BOOLEAN) {
if (p.booleanValue()) {
consumer.accept(v, defaultValue.get());
}
} else {
consumer.accept(v, objectParser.apply(p, c));
}
}, field, ValueType.OBJECT_OR_BOOLEAN);
}
@Override
public <T> void declareNamedObject(BiConsumer<Value, T> consumer, NamedObjectParser<T, Context> namedObjectParser, ParseField field) {
BiFunction<XContentParser, Context, T> objectParser = (XContentParser p, Context c) -> {
try {
XContentParser.Token token = p.nextToken();
assert token == XContentParser.Token.FIELD_NAME;
String currentName = p.currentName();
try {
T namedObject = namedObjectParser.parse(p, c, currentName);
// consume the end object token
token = p.nextToken();
assert token == XContentParser.Token.END_OBJECT;
return namedObject;
} catch (Exception e) {
throw rethrowFieldParseFailure(field, p, currentName, e);
}
} catch (IOException e) {
throw wrapParseError(field, p, e, "error while parsing named object");
}
};
declareField((XContentParser p, Value v, Context c) -> consumer.accept(v, objectParser.apply(p, c)), field, ValueType.OBJECT);
}
@Override
public <T> void declareNamedObjects(
BiConsumer<Value, List<T>> consumer,
NamedObjectParser<T, Context> namedObjectParser,
Consumer<Value> orderedModeCallback,
ParseField field
) {
// This creates and parses the named object
BiFunction<XContentParser, Context, T> objectParser = (XContentParser p, Context c) -> {
if (p.currentToken() != XContentParser.Token.FIELD_NAME) {
throw wrapCanBeObjectOrArrayOfObjects(field, p);
}
// This messy exception nesting has the nice side effect of telling the user which field failed to parse
try {
String currentName = p.currentName();
try {
return namedObjectParser.parse(p, c, currentName);
} catch (Exception e) {
throw rethrowFieldParseFailure(field, p, currentName, e);
}
} catch (IOException e) {
throw wrapParseError(field, p, e, "error while parsing");
}
};
declareField((XContentParser p, Value v, Context c) -> {
List<T> fields = new ArrayList<>();
if (p.currentToken() == XContentParser.Token.START_OBJECT) {
// Fields are just named entries in a single object
while (p.nextToken() != XContentParser.Token.END_OBJECT) {
fields.add(objectParser.apply(p, c));
}
} else if (p.currentToken() == XContentParser.Token.START_ARRAY) {
// Fields are objects in an array. Each object contains a named field.
parseObjectsInArray(orderedModeCallback, field, objectParser, p, v, c, fields);
}
consumer.accept(v, fields);
}, field, ValueType.OBJECT_ARRAY);
}
private <T> void parseObjectsInArray(
Consumer<Value> orderedModeCallback,
ParseField field,
BiFunction<XContentParser, Context, T> objectParser,
XContentParser p,
Value v,
Context c,
List<T> fields
) throws IOException {
orderedModeCallback.accept(v);
XContentParser.Token token;
while ((token = p.nextToken()) != XContentParser.Token.END_ARRAY) {
if (token != XContentParser.Token.START_OBJECT) {
throw wrapCanBeObjectOrArrayOfObjects(field, p);
}
p.nextToken(); // Move to the first field in the object
fields.add(objectParser.apply(p, c));
p.nextToken(); // Move past the object, should be back to into the array
if (p.currentToken() != XContentParser.Token.END_OBJECT) {
throw wrapCanBeObjectOrArrayOfObjects(field, p);
}
}
}
private XContentParseException wrapCanBeObjectOrArrayOfObjects(ParseField field, XContentParser p) {
return new XContentParseException(
p.getTokenLocation(),
"["
+ field
+ "] can be a single object with any number of "
+ "fields or an array where each entry is an object with a single field"
);
}
private XContentParseException wrapParseError(ParseField field, XContentParser p, IOException e, String s) {
return new XContentParseException(p.getTokenLocation(), "[" + field + "] " + s, e);
}
private XContentParseException rethrowFieldParseFailure(ParseField field, XContentParser p, String currentName, Exception e) {
return new XContentParseException(p.getTokenLocation(), "[" + field + "] failed to parse field [" + currentName + "]", e);
}
@Override
public <T> void declareNamedObjects(
BiConsumer<Value, List<T>> consumer,
NamedObjectParser<T, Context> namedObjectParser,
ParseField field
) {
Consumer<Value> orderedModeCallback = (v) -> {
throw new IllegalArgumentException("[" + field + "] doesn't support arrays. Use a single object with multiple fields.");
};
declareNamedObjects(consumer, namedObjectParser, orderedModeCallback, field);
}
/**
* Functional interface for instantiating and parsing named objects. See ObjectParserTests#NamedObject for the canonical way to
* implement this for objects that themselves have a parser.
*/
@FunctionalInterface
public interface NamedObjectParser<T, Context> {
T parse(XContentParser p, Context c, String name) throws IOException;
}
/**
* Get the name of the parser.
*/
@Override
public String getName() {
return name;
}
@Override
public void declareRequiredFieldSet(String... requiredSet) {
if (requiredSet.length == 0) {
return;
}
this.requiredFieldSets.add(requiredSet);
}
@Override
public void declareExclusiveFieldSet(String... exclusiveSet) {
if (exclusiveSet.length == 0) {
return;
}
this.exclusiveFieldSets.add(exclusiveSet);
}
private void parseArray(XContentParser parser, FieldParser fieldParser, String currentFieldName, Value value, Context context) {
assert parser.currentToken() == XContentParser.Token.START_ARRAY : "Token was: " + parser.currentToken();
parseValue(parser, fieldParser, currentFieldName, value, context);
}
private void parseValue(XContentParser parser, FieldParser fieldParser, String currentFieldName, Value value, Context context) {
try {
fieldParser.parser.parse(parser, value, context);
} catch (Exception ex) {
throwFailedToParse(parser, currentFieldName, ex);
}
}
private void throwFailedToParse(XContentParser parser, String currentFieldName, Exception ex) {
throw new XContentParseException(parser.getTokenLocation(), "[" + name + "] failed to parse field [" + currentFieldName + "]", ex);
}
private void parseSub(XContentParser parser, FieldParser fieldParser, String currentFieldName, Value value, Context context) {
final XContentParser.Token token = parser.currentToken();
switch (token) {
case START_OBJECT:
parseValue(parser, fieldParser, currentFieldName, value, context);
/*
* Well behaving parsers should consume the entire object but
* asserting that they do that is not something we can do
* efficiently here. Instead we can check that they end on an
* END_OBJECT. They could end on the *wrong* end object and
* this test won't catch them, but that is the price that we pay
* for having a cheap test.
*/
if (parser.currentToken() != XContentParser.Token.END_OBJECT) {
throwMustEndOn(currentFieldName, XContentParser.Token.END_OBJECT);
}
break;
case START_ARRAY:
parseArray(parser, fieldParser, currentFieldName, value, context);
/*
* Well behaving parsers should consume the entire array but
* asserting that they do that is not something we can do
* efficiently here. Instead we can check that they end on an
* END_ARRAY. They could end on the *wrong* end array and
* this test won't catch them, but that is the price that we pay
* for having a cheap test.
*/
if (parser.currentToken() != XContentParser.Token.END_ARRAY) {
throwMustEndOn(currentFieldName, XContentParser.Token.END_ARRAY);
}
break;
case END_OBJECT:
case END_ARRAY:
case FIELD_NAME:
throw throwUnexpectedToken(parser, token);
case VALUE_STRING:
case VALUE_NUMBER:
case VALUE_BOOLEAN:
case VALUE_EMBEDDED_OBJECT:
case VALUE_NULL:
parseValue(parser, fieldParser, currentFieldName, value, context);
}
}
private void throwMustEndOn(String currentFieldName, XContentParser.Token token) {
throw new IllegalStateException("parser for [" + currentFieldName + "] did not end on " + token);
}
private XContentParseException throwUnexpectedToken(XContentParser parser, XContentParser.Token token) {
return new XContentParseException(parser.getTokenLocation(), "[" + name + "]" + token + " is unexpected");
}
private class FieldParser {
private final Parser<Value, Context> parser;
private final EnumSet<XContentParser.Token> supportedTokens;
private final ParseField parseField;
private final ValueType type;
FieldParser(Parser<Value, Context> parser, EnumSet<XContentParser.Token> supportedTokens, ParseField parseField, ValueType type) {
this.parser = parser;
this.supportedTokens = supportedTokens;
this.parseField = parseField;
this.type = type;
}
void assertSupports(String parserName, XContentParser xContentParser, String currentFieldName) {
boolean match = parseField.match(
parserName,
xContentParser::getTokenLocation,
currentFieldName,
xContentParser.getDeprecationHandler()
);
if (match == false) {
throw new XContentParseException(
xContentParser.getTokenLocation(),
"[" + parserName + "] parsefield doesn't accept: " + currentFieldName
);
}
if (supportedTokens.contains(xContentParser.currentToken()) == false) {
throw new XContentParseException(
xContentParser.getTokenLocation(),
"[" + parserName + "] " + currentFieldName + " doesn't support values of type: " + xContentParser.currentToken()
);
}
}
@Override
public String toString() {
String[] deprecatedNames = parseField.getDeprecatedNames();
String allReplacedWith = parseField.getAllReplacedWith();
String deprecated = "";
if (deprecatedNames != null && deprecatedNames.length > 0) {
deprecated = ", deprecated_names=" + Arrays.toString(deprecatedNames);
}
return "FieldParser{"
+ "preferred_name="
+ parseField.getPreferredName()
+ ", supportedTokens="
+ supportedTokens
+ deprecated
+ (allReplacedWith == null ? "" : ", replaced_with=" + allReplacedWith)
+ ", type="
+ type.name()
+ '}';
}
}
public enum ValueType {
STRING(VALUE_STRING),
STRING_OR_NULL(VALUE_STRING, VALUE_NULL),
FLOAT(VALUE_NUMBER, VALUE_STRING),
FLOAT_OR_NULL(VALUE_NUMBER, VALUE_STRING, VALUE_NULL),
DOUBLE(VALUE_NUMBER, VALUE_STRING),
DOUBLE_OR_NULL(VALUE_NUMBER, VALUE_STRING, VALUE_NULL),
LONG(VALUE_NUMBER, VALUE_STRING),
LONG_OR_NULL(VALUE_NUMBER, VALUE_STRING, VALUE_NULL),
INT(VALUE_NUMBER, VALUE_STRING),
INT_OR_NULL(VALUE_NUMBER, VALUE_STRING, VALUE_NULL),
BOOLEAN(VALUE_BOOLEAN, VALUE_STRING),
BOOLEAN_OR_NULL(VALUE_BOOLEAN, VALUE_STRING, VALUE_NULL),
STRING_ARRAY(START_ARRAY, VALUE_STRING),
FLOAT_ARRAY(START_ARRAY, VALUE_NUMBER, VALUE_STRING),
DOUBLE_ARRAY(START_ARRAY, VALUE_NUMBER, VALUE_STRING),
LONG_ARRAY(START_ARRAY, VALUE_NUMBER, VALUE_STRING),
INT_ARRAY(START_ARRAY, VALUE_NUMBER, VALUE_STRING),
BOOLEAN_ARRAY(START_ARRAY, VALUE_BOOLEAN),
OBJECT(START_OBJECT),
OBJECT_OR_NULL(START_OBJECT, VALUE_NULL),
OBJECT_ARRAY(START_OBJECT, START_ARRAY),
OBJECT_ARRAY_OR_NULL(START_OBJECT, START_ARRAY, VALUE_NULL),
OBJECT_OR_BOOLEAN(START_OBJECT, VALUE_BOOLEAN),
OBJECT_OR_STRING(START_OBJECT, VALUE_STRING),
OBJECT_OR_LONG(START_OBJECT, VALUE_NUMBER),
OBJECT_ARRAY_BOOLEAN_OR_STRING(START_OBJECT, START_ARRAY, VALUE_BOOLEAN, VALUE_STRING),
OBJECT_ARRAY_OR_STRING(START_OBJECT, START_ARRAY, VALUE_STRING),
OBJECT_ARRAY_STRING_OR_NUMBER(START_OBJECT, START_ARRAY, VALUE_STRING, VALUE_NUMBER),
VALUE(VALUE_BOOLEAN, VALUE_NULL, VALUE_EMBEDDED_OBJECT, VALUE_NUMBER, VALUE_STRING),
VALUE_OBJECT_ARRAY(VALUE_BOOLEAN, VALUE_NULL, VALUE_EMBEDDED_OBJECT, VALUE_NUMBER, VALUE_STRING, START_OBJECT, START_ARRAY),
VALUE_ARRAY(VALUE_BOOLEAN, VALUE_NULL, VALUE_NUMBER, VALUE_STRING, START_ARRAY);
private final EnumSet<XContentParser.Token> tokens;
ValueType(XContentParser.Token first, XContentParser.Token... rest) {
this.tokens = EnumSet.of(first, rest);
}
public EnumSet<XContentParser.Token> supportedTokens() {
return this.tokens;
}
}
@Override
public String toString() {
return "ObjectParser{" + "name='" + name + '\'' + ", fields=" + fieldParserMap + '}';
}
}
|
module(...,package.seeall)
local utils = require('pf.utils')
local verbose = os.getenv("PF_VERBOSE");
local set, pp = utils.set, utils.pp
local relop_map = {
['<']='<', ['<=']='<=', ['=']='==', ['!=']='~=', ['>=']='>=', ['>']='>'
}
local relop_inversions = {
['<']='>=', ['<=']='>', ['=']='!=', ['!=']='=', ['>=']='<', ['>']='<='
}
local simple_results = set('true', 'false', 'call')
local function invert_bool(expr)
if expr[1] == 'true' then return { 'false' } end
if expr[1] == 'false' then return { 'true' } end
assert(relop_inversions[expr[1]])
return { relop_inversions[expr[1]], expr[2], expr[3] }
end
local function is_simple_expr(expr)
-- Simple := return true | return false | return call | goto Label
if expr[1] == 'return' then return simple_results[expr[2][1]] end
return expr[1] == 'goto'
end
-- Lua := Do | Return | Goto | If | Bind | Label
-- Do := 'do' Lua+
-- Return := 'return' Bool|Call
-- Goto := 'goto' Label
-- If := 'if' Bool Lua Lua?
-- Bind := 'bind' Name Expr
-- Label := 'label' Lua
local function residualize_lua(program)
-- write blocks, scope is dominator tree
local function nest(block, result, knext)
for _, binding in ipairs(block.bindings) do
table.insert(result, { 'bind', binding.name, binding.value })
end
local control = block.control
if control[1] == 'goto' then
local succ = program.blocks[control[2]]
if succ.idom == block.label then
nest(succ, result)
else
table.insert(result, control)
end
elseif control[1] == 'return' then
table.insert(result, control)
else
assert(control[1] == 'if')
local test, t_label, f_label = control[2], control[3], control[4]
local t_block, f_block = program.blocks[t_label], program.blocks[f_label]
local expr = { 'if', test, { 'do' }, { 'do' } }
-- First, add the test.
table.insert(result, expr)
-- Then fill in the nested then and else arms, if they have no
-- other predecessors.
if #t_block.preds == 1 then
assert(t_block.idom == block.label)
nest(t_block, expr[3])
else
table.insert(expr[3], { 'goto', t_label })
end
if #f_block.preds == 1 then
assert(f_block.idom == block.label)
nest(f_block, expr[4])
else
table.insert(expr[4], { 'goto', f_label })
end
-- Finally add immediately dominated blocks, with labels. We
-- only have to do this in "if" blocks because "return" blocks
-- have no successors, and "goto" blocks do not immediately
-- dominate blocks that are not their successors.
for _,label in ipairs(block.doms) do
local dom_block = program.blocks[label]
if #dom_block.preds ~= 1 then
local wrap = { 'label', label, { 'do' } }
table.insert(result, wrap)
nest(dom_block, wrap[3])
end
end
end
end
local result = { 'do' }
nest(program.blocks[program.start], result, nil)
return result
end
-- Lua := Do | Return | Goto | If | Bind | Label
-- Do := 'do' Lua+
-- Return := 'return' Bool|Call
-- Goto := 'goto' Label
-- If := 'if' Bool Lua Lua?
-- Bind := 'bind' Name Expr
-- Label := 'label' Lua
local function cleanup(expr, is_last)
local function splice_tail(result, expr)
if expr[1] == 'do' then
-- Splice a tail "do" into the parent do.
for j=2,#expr do
if j==#expr then
splice_tail(result, expr[j])
else
table.insert(result, expr[j])
end
end
return
elseif expr[1] == 'if' then
if expr[3][1] == 'return' or expr[3][1] == 'goto' then
-- Splice the consequent of a tail "if" into the parent do.
table.insert(result, { 'if', expr[2], expr[3] })
if expr[4] then splice_tail(result, expr[4]) end
return
end
elseif expr[1] == 'label' then
-- Likewise, try to splice the body of a tail labelled
-- statement.
local tail = { 'do' }
splice_tail(tail, expr[3])
if #tail > 2 then
table.insert(result, { 'label', expr[2], tail[2] })
for i=3,#tail do table.insert(result, tail[i]) end
return
end
end
table.insert(result, expr)
end
local op = expr[1]
if op == 'do' then
if #expr == 2 then return cleanup(expr[2], is_last) end
local result = { 'do' }
for i=2,#expr do
local subexpr = cleanup(expr[i], i==#expr)
if i==#expr then
splice_tail(result, subexpr)
else
table.insert(result, subexpr)
end
end
return result
elseif op == 'return' then
return expr
elseif op == 'goto' then
return expr
elseif op == 'if' then
local test, t, f = expr[2], cleanup(expr[3], true), cleanup(expr[4], true)
if not is_simple_expr(t) and is_simple_expr(f) then
test, t, f = invert_bool(test), f, t
end
if is_simple_expr(t) and is_last then
local result = { 'do', { 'if', test, t } }
splice_tail(result, f)
return result
else
return { 'if', test, t, f }
end
elseif op == 'bind' then
return expr
else
assert (op == 'label')
return { 'label', expr[2], cleanup(expr[3], is_last) }
end
end
local function filter_builder(...)
-- Reserve first part for libraries.
local parts = {'', 'return function('}
local nparts = 2
local indent = ''
local libraries = {}
local builder = {}
function builder.write(str)
nparts = nparts + 1
parts[nparts] = str
end
function builder.writeln(str)
builder.write(indent .. str .. '\n')
end
function builder.bind(var, val)
builder.writeln('local '..var..' = '..val)
end
function builder.push()
indent = indent .. ' '
end
function builder.else_()
builder.write(indent:sub(4) .. 'else\n')
end
function builder.pop()
indent = indent:sub(4)
builder.writeln('end')
end
function builder.jump(label)
builder.writeln('goto '..label)
end
function builder.writelabel(label)
builder.write('::'..label..'::\n')
end
function builder.c(str)
local lib, func = str:match('([a-z]+).([a-z]+)')
if libraries[str] then return func end
libraries[str] = 'local '..func..' = require("'..lib..'").'..func
return func
end
function builder.header()
for _,library in pairs(libraries) do
parts[1] = library.."\n"..parts[1]
end
end
function builder.finish()
builder.pop()
builder.header()
local written = table.concat(parts)
if verbose then print(written) end
return written
end
local needs_comma = false
for _, v in ipairs({...}) do
if needs_comma then builder.write(',') end
builder.write(v)
needs_comma = true
end
builder.write(')\n')
builder.push()
return builder
end
local function read_buffer_word_by_type(builder, buffer, offset, size)
if size == 1 then
return buffer..'['..offset..']'
elseif size == 2 then
return builder.c('ffi.cast')..'("uint16_t*", '..buffer..'+'..offset..')[0]'
elseif size == 4 then
return (builder.c('ffi.cast')..'("uint32_t*", '..buffer..'+'..offset..')[0]')
else
error("bad [] size: "..size)
end
end
local function serialize(builder, stmt)
local function serialize_value(expr)
if expr == 'len' then return 'length' end
if type(expr) == 'number' then return expr end
if type(expr) == 'string' then return expr end
assert(type(expr) == 'table', 'unexpected type '..type(expr))
local op, lhs = expr[1], serialize_value(expr[2])
if op == 'ntohs' then return builder.c('bit.rshift')..'('..builder.c('bit.bswap')..'('..lhs..'), 16)'
elseif op == 'ntohl' then return builder.c('bit.bswap')..'('..lhs..')'
elseif op == 'int32' then return builder.c('bit.tobit')..'('..lhs..')'
elseif op == 'uint32' then return '('..lhs..' % '.. 2^32 ..')'
end
local rhs = serialize_value(expr[3])
assert(expr[4] == nil) -- sanity check
if op == '[]' then
return read_buffer_word_by_type(builder, 'P', lhs, rhs)
elseif op == '+' then return '('..lhs..' + '..rhs..')'
elseif op == '-' then return '('..lhs..' - '..rhs..')'
elseif op == '*' then return '('..lhs..' * '..rhs..')'
elseif op == '*64' then
return 'tonumber(('..lhs..' * 1LL * '..rhs..') % '.. 2^32 ..')'
elseif op == '/' then return builder.c('math.floor')..'('..lhs..' / '..rhs..')'
elseif op == '&' then return builder.c('bit.band')..'('..lhs..','..rhs..')'
elseif op == '^' then return builder.c('bit.bxor')..'('..lhs..','..rhs..')'
elseif op == '|' then return builder.c('bit.bor')..'('..lhs..','..rhs..')'
elseif op == '<<' then return builder.c('bit.lshift')..'('..lhs..','..rhs..')'
elseif op == '>>' then return builder.c('bit.rshift')..'('..lhs..','..rhs..')'
else error('unexpected op', op) end
end
local function serialize_bool(expr)
local op = expr[1]
if op == 'true' then
return 'true'
elseif op == 'false' then
return 'false'
elseif relop_map[op] then
-- An arithmetic relop.
local op = relop_map[op]
local lhs, rhs = serialize_value(expr[2]), serialize_value(expr[3])
return lhs..' '..op..' '..rhs
else
error('unhandled primitive'..op)
end
end
local function serialize_call(expr)
local args = { 'P', 'length' }
for i=3,#expr do table.insert(args, serialize_value(expr[i])) end
return 'self:'..expr[2]..'('..table.concat(args, ', ')..')'
end
local serialize_statement
local function serialize_sequence(stmts)
if stmts[1] == 'do' then
for i=2,#stmts do serialize_statement(stmts[i], i==#stmts) end
else
serialize_statement(stmts, true)
end
end
function serialize_statement(stmt, is_last)
local op = stmt[1]
if op == 'do' then
builder.writeln('do')
builder.push()
serialize_sequence(stmt)
builder.pop()
elseif op == 'return' then
if not is_last then
return serialize_statement({ 'do', stmt }, false)
end
if stmt[2][1] == 'call' then
builder.writeln('return '..serialize_call(stmt[2]))
else
builder.writeln('return '..serialize_bool(stmt[2]))
end
elseif op == 'goto' then
builder.jump(stmt[2])
elseif op == 'if' then
local test, t, f = stmt[2], stmt[3], stmt[4]
local test_str = 'if '..serialize_bool(test)..' then'
if is_simple_expr(t) then
if t[1] == 'return' then
local result
if t[2][1] == 'call' then result = serialize_call(t[2])
else result = serialize_bool(t[2]) end
builder.writeln(test_str..' return '..result..' end')
else
assert(t[1] == 'goto')
builder.writeln(test_str..' goto '..t[2]..' end')
end
if f then serialize_statement(f, is_last) end
else
builder.writeln(test_str)
builder.push()
serialize_sequence(t)
if f then
builder.else_()
serialize_sequence(f)
end
builder.pop()
end
elseif op == 'bind' then
builder.bind(stmt[2], serialize_value(stmt[3]))
else
assert(op == 'label')
builder.writelabel(stmt[2])
serialize_statement(stmt[3], is_last)
end
end
serialize_sequence(stmt)
end
function emit_lua(ssa)
local builder = filter_builder('P', 'length')
serialize(builder, cleanup(residualize_lua(ssa), true))
local str = builder.finish()
if verbose then pp(str) end
return str
end
function emit_match_lua(ssa, ...)
local builder = filter_builder('self', 'P', 'length', ...)
serialize(builder, cleanup(residualize_lua(ssa), true))
local str = builder.finish()
if verbose then pp(str) end
return str
end
function emit_and_load(ssa, name)
return assert(loadstring(emit_lua(ssa), name))()
end
function emit_and_load_match(ssa, name, ...)
return assert(loadstring(emit_match_lua(ssa, ...), name))()
end
function selftest()
print("selftest: pf.backend")
local parse = require('pf.parse').parse
local expand = require('pf.expand').expand
local optimize = require('pf.optimize').optimize
local convert_anf = require('pf.anf').convert_anf
local convert_ssa = require('pf.ssa').convert_ssa
local function test(expr)
local ast = optimize(expand(parse(expr), "EN10MB"))
return emit_and_load(convert_ssa(convert_anf(ast)))
end
test("tcp port 80 or udp port 34")
print("OK")
end
|
package org.pentaho.di.trans.steps.loadsave.setter;
import java.lang.reflect.Method;
public class MethodSetter<T> implements Setter<T> {
private final Method method;
public MethodSetter( Method method ) {
this.method = method;
}
@Override
public void set( Object obj, T value ) {
try {
method.invoke( obj, value );
} catch ( Exception e ) {
throw new RuntimeException( "Error invoking " + method + " on " + obj, e );
}
}
}
|
/***************************************************************************//**
* \file cy_dma.c
* \version 2.20
*
* \brief
* The source code file for the DMA driver.
*
********************************************************************************
* \copyright
* Copyright 2016-2019 Cypress Semiconductor Corporation
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
#include "cy_dma.h"
#ifdef CY_IP_M4CPUSS_DMA
/*******************************************************************************
* Function Name: Cy_DMA_Crc_Init
****************************************************************************//**
*
* Initializes the DMA CRC functionality.
*
* \param base The pointer to the hardware DMA block.
*
* \param crcConfig The pointer to the CRC configuration structure
* \ref cy_stc_dma_crc_config_t.
*
* \return The status /ref cy_en_dma_status_t.
*
* \funcusage
* \snippet dma/snippet/main.c snippet_Cy_DMA_Crc_Init
*
*******************************************************************************/
cy_en_dma_status_t Cy_DMA_Crc_Init(DW_Type * base, cy_stc_dma_crc_config_t const * crcConfig)
{
cy_en_dma_status_t ret = CY_DMA_BAD_PARAM;
if((NULL != base) && (NULL != crcConfig) && CY_DW_CRC)
{
DW_CRC_CTL(base) = _BOOL2FLD(DW_V2_CRC_CTL_DATA_REVERSE, crcConfig->dataReverse) |
_BOOL2FLD(DW_V2_CRC_CTL_REM_REVERSE, crcConfig->reminderReverse);
DW_CRC_DATA_CTL(base) = _VAL2FLD(DW_V2_CRC_DATA_CTL_DATA_XOR, crcConfig->dataXor);
DW_CRC_REM_CTL(base) = _VAL2FLD(DW_V2_CRC_REM_CTL_REM_XOR, crcConfig->reminderXor);
DW_CRC_POL_CTL(base) = _VAL2FLD(DW_V2_CRC_POL_CTL_POLYNOMIAL, crcConfig->polynomial);
DW_CRC_LFSR_CTL(base) = _VAL2FLD(DW_V2_CRC_LFSR_CTL_LFSR32, crcConfig->lfsrInitVal);
ret = CY_DMA_SUCCESS;
}
return ret;
}
/*******************************************************************************
* Function Name: Cy_DMA_Descriptor_Init
****************************************************************************//**
*
* Initializes the descriptor structure in SRAM from a pre-initialized
* configuration structure.
* This function initializes only the descriptor and not the channel.
*
* \param descriptor
* The descriptor structure instance declared by the user/component.
*
* \param config
* This is a configuration structure that has all initialization information for
* the descriptor.
*
* \return
* The status /ref cy_en_dma_status_t.
*
* \funcusage
* \snippet dma/snippet/main.c snippet_Cy_DMA_Enable
*
*******************************************************************************/
cy_en_dma_status_t Cy_DMA_Descriptor_Init(cy_stc_dma_descriptor_t * descriptor, const cy_stc_dma_descriptor_config_t * config)
{
cy_en_dma_status_t ret = CY_DMA_BAD_PARAM;
if ((NULL != descriptor) && (NULL != config))
{
CY_ASSERT_L3(CY_DMA_IS_RETRIG_VALID(config->retrigger));
CY_ASSERT_L3(CY_DMA_IS_TRIG_TYPE_VALID(config->interruptType));
CY_ASSERT_L3(CY_DMA_IS_TRIG_TYPE_VALID(config->triggerOutType));
CY_ASSERT_L3(CY_DMA_IS_TRIG_TYPE_VALID(config->triggerInType));
CY_ASSERT_L3(CY_DMA_IS_XFER_SIZE_VALID(config->srcTransferSize));
CY_ASSERT_L3(CY_DMA_IS_XFER_SIZE_VALID(config->dstTransferSize));
CY_ASSERT_L3(CY_DMA_IS_CHANNEL_STATE_VALID(config->channelState));
CY_ASSERT_L3(CY_DMA_IS_DATA_SIZE_VALID(config->dataSize));
CY_ASSERT_L3(CY_DMA_IS_TYPE_VALID(config->descriptorType));
descriptor->ctl =
_VAL2FLD(CY_DMA_CTL_RETRIG, config->retrigger) |
_VAL2FLD(CY_DMA_CTL_INTR_TYPE, config->interruptType) |
_VAL2FLD(CY_DMA_CTL_TR_OUT_TYPE, config->triggerOutType) |
_VAL2FLD(CY_DMA_CTL_TR_IN_TYPE, config->triggerInType) |
_VAL2FLD(CY_DMA_CTL_SRC_SIZE, config->srcTransferSize) |
_VAL2FLD(CY_DMA_CTL_DST_SIZE, config->dstTransferSize) |
_VAL2FLD(CY_DMA_CTL_CH_DISABLE, config->channelState) |
_VAL2FLD(CY_DMA_CTL_DATA_SIZE, config->dataSize) |
_VAL2FLD(CY_DMA_CTL_TYPE, config->descriptorType);
descriptor->src = (uint32_t)config->srcAddress;
descriptor->dst = (uint32_t)config->dstAddress;
switch(config->descriptorType)
{
case CY_DMA_SINGLE_TRANSFER:
descriptor->xCtl = (uint32_t)config->nextDescriptor;
ret = CY_DMA_SUCCESS;
break;
case CY_DMA_1D_TRANSFER:
CY_ASSERT_L2(CY_DMA_IS_LOOP_INCR_VALID(config->srcXincrement));
CY_ASSERT_L2(CY_DMA_IS_LOOP_INCR_VALID(config->dstXincrement));
CY_ASSERT_L2(CY_DMA_IS_LOOP_COUNT_VALID(config->xCount));
descriptor->xCtl =
_VAL2FLD(CY_DMA_CTL_SRC_INCR, config->srcXincrement) |
_VAL2FLD(CY_DMA_CTL_DST_INCR, config->dstXincrement) |
/* Convert the data count from the user's range (1-256) into the machine range (0-255). */
_VAL2FLD(CY_DMA_CTL_COUNT, config->xCount - 1UL);
descriptor->yCtl = (uint32_t)config->nextDescriptor;
ret = CY_DMA_SUCCESS;
break;
case CY_DMA_2D_TRANSFER:
CY_ASSERT_L2(CY_DMA_IS_LOOP_INCR_VALID(config->srcXincrement));
CY_ASSERT_L2(CY_DMA_IS_LOOP_INCR_VALID(config->dstXincrement));
CY_ASSERT_L2(CY_DMA_IS_LOOP_COUNT_VALID(config->xCount));
CY_ASSERT_L2(CY_DMA_IS_LOOP_INCR_VALID(config->srcYincrement));
CY_ASSERT_L2(CY_DMA_IS_LOOP_INCR_VALID(config->dstYincrement));
CY_ASSERT_L2(CY_DMA_IS_LOOP_COUNT_VALID(config->yCount));
descriptor->xCtl =
_VAL2FLD(CY_DMA_CTL_SRC_INCR, config->srcXincrement) |
_VAL2FLD(CY_DMA_CTL_DST_INCR, config->dstXincrement) |
/* Convert the data count from the user's range (1-256) into the machine range (0-255). */
_VAL2FLD(CY_DMA_CTL_COUNT, config->xCount - 1UL);
descriptor->yCtl =
_VAL2FLD(CY_DMA_CTL_SRC_INCR, config->srcYincrement) |
_VAL2FLD(CY_DMA_CTL_DST_INCR, config->dstYincrement) |
/* Convert the data count from the user's range (1-256) into the machine range (0-255). */
_VAL2FLD(CY_DMA_CTL_COUNT, config->yCount - 1UL);
descriptor->nextPtr = (uint32_t)config->nextDescriptor;
ret = CY_DMA_SUCCESS;
break;
case CY_DMA_CRC_TRANSFER:
if (CY_DW_CRC)
{
CY_ASSERT_L2(CY_DMA_IS_LOOP_INCR_VALID(config->srcXincrement));
CY_ASSERT_L2(CY_DMA_IS_LOOP_COUNT_VALID(config->xCount));
descriptor->xCtl =
_VAL2FLD(CY_DMA_CTL_SRC_INCR, config->srcXincrement) |
/* Convert the data count from the user's range (1-256) into the machine range (0-255). */
_VAL2FLD(CY_DMA_CTL_COUNT, config->xCount - 1UL);
descriptor->yCtl = (uint32_t)config->nextDescriptor;
ret = CY_DMA_SUCCESS;
}
break;
default: /* An unsupported type of a descriptor */
break;
}
}
return ret;
}
/*******************************************************************************
* Function Name: Cy_DMA_Descriptor_DeInit
****************************************************************************//**
*
* Clears the content of the specified descriptor.
*
* \param descriptor
* The descriptor structure instance declared by the user/component.
*
* \funcusage
* \snippet dma/snippet/main.c snippet_Cy_DMA_Descriptor_Deinit
*
*******************************************************************************/
void Cy_DMA_Descriptor_DeInit(cy_stc_dma_descriptor_t * descriptor)
{
descriptor->ctl = 0UL;
descriptor->src = 0UL;
descriptor->dst = 0UL;
descriptor->xCtl = 0UL;
descriptor->yCtl = 0UL;
descriptor->nextPtr = 0UL;
}
/*******************************************************************************
* Function Name: Cy_DMA_Channel_Init
****************************************************************************//**
*
* Initializes the DMA channel with a descriptor and other parameters.
*
* \param base
* The pointer to the hardware DMA block.
*
* \param channel
* A channel number.
*
* \param channelConfig
* The structure that has the initialization information for the
* channel.
*
* \return
* The status /ref cy_en_dma_status_t.
*
* \funcusage
* \snippet dma/snippet/main.c snippet_Cy_DMA_Enable
*
*******************************************************************************/
cy_en_dma_status_t Cy_DMA_Channel_Init(DW_Type * base, uint32_t channel, cy_stc_dma_channel_config_t const * channelConfig)
{
cy_en_dma_status_t ret = CY_DMA_BAD_PARAM;
if ((NULL != base) &&
(NULL != channelConfig) &&
(NULL != channelConfig->descriptor) &&
(CY_DMA_IS_CH_NR_VALID(base, channel)))
{
CY_ASSERT_L2(CY_DMA_IS_PRIORITY_VALID(channelConfig->priority));
/* Set the current descriptor */
Cy_DMA_Channel_SetDescriptor(base, channel, channelConfig->descriptor);
/* Set the channel configuration */
DW_CH_CTL(base, channel) =
_BOOL2FLD(CY_DW_CH_CTL_PREEMPTABLE, channelConfig->preemptable) |
_VAL2FLD(CY_DW_CH_CTL_PRIO, channelConfig->priority) |
_BOOL2FLD(DW_CH_STRUCT_CH_CTL_ENABLED, channelConfig->enable) |
_BOOL2FLD(DW_CH_STRUCT_CH_CTL_B, channelConfig->bufferable);
ret = CY_DMA_SUCCESS;
}
return (ret);
}
/*******************************************************************************
* Function Name: Cy_DMA_Channel_DeInit
****************************************************************************//**
*
* Clears the content of registers corresponding to the channel.
*
* \param base
* The pointer to the hardware DMA block.
*
* \param channel
* A channel number.
*
* \funcusage
* \snippet dma/snippet/main.c snippet_Cy_DMA_Disable
*
*******************************************************************************/
void Cy_DMA_Channel_DeInit(DW_Type * base, uint32_t channel)
{
CY_ASSERT_L1(CY_DMA_IS_CH_NR_VALID(base, channel));
DW_CH_CTL(base, channel) = 0UL;
DW_CH_IDX(base, channel) = 0UL;
DW_CH_CURR_PTR(base, channel) = 0UL;
DW_CH_INTR_MASK(base, channel) = 0UL;
}
/*******************************************************************************
* Function Name: Cy_DMA_Descriptor_SetNextDescriptor
****************************************************************************//**
*
* Sets a Next Descriptor for the specified descriptor.
*
* Based on the descriptor type, the offset of the address for the next descriptor may
* vary. For the single-transfer descriptor type, this register is at offset 0x0c.
* For the 1D-transfer descriptor type, this register is at offset 0x10.
* For the 2D-transfer descriptor type, this register is at offset 0x14.
*
* \param descriptor
* The descriptor structure instance declared by the user/component.
*
* \param nextDescriptor
* The pointer to the next descriptor.
*
* \funcusage
* \snippet dma/snippet/main.c snippet_Cy_DMA_Descriptor_SetterFunctions
*
*******************************************************************************/
void Cy_DMA_Descriptor_SetNextDescriptor(cy_stc_dma_descriptor_t * descriptor, cy_stc_dma_descriptor_t const * nextDescriptor)
{
switch((cy_en_dma_descriptor_type_t) _FLD2VAL(CY_DMA_CTL_TYPE, descriptor->ctl))
{
case CY_DMA_SINGLE_TRANSFER:
descriptor->xCtl = (uint32_t)nextDescriptor;
break;
case CY_DMA_CRC_TRANSFER:
case CY_DMA_1D_TRANSFER:
descriptor->yCtl = (uint32_t)nextDescriptor;
break;
case CY_DMA_2D_TRANSFER:
descriptor->nextPtr = (uint32_t)nextDescriptor;
break;
default:
/* Unsupported type of descriptor */
break;
}
}
/*******************************************************************************
* Function Name: Cy_DMA_Descriptor_GetNextDescriptor
****************************************************************************//**
*
* Returns a next descriptor address of the specified descriptor.
*
* Based on the descriptor type, the offset of the address for the next descriptor may
* vary. For a single-transfer descriptor type, this register is at offset 0x0c.
* For the 1D-transfer descriptor type, this register is at offset 0x10.
* For the 2D-transfer descriptor type, this register is at offset 0x14.
*
* \param descriptor
* The descriptor structure instance declared by the user/component.
*
* \return
* The pointer to the next descriptor.
*
* \funcusage
* \snippet dma/snippet/main.c snippet_Cy_DMA_Descriptor_GetterFunctions
*
*******************************************************************************/
cy_stc_dma_descriptor_t * Cy_DMA_Descriptor_GetNextDescriptor(cy_stc_dma_descriptor_t const * descriptor)
{
cy_stc_dma_descriptor_t * retVal = NULL;
switch((cy_en_dma_descriptor_type_t) _FLD2VAL(CY_DMA_CTL_TYPE, descriptor->ctl))
{
case CY_DMA_SINGLE_TRANSFER:
retVal = (cy_stc_dma_descriptor_t*) descriptor->xCtl;
break;
case CY_DMA_CRC_TRANSFER:
case CY_DMA_1D_TRANSFER:
retVal = (cy_stc_dma_descriptor_t*) descriptor->yCtl;
break;
case CY_DMA_2D_TRANSFER:
retVal = (cy_stc_dma_descriptor_t*) descriptor->nextPtr;
break;
default:
/* An unsupported type of the descriptor */
break;
}
return (retVal);
}
/*******************************************************************************
* Function Name: Cy_DMA_Descriptor_SetDescriptorType
****************************************************************************//**
*
* Sets the descriptor's type for the specified descriptor.
* Moves the next descriptor register value into the proper place in accordance
* to the actual descriptor type.
* During the descriptor's type changing, the Xloop and Yloop settings, such as
* data count and source/destination increment (i.e. the content of the
* xCtl and yCtl descriptor registers) might be lost (overridden by the
* next descriptor value) because of the different descriptor registers structures
* for different descriptor types. Carefully set up the Xloop
* (and Yloop, if used) data count and source/destination increment if the
* descriptor type is changed from a simpler to a more complicated type
* ("single transfer" -> "1D", "1D" -> "2D", etc.).
*
* \param descriptor
* The descriptor structure instance declared by the user/component.
*
* \param descriptorType
* The descriptor type \ref cy_en_dma_descriptor_type_t.
*
* \funcusage
* \snippet dma/snippet/main.c snippet_Cy_DMA_Descriptor_SetterFunctions
*
*******************************************************************************/
void Cy_DMA_Descriptor_SetDescriptorType(cy_stc_dma_descriptor_t * descriptor, cy_en_dma_descriptor_type_t descriptorType)
{
CY_ASSERT_L3(CY_DMA_IS_TYPE_VALID(descriptorType));
if ((CY_DMA_CRC_TRANSFER != descriptorType) || CY_DW_CRC)
{
if (descriptorType != Cy_DMA_Descriptor_GetDescriptorType(descriptor)) /* Do not perform if the type is not changed */
{
/* Store the current nextDescriptor pointer. */
cy_stc_dma_descriptor_t * locNextDescriptor = Cy_DMA_Descriptor_GetNextDescriptor(descriptor);
/* Change the descriptor type. */
CY_REG32_CLR_SET(descriptor->ctl, CY_DMA_CTL_TYPE, descriptorType);
/* Restore the nextDescriptor pointer into the proper place. */
Cy_DMA_Descriptor_SetNextDescriptor(descriptor, locNextDescriptor);
}
}
}
#endif /* CY_IP_M4CPUSS_DMA */
/* [] END OF FILE */
|
/*
* Copyright (C) 2006-2013 Bitronix Software (http://www.bitronix.be)
*
* 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 bitronix.tm.resource.jdbc.proxy;
import bitronix.tm.resource.jdbc.JdbcPooledConnection;
import bitronix.tm.resource.jdbc.LruStatementCache.CacheKey;
import bitronix.tm.resource.jdbc.PooledConnectionProxy;
import bitronix.tm.resource.jdbc.lrc.LrcXAResource;
import bitronix.tm.utils.ClassLoaderUtils;
import net.sf.cglib.proxy.Callback;
import net.sf.cglib.proxy.CallbackFilter;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.Factory;
import net.sf.cglib.proxy.LazyLoader;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
import javax.sql.XAConnection;
import java.lang.reflect.Method;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Map;
import java.util.Set;
/**
* This class generates JDBC proxy classes using CGLIB bytecode generated
* implementations. This factory's proxies are more efficient than JdbcJavaProxyFactory
* but less efficient than JdbcJavassistProxyFactory.
*
* @author Brett Wooldridge
*/
public class JdbcCglibProxyFactory implements JdbcProxyFactory {
private final Class<Connection> proxyConnectionClass;
private final Class<Statement> proxyStatementClass;
private final Class<CallableStatement> proxyCallableStatementClass;
private final Class<PreparedStatement> proxyPreparedStatementClass;
private final Class<ResultSet> proxyResultSetClass;
// For LRC we just use the standard Java Proxies
private final JdbcJavaProxyFactory lrcProxyFactory;
JdbcCglibProxyFactory() {
proxyConnectionClass = createProxyConnectionClass();
proxyStatementClass = createProxyStatementClass();
proxyCallableStatementClass = createProxyCallableStatementClass();
proxyPreparedStatementClass = createProxyPreparedStatementClass();
proxyResultSetClass = createProxyResultSetClass();
lrcProxyFactory = new JdbcJavaProxyFactory();
}
/** {@inheritDoc} */
@Override
public Connection getProxyConnection(JdbcPooledConnection jdbcPooledConnection, Connection connection) {
ConnectionJavaProxy methodInterceptor = new ConnectionJavaProxy(jdbcPooledConnection, connection);
Interceptor interceptor = new Interceptor(methodInterceptor);
FastDispatcher fastDispatcher = new FastDispatcher(connection);
try {
Connection connectionCglibProxy = proxyConnectionClass.newInstance();
((Factory) connectionCglibProxy).setCallbacks(new Callback[] { fastDispatcher, interceptor });
return connectionCglibProxy;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/** {@inheritDoc} */
@Override
public Statement getProxyStatement(JdbcPooledConnection jdbcPooledConnection, Statement statement) {
StatementJavaProxy methodInterceptor = new StatementJavaProxy(jdbcPooledConnection, statement);
Interceptor interceptor = new Interceptor(methodInterceptor);
FastDispatcher fastDispatcher = new FastDispatcher(statement);
try {
Statement statementCglibProxy = proxyStatementClass.newInstance();
((Factory) statementCglibProxy).setCallbacks(new Callback[] { fastDispatcher, interceptor });
return statementCglibProxy;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/** {@inheritDoc} */
@Override
public CallableStatement getProxyCallableStatement(JdbcPooledConnection jdbcPooledConnection, CallableStatement statement) {
CallableStatementJavaProxy methodInterceptor = new CallableStatementJavaProxy(jdbcPooledConnection, statement);
Interceptor interceptor = new Interceptor(methodInterceptor);
FastDispatcher fastDispatcher = new FastDispatcher(statement);
try {
CallableStatement statementCglibProxy = proxyCallableStatementClass.newInstance();
((Factory) statementCglibProxy).setCallbacks(new Callback[] { fastDispatcher, interceptor });
return statementCglibProxy;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/** {@inheritDoc} */
@Override
public PreparedStatement getProxyPreparedStatement(JdbcPooledConnection jdbcPooledConnection, PreparedStatement statement, CacheKey cacheKey) {
PreparedStatementJavaProxy methodInterceptor = new PreparedStatementJavaProxy(jdbcPooledConnection, statement, cacheKey);
Interceptor interceptor = new Interceptor(methodInterceptor);
FastDispatcher fastDispatcher = new FastDispatcher(statement);
try {
PreparedStatement statementCglibProxy = proxyPreparedStatementClass.newInstance();
((Factory) statementCglibProxy).setCallbacks(new Callback[] { fastDispatcher, interceptor });
return statementCglibProxy;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/** {@inheritDoc} */
@Override
public ResultSet getProxyResultSet(Statement statement, ResultSet resultSet) {
ResultSetJavaProxy methodInterceptor = new ResultSetJavaProxy(statement, resultSet);
Interceptor interceptor = new Interceptor(methodInterceptor);
FastDispatcher fastDispatcher = new FastDispatcher(resultSet);
try {
ResultSet resultSetCglibProxy = proxyResultSetClass.newInstance();
((Factory) resultSetCglibProxy).setCallbacks(new Callback[] { fastDispatcher, interceptor });
return resultSetCglibProxy;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/** {@inheritDoc} */
@Override
public XAConnection getProxyXaConnection(Connection connection) {
return lrcProxyFactory.getProxyXaConnection(connection);
}
/** {@inheritDoc} */
@Override
public Connection getProxyConnection(LrcXAResource xaResource, Connection connection) {
return lrcProxyFactory.getProxyConnection(xaResource, connection);
}
// ---------------------------------------------------------------
// Generate CGLIB Proxy Classes
// ---------------------------------------------------------------
@SuppressWarnings("unchecked")
private Class<Connection> createProxyConnectionClass() {
Set<Class<?>> interfaces = ClassLoaderUtils.getAllInterfaces(Connection.class);
interfaces.add(PooledConnectionProxy.class);
Enhancer enhancer = new Enhancer();
enhancer.setInterfaces(interfaces.toArray(new Class<?>[0]));
enhancer.setCallbackTypes(new Class[] {FastDispatcher.class, Interceptor.class} );
enhancer.setCallbackFilter(new InterceptorFilter(new ConnectionJavaProxy()));
return enhancer.createClass();
}
@SuppressWarnings("unchecked")
private Class<PreparedStatement> createProxyPreparedStatementClass() {
Set<Class<?>> interfaces = ClassLoaderUtils.getAllInterfaces(PreparedStatement.class);
Enhancer enhancer = new Enhancer();
enhancer.setInterfaces(interfaces.toArray(new Class<?>[0]));
enhancer.setCallbackTypes(new Class[] {FastDispatcher.class, Interceptor.class} );
enhancer.setCallbackFilter(new InterceptorFilter(new PreparedStatementJavaProxy()));
return enhancer.createClass();
}
@SuppressWarnings("unchecked")
private Class<Statement> createProxyStatementClass() {
Set<Class<?>> interfaces = ClassLoaderUtils.getAllInterfaces(Statement.class);
Enhancer enhancer = new Enhancer();
enhancer.setInterfaces(interfaces.toArray(new Class<?>[0]));
enhancer.setCallbackTypes(new Class[] {FastDispatcher.class, Interceptor.class} );
enhancer.setCallbackFilter(new InterceptorFilter(new StatementJavaProxy()));
return enhancer.createClass();
}
@SuppressWarnings("unchecked")
private Class<CallableStatement> createProxyCallableStatementClass() {
Set<Class<?>> interfaces = ClassLoaderUtils.getAllInterfaces(CallableStatement.class);
Enhancer enhancer = new Enhancer();
enhancer.setInterfaces(interfaces.toArray(new Class<?>[0]));
enhancer.setCallbackTypes(new Class[] {FastDispatcher.class, Interceptor.class} );
enhancer.setCallbackFilter(new InterceptorFilter(new CallableStatementJavaProxy()));
return enhancer.createClass();
}
@SuppressWarnings("unchecked")
private Class<ResultSet> createProxyResultSetClass() {
Set<Class<?>> interfaces = ClassLoaderUtils.getAllInterfaces(ResultSet.class);
Enhancer enhancer = new Enhancer();
enhancer.setInterfaces(interfaces.toArray(new Class<?>[0]));
enhancer.setCallbackTypes(new Class[] {FastDispatcher.class, Interceptor.class} );
enhancer.setCallbackFilter(new InterceptorFilter(new ResultSetJavaProxy()));
return enhancer.createClass();
}
// ---------------------------------------------------------------
// CGLIB Classes
// ---------------------------------------------------------------
static class FastDispatcher implements LazyLoader {
private final Object delegate;
public FastDispatcher(Object delegate) {
this.delegate = delegate;
}
@Override
public Object loadObject() throws Exception {
return delegate;
}
}
static class Interceptor implements MethodInterceptor {
private final JavaProxyBase<?> interceptor;
public Interceptor(JavaProxyBase<?> interceptor) {
this.interceptor = interceptor;
}
@Override
public Object intercept(Object enhanced, Method method, Object[] args, MethodProxy fastProxy) throws Throwable {
interceptor.proxy = enhanced;
return interceptor.invoke(interceptor, method, args);
}
}
static class InterceptorFilter implements CallbackFilter {
private final Map<String, Method> methodMap;
public InterceptorFilter(JavaProxyBase<?> proxyClass) {
methodMap = proxyClass.getMethodMap();
}
@Override
public int accept(Method method) {
if (methodMap.containsKey(JavaProxyBase.getMethodKey(method))) {
// Use the Interceptor
return 1;
}
// Use the FastDispatcher
return 0;
}
}
}
|
/*
* Licensed to Jasig under one or more contributor license
* agreements. See the NOTICE file distributed with this work
* for additional information regarding copyright ownership.
* Jasig 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 the following location:
*
* 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.jasig.cas.util;
import org.aspectj.lang.JoinPoint;
/**
* Utility class to assist with AOP operations.
*
* @author Marvin S. Addison
* @since 3.4
*
*/
public final class AopUtils {
private AopUtils() {}
/**
* Unwraps a join point that may be nested due to layered proxies.
*
* @param point Join point to unwrap.
* @return Innermost join point; if not nested, simply returns the argument.
*/
public static JoinPoint unWrapJoinPoint(final JoinPoint point) {
JoinPoint naked = point;
while (naked.getArgs().length > 0 && naked.getArgs()[0] instanceof JoinPoint) {
naked = (JoinPoint) naked.getArgs()[0];
}
return naked;
}
}
|
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/** Wraps the provided value in an array, unless the provided value is an array. */
export declare function coerceArray<T>(value: T | T[]): T[];
|
/* Copyright 2016 The TensorFlow 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.
==============================================================================*/
// See docs in ../ops/string_ops.cc.
#include <string>
#include "tensorflow/core/framework/kernel_def_builder.h"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/core/lib/strings/stringprintf.h"
namespace tensorflow {
class AsStringOp : public OpKernel {
public:
using OpKernel::OpKernel;
explicit AsStringOp(OpKernelConstruction* ctx) : OpKernel(ctx) {
int32 precision;
bool scientific;
bool shortest;
int32 width;
string fill_string;
DataType dtype;
OP_REQUIRES_OK(ctx, ctx->GetAttr("T", &dtype));
OP_REQUIRES_OK(ctx, ctx->GetAttr("precision", &precision));
OP_REQUIRES_OK(ctx, ctx->GetAttr("scientific", &scientific));
OP_REQUIRES_OK(ctx, ctx->GetAttr("shortest", &shortest));
OP_REQUIRES_OK(ctx, ctx->GetAttr("width", &width));
OP_REQUIRES_OK(ctx, ctx->GetAttr("fill", &fill_string));
switch (dtype) {
case DT_FLOAT:
case DT_DOUBLE:
case DT_COMPLEX64:
case DT_COMPLEX128:
break;
default:
OP_REQUIRES(ctx, !(scientific || shortest),
errors::InvalidArgument("scientific and shortest format "
"not supported for datatype ",
DataTypeString(dtype)));
OP_REQUIRES(ctx, precision < 0,
errors::InvalidArgument("precision not supported "
"for datatype ",
DataTypeString(dtype)));
}
OP_REQUIRES(
ctx, fill_string.size() <= 1,
errors::InvalidArgument("Fill string must be one or fewer characters"));
OP_REQUIRES(ctx, !(scientific && shortest),
errors::InvalidArgument(
"Cannot select both scientific and shortest notation"));
format_ = "%";
if (width > -1) {
strings::Appendf(&format_, "%s%d", fill_string.c_str(), width);
}
if (precision > -1) {
strings::Appendf(&format_, ".%d", precision);
}
switch (dtype) {
case DT_INT8:
case DT_INT16:
case DT_INT32:
strings::Appendf(&format_, "d");
break;
case DT_INT64:
strings::Appendf(&format_, "lld");
break;
case DT_FLOAT:
case DT_DOUBLE:
case DT_COMPLEX64:
case DT_COMPLEX128:
if (shortest) {
strings::Appendf(&format_, "g");
} else if (scientific) {
strings::Appendf(&format_, "e");
} else {
strings::Appendf(&format_, "f");
}
break;
case DT_BOOL:
break;
default:
bool type_not_supported = true;
OP_REQUIRES(ctx, !type_not_supported,
errors::InvalidArgument("Type not supported: ",
DataTypeString(dtype)));
}
if (dtype == DT_COMPLEX64 || dtype == DT_COMPLEX128) {
format_ = strings::Printf("(%s,%s)", format_.c_str(), format_.c_str());
}
}
void Compute(OpKernelContext* context) override {
const Tensor* input_tensor;
OP_REQUIRES_OK(context, context->input("input", &input_tensor));
const DataType& dtype = input_tensor->dtype();
Tensor* output_tensor = nullptr;
OP_REQUIRES_OK(context,
context->allocate_output("output", input_tensor->shape(),
&output_tensor));
auto output_flat = output_tensor->flat<tstring>();
#define ENCODE_TYPE(type, T, enc_str) \
case (type): { \
const auto& input_flat = input_tensor->flat<T>(); \
for (int i = 0; i < input_flat.size(); ++i) { \
output_flat(i) = strings::Printf((enc_str.c_str()), input_flat(i)); \
} \
} break
switch (dtype) {
ENCODE_TYPE(DT_INT32, int32, format_);
ENCODE_TYPE(DT_INT64, int64, format_);
ENCODE_TYPE(DT_FLOAT, float, format_);
ENCODE_TYPE(DT_DOUBLE, double, format_);
ENCODE_TYPE(DT_INT8, int8, format_);
ENCODE_TYPE(DT_INT16, int16, format_);
case (DT_BOOL): {
const auto& input_flat = input_tensor->flat<bool>();
for (int i = 0; i < input_flat.size(); ++i) {
output_flat(i) = (input_flat(i)) ? "true" : "false";
}
} break;
case (DT_COMPLEX64): {
const auto& input_flat = input_tensor->flat<complex64>();
for (int i = 0; i < input_flat.size(); ++i) {
output_flat(i) = strings::Printf(
format_.c_str(), input_flat(i).real(), input_flat(i).imag());
}
} break;
case (DT_COMPLEX128): {
const auto& input_flat = input_tensor->flat<complex128>();
for (int i = 0; i < input_flat.size(); ++i) {
output_flat(i) = strings::Printf(
format_.c_str(), input_flat(i).real(), input_flat(i).imag());
}
} break;
default:
bool can_encode_type = false;
OP_REQUIRES(context, can_encode_type,
errors::InvalidArgument("Cannot encode input of type ",
DataTypeString(dtype)));
}
#undef ENCODE_TYPE
}
private:
string format_;
};
REGISTER_KERNEL_BUILDER(Name("AsString").Device(DEVICE_CPU), AsStringOp);
} // namespace tensorflow
|
// Backward-compat support -*- C++ -*-
// Copyright (C) 2001 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library. This library is free
// software; you can redistribute it and/or modify it under the
// terms of the GNU General Public License as published by the
// Free Software Foundation; either version 2, or (at your option)
// any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License along
// with this library; see the file COPYING. If not, write to the Free
// Software Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307,
// USA.
// As a special exception, you may use this file as part of a free software
// library without restriction. Specifically, if other files instantiate
// templates or use macros or inline functions from this file, or you compile
// this file and link it with other files to produce an executable, this
// file does not by itself cause the resulting executable to be covered by
// the GNU General Public License. This exception does not however
// invalidate any other reasons why the executable file might be covered by
// the GNU General Public License.
/*
* Copyright (c) 1996-1997
* Silicon Graphics Computer Systems, Inc.
*
* Permission to use, copy, modify, distribute and sell this software
* and its documentation for any purpose is hereby granted without fee,
* provided that the above copyright notice appear in all copies and
* that both that copyright notice and this permission notice appear
* in supporting documentation. Silicon Graphics makes no
* representations about the suitability of this software for any
* purpose. It is provided "as is" without express or implied warranty.
*/
#ifndef _CPP_BACKWARD_ALLOC_H
#define _CPP_BACKWARD_ALLOC_H 1
#include "backward_warning.h"
#include <bits/c++config.h>
#include <bits/stl_alloc.h>
using std::__malloc_alloc_template;
using std::__simple_alloc;
using std::__debug_alloc;
using std::__alloc;
using std::__single_client_alloc;
using std::allocator;
using std::__default_alloc_template;
#endif
|
/*
* OutputBuffer.java June 2007
*
* Copyright (C) 2007, Niall Gallagher <niallg@users.sf.net>
*
* 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.simpleframework.xml.stream;
import java.io.IOException;
import java.io.Writer;
/**
* This is primarily used to replace the <code>StringBuffer</code>
* class, as a way for the <code>Formatter</code> to store the start
* tag for an XML element. This enables the start tag of the current
* element to be removed without disrupting any of the other nodes
* within the document. Once the contents of the output buffer have
* been filled its contents can be emitted to the writer object.
*
* @author Niall Gallagher
*/
class OutputBuffer {
/**
* The characters that this buffer has accumulated.
*/
private StringBuilder text;
/**
* Constructor for <code>OutputBuffer</code>. The default
* <code>OutputBuffer</code> stores 16 characters before a
* resize is needed to append extra characters.
*/
public OutputBuffer() {
this.text = new StringBuilder();
}
/**
* This will add a <code>char</code> to the end of the buffer.
* The buffer will not overflow with repeated uses of the
* <code>append</code>, it uses an <code>ensureCapacity</code>
* method which will allow the buffer to dynamically grow in
* size to accommodate more characters.
*
* @param ch the character to be appended to the buffer
*/
public void append(char ch){
text.append(ch);
}
/**
* This will add a <code>String</code> to the end of the buffer.
* The buffer will not overflow with repeated uses of the
* <code>append</code>, it uses an <code>ensureCapacity</code>
* method which will allow the buffer to dynamically grow in
* size to accommodate large string objects.
*
* @param value the string to be appended to this output buffer
*/
public void append(String value){
text.append(value);
}
/**
* This will add a <code>char</code> array to the buffer.
* The buffer will not overflow with repeated uses of the
* <code>append</code>, it uses an <code>ensureCapacity</code>
* method which will allow the buffer to dynamically grow in
* size to accommodate large character arrays.
*
* @param value the character array to be appended to this
*/
public void append(char[] value){
text.append(value, 0, value.length);
}
/**
* This will add a <code>char</code> array to the buffer.
* The buffer will not overflow with repeated uses of the
* <code>append</code>, it uses an <code>ensureCapacity</code>
* method which will allow the buffer to dynamically grow in
* size to accommodate large character arrays.
*
* @param value the character array to be appended to this
* @param off the read offset for the array to begin reading
* @param len the number of characters to append to this
*/
public void append(char[] value, int off, int len){
text.append(value, off, len);
}
/**
* This will add a <code>String</code> to the end of the buffer.
* The buffer will not overflow with repeated uses of the
* <code>append</code>, it uses an <code>ensureCapacity</code>
* method which will allow the buffer to dynamically grow in
* size to accommodate large string objects.
*
* @param value the string to be appended to the output buffer
* @param off the offset to begin reading from the string
* @param len the number of characters to append to this
*/
public void append(String value, int off, int len){
text.append(value, off, len);
}
/**
* This method is used to write the contents of the buffer to the
* specified <code>Writer</code> object. This is used when the
* XML element is to be committed to the resulting XML document.
*
* @param out this is the writer to write the buffered text to
*
* @throws IOException thrown if there is an I/O problem
*/
public void write(Writer out) throws IOException {
out.append(text);
}
/**
* This will empty the <code>OutputBuffer</code> so that it does
* not contain any content. This is used to that when the buffer
* is written to a specified <code>Writer</code> object nothing
* is written out. This allows XML elements to be removed.
*/
public void clear(){
text.setLength(0);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.