content
stringlengths 10
4.9M
|
---|
export const RECORDER_ELEMENT_IDENTIFIER = 'data-test-automation-id';
export const DEFAULT_RECORDER_HOST = 'localhost';
export const DEFAULT_RECORDER_HTTP_PORT = 3050;
export const DEFAULT_RECORDER_WS_PORT = 3051;
|
Eric Decker says money won't be the only factor when it comes to his decision on whether to re-sign with the Denver Broncos.
"It's not all about the money for me. It's about going to work every day and having fun and enjoying my job," the veteran receiver said on SiriusXM NFL Radio.
Eric Decker, set to become an unrestricted free agent next month, made 87 receptions for 1,288 yards and 11 touchdowns with Denver last season. AP Photo/Paul Spinelli
Expected to be one of the top unrestricted free agents available when the market opens March 11, Decker thrived in the Broncos' record-setting offense led by Peyton Manning last season, catching 87 passes for 1,288 yards and 11 touchdowns. He hauled in 85 passes for 1,064 yards and 13 scores in his first season with Manning in Denver.
Decker, 26, said in the interview that he enjoys the culture around the Broncos and has not closed the door on remaining with the team.
"If we can get on the same page, I will welcome a call from the Broncos, but I need to do what is best for my family," he said.
Decker offered similar thoughts at the end of the season when he cleaned out his locker.
"There is a side of playing football and there is the business side," Decker said. "That's something that obviously I'll have to have conversations with my representation. I want to do the best thing for my family and myself. This is an organization that any player wants to come to. I mean, they treat you first-class. It's a winning organization. They've built a culture here that is phenomenal. I would love to play here. Unfortunately, that's something that isn't always in my control. You've just got to take it in stride and again, have those conversations, see what the next couple of months will bring."
This is the first foray into free agency for Decker, who could have the franchise tag used on him. But that may be unlikely because Demaryius Thomas, widely considered to be the club's No. 1 receiver, and tight end Julius Thomas are entering contract years in 2014, which means the team will have to set aside money to ensure neither reaches free agency.
Information from ESPN.com Broncos reporter Jeff Legwold was used in this report. |
def configureClinicalDf(self, clinicalDf, redCapToCbioMappingDf):
assert clinicalDf.columns.isin(redCapToCbioMappingDf["code"]).all()
clinicalDf.columns = [
redCapToCbioMappingDf["cbio"][redCapToCbioMappingDf["code"] == col].values[
0
]
for col in clinicalDf.columns
]
clinicalDf = clinicalDf.drop_duplicates()
assert (
sum(clinicalDf["PATIENT_ID"].isnull()) == 0
), "Must have no null patient ids"
clinicalDf["PATIENT_ID"] = [
patient.replace(" ", "") for patient in clinicalDf["PATIENT_ID"]
]
clinicalDf["PATIENT_ID"] = clinicalDf.apply(
lambda x: process_functions.checkGenieId(x["PATIENT_ID"], x["CENTER"]),
axis=1,
)
if clinicalDf.get("SAMPLE_ID") is not None:
clinicalDf = clinicalDf[~clinicalDf["SAMPLE_ID"].isnull()]
assert (
sum(clinicalDf["SAMPLE_ID"].isnull()) == 0
), "Must have no null sample ids"
clinicalDf["SAMPLE_ID"] = [
sample.replace(" ", "") for sample in clinicalDf["SAMPLE_ID"]
]
clinicalDf["SAMPLE_ID"] = clinicalDf.apply(
lambda x: process_functions.checkGenieId(x["SAMPLE_ID"], x["CENTER"]),
axis=1,
)
else:
clinicalDf["OS_MONTHS"] = (
clinicalDf["DEATH_DATE_INT"] - clinicalDf["MET_DX_DATE_INT"]
)
clinicalDf["SP"] = self._SPONSORED_PROJECT
if clinicalDf.get("OS_STATUS") is not None:
clinicalDf["OS_STATUS"][clinicalDf["OS_STATUS"] == "Dead"] = "DECEASED"
clinicalDf["OS_STATUS"][clinicalDf["OS_STATUS"] == "Alive"] = "LIVING"
for col in clinicalDf:
numMissing = sum(clinicalDf[col].isnull())
if numMissing > 0:
print("Number of missing %s: %d" % (col, numMissing))
return clinicalDf |
/**
* Find out of a column was changed, by column number
*
* @param columnNumber the column to check
*
* @return true if the column was modified by this statement.
* Note that this will always return true for INSERT
* and DELETE regardless of the column name passed in.
*/
public boolean wasColumnModified(int columnNumber)
{
if (changedColIds == null)
{
return true;
}
for (int i = 0; i < changedColNames.length; i++)
{
if (changedColIds[i] == columnNumber)
{
return true;
}
}
return false;
} |
.
Ag-NOR patterns were studied in hepatocytes from nine mink embryo siblings, including a pair of monochorionic (presumably monozygotic, MZ) twins. Both the number and the size of Ag-NORs per cell were found to be identical in MZ twins. All the other sibs had the patterns different from each other and from the MZ ones. The conclusion is that the NORs activity is a strongly inherited character and the Ag-NOR pattern can be used as a reliable genetic marker to distinguish the twin zygosity. |
/*
* FAT16 accessors.
*
* FAT16s are sufficiently small, expect it to always fit in the RAM.
*/
static inline uint8_t *
fat_get_fat16_ptr(struct fat_descriptor *fat, cl_t cl)
{
return (fat->fatbuf + (cl << 1));
} |
use std::path::{Component, Path};
use amethyst::{
assets::{AssetStorage, Handle, Loader, ProgressCounter},
renderer::{formats::texture::ImageFormat, Texture},
Error,
};
use log::error;
use sprite_model::config::SpriteSheetDefinition;
/// Loads textures specified in the sprite sheet definitions.
#[derive(Debug)]
pub struct TextureLoader;
impl TextureLoader {
/// Loads the sprite sheet images as textures and returns the texture handles.
///
/// # Parameters
///
/// * `progress_counter`: `ProgressCounter` to track loading.
/// * `loader`: `Loader` to load assets.
/// * `texture_assets`: `AssetStorage` for `Texture`s.
/// * `object_directory`: Object configuration base directory.
/// * `sprite_sheet_definitions`: List of metadata for sprite sheets to load.
pub fn load_textures(
progress_counter: &mut ProgressCounter,
loader: &Loader,
texture_assets: &AssetStorage<Texture>,
object_directory: &Path,
sprite_sheet_definitions: &[SpriteSheetDefinition],
) -> Result<Vec<Handle<Texture>>, Error> {
let texture_results = sprite_sheet_definitions
.iter()
.map(|sheet_definition| {
// We need to do this to handle mixed slashes on Windows.
let sheet_definition_path = Path::new(&sheet_definition.path);
let sprite_image_path = if sheet_definition_path.is_absolute() {
sheet_definition_path.to_path_buf()
} else {
sheet_definition_path.components().fold(
object_directory.to_path_buf(),
|mut sprite_image_path, sheet_definition_component| {
match sheet_definition_component {
Component::ParentDir => {
sprite_image_path.pop();
}
Component::Normal(segment) => {
sprite_image_path.push(segment);
}
Component::Prefix(_) | Component::RootDir | Component::CurDir => {}
}
sprite_image_path
},
)
};
let sprite_image_path = sprite_image_path.canonicalize().unwrap_or_else(|e| {
panic!(
"Failed to canonicalize texture path: `{}`. Error: {}",
sprite_image_path.display(),
e
)
});
let error_msg = format!(
"Failed to transform sprite image path to String: `{}`",
sprite_image_path.display()
);
let sprite_image_path = sprite_image_path.to_str().ok_or(error_msg)?;
Ok(Self::load(
progress_counter,
loader,
texture_assets,
String::from(sprite_image_path),
))
})
.collect::<Vec<Result<Handle<Texture>, String>>>();
{
let failed_to_load = texture_results
.iter()
.filter(|result| result.is_err())
.map(|result| result.as_ref().unwrap_err().as_str()) // kcov-ignore
.collect::<Vec<&str>>();
if !failed_to_load.is_empty() {
// kcov-ignore-start
let mut error_message = String::with_capacity(30 + failed_to_load.len() * 200);
error_message.push_str("Failed to load textures:\n\n");
failed_to_load.iter().for_each(|error| {
error_message.push_str("* ");
error_message.push_str(error);
error_message.push('\n');
});
error_message.push('\n');
error!("{}", &error_message);
return Err(Error::from_string(error_message));
} // kcov-ignore-end
}
let texture_handles = texture_results
.into_iter()
.map(Result::unwrap)
.collect::<Vec<Handle<Texture>>>();
Ok(texture_handles)
}
/// Returns a `Handle<Texture>` to the image.
///
/// This function expects the image to be in PNG format.
///
/// # Parameters
///
/// * `progress_counter`: `ProgressCounter` to track loading.
/// * `loader`: `Loader` to load assets.
/// * `texture_assets`: `AssetStorage` for `Texture`s.
/// * `path`: Path to the sprite sheet.
fn load<N>(
progress_counter: &mut ProgressCounter,
loader: &Loader,
texture_assets: &AssetStorage<Texture>,
path: N,
) -> Handle<Texture>
where
N: Into<String>,
{
loader.load(
path,
ImageFormat::default(),
progress_counter,
&texture_assets,
)
}
}
|
// IsProd return true if app is in production mode.
func IsProd() bool {
switch RunMode("devel") {
case "prod", "production":
return true
}
return false
} |
Structural evolution of phosphated alumina during sol-gel synthesis.
Phosphated alumina gels were prepared by the sol-gel method. Gels were aged from 1 to 8 days in air. Gel structure evolution, as time went on, was followed by 27Al magic angle spinning nuclear magnetic resonance, X-ray diffraction, and small-angle X-ray scattering. It is concluded that the aging time is a crucial parameter in the formation of coordinately unsaturated sites of aluminum (AlIV and AlV). The gel network is shown to have a fractal structure. |
def recalc(self, fromRect=True):
if fromRect:
self.__dict__['r'] = sqrt(self.x**2 + self.y**2)
self.__dict__['a'] = atan2(self.y, self.x)
else:
self.__dict__['x'] = round(self.r * cos(self.a),15)
self.__dict__['y'] = round(self.r * sin(self.a),15)
return self |
<filename>digsby/src/gui/imwin/imwin_email.py
'''
GUI for the IM window's email tab.
'''
import wx
from util.primitives.funcs import Delegate
from gui.uberwidgets.UberButton import UberButton
from gui.uberwidgets.UberBar import UberBar
from gui.uberwidgets.skintextctrl import SkinTextCtrl
from gui.uberwidgets.cleartext import ClearText
from gui.textutil import default_font
from gui.validators import LengthLimit
from gui import skin
from cgui import SimplePanel
class ImWinEmailPanel(SimplePanel):
def __init__(self, parent):
SimplePanel.__init__(self, parent)
self.OnEditEmail = Delegate()
self.OnSendEmail = Delegate()
self.gui_constructed = False
self.UpdateSkin()
self.construct_gui()
def SetEmailClient(self, email_account):
'''
Changes the "Edit In..." button to show the name of an email client.
If None, the button becomes disabled.
'''
client = email_account.client_name if email_account is not None else None
if client is not None:
self.send_button.Enable(True)
self.openin.Enable(True)
if client:
label = _('Edit in {client}...').format(client=client)
else:
label = _('Edit...')
self.openin.SetLabel(label)
else:
self.send_button.Enable(False)
self.openin.Enable(False)
self.openin.SetLabel(_('Edit...'))
def UpdateSkin(self):
g = skin.get
self.buttonbarskin = g('SendBar.ToolBarSkin', None)
self.subjectskin = g('EmailSubjectBar.ToolBarSkin',None)
self.subjectfont = g('EmailSubjectBar.Fonts.SubjectLabel',lambda: default_font())
self.subjectfc = g('EmailSubjectBar.FontColors.SubjectLabel', wx.BLACK)
self.buttonbarfont = g('SendBar.Font', default_font)
self.buttonnarfc = g('SendBar.FontColor', wx.BLACK)
if self.gui_constructed:
self.subject_bar.SetSkinKey(self.subjectskin)
self.email_buttons.SetSkinKey(self.buttonbarskin)
ept = self.email_progress_text
ept.SetFont(self.buttonbarfont)
ept.SetFontColor(self.buttonnarfc)
sl = self.subject_label
sl.SetFont(self.subjectfont)
sl.SetFontColor(self.subjectfc)
def construct_gui(self):
self.Sizer = wx.BoxSizer(wx.VERTICAL)
s = self.subject_bar = UberBar(self, skinkey = self.subjectskin)
self.subject_input = SkinTextCtrl(s, skinkey = ('EmailSubjectBar', 'SubjectField'),
skinkey_bg = 'EmailSubjectBar.FieldBackgroundColor',
validator=LengthLimit(1024),
)
self.subject_label = ClearText(s, _('Subject:'), alignment = wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT)
self.subject_label.Font = self.subjectfont
self.subject_label.FontColor = self.subjectfc
s.Add(self.subject_label)
s.Add(self.subject_input,1)
# construct email buttons panel
email_buttons = self.email_buttons = UberBar(self, skinkey=self.buttonbarskin)
ept = self.email_progress_text = ClearText(email_buttons, '', alignment = wx.ALIGN_CENTER_VERTICAL)
ept.SetFont(self.buttonbarfont)
ept.SetFontColor(self.buttonnarfc)
# email body text input
self.email_input_area = wx.TextCtrl(self, style = wx.TE_MULTILINE,
validator=LengthLimit(20480),
)
# "open in" and "send"
self.openin = UberButton(email_buttons, -1, _('Edit...'), onclick = self.OnEditEmail)
self.send_button = UberButton(email_buttons, -1, _('Send'), onclick = self.OnSendClicked)
# layout email buttons
email_buttons.Add(ept)
email_buttons.Add(wx.Size(1,1), 1)#StretchSpacer(1)
email_buttons.Add(self.openin)
email_buttons.Add(self.send_button)
# Make sure Tab from the subject input goes to the body input.
self.email_input_area.MoveAfterInTabOrder(self.subject_bar)
s = self.Sizer
s.AddMany([(self.subject_bar, 0, wx.EXPAND),
(self.email_input_area, 1, wx.EXPAND),
(self.email_buttons, 0, wx.EXPAND)])
self.gui_constructed = True
def OnSendClicked(self, e):
self.OnSendEmail(e)
def Clear(self):
self.subject_input.Clear()
self.email_input_area.Clear()
def SetStatusMessage(self, msg):
self.email_progress_text.SetLabel(msg)
def EnableSendButton(self, enabled):
self.send_button.Enable(enabled)
|
import gym
import numpy as np
from typing import Any, Callable, Iterator, List, Optional, Tuple, Union, cast
from d3rlpy.metrics.scorer import AlgoProtocol
def evaluate_initial_state_value_estimate(env: gym.Env, n_trials: int = 10) -> Callable[..., float]:
def scorer(algo: AlgoProtocol, *args: Any) -> float:
initial_state_value_estimate = []
for _ in range(n_trials):
observation = env.reset()
q_values = []
for action in range(env.action_space.n):
q_estimate = algo.predict_value(
np.array([observation]),
np.array([action])
)
q_values.append(q_estimate)
initial_state_value_estimate.append(max(q_values))
return float(np.mean(initial_state_value_estimate))
return scorer
|
import styled from "styled-components";
import Bg from "@components/Bg";
import { Button, RedButton } from "@components/Inputs";
import { SubTitle, LargeCode } from "@components/Title";
import redirect from "@lib/redirect";
const DeleteWrapper = styled.div`
margin-top: 20px;
margin-left: 20px;
`;
const DeleteResource = ({
resourceName,
deleteCallback,
redirectUrl,
}: {
resourceName: string;
deleteCallback: () => Promise<void>;
redirectUrl: string;
}) => {
return (
<Bg altColor>
<DeleteWrapper>
<SubTitle>
Are you sure you want to delete <LargeCode>{resourceName}</LargeCode>?
</SubTitle>
<Button
type="button"
onClick={() => {
redirect(redirectUrl);
}}
>
NO!
</Button>
<RedButton
type="button"
onClick={async () => {
await deleteCallback();
redirect("/admin/");
}}
>
Yes
</RedButton>
</DeleteWrapper>
</Bg>
);
};
export default DeleteResource;
|
<gh_stars>1-10
package main
import (
"crypto/aes"
"crypto/cipher"
"crypto/hmac"
"crypto/sha256"
"crypto/subtle"
"database/sql"
"encoding/hex"
"encoding/json"
"errors"
"io/ioutil"
"log"
"net/http"
"github.com/opencoff/go-srp"
"github.com/pquerna/otp/totp"
)
// jsMap - alias for map[string]interface{}
type jsMap map[string]interface{}
type User struct {
ID int
IH string
Username string
Verifier string
Address string
TOTP string
}
// sign - returns a HMAC signature for a message
func sign(message, key string) string {
mac := hmac.New(sha256.New, []byte(key))
mac.Write([]byte(message))
return hex.EncodeToString(mac.Sum(nil))
}
// isRegistered - check if username is already present in the database
func isRegistered(username string) bool {
row := db.QueryRow(`
SELECT username
FROM accounts
WHERE username = $1;`, username,
)
err := row.Scan()
return err != sql.ErrNoRows
}
// getUser - retrieves a user from the database
func getUser(username string) (*User, error) {
row := db.QueryRow(`
SELECT ih, verifier, username, id, address, totp
FROM accounts
WHERE username = $1;`, username,
)
user := User{}
err := row.Scan(
&user.IH,
&user.Verifier,
&user.Username,
&user.ID,
&user.Address,
&user.TOTP,
)
if err != nil {
log.Println("getUser: ", err)
return nil, err
}
return &user, nil
}
// getBody - retrieves the raw data received in a request
func getBody(req *http.Request) ([]byte, error) {
rawData, err := ioutil.ReadAll(req.Body)
return rawData, err
}
// writeJSON - writes json to the responseWriter
func writeJSON(res http.ResponseWriter, code int, data jsMap) {
res.WriteHeader(code)
json.NewEncoder(res).Encode(data)
}
// authenticateUser - checks if the users credentials are valid
func authenticateUser(user *User, username, password string) ([]byte, error) {
client, err := srpEnv.NewClient([]byte(username), []byte(password))
if err != nil {
return nil, err
}
creds := client.Credentials()
ih, A, err := srp.ServerBegin(creds)
if err != nil {
return nil, err
}
if user.IH != ih {
return nil, errors.New("IH's didn't match")
}
s, verif, err := srp.MakeSRPVerifier(user.Verifier)
if err != nil {
return nil, err
}
srv, err := s.NewServer(verif, A)
if err != nil {
return nil, err
}
creds = srv.Credentials()
cauth, err := client.Generate(creds)
if err != nil {
return nil, err
}
proof, ok := srv.ClientOk(cauth)
if !ok {
return nil, errors.New("Authentication Failed")
}
if !client.ServerOk(proof) {
return nil, errors.New("Authentication Failed")
}
if 1 != subtle.ConstantTimeCompare(client.RawKey(), srv.RawKey()) {
return nil, errors.New("Authentication Failed")
}
return A.Bytes(), nil
}
func verifyTOTP(user *User, passcode string) error {
key, _ := hex.DecodeString(secretKey)
ciphertext, _ := hex.DecodeString(user.TOTP)
block, err := aes.NewCipher(key)
if err != nil {
return err
}
if len(ciphertext) < aes.BlockSize {
return errors.New("ciphertext too short")
}
iv := ciphertext[:aes.BlockSize]
ciphertext = ciphertext[aes.BlockSize:]
if len(ciphertext)%aes.BlockSize != 0 {
return errors.New("ciphertext is not a multiple of the block size")
}
mode := cipher.NewCBCDecrypter(block, iv)
mode.CryptBlocks(ciphertext, ciphertext)
if !totp.Validate(passcode, string(ciphertext)) {
return err
}
return nil
}
|
The electronic structure of a single-walled aluminosilicate nanotube
The geometric structure and electronic structure of an imogolite nanotube have been studied using density functional theory (DFT). The calculation results indicate that the deformation of the material leads to structural electric charges on the tube wall. This hydrous aluminosilicate single-walled nanotube is a wide gap semiconductor with a direct band gap, Eg∼3.67 eV at the Γ point, which may be promising for application in optoelectronic devices. In conjunction with the DFT calculations, molecular dynamics simulations based on empirical potentials are also performed to evaluate the mechanical properties of this material. |
/**
* Returns a map with all namespaces that are valid for the specified pre value.
* @param pre pre value
* @param data data reference
* @return scope
*/
TokenMap scope(final int pre, final Data data) {
final TokenMap nsScope = new TokenMap();
NSNode node = current;
do {
final int[] values = node.values;
final int vl = values.length;
for(int v = 0; v < vl; v += 2) {
nsScope.put(prefix(values[v]), uri(values[v + 1]));
}
final int pos = node.find(pre);
if(pos < 0) break;
node = node.children[pos];
} while(node.pr <= pre && pre < node.pr + data.size(node.pr, Data.ELEM));
return nsScope;
} |
/*
* simply re-trigger the interrupt handler on led timeout
*/
static void
blink_led_timeout(void *arg)
{
struct sysctrl_soft_state *softsp = arg;
int led_state;
ASSERT(softsp);
softsp->sys_fault = process_fault_list();
mutex_enter(&softsp->sys_led_lock);
softsp->sys_led = !softsp->sys_led;
led_state = softsp->sys_led;
mutex_exit(&softsp->sys_led_lock);
toggle_board_green_leds(led_state);
ddi_trigger_softintr(softsp->blink_led_id);
} |
The Xiaomi Mi Band placed the company on the health and fitness tracking radar and according to Chinese sources, the successor is soon to launch. A purported photo of the Mi Band 2 shows the body of the tracker, but sadly it isn't as revealing as we'd hoped.
Apart from the photo, there's no new information regarding the Mi Band 2 at this point. It's expected to pack NFC and slightly larger battery, but nothing is confirmed just yet. A teaser image has been published by Xiaomi, which suggests that we can expect news surrounding a new Amazfit product on September 16.
Amazfit could be the new name of the Xiaomi Mi Band
Back in the summer, we saw the alleged Xiaomi Mi Band 1s. It features the same design as the original Mi Band, but packs a heart rate sensor. We haven't heard anything of the device since.
Expect more information about the fitness tracker duo on September 16, if the teaser above is anything to go by.
Source | Via |
package cn.ieclipse.smartqq;
import java.util.Collections;
import java.util.List;
import com.scienjus.smartqq.client.SmartQQClient;
import com.scienjus.smartqq.model.Category;
import com.scienjus.smartqq.model.Discuss;
import com.scienjus.smartqq.model.Friend;
import com.scienjus.smartqq.model.Group;
import com.scienjus.smartqq.model.QQContact;
import cn.ieclipse.smartim.views.ContactTreeNode;
import cn.ieclipse.smartim.views.IMPanel;
/**
* Created by Jamling on 2017/11/1.
*/
public class QQContactTreeNode extends ContactTreeNode {
public QQContactTreeNode(Object userObject) {
super(userObject);
}
public QQContactTreeNode(boolean check, String name, IMPanel imPanel) {
super(check, name, imPanel);
}
public void update() {
SmartQQClient client = (SmartQQClient)imPanel.getClient();
QQContactTreeNode root = (QQContactTreeNode)getRoot();
root.removeAllChildren();
if ("recent".equals(name)) {
List<QQContact> list = client.getRecents2();
if (list != null) {
synchronized (this) {
Collections.sort(list);
}
for (QQContact target : list) {
QQContactTreeNode cn = new QQContactTreeNode(target);
root.add(cn);
}
}
} else if ("friend".equals(name)) {
List<Category> categories = client.getFriendListWithCategory();
if (categories != null) {
for (Category c : categories) {
QQContactTreeNode cn = new QQContactTreeNode(c);
root.add(cn);
for (Friend f : c.getFriends()) {
QQContactTreeNode fn = new QQContactTreeNode(f);
cn.add(fn);
}
}
}
} else if ("group".equals(name)) {
List<Group> list = client.getGroupList();
if (list != null) {
for (Group r : list) {
QQContactTreeNode cn = new QQContactTreeNode(r);
root.add(cn);
}
}
} else if ("discuss".equals(name)) {
List<Discuss> list = client.getDiscussList();
if (list != null) {
for (Discuss r : list) {
QQContactTreeNode cn = new QQContactTreeNode(r);
root.add(cn);
}
}
}
}
}
|
<filename>k3d/plot.py
from __future__ import print_function
import base64
import ipywidgets as widgets
from IPython.display import display
from functools import wraps
from traitlets import Unicode, Bool, Int, List, Float
from ._version import __version__ as version
from .objects import (Line, Label, MIP, MarchingCubes, Mesh, Points, STL, SparseVoxels, Surface,
Text, Text2d, Texture, TextureText, VectorField, Vectors, Volume, Voxels,
VoxelsGroup, ListOrArray, Drawable, TimeSeries)
objects_map = {
'Line': Line,
'Label': Label,
'MIP': MIP,
'Marchingcubes': MarchingCubes,
'Mesh': Mesh,
'Points': Points,
'STL': STL,
'SparseVoxels': SparseVoxels,
'Surface': Surface,
'Text': Text,
'Text2d': Text2d,
'Texture': Texture,
'TextureText': TextureText,
'VectorField': VectorField,
'Vectors': Vectors,
'Volume': Volume,
'Voxels': Voxels,
'VoxelsGroup': VoxelsGroup
}
import numpy as np
class Plot(widgets.DOMWidget):
"""
Main K3D widget.
Attributes:
antialias: `int`:
Enable antialiasing in WebGL renderer, changes have no effect after displaying.
height: `int`:
Height of the Widget in pixels, changes have no effect after displaying.
background_color: `int`.
Packed RGB color of the plot background (0xff0000 is red, 0xff is blue), -1 is for transparent.
camera_auto_fit: `bool`.
Enable automatic camera setting after adding, removing or changing a plot object.
grid_auto_fit: `bool`.
Enable automatic adjustment of the plot grid to contained objects.
grid_color: `int`.
Packed RGB color of the plot grids (0xff0000 is red, 0xff is blue).
grid_visible: `bool`.
Enable or disable grid.
screenshot_scale: `Float`.
Multipiler to screenshot resolution.
voxel_paint_color: `int`.
The (initial) int value to be inserted when editing voxels.
label_color: `int`.
Packed RGB color of the labels (0xff0000 is red, 0xff is blue).
lighting: `Float`.
Lighting factor.
grid: `array_like`.
6-element tuple specifying the bounds of the plot grid (x0, y0, z0, x1, y1, z1).
camera: `array_like`.
9-element list or array specifying camera position.
camera_no_rotate: `Bool`.
Lock for camera rotation.
camera_no_zoom: `Bool`.
Lock for camera zoom.
camera_no_pan: `Bool`.
Lock for camera pan.
camera_rotate_speed: `Float`.
Speed of camera rotation.
camera_zoom_speed: `Float`.
Speed of camera zoom.
camera_pan_speed: `Float`.
Speed of camera pan.
camera_fov: `Float`.
Camera Field of View.
camera_damping_factor: `Float`.
Defines the intensity of damping. Default is 0 (disabled).
snapshot_type: `string`.
Can be 'full', 'online' or 'inline'.
axes: `list`.
Axes labels for plot.
time: `list`.
Time value (used in TimeSeries)
name: `string`.
Name of the plot. Used to filenames of snapshot/screenshot etc.
mode: `str`.
Mode of K3D viewer.
Legal values are:
:`view`: No interaction with objects,
:`add`: On voxels objects adding mode,
:`change`: On voxels objects edit mode,
:`callback`: Handling click_callback and hover_callback on some type of objects,
:`manipulate`: Enable object transform widget.
camera_mode: `str`.
Mode of camera movement.
Legal values are:
:`trackball`: orbit around point with dynamic up-vector of camera,
:`orbit`: orbit around point with fixed up-vector of camera,
:`fly`: orbit around point with dynamic up-vector of camera, mouse wheel also moves target point.
manipulate_mode: `str`.
Mode of manipulate widgets.
Legal values are:
:`translate`: Translation widget,
:`rotate`: Rotation widget,
:`scale`: Scaling widget.
auto_rendering: `Bool`.
State of auto rendering.
fps: `Float`.
Fps of animation.
objects: `list`.
List of `k3d.objects.Drawable` currently included in the plot, not to be changed directly.
"""
_view_name = Unicode("PlotView").tag(sync=True)
_model_name = Unicode("PlotModel").tag(sync=True)
_view_module = Unicode("k3d").tag(sync=True)
_model_module = Unicode("k3d").tag(sync=True)
_view_module_version = Unicode(version).tag(sync=True)
_model_module_version = Unicode(version).tag(sync=True)
_backend_version = Unicode(version).tag(sync=True)
# readonly (specified at creation)
antialias = Int(min=0, max=5).tag(sync=True)
height = Int().tag(sync=True)
# readonly (not to be modified directly)
object_ids = List().tag(sync=True)
# read-write
camera_auto_fit = Bool(True).tag(sync=True)
auto_rendering = Bool(True).tag(sync=True)
lighting = Float().tag(sync=True)
fps = Float().tag(sync=True)
grid_auto_fit = Bool(True).tag(sync=True)
grid_visible = Bool(True).tag(sync=True)
fps_meter = Bool(True).tag(sync=True)
menu_visibility = Bool(True).tag(sync=True)
screenshot_scale = Float().tag(sync=True)
time = Float().tag(sync=True)
grid = ListOrArray((-1, -1, -1, 1, 1, 1), minlen=6, maxlen=6).tag(sync=True)
grid_color = Int().tag(sync=True)
label_color = Int().tag(sync=True)
background_color = Int().tag(sync=True)
voxel_paint_color = Int().tag(sync=True)
camera = ListOrArray(minlen=9, maxlen=9, empty_ok=True).tag(sync=True)
camera_animation = TimeSeries(List()).tag(sync=True)
camera_no_rotate = Bool(False).tag(sync=True)
camera_no_zoom = Bool(False).tag(sync=True)
camera_no_pan = Bool(False).tag(sync=True)
camera_rotate_speed = Float().tag(sync=True)
camera_zoom_speed = Float().tag(sync=True)
camera_pan_speed = Float().tag(sync=True)
camera_damping_factor = Float().tag(sync=True)
clipping_planes = ListOrArray(empty_ok=True).tag(sync=True)
colorbar_object_id = Int(-1).tag(sync=True)
colorbar_scientific = Bool(False).tag(sync=True)
rendering_steps = Int(1).tag(sync=True)
screenshot = Unicode().tag(sync=True)
snapshot = Unicode().tag(sync=True)
snapshot_type = Unicode().tag(sync=True)
camera_fov = Float().tag(sync=True)
name = Unicode(default_value=None, allow_none=True).tag(sync=True)
axes = List(minlen=3, maxlen=3, default_value=["x", "y", "z"]).tag(sync=True)
axes_helper = Float().tag(sync=True)
mode = Unicode().tag(sync=True)
camera_mode = Unicode().tag(sync=True)
manipulate_mode = Unicode().tag(sync=True)
objects = []
def __init__(
self,
antialias=3,
background_color=0xFFFFFF,
camera_auto_fit=True,
grid_auto_fit=True,
grid_visible=True,
height=512,
voxel_paint_color=0,
grid=(-1, -1, -1, 1, 1, 1),
screenshot_scale=2.0,
lighting=1.5,
time=0.0,
fps_meter=False,
menu_visibility=True,
colorbar_object_id=-1,
rendering_steps=1,
axes=["x", "y", "z"],
camera_no_rotate=False,
camera_no_zoom=False,
camera_rotate_speed=1.0,
camera_zoom_speed=1.2,
camera_pan_speed=0.3,
snapshot_type='full',
camera_no_pan=False,
camera_fov=45.0,
camera_damping_factor=0.0,
axes_helper=1.0,
name=None,
mode="view",
camera_mode="trackball",
manipulate_mode="translate",
auto_rendering=True,
fps=25.0,
grid_color=0xE6E6E6,
label_color=0x444444,
*args,
**kwargs
):
super(Plot, self).__init__()
self.antialias = antialias
self.camera_auto_fit = camera_auto_fit
self.grid_auto_fit = grid_auto_fit
self.fps_meter = fps_meter
self.fps = fps
self.grid = grid
self.grid_visible = grid_visible
self.background_color = background_color
self.grid_color = grid_color
self.label_color = label_color
self.voxel_paint_color = voxel_paint_color
self.screenshot_scale = screenshot_scale
self.height = height
self.lighting = lighting
self.time = time
self.menu_visibility = menu_visibility
self.colorbar_object_id = colorbar_object_id
self.rendering_steps = rendering_steps
self.camera_no_rotate = camera_no_rotate
self.camera_no_zoom = camera_no_zoom
self.camera_no_pan = camera_no_pan
self.camera_rotate_speed = camera_rotate_speed
self.camera_zoom_speed = camera_zoom_speed
self.camera_pan_speed = camera_pan_speed
self.camera_damping_factor = camera_damping_factor
self.camera_fov = camera_fov
self.axes = axes
self.axes_helper = axes_helper
self.name = name
self.mode = mode
self.snapshot_type = snapshot_type
self.camera_mode = camera_mode
self.manipulate_mode = manipulate_mode
self.auto_rendering = auto_rendering
self.camera = []
self.object_ids = []
self.objects = []
self.outputs = []
def __iadd__(self, objs):
"""Add Drawable to plot."""
assert isinstance(objs, Drawable)
for obj in objs:
if obj.id not in self.object_ids:
self.object_ids = self.object_ids + [obj.id]
self.objects.append(obj)
return self
def __isub__(self, objs):
"""Remove Drawable from plot."""
assert isinstance(objs, Drawable)
for obj in objs:
self.object_ids = [id_ for id_ in self.object_ids if id_ != obj.id]
if obj in self.objects:
self.objects.remove(obj)
return self
def display(self, **kwargs):
"""Show plot inside ipywidgets.Output()."""
output = widgets.Output()
with output:
display(self, **kwargs)
self.outputs.append(output)
display(output)
def render(self):
"""Trigger rendering on demand.
Useful when self.auto_rendering == False."""
self.send({"msg_type": "render"})
def start_auto_play(self):
"""Start animation of plot with objects using TimeSeries."""
self.send({"msg_type": "start_auto_play"})
def stop_auto_play(self):
"""Stop animation of plot with objects using TimeSeries."""
self.send({"msg_type": "stop_auto_play"})
def close(self):
"""Remove plot from all its ipywidgets.Output()-s."""
for output in self.outputs:
output.clear_output()
self.outputs = []
def camera_reset(self, factor=1.5):
"""Trigger auto-adjustment of camera.
Useful when self.camera_auto_fit == False."""
self.send({"msg_type": "reset_camera", "factor": factor})
def get_auto_grid(self):
d = np.stack([o.get_bounding_box() for o in self.objects])
return np.dstack(
[np.min(d[:, 0::2], axis=0), np.max(d[:, 1::2], axis=0)]
).flatten()
def get_auto_camera(self, factor=1.5, yaw=25, pitch=15, bounds=None):
""" Compute the camera vector from the specified parameters. If `bounds`
is not provided, then the algorithm will obtain it from the available
meshes.
"""
if bounds is None:
bounds = self.get_auto_grid()
center = (bounds[::2] + bounds[1::2]) / 2.0
radius = 0.5 * np.sum(np.abs(bounds[::2] - bounds[1::2]) ** 2) ** 0.5
cam_distance = radius * factor / np.sin(np.deg2rad(self.camera_fov / 2.0))
x = np.sin(np.deg2rad(pitch)) * np.cos(np.deg2rad(yaw))
y = np.sin(np.deg2rad(pitch)) * np.sin(np.deg2rad(yaw))
z = np.cos(np.deg2rad(pitch))
if pitch not in [0, 180]:
up = [0, 0, 1]
else:
up = [0, 1, 1]
return [
center[0] + x * cam_distance,
center[1] + y * cam_distance,
center[2] + z * cam_distance,
center[0],
center[1],
center[2],
up[0],
up[1],
up[2],
]
def fetch_screenshot(self, only_canvas=False):
"""Request creating a PNG screenshot on the JS side and saving it in self.screenshot
The result is a string of a PNG file in base64 encoding.
This function requires a round-trip of websocket messages. The result will
be available after the current cell finishes execution."""
self.send({"msg_type": "fetch_screenshot", "only_canvas": only_canvas})
def yield_screenshots(self, generator_function):
"""Decorator for a generator function receiving screenshots via yield."""
@wraps(generator_function)
def inner():
generator = generator_function()
def send_new_value(change):
try:
generator.send(base64.b64decode(change.new))
except StopIteration:
self.unobserve(send_new_value, "screenshot")
self.observe(send_new_value, "screenshot")
# start the decorated generator
generator.send(None)
return inner
def fetch_snapshot(self, compression_level=9):
"""Request creating a HTML snapshot on the JS side and saving it in self.snapshot
The result is a string: a HTML document with this plot embedded.
This function requires a round-trip of websocket messages. The result will
be available after the current cell finishes execution."""
self.send(
{"msg_type": "fetch_snapshot", "compression_level": compression_level}
)
def yield_snapshots(self, generator_function):
"""Decorator for a generator function receiving snapshots via yield."""
@wraps(generator_function)
def inner():
generator = generator_function()
def send_new_value(change):
try:
generator.send(base64.b64decode(change.new))
except StopIteration:
self.unobserve(send_new_value, "snapshot")
self.observe(send_new_value, "snapshot")
# start the decorated generator
generator.send(None)
return inner
def get_binary_snapshot(self, compression_level=9, voxel_chunks=[]):
import zlib
import msgpack
snapshot = self.get_binary_snapshot_objects(voxel_chunks)
snapshot['plot'] = self.get_plot_params()
data = msgpack.packb(snapshot, use_bin_type=True)
return zlib.compress(data, compression_level)
def load_binary_snapshot(self, data):
import zlib
import msgpack
from .helpers import from_json
data = msgpack.unpackb(zlib.decompress(data))
self.voxel_chunks = []
for name in ['objects', 'chunkList']:
if name in data.keys():
for o in data[name]:
attributes = {
k: from_json(o[k]) for k in o.keys() if k != 'type'
}
if name == 'objects':
o = objects_map[o['type']](**attributes)
self += o
else:
self.voxel_chunks.append(VoxelChunk(**attributes))
return self.voxel_chunks
def get_binary_snapshot_objects(self, voxel_chunks=[]):
from .helpers import to_json
snapshot = {"objects": [], "chunkList": []}
for name, l in [('objects', self.objects), ('chunkList', voxel_chunks)]:
for o in l:
obj = {}
for k, v in o.traits().items():
if "sync" in v.metadata:
obj[k] = to_json(k, o[k], o, o["compression_level"])
snapshot[name].append(obj)
return snapshot
def get_plot_params(self):
return {
"cameraAutoFit": self.camera_auto_fit,
"viewMode": self.mode,
"menuVisibility": self.menu_visibility,
"gridAutoFit": self.grid_auto_fit,
"gridVisible": self.grid_visible,
"grid": self.grid,
"gridColor": self.grid_color,
"labelColor": self.label_color,
"antialias": self.antialias,
"screenshotScale": self.screenshot_scale,
"clearColor": self.background_color,
"clippingPlanes": self.clipping_planes,
"lighting": self.lighting,
"time": self.time,
"fpsMeter": self.fps_meter,
"cameraMode": self.camera_mode,
"colorbarObjectId": self.colorbar_object_id,
"axes": self.axes,
"camera": self.camera,
"cameraNoRotate": self.camera_no_rotate,
"cameraNoZoom": self.camera_no_zoom,
"cameraNoPan": self.camera_no_pan,
"cameraRotateSpeed": self.camera_rotate_speed,
"cameraZoomSpeed": self.camera_zoom_speed,
"cameraPanSpeed": self.camera_pan_speed,
"cameraDampingFactor": self.camera_damping_factor,
"name": self.name,
"height": self.height,
"cameraFov": self.camera_fov,
"axesHelper": self.axes_helper,
"cameraAnimation": self.camera_animation,
"fps": self.fps,
}
def get_snapshot(self, compression_level=9, voxel_chunks=[], additional_js_code=""):
"""Produce on the Python side a HTML document with the current plot embedded."""
import os
import io
import zlib
dir_path = os.path.dirname(os.path.realpath(__file__))
data = self.get_binary_snapshot(compression_level, voxel_chunks)
if self.snapshot_type == 'full':
f = io.open(
os.path.join(dir_path, "static", "snapshot_standalone.txt"),
mode="r",
encoding="utf-8",
)
template = f.read()
f.close()
f = io.open(
os.path.join(dir_path, "static", "standalone.js"),
mode="r",
encoding="utf-8",
)
template = template.replace(
"[K3D_SOURCE]",
base64.b64encode(
zlib.compress(f.read().encode(), compression_level)
).decode("utf-8"),
)
f.close()
f = io.open(
os.path.join(dir_path, "static", "require.js"),
mode="r",
encoding="utf-8",
)
template = template.replace("[REQUIRE_JS]", f.read())
f.close()
f = io.open(
os.path.join(dir_path, "static", "pako_inflate.min.js"),
mode="r",
encoding="utf-8",
)
template = template.replace("[PAKO_JS]", f.read())
f.close()
else:
if self.snapshot_type == 'online':
template_file = 'snapshot_online.txt'
elif self.snapshot_type == 'inline':
template_file = 'snapshot_inline.txt'
else:
raise Exception('Unknown snapshot_type')
f = io.open(
os.path.join(dir_path, "static", template_file),
mode="r",
encoding="utf-8",
)
template = f.read()
f.close()
template = template.replace("[VERSION]", self._view_module_version)
template = template.replace("[HEIGHT]", str(self.height))
template = template.replace("[ID]", str(id(self)))
template = template.replace("[DATA]", base64.b64encode(data).decode("utf-8"))
template = template.replace("[ADDITIONAL]", additional_js_code)
return template
def get_static_path(self):
import os
dir_path = os.path.dirname(os.path.realpath(__file__))
return os.path.join(dir_path, "static")
|
/**
* Derive key pair with specified @keyIndex
*/
std::tuple<PublicKey, PrivateKey> deriveKeypair(IWalletDB::Ptr storage, uint64_t keyIndex)
{
PrivateKey sk;
PublicKey pk;
storage->get_MasterKdf()->DeriveKey(sk, ECC::Key::ID(keyIndex, Key::Type::Bbs));
pk.FromSk(sk);
return std::make_tuple(pk, sk);
} |
<filename>webui/pages/approval-rulesets/[id].tsx
import { useState } from 'react';
import { useRouter } from 'next/router';
import SwipeableViews from 'react-swipeable-views';
import Link from 'next/link';
import useSWR from 'swr';
import { formatDateTimeString, humanizeUnderscoreString, paginateArray, formatProposalStateString, formatBooleanAsIconWithLabel, formatBooleanAsIcon } from '../../common/utils';
import { IAppContext, declarePageTitle, declareValidatingFetchedData } from '../../components/app_context';
import { NavigationSection } from '../../components/navbar';
import DataRefreshErrorSnackbar from '../../components/data_refresh_error_snackbar';
import DataLoadErrorScreen from '../../components/data_load_error_screen';
import { DataGrid, useDataGrid, RequestedState as DataGridRequestedState } from '../../components/data_grid';
import { useTheme } from '@material-ui/core/styles';
import useMediaQuery from '@material-ui/core/useMediaQuery';
import Box from '@material-ui/core/Box';
import Typography from '@material-ui/core/Typography';
import Paper from '@material-ui/core/Paper';
import Skeleton from '@material-ui/lab/Skeleton';
import Tabs from '@material-ui/core/Tabs';
import Tab from '@material-ui/core/Tab';
import Table from '@material-ui/core/Table';
import TableBody from '@material-ui/core/TableBody';
import TableCell from '@material-ui/core/TableCell';
import TableContainer from '@material-ui/core/TableContainer';
import TableRow from '@material-ui/core/TableRow';
import List from '@material-ui/core/List';
import ListItem from '@material-ui/core/ListItem';
import ListItemAvatar from '@material-ui/core/ListItemAvatar';
import ListItemText from '@material-ui/core/ListItemText';
import Divider from '@material-ui/core/Divider';
import AccessTimeIcon from '@material-ui/icons/AccessTime';
import Container from '@material-ui/core/Container';
import { ColDef } from '@material-ui/data-grid';
import { formatStateString as formatReleaseStateString } from '../releases';
import styles from '../../common/tables.module.scss';
interface IProps {
appContext: IAppContext;
}
export default function ApprovalRulesetPage(props: IProps): JSX.Element {
const { appContext } = props;
const theme = useTheme();
const viewIsLarge = useMediaQuery(theme.breakpoints.up('md'));
const [tabIndex, setTabIndex] = useState(0);
const applicationsDataGridState = useDataGrid();
const releasesDataGridState = useDataGrid();
const router = useRouter();
const id = router.query.id as string;
const hasId = typeof id !== 'undefined';
const { data, error, isValidating, mutate } =
useSWR(hasId ?
`/v1/approval-rulesets/${encodeURIComponent(id)}` :
null);
declarePageTitle(appContext, getPageTitle());
declareValidatingFetchedData(appContext, isValidating);
function getPageTitle() {
if (data) {
if (data.latest_approved_version) {
return `${data.latest_approved_version.display_name} (${id})`;
} else {
return id;
}
} else {
return '';
}
}
function handleTabChange(_event: React.ChangeEvent<any>, newValue: number) {
setTabIndex(newValue);
}
function handleTabIndexChange(index: number) {
setTabIndex(index);
}
return (
<>
{data &&
<DataRefreshErrorSnackbar error={error} refreshing={isValidating} onReload={mutate} />
}
<Tabs
value={tabIndex}
onChange={handleTabChange}
variant={viewIsLarge ? "standard" : "fullWidth"}
indicatorColor="primary"
textColor="primary"
>
<Tab label="General" id="tab-general" aria-controls="tab-panel-general" />
<Tab label="Version history" id="version-history" aria-controls="tab-panel-version-history" />
<Tab label="Rules" id="rules" aria-controls="tab-panel-rules" />
<Tab label="Applications" id="tab-applications" arial-controls="tab-panel-applications" />
<Tab label="Releases" id="tab-releases" arial-controls="tab-panel-releases" />
</Tabs>
<SwipeableViews
index={tabIndex}
onChangeIndex={handleTabIndexChange}
resistance={true}
style={{ display: 'flex', flexDirection: 'column', flexGrow: 1 }}
containerStyle={{ flexGrow: 1 }}
slideStyle={{ display: 'flex', flexDirection: 'column' }}
>
<TabPanel value={tabIndex} index={0} id="general">
<GeneralTabContents
data={data}
error={error}
mutate={mutate}
/>
</TabPanel>
<TabPanel value={tabIndex} index={1} id="version-history">
</TabPanel>
<TabPanel value={tabIndex} index={2} id="rules">
<RulesTabContents
data={data}
error={error}
mutate={mutate}
/>
</TabPanel>
<TabPanel value={tabIndex} index={3} id="applications" style={{ flexGrow: 1 }}>
<ApplicationsTabContents
dataGridState={applicationsDataGridState}
data={data}
error={error}
mutate={mutate}
/>
</TabPanel>
<TabPanel value={tabIndex} index={4} id="releases" style={{ flexGrow: 1 }}>
<ReleasesTabContents
applicationId={id}
dataGridState={releasesDataGridState}
data={data}
error={error}
mutate={mutate}
/>
</TabPanel>
</SwipeableViews>
</>
);
}
ApprovalRulesetPage.navigationSection = NavigationSection.ApprovalRulesets;
ApprovalRulesetPage.pageTitle = 'Approval ruleset';
ApprovalRulesetPage.hasBackButton = true;
interface ITabPanelProps {
children?: React.ReactNode;
index: number;
value: number;
id: string;
style?: any;
}
function TabPanel(props: ITabPanelProps) {
const { children, value, index, id, style, ...other } = props;
return (
<div
role="tabpanel"
hidden={value !== index}
id={`tab-panel-${id}`}
aria-labelledby={`tab-${id}`}
style={{ display: 'flex', ...style }}
{...other}
>
<Box px={2} py={2} style={{ display: 'flex', flexDirection: 'column', flexGrow: 1 }}>
{children}
</Box>
</div>
);
}
interface IGeneralTabContentsProps {
data: any;
error: any;
mutate: () => void;
}
function GeneralTabContents(props: IGeneralTabContentsProps) {
const { data } = props;
if (data) {
return (
<TableContainer component={Paper} className={styles.definition_list_table}>
<Table>
<TableBody>
<TableRow>
<TableCell component="th" scope="row">ID</TableCell>
<TableCell>
<Link href={`/approval-rulesets/${encodeURIComponent(data.id)}`}>
<a>{data.id}</a>
</Link>
</TableCell>
</TableRow>
<TableRow>
<TableCell component="th" scope="row">Display name</TableCell>
<TableCell>
<Link href={`/approval-rulesets/${encodeURIComponent(data.id)}`}>
<a>{data.latest_approved_version?.display_name ?? data.id}</a>
</Link>
</TableCell>
</TableRow>
<TableRow>
<TableCell component="th" scope="row">Description</TableCell>
<TableCell>{data.latest_approved_version?.description || 'N/A'}</TableCell>
</TableRow>
<TableRow>
<TableCell component="th" scope="row">Latest version</TableCell>
<TableCell>{data.latest_approved_version?.version_number ?? 'N/A'}</TableCell>
</TableRow>
<TableRow>
<TableCell component="th" scope="row">Enabled</TableCell>
<TableCell>{formatBooleanAsIconWithLabel(data.latest_approved_version?.enabled) || 'N/A'}</TableCell>
</TableRow>
<TableRow>
<TableCell component="th" scope="row">Proposal state</TableCell>
<TableCell>{formatProposalStateString(data.latest_approved_version?.proposal_state) ?? 'N/A'}</TableCell>
</TableRow>
<TableRow>
<TableCell component="th" scope="row">Created at</TableCell>
<TableCell>{formatDateTimeString(data.created_at as string)}</TableCell>
</TableRow>
<TableRow>
<TableCell component="th" scope="row">Updated at</TableCell>
<TableCell>{formatDateTimeString(data.latest_approved_version?.updated_at as any) ?? 'N/A'}</TableCell>
</TableRow>
</TableBody>
</Table>
</TableContainer>
);
}
if (props.error) {
return <DataLoadErrorScreen error={props.error} onReload={props.mutate} />;
}
return (
<Paper>
<Box mx={2} my={2}>
<Skeleton />
<Skeleton />
<Skeleton />
<Skeleton />
<Skeleton />
<Skeleton />
<Skeleton />
</Box>
</Paper>
);
}
interface IRulesTabContentsProps {
data: any;
error: any;
mutate: () => void;
}
function RulesTabContents(props: IRulesTabContentsProps) {
const { data } = props;
if (data) {
const rules = data.latest_approved_version?.approval_rules ?? [];
return <Paper><List>{rules.map(renderApprovalRule)}</List></Paper>;
}
if (props.error) {
return <DataLoadErrorScreen error={props.error} onReload={props.mutate} />;
}
return (
<Paper>
<Box mx={2} my={2}>
<Skeleton />
<Skeleton />
<Skeleton />
<Skeleton />
<Skeleton />
<Skeleton />
<Skeleton />
</Box>
</Paper>
);
}
function renderApprovalRule(rule: any, index: number) {
const title = <Typography variant="h6">{humanizeApprovalRuleType(rule.type)}</Typography>;
return (
<>
{index > 0 && <Divider variant="inset" component="li" />}
<ListItem alignItems="flex-start">
<ListItemAvatar>
<AccessTimeIcon style={{ fontSize: '2.8rem' }} />
</ListItemAvatar>
<ListItemText
primary={title}
secondary={renderApprovalRuleDetails(rule)}
/>
</ListItem>
</>
);
}
function humanizeApprovalRuleType(type: string): string {
switch (type) {
case "http_api":
return "HTTP API";
case "schedule":
return "Schedule";
case "manual":
return "Manual approval";
default:
return humanizeUnderscoreString(type) as string;
}
}
function renderApprovalRuleDetails(rule: any): JSX.Element {
switch (rule.type) {
case "http_api":
return renderHttpApiApprovalRuleDetails(rule);
case "schedule":
return renderScheduleApprovalRuleDetails(rule);
case "manual":
return renderManualApprovalRuleDetails(rule);
default:
return <></>;
}
}
function renderHttpApiApprovalRuleDetails(_rule: any) {
// TODO
return <></>;
}
function renderScheduleApprovalRuleDetails(rule: any) {
return (
<ul>
{rule.begin_time &&
<li>Begin time: {rule.begin_time}</li>
}
{rule.end_time &&
<li>End time: {rule.end_time}</li>
}
{rule.days_of_week &&
<li>Days of week: {rule.days_of_week}</li>
}
{rule.days_of_month &&
<li>Days of month: {rule.days_of_month}</li>
}
{rule.months_of_year &&
<li>Months of year: {rule.months_of_year}</li>
}
</ul>
);
}
function renderManualApprovalRuleDetails(_rule: any) {
// TODO
return <></>;
}
const APPLICATION_APPROVAL_RULESET_BINDING_COLUMNS: ColDef[] = [
{
field: 'id',
headerName: 'ID',
width: 150,
valueGetter: ({ row }) => row.application.id,
renderCell: ({ row }) => (
<Link href={`/applications/${encodeURIComponent(row.application.id)}`}>
<a>{row.application.id}</a>
</Link>
),
},
{
field: 'display_name',
headerName: 'Display name',
width: 250,
valueGetter: ({ row }) => row.application.latest_approved_version?.display_name ?? row.application.id,
renderCell: ({ row }) => (
<Link href={`/applications/${encodeURIComponent(row.application.id)}`}>
<a>{row.application.latest_approved_version?.display_name ?? row.application.id}</a>
</Link>
),
},
{
field: 'latest_version',
headerName: 'Latest version',
width: 130,
valueGetter: ({ row }) => row.application.latest_approved_version?.version_number,
valueFormatter: ({ value }) => value ?? 'N/A',
},
{
field: 'mode',
headerName: 'Mode',
width: 120,
valueGetter: ({ row }) => row.latest_approved_version?.mode,
valueFormatter: ({ value }) => humanizeUnderscoreString(value as any) ?? 'N/A',
},
{
field: 'enabled',
headerName: 'Enabled',
width: 120,
valueGetter: ({ row }) => row.application.latest_approved_version?.enabled,
valueFormatter: ({ value }) => formatBooleanAsIcon(value as any) ?? 'N/A',
},
{
field: 'proposal_state',
headerName: 'Binding proposal state',
width: 200,
valueGetter: ({ row }) => row.latest_approved_version?.proposal_state,
valueFormatter: ({ value }) => formatProposalStateString(value as any) ?? 'N/A',
},
{
field: 'updated_at',
type: 'dateTime',
width: 180,
headerName: 'Application updated at',
valueGetter: ({ row }) => row.application.latest_approved_version?.updated_at,
valueFormatter: ({ value }) => formatDateTimeString(value as any) ?? 'N/A',
},
];
interface IApplicationsTabContentsProps {
dataGridState: DataGridRequestedState;
data: any;
error: any;
mutate: () => void;
}
function ApplicationsTabContents(props: IApplicationsTabContentsProps) {
const { dataGridState, data } = props;
function addID(binding: any) {
return { id: binding.application.id, ...binding };
}
if (data) {
if (data.application_approval_ruleset_bindings.length == 0 && dataGridState.requestedPage == 1) {
return (
<Container maxWidth="md">
<Box px={2} py={2} textAlign="center">
<Typography variant="h5" color="textSecondary">
There are no applications bound to this approval ruleset.
</Typography>
</Box>
</Container>
);
}
const rulesetBindings =
paginateArray(data.application_approval_ruleset_bindings, dataGridState.requestedPage, dataGridState.requestedPageSize).
map(addID);
return (
<Paper style={{ display: 'flex', flexGrow: 1 }}>
<DataGrid
rows={rulesetBindings}
columns={APPLICATION_APPROVAL_RULESET_BINDING_COLUMNS}
requestedState={dataGridState}
style={{ flexGrow: 1 }} />
</Paper>
);
}
if (props.error) {
return <DataLoadErrorScreen error={props.error} onReload={props.mutate} />;
}
return (
<Paper style={{ flexGrow: 1 }}>
<Box mx={2} my={2}>
<Container maxWidth="md">
<Skeleton />
<Skeleton />
<Skeleton />
<Skeleton />
</Container>
</Box>
</Paper>
);
}
const RELEASE_APPROVAL_RULESET_BINDING_COLUMNS: ColDef[] = [
{
field: 'id',
type: 'number',
headerName: 'ID',
width: 100,
valueGetter: ({ row }) => row.release.id,
renderCell: ({ row }) => (
<Box style={{ flexGrow: 1 }}> {/* Make the content properly align right */}
<Link href={`/releases/${encodeURIComponent(row.release.application.id)}/${row.release.id}`}>
<a>{row.release.id}</a>
</Link>
</Box>
),
},
{
field: 'application',
headerName: 'Application',
width: 250,
valueGetter: ({ row }) => row.release.application.latest_approved_version?.display_name ?? row.release.application.id,
renderCell: ({ row }) => (
<Link href={`/applications/${encodeURIComponent(row.release.application.id)}`}>
<a>{row.release.application.latest_approved_version?.display_name ?? row.release.application.id}</a>
</Link>
),
},
{
field: 'mode',
headerName: 'Mode',
width: 120,
valueFormatter: ({ value }) => humanizeUnderscoreString(value as string),
},
{
field: 'state',
headerName: 'State',
width: 150,
valueGetter: ({ row }) => row.release.state,
valueFormatter: ({ value }) => formatReleaseStateString(value as string),
},
{
field: 'created_at',
type: 'dateTime',
width: 180,
headerName: 'Created at',
valueGetter: ({ row }) => row.release.created_at,
valueFormatter: ({ value }) => formatDateTimeString(value as string),
},
{
field: 'finalized_at',
type: 'dateTime',
width: 180,
headerName: 'Finalized at',
valueGetter: ({ row }) => row.release.finalized_at,
valueFormatter: ({ value }) => formatDateTimeString(value as any) ?? 'N/A',
},
];
interface IReleasesTabContentsProps {
applicationId: string;
dataGridState: DataGridRequestedState;
data: any;
error: any;
mutate: () => void;
}
function ReleasesTabContents(props: IReleasesTabContentsProps) {
const { dataGridState, data } = props;
const rawBindings = data?.latest_approved_version?.release_approval_ruleset_bindings;
function addID(binding: any) {
return { id: binding.release.id, ...binding };
}
if (rawBindings) {
if (rawBindings.length == 0 && dataGridState.requestedPage == 1) {
return (
<Container maxWidth="md">
<Box px={2} py={2} textAlign="center">
<Typography variant="h5" color="textSecondary">
There are no releases bound to this approval ruleset.
</Typography>
</Box>
</Container>
);
}
const bindings =
paginateArray(rawBindings, dataGridState.requestedPage, dataGridState.requestedPageSize).
map(addID);
return (
<Paper style={{ display: 'flex', flexGrow: 1 }}>
<DataGrid
rows={bindings}
columns={RELEASE_APPROVAL_RULESET_BINDING_COLUMNS}
requestedState={dataGridState}
style={{ flexGrow: 1 }} />
</Paper>
);
}
if (props.error) {
return <DataLoadErrorScreen error={props.error} onReload={props.mutate} />;
}
return (
<Paper style={{ flexGrow: 1 }}>
<Box mx={2} my={2}>
<Container maxWidth="md">
<Skeleton />
<Skeleton />
<Skeleton />
<Skeleton />
</Container>
</Box>
</Paper>
);
}
|
Undergraduate curriculum in veterinary schools
SIR, – I read with interest the responses ( VR , June 25, vol 156, p 846) to my recent letter regarding undergraduate education in veterinary schools ( VR , June 11, vol 156, p 788). It is encouraging to see at least two vet schools embracing the idea of integrated and outcome-based veterinary |
<reponame>ldionne/mpl11
/*!
* @file
* Defines the `check_finite_iterable` utility to ease unit testing of
* `Iterable`s.
*/
#ifndef BOOST_MPL11_TEST_CHECK_FINITE_ITERABLE_HPP
#define BOOST_MPL11_TEST_CHECK_FINITE_ITERABLE_HPP
#include <boost/mpl11/fwd/comparable.hpp>
#include <boost/mpl11/fwd/iterable.hpp>
#include <boost/mpl11/integer.hpp>
#include "minimal_iterable.hpp"
#include "static_assert.hpp"
namespace check_finite_iter_detail {
using namespace boost::mpl11;
using boost::mpl11::size_t;
template <typename x, typename y,
typename Expected = typename x::type,
typename Actual = typename y::type>
using assert_eq = static_assert_<equal<x, y>>;
template <typename reference, typename iter,
typename index = size_t<0>,
bool = is_empty<reference>::value>
struct impl;
template <typename reference, typename iter>
struct impl<reference, iter, size_t<length<reference>::value>, false>
: assert_eq<head<reference>, head<iter>>
, assert_eq<tail<reference>, tail<iter>>
, assert_eq<is_empty<reference>, is_empty<iter>>
, assert_eq<last<reference>, last<iter>>
, assert_eq<length<reference>, length<iter>>
{ };
template <typename reference, typename iter, typename index>
struct impl<reference, iter, index, false>
: assert_eq<at<index, reference>, at<index, iter>>
, impl<reference, iter, size_t<index::type::value + 1>>
{ };
template <typename reference, typename iter, typename index>
struct impl<reference, iter, index, true>
: static_assert_<is_empty<iter>>
, assert_eq<size_t<0>, length<iter>>
{ };
} // end namespace check_finite_iter_detail
/*!
* Generic unit test for finite iterables.
*
* To use `check_finite_iterable`, simply instantiate it with the first
* argument being the tested iterable and `xs...` being the
* expected contents of the iterable.
*/
template <typename iter, typename ...xs>
using check_finite_iterable =
check_finite_iter_detail::impl<minimal_iterable<xs...>, iter>;
#endif // !BOOST_MPL11_TEST_CHECK_FINITE_ITERABLE_HPP
|
/**
* NSHM23 Logic Tree Branch implementation but using UCERF3 ingredients (FM, DM, Scaling)
*
* @author kevin
*
*/
public class NSHM23_U3_HybridLogicTreeBranch extends LogicTreeBranch<LogicTreeNode> {
public static List<LogicTreeLevel<? extends LogicTreeNode>> levels;
public static List<LogicTreeLevel<? extends LogicTreeNode>> levelsMaxDist;
// only U3-related ones here
public static LogicTreeLevel<FaultModels> U3_FM =
LogicTreeLevel.forEnum(FaultModels.class, "UCERF3 Fault Model", "FM");
public static LogicTreeLevel<U3_UncertAddDeformationModels> U3_WRAPPED_DM =
LogicTreeLevel.forEnum(U3_UncertAddDeformationModels.class, "UCERF3 Deformation Model", "DM");
public static LogicTreeLevel<ScalingRelationships> SCALE =
LogicTreeLevel.forEnum(ScalingRelationships.class, "Scaling Relationship", "Scale");
public static LogicTreeLevel<SlipAlongRuptureModels> SLIP_ALONG =
LogicTreeLevel.forEnum(SlipAlongRuptureModels.class, "Slip Along Rupture", "SlipAlong");
static {
// exhaustive for now, can trim down later
levels = List.of(U3_FM, NSHM23_LogicTreeBranch.PLAUSIBILITY, U3_WRAPPED_DM, SCALE, SLIP_ALONG,
NSHM23_LogicTreeBranch.SUPRA_B, NSHM23_LogicTreeBranch.SUB_SECT_CONSTR,
NSHM23_LogicTreeBranch.SUB_SEIS_MO, NSHM23_LogicTreeBranch.SEG);
levelsMaxDist = List.of(U3_FM, NSHM23_LogicTreeBranch.PLAUSIBILITY, U3_WRAPPED_DM, SCALE, SLIP_ALONG,
NSHM23_LogicTreeBranch.SUPRA_B, NSHM23_LogicTreeBranch.SUB_SECT_CONSTR,
NSHM23_LogicTreeBranch.SUB_SEIS_MO, NSHM23_LogicTreeBranch.MAX_DIST);
}
/**
* This is the default reference branch
*/
public static final NSHM23_U3_HybridLogicTreeBranch DEFAULT = fromValues(FaultModels.FM3_1,
RupturePlausibilityModels.COULOMB, U3_UncertAddDeformationModels.U3_ZENG, ScalingRelationships.SHAW_2009_MOD,
SlipAlongRuptureModels.UNIFORM, SupraSeisBValues.B_0p8, SubSectConstraintModels.TOT_NUCL_RATE,
SubSeisMoRateReductions.SUB_B_1, SegmentationModels.SHAW_R0_3);
/**
* Creates a NSHM23LogicTreeBranch instance from given set of node values. Null or missing values
* will be replaced with their default value (from NSHM23LogicTreeBranch.DEFAULT).
*
* @param vals
* @return
*/
public static NSHM23_U3_HybridLogicTreeBranch fromValues(List<LogicTreeNode> vals) {
LogicTreeNode[] valsArray = new LogicTreeNode[vals.size()];
for (int i=0; i<vals.size(); i++)
valsArray[i] = vals.get(i);
return fromValues(valsArray);
}
/**
* Creates a NSHM23LogicTreeBranch instance from given set of node values. Null or missing values
* will be replaced with their default value (from NSHM23LogicTreeBranch.DEFAULT).
*
* @param vals
* @return
*/
public static NSHM23_U3_HybridLogicTreeBranch fromValues(LogicTreeNode... vals) {
return fromValues(true, vals);
}
/**
* Creates a LogicTreeBranch instance from given set of node values. Null or missing values
* will be replaced with their default value (from LogicTreeBranch.DEFAULT) if setNullToDefault
* is true.
*
* @param setNullToDefault if true, null or missing values will be set to their default value
* @param vals
* @return
*/
public static NSHM23_U3_HybridLogicTreeBranch fromValues(boolean setNullToDefault, LogicTreeNode... vals) {
// initialize branch with null
List<LogicTreeNode> values = new ArrayList<>();
for (int i=0; i<levels.size(); i++)
values.add(null);
// now add each value
for (LogicTreeNode val : vals) {
if (val == null)
continue;
int ind = -1;
for (int i=0; i<levels.size(); i++) {
LogicTreeLevel<?> level = levels.get(i);
if (level.isMember(val)) {
ind = i;
break;
}
}
Preconditions.checkArgument(ind >= 0, "Value of class '"+val.getClass()+"' does not match any known branch level");
values.set(ind, val);
}
NSHM23_U3_HybridLogicTreeBranch branch = new NSHM23_U3_HybridLogicTreeBranch(values);
if (setNullToDefault) {
for (int i=0; i<levels.size(); i++) {
if (branch.getValue(i) == null)
branch.setValue(i, DEFAULT.getValue(i));
}
}
return branch;
}
@SuppressWarnings("unused") // used for deserialization
public NSHM23_U3_HybridLogicTreeBranch() {
super(levels);
}
public NSHM23_U3_HybridLogicTreeBranch(List<LogicTreeNode> values) {
super(levels, values);
}
} |
<filename>cloudferrylib/os/compute/libvirt.py<gh_stars>0
# Copyright 2015 Mirantis Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import json
import os
from xml.etree import ElementTree
from cloudferrylib.utils import utils
LOG = utils.get_log(__name__)
nova_instances_path = "/var/lib/nova/instances/"
def instance_path(instance_id):
return os.path.join(nova_instances_path, instance_id)
def instance_image_path(instance_id):
return os.path.join(instance_path(instance_id), "disk")
def _qemu_img_rebase(src, dst):
return "qemu-img rebase -b {src} {dst}".format(src=src, dst=dst)
class QemuBackingFileMover(object):
def __init__(self, runner, src, instance_id):
self.runner = runner
self.src = src
self.dst = instance_image_path(instance_id)
def __enter__(self):
cmd = _qemu_img_rebase(self.src, self.dst)
self.runner.run(cmd)
return self
def __exit__(self, exc_type, exc_val, exc_tb):
cmd = _qemu_img_rebase(self.dst, self.src)
self.runner.run_ignoring_errors(cmd)
return self
class DestNovaInstanceDestroyer(object):
"""Fake instance is destroyed from libvirt as part of live migration. In
case something fails during live migration, this action must be rolled
back. The only valid rollback scenario is to delete the same instance from
nova DB."""
def __init__(self, dest_libvirt, dest_nova, libvirt_name, nova_vm_id):
self.dest_libvirt = dest_libvirt
self.dest_nova = dest_nova
self.libvirt_name = libvirt_name
self.nova_vm_id = nova_vm_id
def __enter__(self):
self.do()
def __exit__(self, exc_type, exc_val, exc_tb):
self.undo()
def do(self):
self.dest_libvirt.destroy_vm(self.libvirt_name)
def undo(self):
try:
LOG.debug("Rolling back fake VM %s", self.nova_vm_id)
self.dest_nova.reset_state(self.nova_vm_id)
self.dest_nova.delete_vm_by_id(self.nova_vm_id)
except:
# ignoring all errors since it's a rollback
pass
class Libvirt(object):
def __init__(self, remote_runner):
"""
:remote_runner: `cloudferrylib.utils.remote_runner.RemoteRunner` object
"""
self.runner = remote_runner
def get_backing_file(self, instance_id):
cmd = ("qemu-img info {image_path} --output json".format(
image_path=instance_image_path(instance_id)))
try:
image_info = json.loads(self.runner.run(cmd))
return image_info['backing-filename']
except (ValueError, TypeError) as e:
LOG.error("Invalid value received from qemu: %s!", e)
except KeyError:
LOG.warning("Instance '%s' does not have backing file associated!",
instance_id)
def get_xml(self, libvirt_instance_name):
cmd = ("virsh dumpxml {inst_name}".format(
inst_name=libvirt_instance_name))
return LibvirtXml(self.runner.run(cmd))
def destroy_vm(self, libvirt_instance_name):
cmds = [
"virsh destroy {instance}".format(instance=libvirt_instance_name),
"virsh undefine {instance}".format(instance=libvirt_instance_name)
]
for cmd in cmds:
self.runner.run(cmd)
def move_backing_file(self, source_file, instance_id):
cmd = _qemu_img_rebase(src=source_file,
dst=instance_image_path(instance_id))
self.runner.run(cmd)
def live_migrate(self, libvirt_instance_name, dest_host, migration_xml):
cmd = ("virsh migrate --live --copy-storage-all --verbose {instance} "
"qemu+tcp://{dst_host}/system "
"--xml {migration_xml}".format(instance=libvirt_instance_name,
dst_host=dest_host,
migration_xml=migration_xml))
self.runner.run(cmd)
class LibvirtDeviceInterfaceHwAddress(object):
def __init__(self, element):
self.type = element.get('type')
self.domain = element.get('domain')
self.bus = element.get('bus')
self.slot = element.get('slot')
self.function = element.get('function')
def __repr__(self):
return "HW Address<%s %s %s>" % (self.type, self.bus, self.slot)
def __eq__(self, other):
return (isinstance(other, self.__class__) and
self.type == other.type and
self.domain == other.domain and
self.bus == other.bus and
self.slot == other.slot and
self.function == other.function)
class LibvirtDeviceInterface(object):
def __init__(self, interface):
"""
:interface: - `xml.etree.ElementTree.Element` object
"""
self._xml_element = interface
self.mac = interface.find('mac').get('address')
self.source_iface = interface.find('source').get('bridge')
self.target_iface = interface.find('target').get('dev')
self.hw_address = LibvirtDeviceInterfaceHwAddress(
interface.find('address'))
def __eq__(self, other):
return (isinstance(other, self.__class__) and
self.source_iface == other.source_iface and
self.target_iface == other.target_iface and
self.hw_address == other.hw_address)
def __repr__(self):
return "Iface<mac={mac}, src={src}, dst={dst}>".format(
mac=self.mac, src=self.source_iface, dst=self.target_iface)
@classmethod
def _replace_attr(cls, element, attr, value):
if element.get(attr) != value:
element.clear()
element.attrib = {attr: value}
def element(self):
source = self._xml_element.find('source')
target = self._xml_element.find('target')
self._replace_attr(source, 'bridge', self.source_iface)
self._replace_attr(target, 'dev', self.target_iface)
return self._xml_element
class LibvirtXml(object):
def __init__(self, contents):
"""
:contents - XML file contents (text)
"""
self._xml = ElementTree.fromstring(contents)
self._interfaces = map(LibvirtDeviceInterface,
self._xml.findall('.//devices/interface'))
self.disk_file = self._get('.//disk/source', 'file')
self.serial_file = self._get('.//serial/source', 'path')
self.console_file = self._get('.//console/source', 'path')
def _get(self, element, attribute):
el = self._xml.find(element)
if el is not None:
return el.get(attribute)
def _set(self, element, attribute, value):
el = self._xml.find(element)
if el is not None:
el.set(attribute, value)
@property
def interfaces(self):
return self._interfaces
@interfaces.setter
def interfaces(self, other):
"""Only <source bridge/> and <target dev/> elements must be updated"""
if len(self.interfaces) != len(other):
raise RuntimeError("Source and dest have different number of "
"network interfaces allocated.")
for other_iface in other:
for this_iface in self.interfaces:
identical = (this_iface.mac == other_iface.mac)
if identical:
this_iface.source_iface = other_iface.source_iface
this_iface.target_iface = other_iface.target_iface
break
def dump(self):
self._set('.//disk/source', 'file', self.disk_file)
self._set('.//serial/source', 'path', self.serial_file)
self._set('.//console/source', 'path', self.console_file)
xml_devices = self._xml.find('.//devices')
xml_interfaces = self._xml.findall('.//devices/interface')
for iface in xml_interfaces:
xml_devices.remove(iface)
for iface in self._interfaces:
xml_devices.append(iface.element())
return ElementTree.tostring(self._xml)
|
import React from 'react';
import { Group } from '../../model/Group';
type GroupCardProps = {
group: Group
};
export default class GroupCard extends React.PureComponent<GroupCardProps> {
render() {
const { group } = this.props;
return (
<div className="group-card">
<div className="group-card-title">{group.title}</div>
</div>
);
}
} |
<filename>EC/ProyectoEC/include/temporizadores.h
/*-------------------------------------
temporizadores.h
-------------------------------------*/
extern void IntTemp(); |
/**
* Creates an unconnected socket.
*
* @return unconnected socket
*
* @throws IOException if an I/O error occurs when creating the socket
*/
@Override
public Socket createSocket()
throws IOException
{
return initSSLSocket((SSLSocket) factory.createSocket());
} |
// Copyright 2019 <NAME> <<EMAIL>>
#ifndef INCLUDE_SAM_SYSTEM_EULER_SYSTEM_HPP_
#define INCLUDE_SAM_SYSTEM_EULER_SYSTEM_HPP_
#include <vector>
#include <boost/numeric/odeint/integrate/null_observer.hpp>
#include "./generic_system.hpp"
namespace sam {
/*! \brief A system that is integrated with an Euler method of order O(dt).
*
* A system that is integrated with an Euler method of order O(dt). The Euler
* method is defined as
* \f[ x_{n+1} = x_{n} + f_n dt, \f]
* where \f$ f_n \f$ is the derivative at timestep \f$ n \f$.
*/
template<typename ODE, typename state_type = std::vector<double>>
class EulerSystem: public GenericSystem<ODE, state_type> {
public:
template<typename... Ts>
explicit EulerSystem(unsigned int system_size, unsigned int dimension,
Ts... parameters);
template<typename observer_type = boost::numeric::odeint::null_observer>
void Integrate(double dt, unsigned int number_steps,
observer_type observer
= boost::numeric::odeint::null_observer());
private:
template<typename system_type, typename observer_type>
double EulerMethod(system_type system, state_type& x, double t, double dt,
unsigned int number_steps, observer_type observer);
};
// Implementation
template<typename ODE, typename state_type>
template<typename... Ts>
EulerSystem<ODE, state_type>::EulerSystem(unsigned int system_size,
unsigned int dimension,
Ts... parameters)
: GenericSystem<ODE, state_type>(system_size, dimension, parameters...) {}
template<typename ODE, typename state_type>
template<typename observer_type>
void EulerSystem<ODE, state_type>::Integrate(double dt,
unsigned int number_steps,
observer_type observer) {
this->t_ = EulerMethod(*(this->ode_), this->x_, this->t_, dt, number_steps,
observer);
}
template<typename ODE, typename state_type>
template<typename system_type, typename observer_type>
double EulerSystem<ODE, state_type>::EulerMethod(system_type system,
state_type& x, double t,
double dt,
unsigned int number_steps,
observer_type observer) {
observer(x, t);
for (unsigned int i = 0; i < number_steps; ++i) {
// TODO(boundter): copy the value? how to best initialize?
state_type dx = x;
system(x, dx, t);
// TODO(boundter): Rather use iterators
for (size_t j = 0; j < x.size(); ++j) x[j] += dx[j]*dt;
t += dt;
observer(x, t);
}
return t;
}
} // namespace sam
#endif // INCLUDE_SAM_SYSTEM_EULER_SYSTEM_HPP_
|
import React from "react";
import { Colors } from "../../../style/type";
export interface GiftCardProps {
theme: Colors;
icon?: React.ReactNode;
title: string;
caption: string;
}
|
Control quality measurements of alpha and beta counter with low back-ground ALBA 2000 v.2.5.6.
The article provides a systematic approach to quality control of measurements of total alpha-and beta-activity using a counter with a low background ALPHA / BETA COUNTING SYSTEM ALBA (mod. ALBA / LLAB) and software ALBA 2000 v.2.5.6. The purpose is to determine the compliance of these objects with the requirements of regulatory documentation. The spectrometry method is based on the physical concentration of radionuclides from the sample volume, measuring the rate of alpha, and beta radiation of the obtained dry residue of the sample, comparing the sample count rate with calibration values of activity, and calculating the total alpha, beta activity of the sample. The primary means of testing is a counter with a low background ALPHA / BETA COUNTING SYSTEM ALBA 200, the lower limit of measurements of the alpha activity, which is 0.02 Bq/l, and beta activity of 0.1 Bq/l, the relative random uncertainty of the measurement result is 60 % with a confidence level P = 0.95. The efficiency of registration on the alpha channel of 43 %, background on the alpha channel of 0,11 imp./min, for a measurement time of 60,000 s, the efficiency of registration on the beta channel of 30 %, background on the beta channel of 1,9 imp./min, for measurement time 60000 s. As a comparison sample for calculating total alpha activity, a sample with alpha radiation, 241Am (geometry 2π), is used. To calculate the total beta activity, a sample of beta-emitter of potassium sulfate with radionuclide is used at 40K (geometry 2π). The weight of the counting sample ranges from 200 to 1000 mg. The activity values are calculated automatically, using the software ALBA 2000, v.2.5.6. Measurement of the total activity of radionuclides in counting samples using the method should be performed only in calibrated geometries. At the same time, the safety requirements, personnel qualifications, and test conditions must be met. Quality control of measurements in the alpha, beta counter ALBA-2000 v.2.5.6. It is carried out in qualitative and quantitative ways. |
/**
* Test a move and rename of a referral entry, using JNDI ignore.
*/
@Test
public void testMoveAndRenameIsReferralJNDIIgnore() throws Exception
{
try
{
MNNCtx.addToEnvironment( DirContext.REFERRAL, "ignore" );
MNNCtx.rename( "cn=Emmanuel Lecharny,ou=Roles", "cn=Alex,o=PNN,c=WW,ou=system" );
fail();
}
catch ( PartialResultException pre )
{
assertTrue( true );
}
} |
/** \file AlignableBeamSpot
*
* Original author: Andreas Mussgiller, August 2010
*
* $Date: 2010/10/26 19:53:53 $
* $Revision: 1.2 $
* (last update by $Author: flucke $)
*/
#include "Alignment/CommonAlignment/interface/AlignableDetUnit.h"
#include "CondFormats/Alignment/interface/Alignments.h"
#include "CondFormats/Alignment/interface/AlignmentErrorsExtended.h"
#include "CLHEP/Vector/RotationInterfaces.h"
#include "DataFormats/GeometryCommonDetAlgo/interface/AlignmentPositionError.h"
#include "Alignment/CommonAlignment/interface/AlignableBeamSpot.h"
#include "FWCore/Utilities/interface/Exception.h"
#include "FWCore/MessageLogger/interface/MessageLogger.h"
//__________________________________________________________________________________________________
AlignableBeamSpot::AlignableBeamSpot()
: Alignable(AlignableBeamSpot::detId().rawId(), AlignableSurface()),
theAlignmentPositionError(nullptr),
theInitializedFlag(false) {}
//__________________________________________________________________________________________________
AlignableBeamSpot::~AlignableBeamSpot() { delete theAlignmentPositionError; }
//__________________________________________________________________________________________________
void AlignableBeamSpot::move(const GlobalVector& displacement) {
theSurface.move(displacement);
this->addDisplacement(displacement);
}
//__________________________________________________________________________________________________
void AlignableBeamSpot::rotateInGlobalFrame(const RotationType& rotation) {
theSurface.rotate(rotation);
this->addRotation(rotation);
}
//__________________________________________________________________________________________________
void AlignableBeamSpot::setAlignmentPositionError(const AlignmentPositionError& ape, bool propagateDown) {
if (!theAlignmentPositionError)
theAlignmentPositionError = new AlignmentPositionError(ape);
else
*theAlignmentPositionError = ape;
}
//__________________________________________________________________________________________________
void AlignableBeamSpot::addAlignmentPositionError(const AlignmentPositionError& ape, bool propagateDown) {
if (!theAlignmentPositionError) {
theAlignmentPositionError = new AlignmentPositionError(ape);
} else {
*theAlignmentPositionError += ape;
}
}
//__________________________________________________________________________________________________
void AlignableBeamSpot::addAlignmentPositionErrorFromRotation(const RotationType& rot, bool propagateDown) {}
//__________________________________________________________________________________________________
/// Adds the AlignmentPositionError (in x,y,z coordinates) that would result
/// on the various components from a possible Rotation of a composite the
/// rotation matrix is in interpreted in LOCAL coordinates of the composite
void AlignableBeamSpot::addAlignmentPositionErrorFromLocalRotation(const RotationType& rot, bool propagateDown) {}
//__________________________________________________________________________________________________
void AlignableBeamSpot::setSurfaceDeformation(const SurfaceDeformation*, bool) {
edm::LogInfo("Alignment") << "@SUB=AlignableBeamSpot::setSurfaceDeformation"
<< "Useless method for beam spot, do nothing.";
}
//__________________________________________________________________________________________________
void AlignableBeamSpot::addSurfaceDeformation(const SurfaceDeformation*, bool) {
edm::LogInfo("Alignment") << "@SUB=AlignableBeamSpot::addSurfaceDeformation"
<< "Useless method for beam spot, do nothing.";
}
//__________________________________________________________________________________________________
void AlignableBeamSpot::dump(void) const {
// Dump this
LocalVector lv(0.0, 0.0, 1.0);
GlobalVector gv = theSurface.toGlobal(lv);
edm::LogInfo("AlignableDump") << " Alignable of type " << this->alignableObjectId() << " has 0 components"
<< std::endl
<< " position = " << this->globalPosition() << ", orientation:" << std::endl
<< std::flush << this->globalRotation() << std::endl
<< std::flush << " dxdz = " << gv.x() / gv.z() << " dydz = " << gv.y() / gv.z()
<< std::endl;
}
//__________________________________________________________________________________________________
Alignments* AlignableBeamSpot::alignments() const {
Alignments* m_alignments = new Alignments();
RotationType rot(this->globalRotation());
// Get position, rotation, detId
CLHEP::Hep3Vector clhepVector(globalPosition().x(), globalPosition().y(), globalPosition().z());
CLHEP::HepRotation clhepRotation(
CLHEP::HepRep3x3(rot.xx(), rot.xy(), rot.xz(), rot.yx(), rot.yy(), rot.yz(), rot.zx(), rot.zy(), rot.zz()));
uint32_t detId = theId;
AlignTransform transform(clhepVector, clhepRotation, detId);
// Add to alignments container
m_alignments->m_align.push_back(transform);
return m_alignments;
}
//__________________________________________________________________________________________________
AlignmentErrorsExtended* AlignableBeamSpot::alignmentErrors(void) const {
AlignmentErrorsExtended* m_alignmentErrors = new AlignmentErrorsExtended();
// Add associated alignment position error
uint32_t detId = theId;
CLHEP::HepSymMatrix clhepSymMatrix(6, 0);
if (theAlignmentPositionError) // Might not be set
clhepSymMatrix = asHepMatrix(theAlignmentPositionError->globalError().matrix());
AlignTransformErrorExtended transformError(clhepSymMatrix, detId);
m_alignmentErrors->m_alignError.push_back(transformError);
return m_alignmentErrors;
}
//______________________________________________________________________________
void AlignableBeamSpot::initialize(double x, double y, double z, double dxdz, double dydz) {
if (theInitializedFlag)
return;
GlobalVector gv(x, y, z);
theSurface.move(gv);
double angleY = std::atan(dxdz);
double angleX = -std::atan(dydz);
align::RotationType rotY(std::cos(angleY), 0., -std::sin(angleY), 0., 1., 0., std::sin(angleY), 0., std::cos(angleY));
align::RotationType rotX(1., 0., 0., 0., std::cos(angleX), std::sin(angleX), 0., -std::sin(angleX), std::cos(angleX));
theSurface.rotate(rotY * rotX);
this->dump();
theInitializedFlag = true;
}
//______________________________________________________________________________
void AlignableBeamSpot::reset() {
Alignable::update(this->id(), AlignableSurface());
delete theAlignmentPositionError;
theAlignmentPositionError = nullptr;
theInitializedFlag = false;
}
//______________________________________________________________________________
const align::Alignables AlignableBeamSpot::emptyComponents_{};
|
/**
* Created by Shyamal on 2/6/2015.
*/
public class ArrivalTimeWidget implements Serializable{
private int appWidgetId;
private String agencyID;
private String routeID;
private String stopID;
private String agencyLongName;
private String routeName;
private String stopName;
private String arrivalTimesUrl;
private DateTime nextArrivalTime;
private int minutesUntilArrival;
private int textColor = -1;
private int backgroundColor = R.color.primary_dark;
public ArrivalTimeWidget() {
}
public int getAppWidgetId() {
return appWidgetId;
}
public void setAppWidgetId(int appWidgetId) {
this.appWidgetId = appWidgetId;
}
public String getAgencyID() {
return agencyID;
}
public void setAgencyID(String agencyID) {
this.agencyID = agencyID;
}
public String getRouteID() {
return routeID;
}
public void setRouteID(String routeID) {
this.routeID = routeID;
}
public String getStopID() {
return stopID;
}
public void setStopID(String stopID) {
this.stopID = stopID;
}
public void setAgencyLongName(String agencyLongName) {
this.agencyLongName = agencyLongName;
}
public String getAgencyLongName() {
return agencyLongName;
}
public String getRouteName() {
return routeName;
}
public void setRouteName(String routeName) {
this.routeName = routeName;
}
public void setStopName(String stopName) {
this.stopName = stopName;
}
public String getStopName() {
return stopName;
}
public DateTime getNextArrivalTime() {
return nextArrivalTime;
}
public void setNextArrivalTime(DateTime nextArrivalTime) {
this.nextArrivalTime = nextArrivalTime;
}
public int getMinutesUntilArrival() {
return minutesUntilArrival;
}
public void setMinutesUntilArrival(int minutesUntilArrival) {
this.minutesUntilArrival = minutesUntilArrival;
}
public int getTextColor() {
return textColor;
}
public void setTextColor(int textColor) {
this.textColor = textColor;
}
public int getBackgroundColor() {
return backgroundColor;
}
public void setBackgroundColor(int backgroundColor) {
this.backgroundColor = backgroundColor;
}
public String toString() {
return "ArrivalTimeWidget with info: " + agencyLongName + " | " + routeName + " | " + stopName;
}
private boolean isValidWidget() {
return agencyID != null && routeID != null && stopID != null &&
agencyLongName != null && routeName != null && stopName != null;
}
public String getArrivalTimesUrl() {
if(isValidWidget()) {
return Utils.GET_ARRIVAL_ESTIMATES_URL + getAgencyID() + "&routes=" + getRouteID() + "&stops=" + getStopID();
} else {
throw new IllegalStateException("ArrivalTimeWidget is not a valid widget");
}
}
@Override
public boolean equals(Object o) {
ArrivalTimeWidget arrivalTimeWidget = (ArrivalTimeWidget) o;
return arrivalTimeWidget.getAgencyID().equals(this.getAgencyID()) &&
arrivalTimeWidget.getRouteID().equals(this.getRouteID()) &&
arrivalTimeWidget.getStopID().equals(this.getStopID()) &&
arrivalTimeWidget.getAppWidgetId() == this.getAppWidgetId();
}
} |
// AppendAll appends all elements of given segments after the tail of the collection.
func (s *Segments) AppendAll(t []Segment) {
if s.values == nil {
s.values = make([]Segment, 0, 20)
}
s.values = append(s.values, t...)
} |
/** Removes summary from main window. */
private void removeSummary() {
final int maxElements = 4;
final int summaryElementIndex = 3;
Node node = view.getBorderPane().getCenter();
StackPane sp = (StackPane) node;
if (sp.getChildren().size() == maxElements) {
sp.getChildren().remove(summaryElementIndex);
}
} |
Formation of Hetero-binuclear Pt(II)-M(II) Complexes Based on (2-(1 H-Tetrazol-5-yl)phenyl)diphenylphosphine Oxide for Superior Phosphorescence of Monomers.
Novel hetero-binuclear platinum complexes (HBC-Pt(II)-M(II), M = Ca(II), Mg(II), Zn(II), and Cd(II)) have been synthesized by the reaction of the corresponding precursors 2 with (2-(1 H-tetrazol-5-yl)phenyl)diphenylphosphine oxide (TTPPO). The X-ray structures of the complexes show that two ancillary ligands TTPPO in the square-planar Pt(II) moiety act as a quadridentate chelating agent for the other metal center, eventually forming a distorted octahedral configuration. There are no significant π-π interactions and Pt-M metallophilic interactions in the crystal lattice, due to the steric hindrances associated with the rigid octahedral structure together with the bulky TTPPO. Consequently, HBC-Pt-M complexes show monomer emission characteristics with quantum yields up to 59% in powder, suggesting their great potential for practical applications. DFT and TD-DFT calculations on HBC-Pt-Zn reveal that the phosphorescence can be ascribed to intraligand charge transfer (3ILCT) combined with some metal-to-ligand charge transfer (3MLCT) in the Pt(ppy) moiety, which is consistent with the observations from the photophysical investigations. |
// Shut off all replication.
func (wr *Wrangler) stopSlaves(tabletMap map[topo.TabletAlias]*topo.TabletInfo) error {
errs := make(chan error, len(tabletMap))
f := func(ti *topo.TabletInfo) {
err := wr.ai.StopSlave(ti, wr.ActionTimeout())
if err != nil {
wr.logger.Infof("StopSlave failed: %v", err)
}
errs <- err
}
for _, tablet := range tabletMap {
go f(tablet)
}
for i := 0; i < len(tabletMap); i++ {
if err := <-errs; err != nil {
return err
}
}
return nil
} |
// Given an image file name, read in the data, try to decode it as an image,
// resize it to the requested size, and then scale the values as desired.
Status ReadTensorFromImageFile(string file_name, const int wanted_height,
const int wanted_width, const float input_mean,
const float input_std,
std::vector<Tensor>* out_tensors) {
std::vector<tensorflow::uint8> image_data;
int image_width;
int image_height;
int image_channels;
TF_RETURN_IF_ERROR(LoadJpegFile(file_name, &image_data, &image_width,
&image_height, &image_channels));
LOG(INFO) << "Loaded JPEG: " << image_width << "x" << image_height << "x"
<< image_channels;
const int wanted_channels = 3;
if (image_channels < wanted_channels) {
return tensorflow::errors::FailedPrecondition(
"Image needs to have at least ", wanted_channels, " but only has ",
image_channels);
}
tensorflow::Tensor image_tensor(
tensorflow::DT_FLOAT,
tensorflow::TensorShape(
{1, wanted_height, wanted_width, wanted_channels}));
auto image_tensor_mapped = image_tensor.tensor<float, 4>();
tensorflow::uint8* in = image_data.data();
float* out = image_tensor_mapped.data();
const size_t image_rowlen = image_width * image_channels;
const float width_scale = static_cast<float>(image_width) / wanted_width;
const float height_scale = static_cast<float>(image_height) / wanted_height;
for (int y = 0; y < wanted_height; ++y) {
const float in_y = y * height_scale;
const int top_y_index = static_cast<int>(floorf(in_y));
const int bottom_y_index =
std::min(static_cast<int>(ceilf(in_y)), (image_height - 1));
const float y_lerp = in_y - top_y_index;
tensorflow::uint8* in_top_row = in + (top_y_index * image_rowlen);
tensorflow::uint8* in_bottom_row = in + (bottom_y_index * image_rowlen);
float* out_row = out + (y * wanted_width * wanted_channels);
for (int x = 0; x < wanted_width; ++x) {
const float in_x = x * width_scale;
const int left_x_index = static_cast<int>(floorf(in_x));
const int right_x_index =
std::min(static_cast<int>(ceilf(in_x)), (image_width - 1));
tensorflow::uint8* in_top_left_pixel =
in_top_row + (left_x_index * wanted_channels);
tensorflow::uint8* in_top_right_pixel =
in_top_row + (right_x_index * wanted_channels);
tensorflow::uint8* in_bottom_left_pixel =
in_bottom_row + (left_x_index * wanted_channels);
tensorflow::uint8* in_bottom_right_pixel =
in_bottom_row + (right_x_index * wanted_channels);
const float x_lerp = in_x - left_x_index;
float* out_pixel = out_row + (x * wanted_channels);
for (int c = 0; c < wanted_channels; ++c) {
const float top_left((in_top_left_pixel[c] - input_mean) / input_std);
const float top_right((in_top_right_pixel[c] - input_mean) / input_std);
const float bottom_left((in_bottom_left_pixel[c] - input_mean) /
input_std);
const float bottom_right((in_bottom_right_pixel[c] - input_mean) /
input_std);
const float top = top_left + (top_right - top_left) * x_lerp;
const float bottom =
bottom_left + (bottom_right - bottom_left) * x_lerp;
out_pixel[c] = top + (bottom - top) * y_lerp;
}
}
}
out_tensors->push_back(image_tensor);
return Status::OK();
} |
nerium Profile Blog Joined November 2007 Philippines 507 Posts #2 Wait, you mean march 14 and 15 right? Lulz is a corrupted version of LOL
Clefairy Profile Joined September 2011 1570 Posts Last Edited: 2013-03-12 15:27:19 #3 On March 13 2013 00:25 nerium wrote:
Wait, you mean march 14 and 15 right?
Yes indeed I do. Fixed OP thanks Yes indeed I do. Fixed OP thanks
BLinD-RawR Profile Blog Joined April 2010 ALLEYCAT BLUES 43985 Posts #4 TheMarine is so smart!
everybody should love TheMarine! Moderator Woo Jung Ho, never forget.| Twitter: @BLinDRawR
Seeker Profile Blog Joined April 2005 Where dat snitch at? 31885 Posts #5 Bo3 for every match? Moderator PM me if you want translations done | twitch.tv/dankshrine Weekly SC2 Podcast!
Clefairy Profile Joined September 2011 1570 Posts #6 On March 13 2013 00:38 Seeker wrote:
Bo3 for every match?
Oops forgot to add to OP. It's Bo3 for Ro8 and Bo5 for the rest. Oops forgot to add to OP. It's Bo3 for Ro8 and Bo5 for the rest.
Arceus Profile Blog Joined February 2008 Vietnam 8280 Posts #7 TheMartine is streaming HotS as of now btw
ReachTheSky Profile Joined April 2010 United States 3110 Posts #8 DOOOOODZ! TheMarine used to be so amazing back in the day! I wish he would come out of retirement and play again >< Zerg is hands down the easiest race to play.
Qikz Profile Blog Joined November 2009 United Kingdom 10996 Posts #9 Woo! <3
I love TheMarine, but damn I wish he'd have picked a time when I wasn't supposed to be doing Uni work, this is getting me distracted :p FanTaSy's #1 Fan | STPL Caster/Organiser | SKT BEST KT | https://twitch.tv/qikzsd
lichter Profile Blog Joined September 2010 1001 YEARS KESPAJAIL 22175 Posts #10 On March 13 2013 00:53 Arceus wrote:
TheMartine is streaming HotS as of now btw
Does he appear in the live streams list? Does he appear in the live streams list? Administrator YOU MUST HEED MY INSTRUCTIONS TAKE OFF YOUR THIIIINGS
Clefairy Profile Joined September 2011 1570 Posts #11 On March 13 2013 01:01 lichter wrote:
Show nested quote +
On March 13 2013 00:53 Arceus wrote:
TheMartine is streaming HotS as of now btw
Does he appear in the live streams list? Does he appear in the live streams list?
Nope. He's our little secret Nope. He's our little secret http://www.twitch.tv/TheMarine822
StarStruck Profile Joined April 2010 24047 Posts #12 Awesome.
On an unrelated note: please bring back good team uniforms.
sitromit Profile Joined June 2011 7051 Posts #13 Cool! It's like a pre-MLG warmup to see some Korean action.
yawnoC Profile Joined December 2010 United States 3081 Posts #14 OGN caster. 8 ESF players. This should be amazing :D GG - UNiVeRsE is the best player in the WORLD
jinorazi Profile Joined October 2004 Korea (South) 4933 Posts Last Edited: 2013-03-12 18:50:37 #15 isnt it haebyung, 해병. or am i tripping
people need to learn korean so they understand the greatness of marine's casting.
(greatest caster of all time, not debatable) age: 84 | location: california | sex: 잘함
PhoenixVoid Profile Blog Joined December 2011 Canada 16290 Posts #16 This looks pretty cool, it should show the Korean players who did not get much HotS exposure. I think HyuN or Maru will win, but Monster has always been capable of showing good play. I'm afraid of demented knife-wielding escaped lunatic libertarian zombie mutants
MasterOfPuppets Profile Blog Joined March 2011 Romania 6941 Posts #17 On March 13 2013 00:56 ReachTheSky wrote:
DOOOOODZ! TheMarine used to be so amazing back in the day! I wish he would come out of retirement and play again ><
Yes pls!
If only this tournament were on during the weekend >_< !!!
Oh well hopefully HyuN will stomp face. Hwaiting~ Yes pls!If only this tournament were on during the weekend >_< !!!Oh well hopefully HyuN will stomp face. Hwaiting~ "my shaft scares me too" - strenx 2014
TABlitz Profile Joined March 2011 Australia 43 Posts #18 On March 13 2013 01:44 StarStruck wrote:
Awesome.
On an unrelated note: please bring back good team uniforms.
^^this. I love the old MBCGame and SKT jackets. Would love to buy Bisu's MBC jacket ^^this. I love the old MBCGame and SKT jackets. Would love to buy Bisu's MBC jacket
opterown Profile Blog Joined August 2011 Australia 42225 Posts #19 gogo maru! ^^ Moderator Retired LR Bonjwa
rift Profile Blog Joined September 2007 1817 Posts Last Edited: 2013-03-12 22:14:12 #20 is, he was one of the first great Terrans in 2000, at the top even before Boxer rose to dominance the next year. For those of you who don't know who TheMarine is, he was one of the first great Terrans in 2000, at the top even before Boxer rose to dominance the next year.
1 2 3 4 5 18 19 20 Next All |
Mickey Rooney (born Joseph Yule Jr.; September 23, 1920 – April 6, 2014) was an American actor, vaudevillian, comedian, producer and radio personality. In a career spanning nine decades and continuing until shortly before his death, he appeared in more than 300 films and was one of the last surviving stars of the silent film era.[1]
At the height of a career that was marked by precipitous declines and raging comebacks, Rooney performed the role of Andy Hardy in a series of 15 films in the 1930s and 1940s that epitomized American family values. A versatile performer, he became a celebrated character actor later in his career. Laurence Olivier once said he considered Rooney "the best there has ever been".[2] Clarence Brown, who directed him in two of his earliest dramatic roles, National Velvet and The Human Comedy, said he was "the closest thing to a genius I ever worked with".[3]
Rooney first performed in vaudeville as a child and made his film debut at the age of six. At 14 he played Puck in the play and later the 1935 film adaptation of A Midsummer Night's Dream. Critic David Thomson hailed his performance as "one of the cinema's most arresting pieces of magic". In 1938, he co-starred in Boys Town. At 19 he was the first teenager to be nominated for an Oscar for his leading role in Babes in Arms, and he was awarded a special Academy Juvenile Award in 1939.[4] At the peak of his career between the ages of 15 and 25, he made 43 films, which made him one of Metro-Goldwyn-Mayer's most consistently successful actors and a favorite of MGM studio head Louis B. Mayer.
Rooney was the top box-office attraction from 1939 to 1941[5] and one of the best-paid actors of that era,[2] but his career would never again rise to such heights. Drafted into the Army during World War II, he served nearly two years entertaining over two million troops on stage and radio and was awarded a Bronze Star for performing in combat zones. Returning from the war in 1945, he was too old for juvenile roles but too short to be an adult movie star, and was unable to get as many starring roles. Nevertheless, Rooney's popularity was renewed with well-received supporting roles in films such as Breakfast at Tiffany's (1961), Requiem for a Heavyweight (1962), It's a Mad, Mad, Mad, Mad World (1963), and The Black Stallion (1979). In the early 1980s, he returned to Broadway in Sugar Babies and again became a celebrated star. Rooney made hundreds of appearances on TV, including dramas, variety programs, and talk shows, and won an Emmy in 1982 plus a Golden Globe for his role in Bill (1981).
At his death, Vanity Fair called him "the original Hollywood train wreck".[5] He struggled with alcohol and pill addiction. Ava Gardner was his first wife, and he would go on to marry an additional seven times. Despite earning millions during his career, he had to file for bankruptcy in 1962 due to mismanagement of his finances. Shortly before his death in 2014 at age 93, he alleged mistreatment by some family members and testified before Congress about what he alleged was physical abuse and exploitation by family members. By the end of his life, his millions in earnings had dwindled to an estate that was valued at only $18,000. He died owing medical bills and back taxes, and contributions were solicited from the public.[6][7]
Early life [ edit ]
Rooney was born Joseph Yule, Jr. on September 23, 1920, in Brooklyn, New York, the only child of vaudevillians Nellie W. Carter, from Kansas City, Missouri and Joe Yule, a native of Glasgow, Scotland.[8] His mother was a former chorus girl and a burlesque performer.[2] When Rooney was born, his parents were appearing in a Brooklyn production of A Gaiety Girl. Rooney later recounted in his memoirs that he began performing at the age of 17 months as part of his parents' routine, wearing a specially tailored tuxedo.[9][10][11]
Career [ edit ]
Child actor [ edit ]
Rooney's parents separated when he was four years old in 1924, and he and his mother moved to Hollywood the following year from Greenpoint, Brooklyn.[12] He made his first film appearance at age six in 1926, in the short Not to be Trusted.[2][13] Rooney got bit parts in films such as The Beast of the City (1932) and The Life of Jimmy Dolan (1933), which allowed him to work alongside stars such as Joel McCrea, Colleen Moore, Clark Gable, Douglas Fairbanks Jr., John Wayne and Jean Harlow. He enrolled in the Hollywood Professional School and later attended Hollywood High School, graduating in 1938.[14][15]
Mickey McGuire [ edit ]
His mother saw an advertisement for a child to play the role of "Mickey McGuire" in a series of short films.[16] Rooney got the role and became "Mickey" for 78 of the comedies, running from 1927 to 1936, starting with Mickey's Circus (1927), his first starring role.[a][b] During this period, he also briefly voiced Oswald the Lucky Rabbit.[20]
He made other films in his adolescence, including several more of the McGuire films. At age 15 he played the role of Puck in the Warner Brothers all-star adaptation of A Midsummer Night's Dream in 1935. Rooney then moved to MGM, where he befriended Judy Garland, with whom he began making a series of musicals that propelled both of them to stardom.[21][22][23]
Andy Hardy, Boys Town and Hollywood stardom [ edit ]
In 1937, Rooney was selected to portray Andy Hardy in A Family Affair, which MGM had planned as a B-movie.[16] Rooney provided comic relief as the son of Judge James K. Hardy, portrayed by Lionel Barrymore (although Lewis Stone would play the role of Judge Hardy in subsequent films). The film was an unexpected success, and led to 13 more Andy Hardy films between 1937 and 1946, and a final film in 1958.
According to author Barry Monush, MGM wanted the Andy Hardy films to appeal to all family members. Rooney's character would portray a typical "anxious, hyperactive, girl-crazy teenager", and he soon became the unintended main star of the films. Although some critics describe the series of films as "sweet, overly idealized, and pretty much interchangeable," their ultimate success was because they gave viewers a "comforting portrait of small-town America that seemed suited for the times", with Rooney instilling "a lasting image of what every parent wished their teen could be like".[24]
Behind the scenes, however, Rooney was like the "hyperactive girl-crazy teenager" he portrayed on the screen. Wallace Beery, his co-star in Stablemates, described him as a "brat", but a "fine actor".[25] MGM head Louis B. Mayer found it necessary to manage Rooney's public image, explains historian Jane Ellen Wayne:
Mayer naturally tried to keep all his child actors in line, like any father figure. After one such episode, Mickey Rooney replied, "I won't do it. You're asking the impossible." Mayer then grabbed young Rooney by his lapels and said, "Listen to me! I don't care what you do in private. Just don't do it in public. In public, behave. Your fans expect it. You're Andy Hardy! You're the United States! You're the Stars and Stripes. Behave yourself! You're a symbol!" Mickey nodded. "I'll be good, Mr. Mayer. I promise you that." Mayer let go of his lapels, "All right," he said.[26]
Fifty years later, Rooney realized in hindsight that these early confrontations with Mayer were necessary for him to develop into a leading film star: "Everybody butted heads with him, but he listened and you listened. And then you'd come to an agreement you could both live with. ... He visited the sets, he gave people talks ... What he wanted was something that was American, presented in a cosmopolitan manner."[27]:323
In 1937, Rooney made his first film alongside Judy Garland with Thoroughbreds Don't Cry.[28] Garland and Rooney became close friends as they co-starred in future films and became a successful song-and-dance team. Audiences delighted in seeing the "playful interactions between the two stars showcase a wonderful chemistry".[29] Along with three of the Andy Hardy films, where she portrayed a girl attracted to Andy, they appeared together in a string of successful musicals, including Babes in Arms (1939). During an interview in the 1992 documentary film MGM: When the Lion Roars, Rooney describes their friendship:[30]
Judy and I were so close we could've come from the same womb. We weren't like brothers or sisters but there was no love affair there; there was more than a love affair. It's very, very difficult to explain the depths of our love for each other. It was so special. It was a forever love. Judy, as we speak, has not passed away. She's always with me in every heartbeat of my body.
In 1937, Rooney received top billing as Shockey Carter in Hoosier Schoolboy but his breakthrough-role as a dramatic actor came in 1938's Boys Town opposite Spencer Tracy as Father Flanagan, who runs a home for wayward and homeless boys. Rooney was awarded a special Juvenile Academy Award in 1939, for "significant contribution in bringing to the screen the spirit and personification of youth".[11]:161[31] Wayne describes one of the "most famous scenes" in the film, where tough young Rooney is playing poker with a cigarette in his mouth, his hat is cocked and his feet are up on the table. "Tracy grabs him by the lapels, throws the cigarette away and pushes him into a chair. 'That's better,' he tells Mickey."[26] Louis B. Mayer said Boys Town was his favorite film during his years at MGM.[11]:161
The popularity of his films made Rooney the biggest box-office draw in 1939, 1940 and 1941.[32] For their roles in Boys Town, Rooney and Tracy won first and second place in the Motion Picture Herald 1940 National Poll of Exhibitors, based on the box office appeal of 200 players. Boys' Life magazine wrote, "Congratulations to Messrs. Rooney and Tracy! Also to Metro-Goldwyn-Mayer we extend a hearty thanks for their very considerable part in this outstanding achievement."[33] Actor Laurence Olivier once called Rooney "the greatest actor of them all".[34]
A major star in the early 1940s, he appeared on the cover of Time magazine in 1940, timed to coincide with the release of Young Tom Edison;[35] the cover story began:[36]
Hollywood's No. 1 box office bait in 1939 was not Clark Gable, Errol Flynn or Tyrone Power, but a rope-haired, kazoo-voiced kid with a comic-strip face, who until this week had never appeared in a picture without mugging or overacting it. His name (assumed) was Mickey Rooney, and to a large part of the more articulate U.S. cinema audience, his name was becoming a frequently used synonym for brat.
During his long and illustrious career, Rooney also worked with many of the screen's female stars, including Elizabeth Taylor in National Velvet (1944) and Audrey Hepburn in Breakfast at Tiffany's (1961)."[37] Rooney's "bumptiousness and boyish charm" as an actor would develop more "smoothness and polish" over the years, writes biographer Scott Eyman. The fact that Rooney fully enjoyed his life as an actor played a large role in those changes:
You weren't going to work, you were going to have fun. It was home, everybody was cohesive; it was family. One year I made nine pictures; I had to go from one set to another. It was like I was on a conveyor belt. You did not read a script and say, "I guess I'll do it." You did it. They had people that knew the kind of stories that were suited to you. It was a conveyor belt that made motion pictures.[27]:224
Clarence Brown, who directed Rooney in his Oscar-nominated performance in The Human Comedy (1943) and again in National Velvet (1944), enjoyed working with Rooney in films:
Mickey Rooney is the closest thing to a genius that I ever worked with. There was Chaplin, then there was Rooney. The little bastard could do no wrong in my book ... All you had to do with him was rehearse it once.[38]
World War II and later career [ edit ]
Rooney entertains American troops in Germany, April 1945
In June 1944, Rooney was inducted into the United States Army, where [39] he served more than 21 months (until shortly after the end of World War II) entertaining the troops in America and Europe in Special Services. He spent part of the time as a radio personality on the American Forces Network and was awarded the Bronze Star Medal for entertaining troops in combat zones. In addition to the Bronze Star Medal, Rooney also received the Army Good Conduct Medal, American Campaign Medal, European-African-Middle Eastern Campaign Medal, and World War II Victory Medal, for his military service.[40][self-published source][41][11]
Rooney's career slumped after his return to civilian life. He was now an adult with a height of only 5 feet 2 inches (1.57 m)[42] and he could no longer play the role of a teenager, but he also lacked the stature of most leading men. He appeared in a number of films, including Words and Music in 1948, which paired him for the last time with Garland on film (he appeared with her on one episode as a guest on The Judy Garland Show). He briefly starred in a CBS radio series, Shorty Bell, in the summer of 1948, and reprised his role as "Andy Hardy", with most of the original cast, in a syndicated radio version of The Hardy Family in 1949 and 1950 (repeated on Mutual during 1952).[43]
In 1949 Variety reported that Rooney had renegotiated his deal with MGM. He agreed to make one film a year for them for five years at $25,000 a movie (his fee until then had been $100,000 but Rooney wanted to enter independent production.) Rooney claimed he was unhappy with the billing MGM gave him for Words and Music.[44]
His first television series, The Mickey Rooney Show (also known as Hey, Mulligan; created by Blake Edwards with Rooney as his own producer), appeared on NBC television for 32 episodes between August 28, 1954, and June 4, 1955.[11]:317 In 1951, he made his directorial debut with My True Story, starring Helen Walker.[11]:413 Rooney also starred as a ragingly egomaniacal television comedian, loosely based on Red Buttons, in the live 90-minute television drama The Comedian, in the Playhouse 90 series on the evening of Valentine's Day in 1957, and as himself in a revue called The Musical Revue of 1959 based on the 1929 film The Hollywood Revue of 1929, which was edited into a film in 1960.
In 1958, Rooney joined Dean Martin and Frank Sinatra in hosting an episode of NBC's short-lived Club Oasis comedy and variety show. In 1960, Rooney directed and starred in The Private Lives of Adam and Eve, an ambitious comedy known for its multiple flashbacks and many cameos. In the 1960s, Rooney returned to theatrical entertainment. He still accepted film roles in undistinguished films but occasionally would appear in better works, such as Requiem for a Heavyweight (1962) and It's a Mad, Mad, Mad, Mad World (1963).
He portrayed a Japanese character, Mr. Yunioshi, in the 1961 film version of Truman Capote's novella Breakfast at Tiffany's. His performance was criticized by some in subsequent years as a racist stereotype.[45][46] Rooney later said that he would not have taken the role if he had known it would offend people.[47]
On December 31, 1961, Rooney appeared on television's What's My Line and mentioned that he had already started enrolling students in the MRSE (Mickey Rooney School of Entertainment). His school venture never came to fruition. This was a period of professional distress for Rooney; as a childhood friend, director Richard Quine put it: "Let's face it. It wasn't all that easy to find roles for a 5-foot-3 man who'd passed the age of Andy Hardy."[48] In 1962, his debts had forced him into filing for bankruptcy.[49]
In 1966, Rooney was working on the film Ambush Bay in the Philippines when his wife Barbara Ann Thomason— a former model and aspiring actress who had won 17 straight beauty contests in Southern California—was found dead in her bed. Her lover, Milos Milos—who was one of Rooney's actor-friends—was found dead beside her. Detectives ruled it a murder-suicide, which was committed with Rooney's own gun.[11]:362
Francis Ford Coppola had bought the rights to make The Black Stallion (1979), and when casting it, he called Rooney and asked him if he thought he could play a jockey. Rooney replied saying, "Gee, I don't know. I never played a jockey before." He was kidding, he said, since he had played a jockey in at least three past films, including Down the Stretch, Thoroughbreds Don't Cry, and National Velvet.[11]:450 The film garnered excellent reviews and earned $40 million in its first run, which gave Coppola's struggling studio, American Zoetrope, a major boost. It also gave Rooney newfound recognition, along with a nomination for Best Supporting Actor.[11]:452
In 1983, the Academy of Motion Picture Arts and Sciences gave Rooney their Academy Honorary Award for his lifetime of achievement.[11]:482[50][51]
Character roles and Broadway comeback [ edit ]
Television roles [ edit ]
In addition to his movie roles, Rooney made numerous guest-starring roles as a television character actor for nearly six decades, beginning with an episode of Celanese Theatre. The part led to other roles on such television series as Schlitz Playhouse,[11]:542 Playhouse 90,[11]:542 Producers' Showcase, Alcoa Theatre,[11]:542 The Soldiers, Wagon Train, General Electric Theater,[11]:587 Hennesey,[11]:486 The Dick Powell Theatre,[11]:544 Arrest and Trial (1964),[11]:544 Burke's Law (1963),[11]:542 Combat! (1964),[11]:544 The Fugitive, Bob Hope Presents the Chrysler Theatre, The Jean Arthur Show (1966),[11]:544 The Name of the Game (1970),[11]:542 Dan August (1970),[11]:545 Night Gallery (1970),[11]:545 The Love Boat,[11]:594 Kung Fu: The Legend Continues (1995),[11]:545 Murder, She Wrote (1992),[11]:545 The Golden Girls (1988)[11]:545 among many others.
In 1961, he guest-starred in the 13-week James Franciscus adventure–drama CBS television series The Investigators.[11]:544 In 1962, he was cast as himself in the episode "The Top Banana" of the CBS sitcom, Pete and Gladys,[11]:542 starring Harry Morgan and Cara Williams.
In 1963, he entered CBS's The Twilight Zone,[11]:595 giving a one-man performance in the episode "The Last Night of a Jockey" (1963).[11]:544 Also in 1963, in 'The Hunt' for Suspense Theater,[11]:544 he played the sadistic sheriff hunting the young surfer played by James Caan. In 1964, he launched another half-hour sitcom, Mickey. The story line had "Mickey" operating a resort hotel in southern California. His own son Tim Rooney appeared as his character's teenage son on this program, and Emmaline Henry starred as Rooney's wife. The program lasted for 17 episodes.[52]
Rooney garnered a Golden Globe and an Emmy Award for Outstanding Lead Actor in a Limited Series or a Special for his role in 1981's Bill. Playing opposite Dennis Quaid, Rooney's character was a mentally handicapped man attempting to live on his own after leaving an institution. His acting quality in the film has been favorably compared to other actors who took on similar roles, including Sean Penn, Dustin Hoffman and Tom Hanks.[53] He reprised his role in 1983's Bill: On His Own, earning an Emmy nomination for the turn.
Rooney did voice acting from time to time. He provided the voice of Santa Claus in four stop-motion animated Christmas TV specials: Santa Claus Is Comin' to Town (1970), The Year Without a Santa Claus (1974),[11]:540 Rudolph and Frosty's Christmas in July (1979)[11]:540 and A Miser Brothers' Christmas (2008). In 1995, he appeared as himself on The Simpsons episode "Radioactive Man".[11]:545
After starring in one unsuccessful TV series and turning down an offer for a huge TV series, Rooney, now 70, starred in the Family Channel's The Adventures of the Black Stallion, where he reprised his role as Henry Dailey in the film of the same name, eleven years earlier.[11]:594 The series ran for three years and was an international hit.,[11]:484
Rooney appeared in television commercials for Garden State Life Insurance Company in 2002.[54]
Broadway shows [ edit ]
A major turning point came in 1979, when Rooney made his Broadway debut in the acclaimed stage play Sugar Babies, a musical revue tribute to the burlesque era costarring former MGM dancing star Ann Miller. Aljean Harmetz noted that "Mr. Rooney fought over every skit and argued over every song and almost always got things done his way. The show opened on Broadway on October 8, 1979, to rave reviews, and this time he did not throw success away.[55] Rooney and Miller performed the show 1,208 times in New York and then toured with it for five years, including eight months in London.[56] Co-star Miller recalls that Rooney "never missed a performance or a chance to ad-lib or read the lines the same way twice, if he even stuck to the script".[49] Biographer Alvin Marill states that "at 59, Mickey Rooney was reincarnated as a baggy-pants comedian—back as a top banana in show biz in his belated Broadway debut."[49]
Following this, he toured as Pseudelous in Stephen Sondheim's A Funny Thing Happened on the Way to the Forum.[11]:351 In the 1990s, he returned to Broadway for the final months of Will Rogers Follies, playing the ghost of Will's father.[11]:547 On television, he starred in the short-lived sitcom, One of the Boys,[11]:539 along with two unfamiliar young stars, Dana Carvey and Nathan Lane, in 1982.
He toured Canada in a dinner theatre production of The Mind with the Naughty Man in the mid-1990s.[11]:548 He played The Wizard in a stage production of The Wizard of Oz with Eartha Kitt at Madison Square Garden.[11]:489 Kitt was later replaced by Jo Anne Worley.
Mickey Rooney speaks at the Pentagon in 2000 during a ceremony honoring the USO
Final years [ edit ]
Rooney wrote a memoir titled Life is Too Short, published by Villard Books in 1991. A Library Journal review said that "From title to the last line, 'I'll have a short bier', Rooney's self-deprecating humor powers this book." He wrote a novel about a child star, published in 1994, The Search For Sunny Skies.[57]
Despite the millions of dollars that he earned over the years, such as his $65,000 a week earnings from Sugar Babies, Rooney was plagued by financial problems late in life. His longtime gambling habit caused him to "gamble away his fortune again and again". He declared bankruptcy for the second time in 1996 and described himself as "broke" in 2005. He kept performing on stage and in the movies, but his personal property was valued at only $18,000 when he died in 2014.[58]
Rooney and his wife Jan toured the country in 2005 through 2011 in a musical revue called Let's Put on a Show. Vanity Fair called it "a homespun affair full of dog-eared jokes" that featured Rooney singing George Gershwin songs.[5]
In 2006, Rooney played Gus in Night at the Museum.[59][60] He returned to play the role again in the sequel Night at the Museum: Battle of the Smithsonian in 2009, in a scene that was deleted from the final film.[59]
On May 26, 2007, he was grand marshal at the Garden Grove Strawberry Festival. Rooney made his British pantomime debut, playing Baron Hardup in Cinderella, at the Sunderland Empire Theatre over the 2007 Christmas period,[61][62] a role he reprised at Bristol Hippodrome in 2008 and at the Milton Keynes theatre in 2009.[63]
In 2011, Rooney made a brief cameo appearance in The Muppets and in 2014, at age 93, he reprised his role as Gus in Night at the Museum: Secret of the Tomb, with the film being dedicated in the honor of Rooney and Robin Williams, who also died that year.[64] Although confined to a wheelchair, he was described by director Shawn Levy as "energetic and so pleased to be there. He was just happy to be invited to the party."[65]
An October 2015 article in The Hollywood Reporter maintained that Rooney was frequently abused and financially depleted by his closest relatives in the last years of his life. The article said that it was clear that "one of the biggest stars of all time, who remained aloft longer than anyone in Hollywood history, was in the end brought down by those closest to him. He died humiliated and betrayed, nearly broke and often broken."[2] Rooney suffered from bipolar disorder and had attempted suicide two or three times over the years, with resulting hospitalizations reported as "nervous breakdowns".[2]
Personal life [ edit ]
Mickey Rooney in 1986, aged 66
At the time of his death, he was married to Jan Chamberlin Rooney, although they had separated in June 2012.[66] He had nine children and two stepchildren, as well as 19 grandchildren and several great-grandchildren.[67][68]
Rooney had been addicted to sleeping pills; he overcame the sleeping pill addiction in 2000, when he was in his late 70s.[5]
Rooney and his wife Jan at a military concert in Beverly Hills, California in 2000
On February 16, 2011, Rooney was granted a temporary restraining order against stepson Christopher Aber and Aber's wife, Christina, and they were ordered to stay 100 yards from Rooney, his stepson Mark Rooney and his wife, Charlene Rooney.[69][70] Rooney claimed that he was a victim of elder abuse.[71]
On March 2, 2011, Rooney appeared before a special U.S. Senate committee that was considering legislation to curb elder abuse, testifying about the abuse he claimed to have suffered at the hands of family members.[69] In 2011 all of Rooney's finances were permanently handed over to a conservator,[72] who called Rooney "completely competent".[71]
In April 2011, the temporary restraining order that Rooney was previously granted was replaced by a confidential settlement between Rooney and his stepson, Aber.[73] Christopher Aber and Jan Rooney denied all the allegations.[74][75]
In 1997, Rooney was arrested on suspicion of beating his wife, but charges were dropped due to lack of evidence.[76]
In May 2013, Rooney sold his home of many years, reportedly for $1.3 million, and split the proceeds with his wife, Jan.[13][77]
Marriages [ edit ]
Rooney was married eight times, with six of the marriages ending in divorce. In 1942, he married his first wife, actress Ava Gardner, who at that time was still an obscure teenage starlet. They divorced the following year, partly because he had apparently been unfaithful.[2] While stationed in the military in Alabama in 1944, Rooney met and married Betty Jane Phillips, who later became a singer under the name B.J. Baker. They had two sons together. This marriage ended in divorce after he returned from Europe at the end of World War II. His marriage to actress Martha Vickers in 1949 produced one son but ended in divorce in 1951. He married actress Elaine Mahnken in 1952 and they divorced in 1958.[67][68]
In 1958, Rooney married Barbara Ann Thomason, but she was murdered by her secret lover in 1966.[78] He then married Barbara's best friend, Marge Lane. That marriage lasted 100 days. He was married to Carolyn Hockett from 1969 to 1975.[67] In 1978, Rooney married his eighth and final wife, Jan Chamberlin. Their marriage lasted until his death, a total of 34 years (longer than his seven previous unions combined), although they separated in 2012.[66]
Death [ edit ]
Rooney died on April 6, 2014, of natural causes,[80] including complications from diabetes in Los Angeles at the age of 93.[81]
A group of family members and friends, including Mickey Rourke, held a memorial service on April 18. A private funeral, organized by another set of family members, was held at Hollywood Forever Cemetery, where he was ultimately interred, on April 19. His eight surviving children said in a statement that they were barred from seeing Rooney during his final years.[82][83][84]
Legacy [ edit ]
Rooney was one of the last surviving actors of the silent picture era. His movie career spanned 88 years, from 1926 to 2014, continuing until shortly before his death. During his peak years from the late 1930s to the early 1940s, Rooney was among the top box-office stars in the United States.[85]
He made forty-three pictures between the age of 15 and 25. Among those, his role as Andy Hardy became one of "Hollywood's best-loved characters," with Marlon Brando calling him "the best actor in films".[24]
"There was nothing he couldn't do", said actress Margaret O'Brien.[85] MGM boss Louis B. Mayer treated him like a son and saw in Rooney "the embodiment of the amiable American boy who stands for family, humbug, and sentiment," writes critic and author, David Thomson.[86]
By the time Rooney was 20, his consistent portrayals of characters with youth and energy suggested that his future success was unlimited. Thomson also explains that Rooney's characters were able to cover a wide range of emotional types, and gives three examples where "Rooney is not just an actor of genius, but an artist able to maintain a stylized commentary on the demon impulse of the small, belligerent man:"[86]
Rooney's Puck in A Midsummer Night's Dream (1935) is truly inhuman, one of cinema's most arresting pieces of magic. ... His toughie in Boys Town (1938) struts and bullies like something out of a nightmare and then comes clean in a grotesque but utterly frank outburst of sentimentality in which he aspires to the boy community ... His role as Baby Face Nelson (1957), the manic, destructive response of the runt against a pig society.[86]
By the end of the 1940s, Rooney's movie characters were no longer in demand and his career went downhill. "In 1938," he said, "I starred in eight pictures. In 1948 and 1949 together, I starred in only three."[51] However, film historian Jeanine Basinger notes that although his career "reached the heights and plunged to the depths, Rooney kept on working and growing, the mark of a professional." Some of the films which reinvigorated his popularity, were Requiem for a Heavyweight (1962), It's a Mad, Mad, Mad, Mad World (1963) and The Black Stallion (1979). In the early 1980s, he returned to Broadway in Sugar Babies, and "found himself once more back on top".[51]
Basinger tries to encapsulate Rooney's career:
Rooney's abundant talent, like his film image, might seem like a metaphor for America: a seemingly endless supply of natural resources that could never dry up, but which, it turned out, could be ruined by excessive use and abuse, by arrogance or power, and which had to be carefully tended to be returned to full capacity. From child star to character actor, from movie shorts to television specials, and from films to Broadway, Rooney ultimately did prove he could do it all, do it well, and keep on doing it. His is a unique career, both for its versatility and its longevity.[51]
Filmography [ edit ]
One of the most enduring performers in show business history, Rooney appeared in over 300 films. He was one of the last surviving stars of the silent film era, having one of the longest careers in movie history.[87]
Stage [ edit ]
Awards and honors [ edit ]
Awards [ edit ]
Honors [ edit ]
On February 8, 1960, Rooney was initiated into the Hollywood Walk of Fame with a star heralding his work in motion pictures, located at 1718 Vine Street, one for his television career located at 6541 Hollywood Boulevard, and a third dedicated to his work in radio, located at 6372 Hollywood Boulevard. On March 29, 1984, he received a fourth star, this one for his live performances, located at 6211 Hollywood Boulevard.[88]
In 1996, a Golden Palm Star on the Palm Springs Walk of Stars was dedicated to Rooney.[89]
See also [ edit ]
Notes [ edit ]
^ [17] The film was long believed lost, but in 2014 was reported found in the Netherlands. ^ Toonerville Trolley comic strip, which contained a character named Mickey McGuire. Joe Yule briefly became Mickey McGuire legally "trump an attempted copyright lawsuit so the film producer Larry Darmour would not have to pay the comic strip writers royalties" His mother also changed her surname to McGuire in an attempt to bolster the argument, but the film producers lost. The litigation settlement awarded damages to the owners of the cartoon character, compelling the twelve-year-old actor to refrain from calling himself Mickey McGuire on- and off-screen.[18][19]
During an interruption in the series in 1932, Mrs. Yule made plans to take her son on a 10-week vaudeville tour as McGuire, and Fox sued successfully to stop him from using the name. Mrs. Yule suggested the stage name of Mickey Looney for her comedian son. He altered this to Rooney, which did not infringe upon the copyright of [16] The Mickey McGuire films were adapted from thecomic strip, which contained a character named Mickey McGuire. Joe Yule briefly became Mickey McGuire legally "trump an attempted copyright lawsuit so the film producer Larry Darmour would not have to pay the comic strip writers royalties" His mother also changed her surname to McGuire in an attempt to bolster the argument, but the film producers lost. The litigation settlement awarded damages to the owners of the cartoon character, compelling the twelve-year-old actor to refrain from calling himself Mickey McGuire on- and off-screen.During an interruption in the series in 1932, Mrs. Yule made plans to take her son on a 10-week vaudeville tour as McGuire, and Fox sued successfully to stop him from using the name. Mrs. Yule suggested the stage name of Mickey Looney for her comedian son. He altered this to Rooney, which did not infringe upon the copyright of Warner Brothers animation series called Looney Tunes
References [ edit ]
Bibliography |
#include <iostream>
#include <fstream>
#include <iomanip>
#include <math.h>
#include <limits.h>
#include <algorithm>
#include <vector>
#include <list>
#include <stack>
#include <queue>
#include <set>
#include <map>
#include <bitset>
#include <string>
#include <string.h>
#include <sstream>
#include <ctime>
using namespace std;
#define eps 1e-12
#define pi 3.14159265358979323846
#define pb push_back
#define mp make_pair
#define st first
#define nd second
#define bgn begin
#define ll long long
#define ld long double
#define ull unsigned long long
#define ii pair<ll,ll>
struct gcdExtnd
{
ll x,y,g;
ll gcd(ll a,ll b)
{
if(b==0)
{
x=1;
y=0;
return a;
}
g=gcd(b,a%b);
ll t=y;
y=x-(a/b)*y;
x=t;
return g;
}
};
ll invrsMod(ll a, ll m)
{
gcdExtnd o;
ll g=o.gcd(a,m);
ll x=(o.x)%m;
if(x<0)x+=m;
return x;
}
const int N = 2010, M = 1000000007;
ll n, k, dp[N], sdp[N], fct[N], invrsFct[N], res;
void solve()
{
cin >> n >> k;
fct[0] = 1;
invrsFct[0] = 1;
for(ll i = 1; i <= k; i++)
{
fct[i] = (fct[i - 1] * i) % M;
invrsFct[i] = invrsMod(fct[i], M);
}
for(int j = n; j >= 1; j--)sdp[j] = 1;
res = 0;
for(int i = 1; i <= 14 && i <= k; i++)
{
for(int j = n; j >= 1; j--)
{
dp[j] = sdp[j];
res = res + ((dp[j]*((((fct[k - 1] * invrsFct[i - 1]) % M)*invrsFct[k-i]) % M))%M);
if(res >= M)res -= M;
}
sdp[n + 1] = 0;
for(int j = n; j >= 1; j--)
{
sdp[j] = 0;
for(int x = (j << 1); x <= n; x += j)
{
sdp[j] += dp[x];
if(sdp[j] >= M)sdp[j] -= M;
}
}
}
cout << res << "\n";
}
int main()
{
std::ios::sync_with_stdio(0);
cin.tie(0);
#ifdef localProject
freopen("in.txt","r",stdin);
#endif
solve();
return 0;
} |
def find(self, expr, first = -1, reverse = False):
try:
ret = _datascope._dbfind(self, expr, first, reverse)
except _datascope._ElogException, _e:
stock._raise_elog(_e)
return ret |
<filename>src/app/component/visualization/visualization.abstract.component.ts
import { SelectionToolConfig } from './../../model/selection-config.model';
import { ChartSelection } from './../../model/chart-selection.model';
import * as THREE from 'three';
import { EventEmitter } from '@angular/core';
import { EntityTypeEnum, GraphEnum } from 'app/model/enum.model';
import { GraphData } from 'app/model/graph-data.model';
import { Subscription } from 'rxjs';
import { Vector3, Camera } from 'three';
import { TooltipController, ComplexTooltipData } from '../../controller/tooltip/tooltip.controller';
import { LabelController } from './../../controller/label/label.controller';
import { TooltipOptions } from './../../controller/tooltip/tooltip.controller';
import { VisualizationView } from './../../model/chart-view.model';
import { ChartObjectInterface } from './../../model/chart.object.interface';
import { DataDecorator, DataDecoratorTypeEnum } from './../../model/data-map.model';
import { WorkspaceLayoutEnum } from './../../model/enum.model';
import { GraphConfig } from './../../model/graph-config.model';
import { ChartEvent, ChartEvents } from './../workspace/chart/chart.events';
import { EdgeConfigModel } from './edges/edges.model';
import { OncoData } from 'app/oncoData';
import { AbstractScatterVisualization } from './visualization.abstract.scatter.component';
import { OrbitControls } from 'three-orbitcontrols-ts';
import { TooltipOverride } from 'app/model/dataset-table-info.model';
declare var $: any;
export class AbstractVisualization implements ChartObjectInterface {
// Common Objects
public canRegenLinks: boolean = false;
public _data: GraphData;
public _config: GraphConfig;
// public selectionToolConfig: SelectionToolConfig;
public decorators: Array<DataDecorator>;
public $MouseMove: Subscription;
public $MouseDown: Subscription;
public $MouseUp: Subscription;
public $KeyPress: Subscription;
public $KeyDown: Subscription;
public $KeyUp: Subscription;
public $onShowLabels: Subscription;
public $onHideLabels: Subscription;
public $onShowTooltip: Subscription;
public $onHideTooltip: Subscription;
public html: HTMLElement;
public tooltips: HTMLElement;
public tooltip: string | ComplexTooltipData;
public tooltipColor: string;
public labels: HTMLElement;
public events: ChartEvents;
public view: VisualizationView;
public isEnabled: boolean;
public isVisible: boolean;
public meshes: THREE.Object3D[];
public entity: EntityTypeEnum;
protected labelController: LabelController;
protected tooltipOptions: TooltipOptions;
protected tooltipController: TooltipController;
public
// Emitters
public onRequestRender: EventEmitter<GraphEnum> = new EventEmitter();
public onConfigEmit: EventEmitter<{ type: GraphConfig }> = new EventEmitter<{
type: GraphConfig;
}>();
public onSelect: EventEmitter<ChartSelection> = new EventEmitter<ChartSelection>();
public adjustGraphDetailsBasedOnZoomChange(oldZoom:number, newZoom:number, addHistory:boolean) {
// For example, GenomeGraph keeps the gene circles the same size as we zoom in/out.
}
public static rgbIntToHex = function (rgb) {
var hex = '000000' + Number(rgb).toString(16);
return '#' + hex.substr(-6);
};
public tooltipSnippetFromColorDecorator(id:any, tooltipOverride:TooltipOverride):string {
if(this.decorators) {
let colorDecorator = this.decorators.find(v => v.type == DataDecoratorTypeEnum.COLOR);
if(colorDecorator){
if(id){
let pid = null;
let match = colorDecorator.values.find(v=> {
if (this.entity == EntityTypeEnum.SAMPLE){
pid = v.pid;
return v.sid == id;
}
if (this.entity == EntityTypeEnum.PATIENT){
pid = v.pid;
return v.pid == id;
}
if (this.entity == EntityTypeEnum.GENE){
pid = v.pid;
return v.mid == id;
}
return false
});
if(match) {
// Use colorDecoratorlegend to look up color,
// and thus label.
/*
labels: (3) ["dead", "alive", "not reported"]
values: (4) ["#3949ab", "#ffb300", "#f44336", "#dddddd"]
*/
let color:string = "#aabbcc";
let colorString:string = match.value.toString();
if(colorString.startsWith("#")==false){
// Convert from int to #hex
color = AbstractVisualization.rgbIntToHex(match.value);
} else {
color = colorString;
}
let idx = colorDecorator.legend.values.indexOf(color);
if(idx > -1) {
// Turn "sample vital status" into "vital status"
let name = colorDecorator.legend.name.split(' ').slice(1,1000).join(' ');
// If the field name is in an override, use the fancy "title" from the override as the displayed name.
if(tooltipOverride && (this.entity == tooltipOverride.entity)){
let tooltipField = tooltipOverride.fields.find(f => f.name == name);
if(tooltipField) {
name = tooltipField.title;
}
}
let label = colorDecorator.legend.labels[idx];
let pd = OncoData.instance.currentCommonSidePanel.commonSidePanelModel.patientData;
let patientKeyValue = pd.find(p => p.p == pid);
label = patientKeyValue ? patientKeyValue[colorDecorator.field.key] : label;
return `<table border="0"><tr><td width="5" bgcolor="${color}"> </td><td><b>${name}:</b> ${label}</td></tr></table>`;
} else {
return ' ERROR_TSFCD '
}
}
}
}
return "";
}
}
public tooltipColorFromDecorator(id:any, originalColor:any){
let color = originalColor;
if(this.decorators) {
let colorDecorator = this.decorators.find(v => v.type == DataDecoratorTypeEnum.COLOR);
if(colorDecorator){
if(id){
let match = colorDecorator.values.find(v=> {
if (this.entity == EntityTypeEnum.SAMPLE){
return v.sid == id;
}
if (this.entity == EntityTypeEnum.PATIENT){
return v.pid == id;
}
if (this.entity == EntityTypeEnum.GENE){
return v.mid == id;
}
return false
});
if(match) {
let colorString:string = match.value.toString();
if(colorString.startsWith("#")){
// Convert from //#
color = parseInt(colorString.substring(1), 16)
} else {
color = match.value;
}
}
}
}
return color;
}
}
public getTargets(): {
point: Vector3;
id: string;
idType: EntityTypeEnum;
}[] {
return null;
}
public getTargetsFromMeshes(
entityType: EntityTypeEnum
): Array<{ point: THREE.Vector3; id: string; idType: EntityTypeEnum }> {
return this.meshes.map(mesh => {
return { point: mesh.position, id: mesh.userData.id, idType: entityType };
});
}
public notifyEdgeGraphOfSelectionChange(weKnowNothingIsInSelection:boolean) {
console.warn('NYI: notifyEdgeGraphOfSelectionChange from base viz class. ' + this._config.graph );
}
public regenLinks(){
}
public notifiedOfVariantChanges(reason:string){
console.log(`In genome, notifiedOfVariantChanges because ${reason}.`);
}
// Allows GenomeGraph to return list of variants that should be edges.
// This is consumed by edges.graph.
public filterGenesForEdges(
entityA: EntityTypeEnum,
entityB: EntityTypeEnum,
key: string
){
return [];
}
enable(truthy: boolean) {
if (this.isEnabled === truthy) {
return;
}
this.isEnabled = truthy;
this.labelController.enable = this.isEnabled;
this.tooltipController.enable = this.isEnabled;
this.view.controls.enabled = this.isEnabled;
if (truthy) {
this.$MouseMove = this.events.chartMouseMove.subscribe(this.onMouseMove.bind(this));
this.$MouseDown = this.events.chartMouseDown.subscribe(this.onMouseDown.bind(this));
this.$MouseUp = this.events.chartMouseUp.subscribe(this.onMouseUp.bind(this));
this.$KeyPress = this.events.chartKeyPress.subscribe(this.onKeyPress.bind(this));
this.$KeyDown = this.events.chartKeyDown.subscribe(this.onKeyDown.bind(this));
this.$KeyUp = this.events.chartKeyUp.subscribe(this.onKeyUp.bind(this));
} else {
this.$MouseMove.unsubscribe();
this.$MouseDown.unsubscribe();
this.$MouseUp.unsubscribe();
this.$KeyPress.unsubscribe();
this.$KeyDown.unsubscribe();
this.$KeyUp.unsubscribe();
this.labels.innerHTML = '';
this.tooltips.innerHTML = '';
}
}
updatedEdgeConfig(edgeConfig: EdgeConfigModel) {
// Subclasses which filter by edge connection, etc.,
// need to know update changes there. For example,
// GenomeGraph will display gene sizes based on the number of
// variants matching the edge connections setting.
// But most subclasses will leave this empty.
console.log('TEMPNOTE: updatedEdgeConfig in abstract vis.');
}
updateDecorator(config: GraphConfig, decorators: DataDecorator[]) {
this.decorators = decorators;
}
updateData(config: GraphConfig, data: any) {
this._config = config as GraphConfig;
this._data = data;
}
// updateSelectionTool(selectionToolConfig: SelectionToolConfig): void {
// this.selectionToolConfig = selectionToolConfig;
// }
public createdOrbitControlsChangeFunction;
create(entity:EntityTypeEnum, html: HTMLElement, events: ChartEvents, view: VisualizationView): ChartObjectInterface {
if(window['computedFeedbackForForm'] == null) {
window['computedFeedbackForForm'] = {};
// MJ TBD find better place to put this.
}
this.entity = entity;
this.html = html;
this.html.innerText = '';
this.events = events;
this.view = view;
this.isEnabled = false;
this.meshes = [];
this.decorators = [];
this.labels = <HTMLDivElement>document.createElement('div');
this.labels.className = 'graph-overlay';
this.html.appendChild(this.labels);
this.tooltipOptions = new TooltipOptions();
this.tooltip = '';
this.tooltips = <HTMLDivElement>document.createElement('div');
this.tooltips.id = 'visTooltipsDiv' + view.config.graph; // visTooltipsDiv1 or visTooltipsDiv2
this.tooltips.className = 'xtooltiptext' ; // 'graph-tooltip';
this.html.appendChild(this.tooltips);
view.camera.position.set(0, 0, 1000);
view.camera.lookAt(new Vector3(0, 0, 0));
view.scene.add(view.camera);
this.labelController = new LabelController(view, events);
this.tooltipController = new TooltipController(view, events, this, this.tooltips as HTMLDivElement);
let self = this;
this.$onShowLabels = this.labelController.onShow.subscribe(this.onShowLabels.bind(this));
this.$onHideLabels = this.labelController.onHide.subscribe(this.onHideLabels.bind(this));
this.$onShowTooltip = this.tooltipController.onShow.subscribe(this.onShowTooltip.bind(this));
this.$onHideTooltip = this.tooltipController.onHide.subscribe(this.onHideTooltip.bind(this));
let f = (evt) => {
self.onOrbitControlsChange(self, self.view, evt)
};
self.view.controls.addEventListener('change', f);
self.createdOrbitControlsChangeFunction = f;
this.lastZoomDistance = view.camera.position.length(); // MJ
this.originalZoomDistance = this.lastZoomDistance;
return this;
}
public lastZoomDistance:number = 1;
public originalZoomDistance:number = 1;
onOrbitControlsChange(graph:AbstractVisualization, view:VisualizationView, evt) {
if(view && view.camera){
if(OncoData.instance.inHistoryUndoRedo == false) {
let orbitControls = view.controls;
let dist:number = view.controls.target.distanceTo(view.controls.object.position)
let sanity = view.camera.position.length();
let zoom:number = this.originalZoomDistance / dist;
let lastAngles = orbitControls['lastAngles'];
if (lastAngles.azimuthal == orbitControls.getAzimuthalAngle().toPrecision(6) &&
lastAngles.polar == orbitControls.getPolarAngle().toPrecision(6)) {
// Angles are the same as last change, so this change is just zooming?
// Need to check against last target too.
if (dist.toPrecision(11) != graph.lastZoomDistance.toPrecision(11)){ // dist was zoom
let oldZoomDistance = graph.lastZoomDistance;
graph.lastZoomDistance = dist; // dist was zoom
graph.adjustGraphDetailsBasedOnZoomChange( oldZoomDistance, dist, true);
}
} else {
// console.log('just rotation change');
lastAngles.azimuthal = orbitControls.getAzimuthalAngle().toPrecision(6);
lastAngles.polar = orbitControls.getPolarAngle().toPrecision(6);
}
} else {
// console.log('Avoiding orbit changes while in undo.');
}
}
}
destroy() {
this.view.controls.removeEventListener('change', this.createdOrbitControlsChangeFunction);
// TEMPNOTE: Adding "if" wrappers so we can call this super.destroy() from any child,
// even if it has not set up each of these objects.
if (this.$MouseDown) {
this.$MouseDown.unsubscribe();
}
if (this.$MouseMove) {
this.$MouseMove.unsubscribe();
}
if (this.$MouseUp) {
this.$MouseUp.unsubscribe();
}
if (this.$KeyPress) {
this.$KeyPress.unsubscribe();
}
if (this.$KeyDown) {
this.$KeyDown.unsubscribe();
}
if (this.$KeyUp) {
this.$KeyUp.unsubscribe();
}
if (this.$onHideLabels) {
this.$onHideLabels.unsubscribe();
}
if (this.$onShowLabels) {
this.$onShowLabels.unsubscribe();
}
if (this.$onShowTooltip) {
this.$onShowTooltip.unsubscribe();
}
if (this.$onHideTooltip) {
this.$onHideTooltip.unsubscribe();
}
if (this.labelController) {
this.labelController.destroy();
}
if (this.tooltipController) {
this.tooltipController.destroy();
}
this.enable(false);
}
preRender(views: VisualizationView[], layout: WorkspaceLayoutEnum, renderer: THREE.Renderer): void {}
public onKeyDown(e: KeyboardEvent): void {}
public onKeyUp(e: KeyboardEvent): void {}
public onKeyPress(e: KeyboardEvent): void {}
public onMouseDown(e: ChartEvent): void {}
public onMouseUp(e: ChartEvent): void {}
public onMouseMove(e: ChartEvent): void {
// console.log('lowlevel onMouseMove, this._config.graph=' + this._config.graph.toString());
if(window['globalOncoscapeMenuState'] == 1) {
console.log('MENU ON, inside visabstract mousemove');
return;
}
let self = this;
let xoffset = 0;
let x = e.event.clientX;
if (this._config.graph === GraphEnum.GRAPH_B) {
x -= this.view.viewport.width;
xoffset = this.view.viewport.width;
}
let y = e.event.clientY;
this.tooltipController.manualMouseMove(e, xoffset);
if (this.tooltip === '') {
return;
} else {
}
if((e.event.buttons == 0) && this.tooltipController.mouseIsInside == false){
this.tooltips.innerHTML = TooltipController.generateHtml(
this.view,
this.entity,
{
position: new Vector3(x + 15, e.event.clientY - 20, 0),
userData: { tooltip: this.tooltip, color: this.tooltipColor }
},
this.tooltipOptions
);
} else {
}
}
public onShowTooltip(e: { text: string; color: string; event: ChartEvent; complexTooltip: ComplexTooltipData}): void {
// console.log('mjtooltip onShowTooltip')
if(e.complexTooltip == null) {
this.tooltip = e.text;
} else {
this.tooltip = e.complexTooltip;
}
this.tooltipColor = e.color;
// ===>this.onMouseMove(e.event);
}
public onHideTooltip(): void {
this.tooltip = '';
this.tooltips.innerText = '';
}
public onShowLabels(): void {}
public onHideLabels(): void {
this.labels.innerHTML = '';
}
constructor() {}
}
|
"""
Unit and regression test for kissim.encoding.FingerprintGeneratorNormalized.
"""
import pytest
import numpy as np
from kissim.encoding import FingerprintGeneratorNormalized
class TestFingerprintGeneratorNormalized:
"""
Test normalized fingerprints class.
"""
@pytest.mark.parametrize(
"method, fine_grained, structure_klifs_id, fingerprint_values_array_sum, fingerprint_normalized_values_array_sum",
[
("min_max", True, 109, 5108.2262, 409.0577),
("min_max", False, 109, 5108.2262, 398.9509),
],
)
def test_from_fingerprint_generator(
self,
fingerprint_generator,
method,
fine_grained,
structure_klifs_id,
fingerprint_values_array_sum,
fingerprint_normalized_values_array_sum,
):
"""
Test for the first fingerprint in the template fingerprints if the sum of unnormalized and
normalized fingerprint values is correct.
"""
fingerprint_generator_normalized = (
FingerprintGeneratorNormalized.from_fingerprint_generator(
fingerprint_generator, method, fine_grained
)
)
fingerprint = fingerprint_generator.data[structure_klifs_id]
fingerprint_normalized = fingerprint_generator_normalized.data[structure_klifs_id]
fingerprint_values_array_sum_calculated = np.nansum(fingerprint.values_array())
assert (
pytest.approx(fingerprint_values_array_sum_calculated, abs=1e-4)
== fingerprint_values_array_sum
)
fingerprint_normalized_values_array_sum_calculated = np.nansum(
fingerprint_normalized.values_array()
)
assert (
pytest.approx(fingerprint_normalized_values_array_sum_calculated, abs=1e-4)
== fingerprint_normalized_values_array_sum
)
|
class PEReadUploaderTest:
'''
Module Name:
PEReadUploaderTest
Module Description:
A KBase module to wrap the MegaHit package.
'''
######## WARNING FOR GEVENT USERS #######
# Since asynchronous IO can lead to methods - even the same method -
# interrupting each other, you must be *very* careful when using global
# state. A method could easily clobber the state set by another while
# the latter method is running.
#########################################
#BEGIN_CLASS_HEADER
# Helper script borrowed from the transform service, logger removed
def upload_file_to_shock(self,
shock_service_url = None,
filePath = None,
ssl_verify = True,
token = None):
"""
Use HTTP multi-part POST to save a file to a SHOCK instance.
"""
if token is None:
raise Exception("Authentication token required!")
#build the header
header = dict()
header["Authorization"] = "Oauth {0}".format(token)
if filePath is None:
raise Exception("No file given for upload to SHOCK!")
dataFile = open(os.path.abspath(filePath), 'rb')
m = MultipartEncoder(fields={'upload': (os.path.split(filePath)[-1], dataFile)})
header['Content-Type'] = m.content_type
#logger.info("Sending {0} to {1}".format(filePath,shock_service_url))
try:
response = requests.post(shock_service_url + "/node", headers=header, data=m, allow_redirects=True, verify=ssl_verify)
dataFile.close()
except:
dataFile.close()
raise
if not response.ok:
response.raise_for_status()
result = response.json()
if result['error']:
raise Exception(result['error'][0])
else:
return result["data"]
#END_CLASS_HEADER
# config contains contents of config file in a hash or None if it couldn't
# be found
def __init__(self, config):
#BEGIN_CONSTRUCTOR
self.workspaceURL = config['workspace-url']
self.shockURL = config['shock-url']
self.handleURL = config['handle-service-url']
self.scratch = os.path.abspath(config['scratch'])
print("Handle URL:")
print(self.handleURL)
# HACK!! temporary hack for issue where megahit fails on mac because of silent named pipe error
#self.host_scratch = self.scratch
self.scratch = os.path.join('/kb','module','local_scratch')
# end hack
if not os.path.exists(self.scratch):
os.makedirs(self.scratch)
#END_CONSTRUCTOR
pass
def upload(self, ctx, params):
# ctx is the context object
# return variables are: output
#BEGIN upload
print('Parameters:')
pprint(params)
# 0) download file from shock
### NOTE: this section is what could be replaced by the transform services
forward_reads_file_location = os.path.join(self.scratch,'f1.fq')
forward_reads_file = open(forward_reads_file_location, 'w', 0)
print('downloading reads file from staging: '+str(forward_reads_file_location))
headers = {'Authorization': 'OAuth '+ctx['token']}
r = requests.get(self.shockURL+'/node/'+params['fastqFile1']+'?download', stream=True, headers=headers)
for chunk in r.iter_content(1024):
forward_reads_file.write(chunk)
forward_reads_file.close();
print('done downloading')
# 1) upload files to shock
token = ctx['token']
forward_shock_file = self.upload_file_to_shock(
shock_service_url = self.shockURL,
filePath = forward_reads_file_location,
token = token
)
pprint(forward_shock_file)
# 2) create handle
hs = HandleService(url=self.handleURL, token=token)
forward_handle = hs.persist_handle({
'id' : forward_shock_file['id'],
'type' : 'shock',
'url' : self.shockURL,
'file_name': forward_shock_file['file']['name'],
'remote_md5': forward_shock_file['file']['checksum']['md5']})
# 3) save to WS
paired_end_library = {
'lib1': {
'file': {
'hid':forward_handle,
'file_name': forward_shock_file['file']['name'],
'id': forward_shock_file['id'],
'url': self.shockURL,
'type':'shock',
'remote_md5':forward_shock_file['file']['checksum']['md5']
},
'encoding':'UTF8',
'type':'fastq',
'size':forward_shock_file['file']['size']
},
'interleaved':1,
'sequencing_tech':'artificial reads'
}
provenance = [{}]
if 'provenance' in ctx:
provenance = ctx['provenance']
ws = workspaceService(self.workspaceURL, token=ctx['token'])
new_obj_info = ws.save_objects({
'workspace':params['workspace_name'],
'objects':[
{
'type':'KBaseFile.PairedEndLibrary',
'data':paired_end_library,
'name':params['read_library_name'],
'meta':{},
'provenance':provenance
}]
})
new_obj_info = new_obj_info[0]
print('saved data to WS:')
pprint(new_obj_info)
# create a Report
report = ''
report += 'Uploaded read library to: '+params['workspace_name']+'/'+params['read_library_name']+'\n'
reportObj = {
'objects_created':[{'ref':params['workspace_name']+'/'+params['read_library_name'], 'description':'Uploaded reads library'}],
'text_message':report
}
reportName = 'pe_uploader_report'+str(hex(uuid.getnode()))
report_obj_info = ws.save_objects({
'id':new_obj_info[6],
'objects':[
{
'type':'KBaseReport.Report',
'data':reportObj,
'name':reportName,
'meta':{},
'hidden':1,
'provenance':provenance
}
]
})[0]
output = { 'report_name': reportName, 'report_ref': str(report_obj_info[6]) + '/' + str(report_obj_info[0]) + '/' + str(report_obj_info[4]) }
print('all done!')
#END upload
# At some point might do deeper type checking...
if not isinstance(output, dict):
raise ValueError('Method upload return value ' +
'output is not type dict as required.')
# return the results
return [output] |
Premotor Potential Study for Diagnosis of Carpal Tunnel Syndrome.
INTRODUCTION
The second lumbrical-interossei latency difference test (2LINT) is used frequently for electrodiagnosis of carpal tunnel syndrome (CTS). A premotor potential observed with 2LINT has been identified as a median-nerve sensory nerve action potential. We evaluated the utility of the premotor potential latency analysis (i.e., premotor potential study; PPS) for CTS electrodiagnosis.
METHODS
Sensitivity, specificity, and percentage "no evoked response" (%NER) values were compared prospectively among PPS, median-nerve sensory nerve-conduction studies (NCSs) for digits 1, 2, and 4, and palmar mixed NCS.
RESULTS
Sixty-four healthy control hands and 104 hands with CTS were enrolled in this study. PPS sensitivity was superior to other sensory/mixed NCSs (75% vs. 42%-62%). All NCS specificities were acceptable (95%-97%). The %NER of PPS was lower than that of other NCSs (13% vs. 25%-44%).
CONCLUSION
Premotor potential could be evoked in more CTS hands and was the most sensitive among median-nerve sensory and mixed NCSs. Therefore, we could use the 2LINT with PPS as median and ulnar motor NCS as well as median sensory NCS. |
/**
*
* Generic controller to select a business group
*
* @author srosse, [email protected], http://www.frentix.com
*/
public class SelectBusinessGroupController extends AbstractBusinessGroupListController {
private FlexiFiltersTab bookmarkTab;
private FlexiFiltersTab ownedGroupsTab;
private FlexiFiltersTab courseGroupsTab;
public SelectBusinessGroupController(UserRequest ureq, WindowControl wControl, BusinessGroupViewFilter filter, Object uobject) {
super(ureq, wControl, "group_list", false, "sel-search", true, uobject);
setFilter(filter);
selectFilterTab(ureq, bookmarkTab);
if(isEmpty()) {
selectFilterTab(ureq, ownedGroupsTab);
}
}
@Override
protected boolean canCreateBusinessGroup() {
return false;
}
@Override
protected void initButtons(FormItemContainer formLayout, UserRequest ureq) {
initButtons(formLayout, ureq, false, true, false, false);
}
@Override
protected FlexiTableColumnModel initColumnModel() {
FlexiTableColumnModel columnsModel = FlexiTableDataModelFactory.createFlexiTableColumnModel();
//mark
columnsModel.addFlexiColumnModel(new DefaultFlexiColumnModel(Cols.mark));
//group name
columnsModel.addFlexiColumnModel(new DefaultFlexiColumnModel(Cols.name.i18nHeaderKey(), Cols.name.ordinal(), TABLE_ACTION_LAUNCH,
true, Cols.name.name(), new StaticFlexiCellRenderer(TABLE_ACTION_LAUNCH, new BusinessGroupNameCellRenderer())));
//id and reference
columnsModel.addFlexiColumnModel(new DefaultFlexiColumnModel(false, Cols.key));
if(groupModule.isManagedBusinessGroups()) {
columnsModel.addFlexiColumnModel(new DefaultFlexiColumnModel(false, Cols.externalId));
}
//description
columnsModel.addFlexiColumnModel(new DefaultFlexiColumnModel(false, Cols.description.i18nHeaderKey(), Cols.description.ordinal(),
false, null, FlexiColumnModel.ALIGNMENT_LEFT, new TextFlexiCellRenderer(EscapeMode.antisamy)));
//courses
columnsModel.addFlexiColumnModel(new DefaultFlexiColumnModel(true, Cols.resources.i18nHeaderKey(), Cols.resources.ordinal(),
true, Cols.resources.name(), FlexiColumnModel.ALIGNMENT_LEFT, new BGResourcesCellRenderer(flc)));
//stats
DefaultFlexiColumnModel tutorColumnModel = new DefaultFlexiColumnModel(true, Cols.tutorsCount);
tutorColumnModel.setAlignment(FlexiColumnModel.ALIGNMENT_RIGHT);
tutorColumnModel.setHeaderAlignment(FlexiColumnModel.ALIGNMENT_RIGHT);
columnsModel.addFlexiColumnModel(tutorColumnModel);
DefaultFlexiColumnModel participantsColumnModel = new DefaultFlexiColumnModel(true, Cols.participantsCount);
participantsColumnModel.setAlignment(FlexiColumnModel.ALIGNMENT_RIGHT);
participantsColumnModel.setHeaderAlignment(FlexiColumnModel.ALIGNMENT_RIGHT);
columnsModel.addFlexiColumnModel(participantsColumnModel);
DefaultFlexiColumnModel freePlacesColumnModel = new DefaultFlexiColumnModel(true, Cols.freePlaces.i18nHeaderKey(),
Cols.freePlaces.ordinal(), true, Cols.freePlaces.name(), FlexiColumnModel.ALIGNMENT_LEFT,
new TextFlexiCellRenderer(EscapeMode.none));
freePlacesColumnModel.setAlignment(FlexiColumnModel.ALIGNMENT_RIGHT);
freePlacesColumnModel.setHeaderAlignment(FlexiColumnModel.ALIGNMENT_RIGHT);
columnsModel.addFlexiColumnModel(freePlacesColumnModel);
DefaultFlexiColumnModel waitingListColumnModel = new DefaultFlexiColumnModel(true, Cols.waitingListCount);
waitingListColumnModel.setAlignment(FlexiColumnModel.ALIGNMENT_RIGHT);
waitingListColumnModel.setHeaderAlignment(FlexiColumnModel.ALIGNMENT_RIGHT);
columnsModel.addFlexiColumnModel(waitingListColumnModel);
//actions
columnsModel.addFlexiColumnModel(new DefaultFlexiColumnModel("select", translate("select"), TABLE_ACTION_SELECT));
return columnsModel;
}
@Override
protected void initFilterTabs() {
List<FlexiFiltersTab> tabs = new ArrayList<>();
bookmarkTab = FlexiFiltersTabFactory.tabWithImplicitFilters("Bookmarks", translate("marked.groups"),
TabSelectionBehavior.reloadData, List.of(FlexiTableFilterValue.valueOf(BGSearchFilter.MARKED, "marked")));
bookmarkTab.setElementCssClass("o_sel_group_bookmarked_groups");
tabs.add(bookmarkTab);
ownedGroupsTab = FlexiFiltersTabFactory.tabWithImplicitFilters("MyGroups", translate("owned.groups.2"),
TabSelectionBehavior.reloadData, List.of(FlexiTableFilterValue.valueOf(BGSearchFilter.ROLE, "all")));
ownedGroupsTab.setElementCssClass("o_sel_group_groups");
tabs.add(ownedGroupsTab);
courseGroupsTab = FlexiFiltersTabFactory.tabWithImplicitFilters("Courses", translate("course.groups"),
TabSelectionBehavior.reloadData, List.of(FlexiTableFilterValue.valueOf(BGSearchFilter.AUTHOR, "conn")));
courseGroupsTab.setElementCssClass("o_sel_group_courses");
tabs.add(courseGroupsTab);
FlexiFiltersTab searchTab = FlexiFiltersTabFactory.tab("Search", translate("search.generic"), TabSelectionBehavior.clear);
searchTab.setElementCssClass("o_sel_group_search_groups");
searchTab.setPosition(FlexiFilterTabPosition.right);
searchTab.setLargeSearch(true);
searchTab.setFiltersExpanded(true);
tabs.add(searchTab);
tableEl.setFilterTabs(true, tabs);
}
@Override
protected void initFilters() {
tableEl.setSearchEnabled(true);
List<FlexiTableExtendedFilter> filters = new ArrayList<>();
// external id
filters.add(new FlexiTableTextFilter(translate("cif.id"), BGSearchFilter.ID.name(), admin));
// bookmarks
SelectionValues bookmarkValues = new SelectionValues();
bookmarkValues.add(SelectionValues.entry("mark", translate("cif.bookmarks")));
filters.add(new FlexiTableMultiSelectionFilter(translate("cif.bookmarks"), BGSearchFilter.MARKED.name(), bookmarkValues, true));
// roles
SelectionValues roleValues = new SelectionValues();
if(admin) {
roleValues.add(SelectionValues.entry("none", translate("search.none")));
}
roleValues.add(SelectionValues.entry("all", translate("search.all")));
roleValues.add(SelectionValues.entry("owner", translate("search.owner")));
roleValues.add(SelectionValues.entry("attendee", translate("search.attendee")));
roleValues.add(SelectionValues.entry("waiting", translate("search.waiting")));
filters.add(new FlexiTableSingleSelectionFilter(translate("search.roles"), BGSearchFilter.ROLE.name(), roleValues, true));
// author connection of groups to courses
SelectionValues authorValues = new SelectionValues();
authorValues.add(SelectionValues.entry("conn", translate("course.groups")));
filters.add(new FlexiTableMultiSelectionFilter(translate("course.groups"), BGSearchFilter.AUTHOR.name(), authorValues, true));
if(admin) {
// coaches
filters.add(new FlexiTableTextFilter(translate("cif.owner"), BGSearchFilter.COACH.name(), false));
// description
filters.add(new FlexiTableTextFilter(translate("cif.description"), BGSearchFilter.DESCRIPTION.name(), false));
// course title
filters.add(new FlexiTableTextFilter(translate("cif.coursetitle"), BGSearchFilter.COURSETITLE.name(), false));
// published
SelectionValues yesNoValues = new SelectionValues();
yesNoValues.add(SelectionValues.entry("all", translate("search.all")));
yesNoValues.add(SelectionValues.entry("yes", translate("search.yes")));
yesNoValues.add(SelectionValues.entry("no", translate("search.no")));
filters.add(new FlexiTableSingleSelectionFilter(translate("search.open"), BGSearchFilter.OPEN.name(), yesNoValues, true));
//resources
filters.add(new FlexiTableSingleSelectionFilter(translate("search.resources"), BGSearchFilter.RESOURCES.name(), yesNoValues, true));
// last visit
filters.add(new FlexiTableTextFilter(translate("search.last.usage"), BGSearchFilter.LASTVISIT.name(), false));
}
tableEl.setFilters(true, filters, true, false);
}
@Override
protected List<BGTableItem> searchTableItems(BusinessGroupQueryParams params) {
List<StatisticsBusinessGroupRow> rows = businessGroupService.findBusinessGroupsForSelection(params, getIdentity());
List<BGTableItem> items = new ArrayList<>(rows.size());
for(StatisticsBusinessGroupRow row:rows) {
FormLink markLink = uifactory.addFormLink("mark_" + row.getKey(), "mark", "", null, null, Link.NONTRANSLATED);
markLink.setIconLeftCSS(row.isMarked() ? Mark.MARK_CSS_LARGE : Mark.MARK_ADD_CSS_LARGE);
BGTableItem item = new BGTableItem(row, markLink, Boolean.FALSE, Boolean.FALSE);
item.setNumOfOwners(row.getNumOfCoaches());
item.setNumOfParticipants(row.getNumOfParticipants());
item.setNumWaiting(row.getNumWaiting());
item.setNumOfPendings(row.getNumPending());
items.add(item);
}
return items;
}
@Override
protected BusinessGroupQueryParams getDefaultSearchParams() {
BusinessGroupQueryParams params = new BusinessGroupQueryParams();
params.setTechnicalTypes(List.of(BusinessGroup.BUSINESS_TYPE));
params.setGroupStatus(List.of(BusinessGroupStatusEnum.active));
return params;
}
@Override
protected void changeFilterTab(UserRequest ureq, FlexiFiltersTab tab) {
//
}
protected void updateSearch(UserRequest ureq) {
doSearch(ureq, (FlexiFiltersTab)null);
}
} |
Proteome and secretome profiling of zinc availability in Cryptococcus neoformans identifies Wos2 as a subtle influencer of fungal virulence determinants
Background Fungal infections impact over 25% of the global population. For the opportunistic fungal pathogen, Cryptococcus neoformans, infection leads to cryptococcosis. In the presence of the host, disease is enabled by elaboration of sophisticated virulence determinants, including polysaccharide capsule, melanin, thermotolerance, and extracellular enzymes. Conversely, the host protects itself from fungal invasion by regulating and sequestering transition metals (e.g., iron, zinc, copper) important for microbial growth and survival. Results Here, we explore the intricate relationship between zinc availability and fungal virulence via mass spectrometry-based quantitative proteomics. We observe a core proteome along with a distinct zinc-regulated protein-level signature demonstrating a shift away from transport and ion binding under zinc-replete conditions towards transcription and metal acquisition under zinc-limited conditions. In addition, we revealed a novel connection among zinc availability, thermotolerance, as well as capsule and melanin production through the detection of a Wos2 ortholog in the secretome under replete conditions. Conclusions Overall, we provide new biological insight into cellular remodeling at the protein level of C. neoformans under regulated zinc conditions and uncover a novel connection between zinc homeostasis and fungal virulence determinants. Supplementary Information The online version contains supplementary material available at 10.1186/s12866-021-02410-z.
emergence and evolution of resistant strains . C. neoformans is an opportunistic fungus found ubiquitously within the environment and is equipped with sophisticated virulence determinants, including a polysaccharide capsule, melanin, thermotolerance, and extracellular enzymes . This arsenal of determinants provides resources to modulate the host immune system and promote fungal survival in over 230,000 immunocompromised individuals (e.g., HIV/AIDS patients) annually . To overcome the expanding dangers of serious fungal infections, it is crucial to better understand the fungi-specific mechanisms required to infect and survive within a human host.
Transition metals, including iron, copper, and zinc, are fundamental requirements for the survival of all living organisms . The concept of transition metal homeostasis is a well-established research discipline concerning pathogenic microbes. The connection between virulence and trace elements of transition metals is dominated mainly by the study of iron limitation involving acquisition, storage, and detoxification . However, beyond the iron paradigm, zinc is an essential cofactor of many proteins providing pivotal catalytic and structural roles; zinc-binding proteins constitute approximately 9% of the eukaryote and 5-6% of the prokaryote proteome . Despite its inactive redox status, excess zinc induces cellular toxicity and physiological stress, which includes protein inhibition from binding unfavourably to sites not normally associated with a metal ion . Additionally, previous studies report the impediment of fungal growth under reduced zinc conditions in minimal and chelated mediums . Therefore, it is necessary to tightly regulate intracellular labile zinc content to maintain precise metal homeostasis. Mammalian hosts manipulate these delicate margins of nutritional requirements as a sophisticated technique to combat pathogenic microbes from securing essential micronutrients. Moreover, host cells may also release transition metals targeted towards invading microbes to lethal or growth-inhibiting concentrations. These collective protective measures have been termed 'nutritional immunity' .
Pathogenic microorganisms have evolved counterattack measures to facilitate zinc assimilation and ensure survival within the host. We recently explored the impact of zinc availability in the bacterial pathogen, Klebsiella pneumoniae through proteomic profiling and uncovered a novel connection between zinc homeostasis and capsule regulation . For fungal pathogens, strategies to maintain zinc homeostasis are best characterized in the model organism Saccharomyces cerevisiae, in which zinc assimilation in zinc-limiting conditions is mainly allocated by the Zrt-Irt-like (Zip) protein family of membrane transporters . In addition, C. neoformans ZIP1 deficient mutants demonstrated zinc limited growth defects, reduced infectivity towards host immune cells, and impaired virulence in a murine model of cryptococcal infection . Conversely, cation diffusion facilitator proteins are involved in processes of zinc-excess (or replete) conditions and mediate intracellular zinc transport to organelles for storage or detoxification, suggesting homeostasis of microbial and environmental zinc levels is tightly regulated through protein activation and cellular remodeling . Moreover, heat shock proteins (HSPs), including Wos2 (P21), a homolog of P23 in Schizosaccharomyces pombe, are involved in cell cycle progression and show a decrease in expression when cells enter stationary growth or are grown under nutrient limited conditions . These findings demonstrate a connection between cell cycle progression and metal ion homeostasis. Given the crucial role of master regulators (e.g., Zap1, a zinc finger transcription factor) of metal ion homeostasis in biological processes of fungal pathogens, there is a need to comprehensively define zinc metabolism determinants in relation to fungal survival and development . Mass spectrometry-based proteomics is a technology capable of defining changes in cellular remodeling of a pathogen under distinct growth conditions, and detecting proteins critical to microbial adaptation .
Here, we describe the first quantitative proteomics investigation focused on how a zinc-limited environment modulates the cellular proteome and secretome of C. neoformans (Fig. 1). A comparative analysis of the physiological responses of fungal proliferation in zinc-limited and -replete conditions identified differentially abundant proteins. Investigation of proteins produced during zinc starvation revealed a shift of the signature proteomic profile towards transcription and metal acquisition, including a significant increase in abundance for the zinc transporter, ZIP1. Conversely, we detected a Wos2 protein (a HSP90 co-chaperone) at high abundance within the extracellular environment under replete conditions. Deletion of WOS2 (CNAG_07558) revealed subtle phenotypic changes of fungal thermotolerance, zinc utilization, melanin production, and capsule elaboration. These data suggest a novel connection between regulation of zinc homeostasis and fungal virulence determinants at the protein level. Overall, this study provides crucial details to bridge the gaps in knowledge surrounding the global impact of zinc deprivation in the pathogen C. neoformans.
Modulating zinc availability promotes cellular remodeling of the C. neoformans proteome
To explore the relationship between zinc availability and protein production in C. neoformans, we profiled the cellular proteome (cell pellet) and secretome (extracellular environment) under zinc-limited and -replete conditions using mass spectrometry-based proteomics (Fig. 1). We hypothesized that changes to zinc availability in the culture medium would influence the production of proteins to promote fungal survival and adaptation. This information drives our understanding of fungal response to changing environmental conditions and uncovers proteins critical to cellular remodeling for an effective response.
Within the cell pellet, we detected and quantified 3411 unique proteins (3071 proteins after valid value filtering) across the samples, representing 46% of the proteome of C. neoformans. Of these, 2858 proteins were identified under both zinc-limited and -replete conditions, designated as a core proteome, whereas 114 proteins were detected only under zinc-limited conditions and 99 proteins were detected only under zinc-replete conditions ( Fig. 2A). Of the unique proteins under zinc-limited conditions, we observed the largest categories of proteins associated with 'metabolism and biosynthesis' , 'transport and ion binding' , and 'uncharacterized' (Fig. 2B). These were also well-represented categories under zinc-replete conditions, but to a lesser extent for 'transport and ion binding' and 'uncharacterized' compared to a greater emphasis on 'translation' as well as 'cell assembly and growth' (Fig. 2C). Taken together, this qualitative assessment highlights a zinc-regulated protein signature within the cellular proteome of C. neoformans.
To assess factors influencing the proteomic profiling, we performed a principal component analysis (PCA), which indicated separation between zinc-limited and -replete conditions as the largest component of distinction (component 1, 32.6%), while biological variability amongst the replicates accounted for the second most impactful component (component 2, 23.9%) (Fig. 3A). Biological replicate reproducibility was 96.8-97.0%. (Supp. Fig. 1). Next, we analyzed the proteomics data to detect proteins with significant changes in abundance under the different zinc conditions to identify specific proteins impacted by modified zinc availability (Fig. 3B). Under zinc-limited conditions, we observed a significant increase (p-value ≤0.05; FDR = 0.05) in abundance of a zinc transporter, ZIP1 (CNAG_00895; > 5-fold), aligning with previously reported transcript profiling of zinc limitation in C. neoformans . This finding supports our experimental design and ability to profile zinc-regulated changes in the fungal proteome. We also detected a cobalamin synthesis protein (CNAG_02548; > 7-fold) with higher abundance under limited conditions, which builds upon a known relationship between cobalamin biosynthesis and zinc in microbial systems . On the contrary, under replete conditions, we observed a significant increase in abundance of a ribosomal protein (CNAG_03127; > 5-fold), supporting our observation of translation-associated proteins identified under replete Fig. 1 Overview of experimental design and mass spectrometry workflow. Cell pellets and supernatant from C. neoformans cultured in minimal medium (MM) MM + Zn or MM-Zn were subjected to protein extraction (e.g., sonication and detergent) and enzyme digestion (e.g., trypsin/Lys-C) followed by purification (C18 STAGE-tips) and measurement on a quadrupole orbitrap mass spectrometer . Data analysis and visualization performed with MaxQuant and Perseus. Experiment performed in biological quadruplicate. Figure generated with Biore nder. com conditions, and a hypothetical protein (CNAG_01290; 6-fold) with no known orthologs.
To define a comprehensive impact of zinc availability on fungal cells by considering the abundance of all proteins (and not only those with significant differences in abundance) we performed a 1D annotation enrichment (i.e., tests for every annotation term whether the corresponding numerical values have a preference to be systematically larger or smaller than the global distribution of the values for all proteins ) based on Gene Ontology Biological Processes (Fig. 3C). Here, we observed the greatest enrichment of proteins associated with 'translation' and 'macromolecule biosynthetic process' under zinc-replete conditions, compared to 'cellular process' and 'cellular and primary metabolic process' under zinc-limited conditions. Taken together, enrichment of cellular and metabolic processes under zinc-limited conditions may be associated with intrinsic responses to a nutrient-poor environment. However, our assessment of specific proteins with altered abundance between the tested growth conditions teases apart nutrient-limited vs. zinc-specific responses, demonstrating cellular remodeling at the protein level influenced by zinc availability.
Zinc availability alters secreted protein profiles
The extracellular environment plays an important role in influencing the secretion and/or release of proteins for nutrient sensing and acquisition in biological systems . Here, we profiled the supernatant (i.e., extracellular environment) of C. neoformans grown in zinc-limited vs.
-replete conditions to evaluate the role of zinc on fungal secretion. We identified 33 proteins (22 proteins after valid value filtering), of which, 14 were common between the conditions, with three proteins unique to zinc-limited conditions and five proteins unique to zinc-replete conditions (Fig. 4A). A PCA plot demonstrated the largest component of separation between the data sets to be zinc-regulated (component 1, 48.9%) and the second component associated with biological variability (component 2, 23.5%) (Fig. 4B). Biological replicate reproducibility was 83.6-89.4%, demonstrating good reproducibility among the supernatant samples. (Supp. Fig. 2). Investigation into changes in protein abundance influenced by zinc availability revealed two proteins with a significant increase in abundance (p-value ≤0.05; FDR = 0.05) under limited conditions, including actin (CNAG_00483; > 4-fold) and ATP-citrate synthase (CNAG_04640; > 1-fold) (Fig. 4C). Detection of these proteins under zinc-regulation in fungal pathogens is supported by previous work in Paracoccidioides . Conversely, three proteins showed a significant increase in abundance under replete conditions, including a hypothetical protein (CNAG_07558; > 1-fold), a HSP60-like protein (CNAG_03891; > 2-fold), and a ribosomal protein (CNAG_04448; > 1-fold). Notably, several proteins identified in the supernatant with traditional intracellular roles (e.g., actin, ribosomal, chaperone) were previously detected in extracellular vesicles of C. neoformans upon proteome profiling, conferring a role for these proteins in vesicular transport . Moreover, metabolic, ribosomal, and chaperone proteins have been referred to as 'moonlighting proteins' or proteins with changing roles given the environmental conditions. For example, classically intracellular proteins may be produced and released into the environment to assist with colonization and invasion of host cells, as described in other fungal pathogens .
In Silico assessment of zinc-regulated proteins
Based on our proteomic profiling, we identified four proteins with significant changes in protein abundance (two increased in replete; two increased in limited) in the cellular proteome and five proteins with significant changes in abundance (three increased in replete; two increased in limited) in the secretome (Table 1). Given previous reports of Wos2 (P21; P23 homolog in S. pombe) showing decreased expression in nutrient-limited conditions , and our supporting observation of increased production of Wos2 under nutrient-replete conditions, we further explored the role of this protein in C. neoformans (Supp. Fig. 3).
Wos2 is a HSP90 co-chaperone associated with capsule growth and cell cycle progression that interacts with additional chaperones and HSP detected within C. neoformans vesicles, including CNAG_06150 (CNM01520), as well as metal ion binding proteins (e.g., CNAG_01496; CNC06840) ( Fig. 4D; 4E) . The increased abundance of Wos2 under replete conditions suggests a connection between zinc availability and production of virulence determinants in the presence of zinc.
Wos2 protein influences fungal virulence
To further explore the role of Wos2 in C. neoformans, we constructed and characterized a deletion strain for potential roles in fungal virulence; deletion of the gene was confirmed by PCR and whole genome assembly (Supp. Fig. 4). To begin, we assessed a role for Wos2 in thermotolerance by comparing the deletion strains to WT at 30 °C and 37 °C in zinc-replete conditions to promote production of Wos2 in the WT for a true comparison with the mutant strain. We observed similar growth for WT and wos2Δ at 30 °C (Fig. 5A). Conversely, we observed a significant decrease in growth of the deletion strains at 37 °C compared to WT (Fig. 5A). Next, we evaluated differences in fungal growth under zinc-limited vs.
-replete conditions at 30 °C and 37 °C between the strains and observed an increase in growth in the presence of excess zinc at both temperatures (Fig. 5B). We also evaluated a connection between Wos2 and melanin production and observed a slight increase in melanin production in the deletion strains at 37 °C relative to the WT strain (Fig. 5C). These data support a role for Wos2 in thermotolerance, zinc utilization, and melanin production of C. neoformans.
Given the established connection among Wos2, cell cycle progression, and capsule production , we evaluated the impact of deleting WOS2 from C. neoformans H99 on capsule size. Visually, we observed an increase in cell size but a decrease in capsule size in the deletion strains relative to the WT and complemented strains (Fig. 6A). This data was supported by measuring cell diameter and capsule thickness for 50 cells, which showed a significant decrease in the raio of capsule to cell diameter in the wos2Δ strains relative to WT and the complemented strains (Fig. 6B). Lastly, based on our observation that deleting WOS2 from C. neoformans influences the production of classical fungal virulence determinants, and the role of capsule production in protecting the fungus from the innate immune response , we tested an infection model in immortalized macrophages and measured changes in macrophage cell death over a time course of infection. Here, performing antibody-associated opsonization prior to co-culture of the macrophages with cryptococcal cells, we observed a consistent release of lactate dehydrogenase (LDH), supporting similar patterns of host cell death, among the strains relative to the uninfected control (Fig. 6C). Based on our findings, we propose that WOS2 influences capsule and cell size, but these differences do not correspond to altered infection of macrophages in an in vitro model.
Discussion
In this study, we use high resolution mass spectrometry-based proteomics to identify and quantify changes in protein abundance within the fungal pathogen, C. neoformans under zinc-limited and -replete conditions. Our approach confirms the role of a known zinc transporter (Zip1) in transition-metal acquisition through detection under limited conditions in the cellular proteome and uncovers a new connection between Wos2 (CNAG_07558) and zinc homeostasis within the extracellular environment. Moreover, characterization of the WOS2 deletion strain demonstrates a subtle role in thermotolerance, zinc utilization, melanin production, and capsule elaboration. Overall, we provide new biological insight into cellular remodeling at the protein level of C. neoformans under regulated zinc conditions and uncover a novel connection between zinc homeostasis and regulation of fungal virulence determinants. Our detection of a HSP90 co-chaperone (CNAG_07558 ortholog) in the supernatant of C. neoformans under zinc-replete conditions, in combination with known interactions with vesicle-associated proteins, suggests localization of Wos2 to the vesicular fraction. The connection between vesicle production and zinc homeostasis was previously explored with the introduction of zincosomes . Zincosomes are vesicles containing labile zinc observed in both mammalian and yeast cells, they may serve to both detoxify excess zinc and mobilize the metal upon deprivation; however, the exact nature of these compartments, and the mechanisms of action have not been elucidated . In our dataset, the increased cell size for wos2Δ may be associated with a larger vacuole influenced by protein aggregation from a lack of proper folding or degredation and a theory worth exploring further in future studies. We also note that Wos2 or other zinc-associated proteins may assist with detoxification during infection proceeses when zinc may be pumped into the phagosome at high levels to damage engulfed pathogens through intoxification and subsequentely, promote pathogen cell death . Moreover, we identified CNAG_02806 (Zrc1), a critical protein for zinc sequestration and adaptation to zinc excess via vacuole (C. neoformans) and zincosomes (Candida albicans) in our cellular proteome profiling with a higher abundance under replete conditions (2.09-fold; not significantly different) . This similar trend in increased protein abundance between Zrc1 and Wos2 under replete conditions supports our identification of zinc homeostasis-associated proteins within the extracellular environment of C. neoformans. Further exploration into intracellular zinc levels under limited and replete conditions, along with proteomic profiling of intra-and extracellular vesicle contents may provide further evidence of such a regulatory system in C. neoformans.
A connection between regulation of zinc transporters (e.g., ZIP1, ZAP1) and attenuated virulence has been well-defined in C. neoformans and Cryptococcus gattii, respectively, as well as C. albicans, Aspergillus fumigatus, and the plant fungal pathogen, Fusarium oxysporum . In addition, coordinated zinc homeostasis is critical amongst bacterial pathogens for maintaining virulence . These studies underscore the important role zinc plays in microbial pathogenesis and emphasize the outcome on virulence if zinc regulatory mechanisms are altered within the pathogen. However, a link between the production of proteins involved in maintaining zinc homeostasis under nutrient-rich conditions (e.g., zinc replete medium) and virulence has not been explored. Here, we report the novel findings of enhanced production of a virulence determinant (i.e., melanin) for the wos2Δ strains relative to WT. Moreover, our observation of increased cell size in the deletion strains may influence interactions with host cells, as defined for cryptococcal titan cells with roles in fungal virulence . Notably, an in vitro macrophage infection model did not highlight changes in virulence; however, we hypothesize that given the subtle difference in virulence determinant regulation, the fungal strains may differ in their ability to infect and potentially, disseminate within an in vivo murine model of infection. Fungal infections present unique challenges to treatment, including a limited number of effective antifungal agents influenced by host cytotoxicity, intrinsic resistance, and the development and emergence of resistant strains . To overcome such limitations and uncover new drug development pipelines, the discovery of novel agents targeting new pathways (e.g., metal ion homeostasis) are being explored . For example, disruption of essential micronutrient (zinc and iron) homeostasis in fungal pathogens by interfering with metal uptake, transcriptional regulation, or sequestration processes in C. albicans, established a high-throughput drug screening platform . This work presents a method for identification and verification of new antifungal drugs targeting the perturbation of zinc and iron homeostasis using C. albicans as a model fungal pathogen. Given our observation of Wos2 in regulating zinc homeostasis under replete conditions and the influence of WOS2 on cell size and thermotolerance, we anticipate that the protein may serve as a viable target for therapeutic intervention; however, sensitivity to current antifungals (e.g., azoles) is a logical experimental direction to follow in the future .
Lastly, our proteomics profiling identified nine proteins with significant changes in abundance under zinc-limited or -replete conditions. Although, several of these proteins are very well characterized (e.g., CNAG_03127, Ribosomal protein; CNAG_00483, Actin; CNAG_04448, Ribosomal protein; CNAG_04640, ATP-citrate synthase) and/ or their role in nutrient limitation is well defined (e.g., CNAG_00895, solute carrier Zip1), other candidates are Fig. 6 Assessment of capsule production and virulence of C. neoformans. A Capsule production of WT, wos2Δ, and complemented strains measured by India ink staining and differential interference microscopy. Capsule assays performed in LIM at mid-log phase (OD 600nm = 1.0-1.2). Scale bar = 4.5 μm. B Quantification of the ratio between capsule thickness and cell size diameter for WT, wos2Δ, and complemented strains. A minimum of 50 cells were measured for capsule and cell size assays. *denotes significant difference between comparisons to WT by Student's t-test, asterisks as follows: *P < 0.05; **, P < 0.01. C Quantification of LDH release upon macrophage cell death following co-culture with C. neoformans H99, wos2Δ, and complemented strains grown in YPD. Uninfected refers to macrophage only culture. Macrophages undergone opsonization with antibody 18b7 prior to co-culture. Experiment performed in biological triplicate and technical duplicate uncharacterized (e.g., CNAG_01290) and/or their role in zinc homeostasis (e.g., CNAG_02548, cobalamin synthesis; CNAG_03891, Hsp60-like) have yet to be explored. We propose future experimentation to investigate the role of these three proteins in zinc homeostasis and fungal virulence to provide further biological insight into connections between the regulatory systems.
Conclusion
Quantitative proteomic profiling of zinc limitation in C. neoformans supports previously reported transcriptomics datasets through detection of zinc transporters regulated by nutrient limitation. In addition, we uncover an uncharacterized protein (CNAG_07558) orthologous to a Wos2 protein associated with cell cycle progression and capsule production. Characterization of the candidate deletion strain defines new roles for Wos2 in C. neoformans virulence determinant production, supporting the protein's role in maintaining zinc homeostasis under replete conditions. Overall, our findings substantially build upon our knowledge of zinc utilization within the fungal pathogen at the protein level and support further exploration into the connection between zinc availability and fungal virulence in C. neoformans.
Fungal strains, growth conditions and media
Cryptococcus neoformans var. grubii strain H99 (serotype A) was used for all analyses and as a reference strain for mutant construction. The wildtype strain was maintained on yeast peptone dextrose (YPD) medium (2% dextrose, 2% peptone, 1% yeast extract) and all mutant strains were maintained on YPD supplemented with 100 μg/mL nourseothricin (NAT) at 30 °C unless otherwise stated. Zinc minimal media (MM-Zn) was prepared with Chelex ® 100-treated (Bio-Rad) dH 2 O containing 29.4 mM KH 2 PO 4 , 10 mM MgSO 4 -7 H 2 O, 13 mM glycine, 3 μM thiamine, 0.27% dextrose, and supplemented with 10 μM ZnSO 4 (MM + Zn) for replete conditions. MM followed the recipe as above for MM-Zn but with the use of dH 2 O, instead of Chelex ® 100-treated (Bio-Rad) dH 2 O. For in vitro cultures, C. neoformans was pre-cultured in YPD media overnight, followed by subculture in yeast nitrogen base (YNB) medium with amino acids (BD Difco, Franklin Lakes, NJ) supplemented with 0.05% dextrose overnight, and sub-cultured in MM-Zn or MM + Zn and grown to mid-log phase. For macrophage infection, C. neoformans was grown overnight in YPD media at 37 °C, sub-cultured in YPD at 37 °C to mid-log phase. Samples were collected in triplicate for phenotypic and macrophage infection assays, and in quadruplicate for proteomic analyses.
Sample preparation for mass spectrometry analysis
Sample preparation for mass spectrometry was performed as previously described . Briefly, cell pellets were resuspended in 100 mM Tris-HCl (pH 8.5) and lysed using a probe sonicator (Thermo Fisher Scientific). Sodium dodecyl sulphate (SDS) and dithiothreitol (DTT) were added to final concentrations of 2% and 10 mM, respectively, followed by incubation at 95 °C for 10 min with shaking at 800 rpm, and incubation with 55 mM iodoacetamide (IAA) for 20 min in the dark. Next, ice cold 100% acetone was added to the samples to a final concentration of 80% and incubated overnight at − 20 °C. Samples were collected by centrifugation at 10,000 xg, 4 °C, for 10 min, washed with 80% acetone twice, air dried, and resuspended in 8 M urea/40 mM HEPES. Protein concentrations were determined using a bovine serum albumin (BSA) tryptophan assay . Samples were diluted in 50 mM ammonium bicarbonate and normalized to 100 μg of protein prior to overnight digestion with a mixture LysC and trypsin proteases (Promega, protein:enzyme ratio, 50:1). To stop the digestion, 10% v/v trifluoroacetic acid (TFA) was added, and 50 μg of acidified peptides were desalted and purified using C18 (three layers) Stop And Go Extraction (STAGE) tips .
Secretome samples were processed according to an in-solution digestion as previously described . Cellular debris was filtered from the culture supernatant by 0.22 μm syringe filters, then one-third volume of 8 M urea/40 mM HEPES was added to filtered supernatant followed by ultrasonication in ice bath for 15 cycles (30s on/30 s off ). Samples were reduced and alkylated with DTT and IAA, respectively, followed by enzymatic digestion and STAGE-tip purification.
Mass spectrometry
Mass spectrometry was performed as previously described with some modifications . Purified peptides were lyophilized and resuspended in buffer A* (0.1% TFA) and analyzed by nanoflow liquid chromatography on an Ultimate 3000 LC system (Thermo Fisher Scientific) online coupled to QExactive HF quadrupole orbitrap mass spectrometer (Thermo Fisher Scientific). This includes a 5 mm μ-precolumn (Thermo Fisher Scientific) with 300 μm inner diameter filled with 5 μm C18 PepMap100 beads. Separation of peptides occurred on a 15 cm column with 75 μm inner diameter with 2 μm reverse-phase silica beads and directly electrosprayed into the mass spectrometer using a linear gradient from 4 to 30% ACN in 0.1% formic acid over 60 min at a constant flow of 300 nl/min. To clean the column, up to 95% ACN was used as washout following the linear gradient, and re-equilibrated to prepare the column for subsequent runs. The mass spectrometer was operated in data-dependent mode, switching automatically between one full scan and subsequent MS/MS scans of the fifteen most abundant peaks (Top15 method), with full scan (m/z 300-1650) acquired in the Oribtrap analyzer with a resolution of 60,000 at 100 m/z.
Mass spectrometry data processing
Analysis of mass spectrometry raw data files were performed using MaxQuant software (version 1.6.0.26) . The search was completed using the incorporated Andromeda search engine against the reference C. neoformans var. grubii serotype A (strain H99/ATCC 208821) proteome (Aug. 2018; 7,430 sequences) from Uniprot . The parameters established include: trypsin enzyme specificity with 2 max missed cleavages; minimum peptide length of seven amino acids; fixed modifications -carbamidomethylation of cysteine, variable modifications -methionine oxidation and N-acetylation of proteins. Peptide spectral matches were filtered using a target-decoy approach at a false discovery rate (FDR) of 1% with a minimum of two peptides required for protein identification. Relative label-free quantification (LFQ) and match between runs was enabled with a match time window of 0.7 min, in which LFQ used the MaxLFQ algorithm integrated into MaxQuant using a minimum ratio count of one . The. RAW and affiliated files were deposited into the publicly available PRIDE partner database for the ProteomeXchange consortium with the data set identifier: PXD023204.
Bioinformatics
Statistical analysis and data visualization of the Max-Quant-processed data were performed using Perseus (version 1.6.2.2) . Data were prepared by filtering proteins to the reverse database, contaminants, and proteins solely identified by one site, followed by log 2 transformation of LFQ intensities. Identification of protein intensities present in triplicate within one sample set was filtered for statistical processing (3 valid values of 4 replicates in at least one group), missing values were imputed from normal distribution (width: 0.3, downshift: 1.8 standard deviations). Data corresponding to fold changes of growth conditions were identified using a Student's t-test (p ≤ 0.05) with multiple hypothesis testing correction using the Benjamini-Hochberg FDR cut off at 0.05 . Based on assessment of replicate reproducibility and protein identification numbers, one biological replicate from each condition in the cellular proteome data set was removed from further analysis. The projection of data was visualized with a principal component analysis (PCA) and hierarchical clustering (Pearson correlation) by Euclidean distance for replicate reproducibility. For 1D annotation enrichment, Student's t-test (permutation-based FDR = 0.05; S 0 = 1) was performed followed by 1D annotation enrichment function in Perseus using the Student's t-test difference values with an FDR threshold of 0.05 using the Benjamini-Hochberg method. This analysis generates a numerical "score" value, which represents the direction in which the protein LFQ intensities within a given category tend to deviate from the overall distribution of all proteins. Visualization of 1D annotation enrichments by Gene Ontology and Keywords was performed within the RStudio platform (http:// www.R-proje ct. org/) . The STRING functional protein association networks provided visualization of protein networks (https:// stringdb. org) .
Construction of gene deletion and complementation strains
All gene deletion strains were produced by biolistic transformation of linear constructs generated by double joint PCR as previously described . The constructs contained the nourseothricin (NAT) resistance cassette and were prepared with the reported primers and plasmids (Supp. Table 1). Each construct was generated by a first round of PCR amplification of the upstream (5′-gene) and downstream (3′-gene) regions of WOS2 using primers P1/P3 and P4/P6. The NAT resistance marker was amplified from pAI3 (generously provided by Dr. J. P. Xu, McMaster University) using primers NAT F/R. The 5′-gene and NAT amplicon were combined by a double-joint PCR with primers P1/P10, followed by similarly linking the 3′-gene and NAT amplicons with primers P9/P6. The amplified deletion cassette purified using the QIAquick Gel Extraction Kit (Qiagen) and was combined with gold microcarrier beads (Bio-Rad) and introduced into C. neoformans H99 strain via biolistic transformation . Stable transformants (i.e., two independent mutants) were selected on YPD-NAT (100 μg/ mL) plates and confirmed by diagnostic PCR, multiple stable mutants were constructed in independent transformation experiments. Insertion of NAT into a single site within the C. neoformans genome was confirmed by whole genome assembly (Supp. Fig. 4).
To construct the Wos2-FLAG complemented strain, the WOS2 open reading frame (ORF) and promoter region were amplified with 7558_NOTI_Promoter_F/7558_ NOTI_R. The amplified PCR product was digested using NotI and cloned into plasmid pHP1, which contains a 4X FLAG tag and hygromycin selectable marker (generously provided by Dr. J. Heitman, Duke University) . Correct insert orientation for a 3′ gene FLAG-tag was confirmed using primer pair M13_F/7558_pHP1_R, followed by sequencing of the constructed site at the Advanced Analysis Centre -Genome facility (University of Guelph). The resulting WOS2-FLAG plasmid was introduced into the wos2Δ strain using biolistic transformation, and multiple transformants were selected using YPD supplemented with hygromycin B (100 μg/ mL) (Sigma-Aldrich) and were confirmed by western blot (Supp. Fig. 5).
For Western blotting, whole cell extracts of the C. neoformans strains were separated by SDS-PAGE and transferred to a polyvinylidene difluoride membrane using a transfer apparatus, according to the manufacturer's protocols (Bio-Rad), as previously described . Briefly, membranes were blocked with 3% non-fat milk in 1X TBS (50 mM Tris, 150 mM NaCl, pH 7.5) at 4 °C overnight, followed by washing with TBST (1X TBS, 0.05% Tween-20) five times. Next, membranes were incubated with Monoclonal ANTI-FLAG ® M2 antibody (Sigma-Aldrich) for 1 h, washed three times for 5 min, and incubated with 1:3000 dilution of horseradish peroxidase-conjugated Goat anti-mouse IgG Fc secondary antibody (Invitrogen) for 1 h. Incubations were performed at room temperature. Blots were washed three times with TBST and developed using the Clarity Max Western ECL Substrates system (BioRad). The xxperiment was performed in biological and technical duplicates.
Genomic DNA extraction, Illumina sequencing and whole genome analysis
Genomic DNA (gDNA) was extracted from C. neoformans H99 WT and independent wos2Δ mutants using PureLink ™ Genomic DNA Mini Kit (ThermoFisher Scientific). Purified gDNA were prepared using an Illumina Nextera kit by the Microbial Genome Sequencing Center (Pennsylvania, USA) followed by Illumina sequencing on a NextSeq 550 platform. Raw .fastq files were processed using Geneious Prime 2021.0 (www. genei ous. com) . C. neoformans H99 WT files were initially trimmed using an in-suite BBDuk plug-in to trim adaptors and low-quality reads . The trimmed reads were mapped to a reference genome retrieved from NCBI. Correct assembly was validated by searching for variations (i.e., deletion or insertion) and SNPs. Upon confirmation of correct assembly, the independent deletion mutants were mapped to the assembled WT genome. To identify any non-specific insertions of NAT into the C. neoformans mapping, settings were modified to search for insertions or deletions up to 1600 bp (matching the expected size of the NAT gene). Whole genome alignment between the WT and wos2Δ strain was performed using a progressive-Mauve alignment from the Mauve plug-in using default alignment settings for a single chromosome and Mauve Contig Mover algorithm ordered and aligned 15 contigs (i.e., 14 chromosomes and one mitochondrion) .
Growth curves and zinc utilization
To analyse thermotolerance of C. neoformans strains, fungal cells were grown overnight at 30 °C in YPD, followed by 1:100 subculture in YNB. For growth curves, resuspended fungal cells inoculated into a final volume of 200 μL with 1 × 10 5 cells/mL into zinc-replete media and incubated at 30 °C or 37 °C. OD 600nm measurements were performed on BioTek HM1 plate reader every 15 min over 80 h. For zinc utilization assays, cells were collected by centrifugation at 1500 x g for 5 mins, washed twice with MM-Zn and resuspended in MM-Zn or MM + Zn followed by serial dilution in tenfold (10 6 cells/ml) on zinc-limited or -replete agar. Plates were incubated at either 30 °C or 37 °C for 3 d, with images taken every 24 h.
Capsule assay and shedding
To visualize polysaccharide capsule production, C. neoformans strains were grown overnight at 37 °C in YPD, followed by 1:100 subculture in YNB overnight, cells were washed twice in LIM, and inoculated into LIM for 16 h at 37 °C . Capsule production was examined by differential interference contrast microscopy by staining with India ink dye (Hardy Diagnostics). Cell diameter and capsule thickness were measured for 50 cells per strain, and relative capsule sizes were defined as the ratio of the capsule thickness to the diameter of the cell using ImageJ software (https:// imagej. nih. gov/ ij/ index. html). For the capsule shedding blot, supernatant was collected from each C. neoformans strain following 72 h of growth in LIM and diluted to an OD 600nm of 1 . The supernatant was denatured at 70 °C for 15 min, run on a 0.6% agarose gel, and blotted onto nylon membrane (GE healthcare), followed by membrane incubation with a 1:1000 dilution of 18B7 monoclonal antibody. Next, a 1:2500 dilution of anti-mouse horseradish peroxidase antibody was added, and polysaccharide was visualized by chemiluminescence (GE Healthcare) (Supp. Fig. 6).
Melanin plate assay
To examine the effects of gene deletion on C. neoformans ability to produce melanin pigmentation, C. neoformans strains were grown overnight at 30 °C in YPD, followed by 1:100 subculture and overnight incubation in YNB. Next, cultures underwent a final 1:100 overnight subculture into MM, washed with 1 mL of MM, and serially diluted tenfold (10 6 cells/ml) on MM agar containing 1 mM L-DOPA (Sigma-Aldrich) and incubated at either 30 °C or 37 °C for 7 days, with imaging every 24 h. |
/*
* Copyright (c) 2017, Intel Corporation
*
* 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.
*/
//!
//! \file cm_hal.cpp
//! \brief HAL Layer for CM Component
//!
#include "mos_os.h"
#include "cm_hal.h"
#include "media_interfaces_cmhal.h"
#include "media_interfaces_mhw.h"
#include "cm_common.h"
#include "cm_hal_vebox.h"
#include "cm_mem.h"
#include "renderhal_platform_interface.h"
#include "cm_execution_adv.h"
#include "cm_extension_creator.h"
#define INDEX_ALIGN(index, elemperIndex, base) ((index * elemperIndex)/base + ( (index *elemperIndex % base))? 1:0)
//----------------------------------
//| CM scoreboard XY
//----------------------------------
struct CM_HAL_SCOREBOARD_XY
{
int32_t x;
int32_t y;
};
typedef CM_HAL_SCOREBOARD_XY *PCM_HAL_SCOREBOARD_XY;
//---------------------------------------
//| CM scoreboard XY with mask
//---------------------------------------
struct CM_HAL_SCOREBOARD_XY_MASK
{
int32_t x;
int32_t y;
uint8_t mask;
uint8_t resetMask;
};
typedef CM_HAL_SCOREBOARD_XY_MASK *PCM_HAL_SCOREBOARD_XY_MASK;
//------------------------------------------------------------------------------
//| CM kernel slice and subslice being assigned to (for EnqueueWithHints)
//------------------------------------------------------------------------------
struct CM_HAL_KERNEL_SLICE_SUBSLICE
{
uint32_t slice;
uint32_t subSlice;
};
typedef CM_HAL_KERNEL_SLICE_SUBSLICE *PCM_HAL_KERNEL_SLICE_SUBSLICE;
//------------------------------------------------------------------------------
//| CM kernel information for EnqueueWithHints to assign subslice
//------------------------------------------------------------------------------
struct CM_HAL_KERNEL_SUBSLICE_INFO
{
uint32_t numSubSlices;
uint32_t counter;
PCM_HAL_KERNEL_SLICE_SUBSLICE destination;
};
typedef CM_HAL_KERNEL_SUBSLICE_INFO *PCM_HAL_KERNEL_SUBSLICE_INFO;
// forward declaration
int32_t HalCm_InsertCloneKernel(
PCM_HAL_STATE state,
PCM_HAL_KERNEL_PARAM kernelParam,
PRENDERHAL_KRN_ALLOCATION &kernelAllocation);
extern MOS_STATUS HalCm_GetSipBinary(
PCM_HAL_STATE state);
#if MDF_COMMAND_BUFFER_DUMP
extern int32_t HalCm_InitDumpCommandBuffer(PCM_HAL_STATE state);
extern int32_t HalCm_DumpCommadBuffer(PCM_HAL_STATE state, PMOS_COMMAND_BUFFER cmdBuffer,
int offsetSurfaceState, size_t sizeOfSurfaceState);
#endif
#if MDF_CURBE_DATA_DUMP
extern int32_t HalCm_InitDumpCurbeData(PCM_HAL_STATE state);
extern int32_t HalCm_DumpCurbeData(PCM_HAL_STATE state);
#endif
#if MDF_SURFACE_CONTENT_DUMP
extern int32_t HalCm_InitSurfaceDump(PCM_HAL_STATE state);
#endif
#if MDF_SURFACE_STATE_DUMP
extern int32_t HalCm_InitDumpSurfaceState(PCM_HAL_STATE state);
extern int32_t HalCm_DumpSurfaceState(PCM_HAL_STATE state, int offsetSurfaceState, size_t sizeOfSurfaceState);
#endif
#if MDF_INTERFACE_DESCRIPTOR_DATA_DUMP
extern int32_t HalCm_InitDumpInterfaceDescriporData(PCM_HAL_STATE state);
extern int32_t HalCm_DumpInterfaceDescriptorData(PCM_HAL_STATE state);
#endif
extern uint64_t HalCm_GetTsFrequency(PMOS_INTERFACE pOsInterface);
//===============<Private Functions>============================================
//*-----------------------------------------------------------------------------
//| Purpose: Align to the next power of 2
//| Returns: Aligned data
//| Reference: http://graphics.stanford.edu/~seander/bithacks.html#DetermineIfPowerOf2
//*-----------------------------------------------------------------------------
__inline uint32_t HalCm_GetPow2Aligned(uint32_t d)
{
CM_ASSERT(d > 0);
// subtract the number first
--d;
d |= d >> 1;
d |= d >> 2;
d |= d >> 4;
d |= d >> 8;
d |= d >> 16;
return ++d;
}
//*-----------------------------------------------------------------------------
//| Purpose: Checks if Task has any thread arguments
//| Returns: True if task has any thread arguments, false otherwise
//*-----------------------------------------------------------------------------
bool HalCm_GetTaskHasThreadArg(PCM_HAL_KERNEL_PARAM *kernels, uint32_t numKernels)
{
PCM_HAL_KERNEL_PARAM kernelParam;
PCM_HAL_KERNEL_ARG_PARAM argParam;
bool threadArgExists = false;
for( uint32_t krn = 0; krn < numKernels; krn++)
{
kernelParam = kernels[krn];
for(uint32_t argIndex = 0; argIndex < kernelParam->numArgs; argIndex++)
{
argParam = &kernelParam->argParams[argIndex];
if( argParam->perThread )
{
threadArgExists = true;
break;
}
}
if( threadArgExists )
break;
}
return threadArgExists;
}
//*-----------------------------------------------------------------------------
//| Purpose: Allocate Timestamp Resource
//| Returns: Result of the operation
//*-----------------------------------------------------------------------------
MOS_STATUS HalCm_AllocateTsResource(
PCM_HAL_STATE state) // [in] Pointer to CM HAL State
{
MOS_STATUS eStatus = MOS_STATUS_SUCCESS;
uint32_t size;
PMOS_INTERFACE osInterface;
MOS_ALLOC_GFXRES_PARAMS allocParams;
MOS_LOCK_PARAMS lockFlags;
osInterface = state->osInterface;
size = state->cmHalInterface->GetTimeStampResourceSize() * state->cmDeviceParam.maxTasks;
// allocate render engine Ts Resource
MOS_ZeroMemory(&allocParams, sizeof(MOS_ALLOC_GFXRES_PARAMS));
allocParams.Type = MOS_GFXRES_BUFFER;
allocParams.dwBytes = size;
allocParams.Format = Format_Buffer; //used in RenderHal_OsAllocateResource_Linux
allocParams.TileType= MOS_TILE_LINEAR;
allocParams.pBufName = "TsResource";
CM_CHK_HRESULT_GOTOFINISH_MOSERROR(osInterface->pfnAllocateResource(
osInterface,
&allocParams,
&state->renderTimeStampResource.osResource));
// Lock the Resource
MOS_ZeroMemory(&lockFlags, sizeof(MOS_LOCK_PARAMS));
lockFlags.ReadOnly = 1;
lockFlags.ForceCached = true;
state->renderTimeStampResource.data = (uint8_t*)osInterface->pfnLockResource(
osInterface,
&state->renderTimeStampResource.osResource,
&lockFlags);
CM_CHK_NULL_GOTOFINISH_MOSERROR(state->renderTimeStampResource.data);
state->renderTimeStampResource.locked = true;
//allocated for vebox TS resource
MOS_ZeroMemory(&allocParams, sizeof(MOS_ALLOC_GFXRES_PARAMS));
allocParams.Type = MOS_GFXRES_BUFFER;
allocParams.dwBytes = size;
allocParams.Format = Format_Buffer; //used in RenderHal_OsAllocateResource_Linux
allocParams.TileType = MOS_TILE_LINEAR;
allocParams.pBufName = "TsResource";
CM_CHK_HRESULT_GOTOFINISH_MOSERROR(osInterface->pfnAllocateResource(
osInterface,
&allocParams,
&state->veboxTimeStampResource.osResource));
// Lock the Resource
MOS_ZeroMemory(&lockFlags, sizeof(MOS_LOCK_PARAMS));
lockFlags.ReadOnly = 1;
lockFlags.ForceCached = true;
state->veboxTimeStampResource.data = (uint8_t*)osInterface->pfnLockResource(
osInterface,
&state->veboxTimeStampResource.osResource,
&lockFlags);
CM_CHK_NULL_GOTOFINISH_MOSERROR(state->veboxTimeStampResource.data);
state->veboxTimeStampResource.locked = true;
finish:
return eStatus;
}
//! \brief Allocate tracker resource
//! \param [in] state
//! Pointer to CM_HAL_STATE structure
//! \return MOS_STATUS
MOS_STATUS HalCm_AllocateTrackerResource(
PCM_HAL_STATE state)
{
MOS_STATUS eStatus = MOS_STATUS_SUCCESS;
MOS_ALLOC_GFXRES_PARAMS allocParamsLinearBuffer;
MOS_LOCK_PARAMS lockFlags;
PMOS_INTERFACE osInterface;
PRENDERHAL_INTERFACE renderHal;
osInterface = state->osInterface;
renderHal = state->renderHal;
// Tracker resource for RENDER engine
Mos_ResetResource(&renderHal->trackerResource.osResource);
MOS_ZeroMemory(&allocParamsLinearBuffer, sizeof(MOS_ALLOC_GFXRES_PARAMS));
allocParamsLinearBuffer.Type = MOS_GFXRES_BUFFER;
allocParamsLinearBuffer.TileType = MOS_TILE_LINEAR;
allocParamsLinearBuffer.Format = Format_Buffer;
allocParamsLinearBuffer.dwBytes = MHW_CACHELINE_SIZE;
allocParamsLinearBuffer.pBufName = "TrackerResource";
CM_CHK_HRESULT_GOTOFINISH_MOSERROR(osInterface->pfnAllocateResource(
osInterface,
&allocParamsLinearBuffer,
&renderHal->trackerResource.osResource));
// Lock the Resource
MOS_ZeroMemory(&lockFlags, sizeof(MOS_LOCK_PARAMS));
lockFlags.ReadOnly = 1;
lockFlags.ForceCached = true;
renderHal->trackerResource.data = (uint32_t*)osInterface->pfnLockResource(
osInterface,
&renderHal->trackerResource.osResource,
&lockFlags);
CM_CHK_NULL_GOTOFINISH_MOSERROR(renderHal->trackerResource.data);
*(renderHal->trackerResource.data) = MemoryBlock::m_invalidTrackerId;
renderHal->trackerResource.currentTrackerId = 1;
renderHal->trackerResource.locked = true;
// Tracker resource for VeBox engine
Mos_ResetResource(&renderHal->veBoxTrackerRes.osResource);
MOS_ZeroMemory(&allocParamsLinearBuffer, sizeof(MOS_ALLOC_GFXRES_PARAMS));
allocParamsLinearBuffer.Type = MOS_GFXRES_BUFFER;
allocParamsLinearBuffer.TileType = MOS_TILE_LINEAR;
allocParamsLinearBuffer.Format = Format_Buffer;
allocParamsLinearBuffer.dwBytes = MHW_CACHELINE_SIZE;
allocParamsLinearBuffer.pBufName = "VeboxTrackerRes";
CM_CHK_HRESULT_GOTOFINISH_MOSERROR(osInterface->pfnAllocateResource(
osInterface,
&allocParamsLinearBuffer,
&renderHal->veBoxTrackerRes.osResource));
// Lock the Resource
MOS_ZeroMemory(&lockFlags, sizeof(MOS_LOCK_PARAMS));
lockFlags.ReadOnly = 1;
lockFlags.ForceCached = true;
renderHal->veBoxTrackerRes.data = (uint32_t*)osInterface->pfnLockResource(
osInterface,
&renderHal->veBoxTrackerRes.osResource,
&lockFlags);
CM_CHK_NULL_GOTOFINISH_MOSERROR(renderHal->veBoxTrackerRes.data);
*(renderHal->veBoxTrackerRes.data) = MemoryBlock::m_invalidTrackerId;
renderHal->veBoxTrackerRes.currentTrackerId = 1;
renderHal->veBoxTrackerRes.locked = true;
finish:
return eStatus;
}
//! \brief Initialize dynamic state heap
//! \param [in] state
//! Pointer to CM_HAL_STATE structure
//! \param [in] heapParam
//! Pointer to CM_HAL_HEAP_PARAM structure
//! \return MOS_STATUS
MOS_STATUS HalCm_InitializeDynamicStateHeaps(
PCM_HAL_STATE state,
CM_HAL_HEAP_PARAM *heapParam)
{
MOS_STATUS eStatus = MOS_STATUS_SUCCESS;
HeapManager* dgsHeap = state->renderHal->dgsheapManager;
CM_CHK_NULL_GOTOFINISH_MOSERROR(heapParam);
dgsHeap = MOS_New(HeapManager);
CM_CHK_NULL_GOTOFINISH_MOSERROR(dgsHeap);
CM_CHK_MOSSTATUS_GOTOFINISH(dgsHeap->RegisterOsInterface(state->osInterface));
dgsHeap->SetDefaultBehavior(heapParam->behaviorGSH);
CM_CHK_MOSSTATUS_GOTOFINISH(dgsHeap->SetInitialHeapSize(heapParam->initialSizeGSH));
CM_CHK_MOSSTATUS_GOTOFINISH(dgsHeap->SetExtendHeapSize(heapParam->extendSizeGSH));
CM_CHK_MOSSTATUS_GOTOFINISH(dgsHeap->RegisterTrackerResource(heapParam->trackerResourceGSH));
// lock the heap in the beginning, so cpu doesn't need to wait gpu finishing occupying it to lock it again
CM_CHK_MOSSTATUS_GOTOFINISH(dgsHeap->LockHeapsOnAllocate());
state->renderHal->dgsheapManager = dgsHeap;
finish:
return eStatus;
}
//*-----------------------------------------------------------------------------
//| Purpose: Free Timestamp Resource
//| Returns: Result of the operation
//*-----------------------------------------------------------------------------
__inline void HalCm_FreeTsResource(
PCM_HAL_STATE state) // [in] Pointer to CM HAL State
{
PMOS_INTERFACE osInterface;
MOS_STATUS hr;
osInterface = state->osInterface;
if (!Mos_ResourceIsNull(&state->renderTimeStampResource.osResource))
{
if (state->renderTimeStampResource.locked)
{
hr = (MOS_STATUS)osInterface->pfnUnlockResource(
osInterface,
&state->renderTimeStampResource.osResource);
CM_ASSERT(hr == MOS_STATUS_SUCCESS);
}
osInterface->pfnFreeResourceWithFlag(
osInterface,
&state->renderTimeStampResource.osResource,
SURFACE_FLAG_ASSUME_NOT_IN_USE);
}
//free vebox TS resource
if (!Mos_ResourceIsNull(&state->veboxTimeStampResource.osResource))
{
if (state->veboxTimeStampResource.locked)
{
hr = (MOS_STATUS)osInterface->pfnUnlockResource(
osInterface,
&state->veboxTimeStampResource.osResource);
CM_ASSERT(hr == MOS_STATUS_SUCCESS);
}
osInterface->pfnFreeResourceWithFlag(
osInterface,
&state->veboxTimeStampResource.osResource,
SURFACE_FLAG_ASSUME_NOT_IN_USE);
}
}
//! \brief Free tracker resource
//! \param PCM_HAL_STATE state
//! [in] Pointer to CM_HAL_STATE structure
//! \return void
__inline void HalCm_FreeTrackerResources(
PCM_HAL_STATE state) // [in] Pointer to CM HAL State
{
PMOS_INTERFACE osInterface;
MOS_STATUS hr;
osInterface = state->osInterface;
if (!Mos_ResourceIsNull(&state->renderHal->trackerResource.osResource))
{
if(state->renderHal->trackerResource.locked)
{
hr = (MOS_STATUS)osInterface->pfnUnlockResource(
osInterface,
&state->renderHal->trackerResource.osResource);
CM_ASSERT(hr == MOS_STATUS_SUCCESS);
}
osInterface->pfnFreeResourceWithFlag(
osInterface,
&state->renderHal->trackerResource.osResource,
SURFACE_FLAG_ASSUME_NOT_IN_USE);
}
if (!Mos_ResourceIsNull(&state->renderHal->veBoxTrackerRes.osResource))
{
if (state->renderHal->veBoxTrackerRes.locked)
{
hr = (MOS_STATUS)osInterface->pfnUnlockResource(
osInterface,
&state->renderHal->veBoxTrackerRes.osResource);
CM_ASSERT(hr == MOS_STATUS_SUCCESS);
}
osInterface->pfnFreeResourceWithFlag(
osInterface,
&state->renderHal->veBoxTrackerRes.osResource,
SURFACE_FLAG_ASSUME_NOT_IN_USE);
}
}
//*-----------------------------------------------------------------------------
//| Purpose: Allocate CSR Resource
//| Returns: Result of the operation
//*-----------------------------------------------------------------------------
MOS_STATUS HalCm_AllocateCSRResource(
PCM_HAL_STATE state) // [in] Pointer to CM HAL State
{
PMOS_INTERFACE osInterface = state->osInterface;
MOS_STATUS eStatus = MOS_STATUS_SUCCESS;
uint32_t size;
MOS_ALLOC_GFXRES_PARAMS allocParams;
//Enable Mid-thread
state->renderHal->pfnEnableGpgpuMiddleThreadPreemption(state->renderHal);
size = CM_CSR_SURFACE_SIZE;
MOS_ZeroMemory(&allocParams, sizeof(MOS_ALLOC_GFXRES_PARAMS));
allocParams.Type = MOS_GFXRES_BUFFER;
allocParams.dwBytes = size;
allocParams.Format = Format_RAW; //used in VpHal_OsAllocateResource_Linux
allocParams.TileType = MOS_TILE_LINEAR;
allocParams.pBufName = "CSRResource";
CM_CHK_HRESULT_GOTOFINISH_MOSERROR(osInterface->pfnAllocateResource(
osInterface,
&allocParams,
&state->csrResource));
finish:
return eStatus;
}
//*-----------------------------------------------------------------------------
//| Purpose: Allocate Sip Resource
//| Returns: Result of the operation
//*-----------------------------------------------------------------------------
MOS_STATUS HalCm_AllocateSipResource(
PCM_HAL_STATE state) // [in] Pointer to CM HAL State
{
PMOS_INTERFACE osInterface = state->osInterface;
MOS_STATUS eStatus = MOS_STATUS_SUCCESS;
uint32_t size;
MOS_ALLOC_GFXRES_PARAMS allocParams;
MOS_LOCK_PARAMS lockFlags;
size = CM_DEBUG_SURFACE_SIZE;
MOS_ZeroMemory(&allocParams, sizeof(MOS_ALLOC_GFXRES_PARAMS));
allocParams.Type = MOS_GFXRES_BUFFER;
allocParams.dwBytes = size;
allocParams.Format = Format_Buffer; //used in RenderHal_OsAllocateResource_Linux
allocParams.TileType = MOS_TILE_LINEAR;
allocParams.pBufName = "SipResource";
CM_CHK_HRESULT_GOTOFINISH_MOSERROR(osInterface->pfnAllocateResource(
osInterface,
&allocParams,
&state->sipResource.osResource));
// Lock the Resource
MOS_ZeroMemory(&lockFlags, sizeof(MOS_LOCK_PARAMS));
lockFlags.ReadOnly = 1;
lockFlags.ForceCached = true;
state->sipResource.data = (uint8_t*)osInterface->pfnLockResource(
osInterface,
&state->sipResource.osResource,
&lockFlags);
CM_CHK_NULL_GOTOFINISH_MOSERROR(state->sipResource.data);
state->sipResource.locked = true;
finish:
return eStatus;
}
//*-----------------------------------------------------------------------------
//| Purpose: Free CSR Resource
//| Returns: Result of the operation
//*-----------------------------------------------------------------------------
__inline void HalCm_FreeCsrResource(
PCM_HAL_STATE state) // [in] Pointer to CM HAL State
{
PMOS_INTERFACE osInterface = state->osInterface;
if (!Mos_ResourceIsNull(&state->csrResource))
{
osInterface->pfnFreeResourceWithFlag(
osInterface,
&state->csrResource,
SURFACE_FLAG_ASSUME_NOT_IN_USE);
}
}
//*-----------------------------------------------------------------------------
//| Purpose: Free Sip Resource
//| Returns: Result of the operation
//*-----------------------------------------------------------------------------
__inline void HalCm_FreeSipResource(
PCM_HAL_STATE state) // [in] Pointer to CM HAL State
{
PMOS_INTERFACE osInterface = state->osInterface;
MOS_STATUS hr = MOS_STATUS_SUCCESS;
if (!Mos_ResourceIsNull(&state->sipResource.osResource))
{
if (state->sipResource.locked)
{
hr = (MOS_STATUS)osInterface->pfnUnlockResource(
osInterface,
&state->sipResource.osResource);
CM_ASSERT(hr == MOS_STATUS_SUCCESS);
}
osInterface->pfnFreeResourceWithFlag(
osInterface,
&state->sipResource.osResource,
SURFACE_FLAG_ASSUME_NOT_IN_USE);
}
}
//*-----------------------------------------------------------------------------
//| Purpose: Sets Arg data in the buffer
//| Returns: Result of the operation
//*-----------------------------------------------------------------------------
__inline void HalCm_SetArgData(
PCM_HAL_KERNEL_ARG_PARAM argParam,
uint32_t threadIndex,
uint8_t *buffer)
{
uint8_t *dst;
uint8_t *src;
dst = buffer + argParam->payloadOffset;
src = argParam->firstValue + (threadIndex * argParam->unitSize);
MOS_SecureMemcpy(dst, argParam->unitSize, src, argParam->unitSize);
}
//*-----------------------------------------------------------------------------
//| Purpose: Get the Buffer Entry
//| Returns: Result of the operation.
//*-----------------------------------------------------------------------------
__inline MOS_STATUS HalCm_GetResourceUPEntry(
PCM_HAL_STATE state, // [in] Pointer to CM State
uint32_t handle, // [in] Handle
PCM_HAL_SURFACE2D_UP_ENTRY *entryOut) // [out] Buffer Entry
{
MOS_STATUS eStatus;
PCM_HAL_SURFACE2D_UP_ENTRY entry;
eStatus = MOS_STATUS_SUCCESS;
if (handle >= state->cmDeviceParam.max2DSurfaceUPTableSize)
{
eStatus = MOS_STATUS_INVALID_HANDLE;
CM_ASSERTMESSAGE("Invalid handle '%d'", handle);
goto finish;
}
entry = &state->surf2DUPTable[handle];
if (entry->width == 0)
{
eStatus = MOS_STATUS_INVALID_HANDLE;
CM_ASSERTMESSAGE("handle '%d' is not set", handle);
goto finish;
}
*entryOut = entry;
finish:
return eStatus;
}
//*-----------------------------------------------------------------------------
//| Purpose: Get the Buffer Entry
//| Returns: Result of the operation.
//*-----------------------------------------------------------------------------
__inline MOS_STATUS HalCm_GetBufferEntry(
PCM_HAL_STATE state, // [in] Pointer to CM State
uint32_t handle, // [in] Handle
PCM_HAL_BUFFER_ENTRY *entryOut) // [out] Buffer Entry
{
MOS_STATUS eStatus;
PCM_HAL_BUFFER_ENTRY entry;
eStatus = MOS_STATUS_SUCCESS;
if (handle >= state->cmDeviceParam.maxBufferTableSize)
{
eStatus = MOS_STATUS_INVALID_HANDLE;
CM_ASSERTMESSAGE("Invalid handle '%d'", handle);
goto finish;
}
entry = &state->bufferTable[handle];
if (entry->size == 0)
{
eStatus = MOS_STATUS_INVALID_HANDLE;
CM_ASSERTMESSAGE("handle '%d' is not set", handle);
goto finish;
}
*entryOut = entry;
finish:
return eStatus;
}
//*-----------------------------------------------------------------------------
//| Purpose: Get the Surface2D Entry
//| Returns: Result of the operation.
//*-----------------------------------------------------------------------------
__inline MOS_STATUS HalCm_GetSurface2DEntry(
PCM_HAL_STATE state, // [in] Pointer to CM State
uint32_t handle, // [in] Handle
PCM_HAL_SURFACE2D_ENTRY *entryOut) // [out] Buffer Entry
{
MOS_STATUS eStatus;
PCM_HAL_SURFACE2D_ENTRY entry;
eStatus = MOS_STATUS_SUCCESS;
if (handle >= state->cmDeviceParam.max2DSurfaceTableSize)
{
eStatus = MOS_STATUS_INVALID_HANDLE;
CM_ASSERTMESSAGE("Invalid handle '%d'", handle);
goto finish;
}
entry = &state->umdSurf2DTable[handle];
if ((entry->width == 0)||(entry->height == 0))
{
eStatus = MOS_STATUS_INVALID_HANDLE;
CM_ASSERTMESSAGE("handle '%d' is not set", handle);
goto finish;
}
*entryOut = entry;
finish:
return eStatus;
}
//*-----------------------------------------------------------------------------
//| Purpose: Get the 3D Entry
//| Returns: Result of the operation.
//*-----------------------------------------------------------------------------
__inline MOS_STATUS HalCm_Get3DResourceEntry(
PCM_HAL_STATE state, // [in] Pointer to CM State
uint32_t handle, // [in] Handle
PCM_HAL_3DRESOURCE_ENTRY *entryOut) // [out] Buffer Entry
{
MOS_STATUS eStatus;
PCM_HAL_3DRESOURCE_ENTRY entry;
eStatus = MOS_STATUS_SUCCESS;
if (handle >= state->cmDeviceParam.max3DSurfaceTableSize)
{
eStatus = MOS_STATUS_INVALID_HANDLE;
CM_ASSERTMESSAGE("Invalid handle '%d'", handle);
goto finish;
}
entry = &state->surf3DTable[handle];
if (Mos_ResourceIsNull(&entry->osResource))
{
eStatus = MOS_STATUS_INVALID_HANDLE;
CM_ASSERTMESSAGE("3D handle '%d' is not set", handle);
goto finish;
}
*entryOut = entry;
finish:
return eStatus;
}
//*-----------------------------------------------------------------------------
//| Purpose: Allocates and sets up Task Param memory structure
//| Return: true if enabled
//| Note: A single layer of memory is allocated to avoid fragmentation
//*-----------------------------------------------------------------------------
MOS_STATUS HalCm_AllocateTables(
PCM_HAL_STATE state) // [in] Pointer to HAL CM state
{
MOS_STATUS eStatus = MOS_STATUS_SUCCESS;
PCM_HAL_DEVICE_PARAM deviceParam;
uint8_t *pb;
uint32_t lookUpTableSize;
uint32_t samplerTableSize;
uint32_t vmeTableSize;
uint32_t sampler8x8TableSize;
uint32_t taskStatusTableSize;
uint32_t bt2DIndexTableSize;
uint32_t bt2DUPIndexTableSize;
uint32_t bt3DIndexTableSize;
uint32_t btbufferIndexTableSize;
uint32_t samplerIndexTableSize;
uint32_t vmeIndexTableSize;
uint32_t sampler8x8IndexTableSize;
uint32_t bufferTableSize;
uint32_t i2DSURFUPTableSize;
uint32_t i3DSurfTableSize;
uint32_t size;
uint32_t i2DSURFTableSize;
deviceParam = &state->cmDeviceParam;
lookUpTableSize = deviceParam->max2DSurfaceTableSize *
sizeof(CMLOOKUP_ENTRY);
i2DSURFTableSize = deviceParam->max2DSurfaceTableSize *
sizeof(CM_HAL_SURFACE2D_ENTRY);
bufferTableSize = deviceParam->maxBufferTableSize *
sizeof(CM_HAL_BUFFER_ENTRY);
i2DSURFUPTableSize = deviceParam->max2DSurfaceUPTableSize *
sizeof(CM_HAL_SURFACE2D_UP_ENTRY);
i3DSurfTableSize = deviceParam->max3DSurfaceTableSize *
sizeof(CM_HAL_3DRESOURCE_ENTRY);
samplerTableSize = deviceParam->maxSamplerTableSize *
sizeof(MHW_SAMPLER_STATE_PARAM);
sampler8x8TableSize = deviceParam->maxSampler8x8TableSize *
sizeof(CM_HAL_SAMPLER_8X8_ENTRY);
taskStatusTableSize = deviceParam->maxTasks * sizeof(char);
bt2DIndexTableSize = deviceParam->max2DSurfaceTableSize * sizeof(CM_HAL_MULTI_USE_BTI_ENTRY);
bt2DUPIndexTableSize = deviceParam->max2DSurfaceUPTableSize * sizeof(CM_HAL_MULTI_USE_BTI_ENTRY);
bt3DIndexTableSize = deviceParam->max3DSurfaceTableSize * sizeof(CM_HAL_MULTI_USE_BTI_ENTRY);
btbufferIndexTableSize = deviceParam->maxBufferTableSize * sizeof(CM_HAL_MULTI_USE_BTI_ENTRY);
samplerIndexTableSize = deviceParam->maxSamplerTableSize * sizeof(char);
sampler8x8IndexTableSize = deviceParam->maxSampler8x8TableSize * sizeof(char);
size = lookUpTableSize +
i2DSURFTableSize +
bufferTableSize +
i2DSURFUPTableSize +
i3DSurfTableSize +
samplerTableSize +
sampler8x8TableSize +
taskStatusTableSize +
bt2DIndexTableSize +
bt2DUPIndexTableSize +
bt3DIndexTableSize +
btbufferIndexTableSize +
samplerIndexTableSize +
sampler8x8IndexTableSize;
state->tableMemories = MOS_AllocAndZeroMemory(size);
CM_CHK_NULL_GOTOFINISH_MOSERROR(state->tableMemories);
pb = (uint8_t*)state->tableMemories;
state->surf2DTable = (PCMLOOKUP_ENTRY)pb;
pb += lookUpTableSize;
state->umdSurf2DTable = (PCM_HAL_SURFACE2D_ENTRY)pb;
pb += i2DSURFTableSize;
state->bufferTable = (PCM_HAL_BUFFER_ENTRY)pb;
pb += bufferTableSize;
state->surf2DUPTable = (PCM_HAL_SURFACE2D_UP_ENTRY)pb;
pb += i2DSURFUPTableSize;
state->surf3DTable = (PCM_HAL_3DRESOURCE_ENTRY)pb;
pb += i3DSurfTableSize;
state->samplerTable = (PMHW_SAMPLER_STATE_PARAM)pb;
pb += samplerTableSize;
state->sampler8x8Table = (PCM_HAL_SAMPLER_8X8_ENTRY)pb;
pb += sampler8x8TableSize;
state->taskStatusTable = (char *)pb;
pb += taskStatusTableSize;
state->bti2DIndexTable = (PCM_HAL_MULTI_USE_BTI_ENTRY)pb;
pb += bt2DIndexTableSize;
state->bti2DUPIndexTable = (PCM_HAL_MULTI_USE_BTI_ENTRY)pb;
pb += bt2DUPIndexTableSize;
state->bti3DIndexTable = (PCM_HAL_MULTI_USE_BTI_ENTRY)pb;
pb += bt3DIndexTableSize;
state->btiBufferIndexTable = (PCM_HAL_MULTI_USE_BTI_ENTRY)pb;
pb += btbufferIndexTableSize;
state->samplerIndexTable = (char *)pb;
pb += samplerIndexTableSize;
state->sampler8x8IndexTable = (char *)pb;
pb += sampler8x8IndexTableSize;
finish:
return MOS_STATUS_SUCCESS;
}
//*-----------------------------------------------------------------------------
//| Purpose: Adds a tag to distinguish between same kernel ID
//| Used for batch buffer re-use when splitting large task into
//| smaller pieces for EnqueueWithHints
//| Using bits [48:42] from kernel ID for extra tag
//| Returns: Result of the operation
//*-----------------------------------------------------------------------------
MOS_STATUS HalCm_AddKernelIDTag(
PCM_HAL_KERNEL_PARAM *pKernels,
uint32_t numKernels,
uint32_t numTasks,
uint32_t numCurrentTask)
{
uint32_t i;
uint64_t tmpNumTasks;
uint64_t tmpNumCurrentTask;
uint64_t tmpNumTasksMask;
uint64_t tmpNumCurrentTaskMask;
tmpNumTasks = numTasks;
tmpNumCurrentTask = numCurrentTask;
tmpNumTasksMask = tmpNumTasks << 45;
tmpNumCurrentTaskMask = tmpNumCurrentTask << 42;
for( i = 0; i < numKernels; ++i )
{
pKernels[i]->kernelId |= tmpNumTasksMask;
pKernels[i]->kernelId |= tmpNumCurrentTaskMask;
}
return MOS_STATUS_SUCCESS;
}
//*-----------------------------------------------------------------------------
//| Purpose: Gets the Batch Buffer for rendering. If needed, de-allocate /
//| allocate the memory for BB
//| Returns: Result of the operation
//*-----------------------------------------------------------------------------
MOS_STATUS HalCm_GetBatchBuffer(
PCM_HAL_STATE state, // [in] Pointer to CM State
uint32_t numKernels, // [in] Number of Kernels
PCM_HAL_KERNEL_PARAM *kernels, // [in] Array for kernel data
PMHW_BATCH_BUFFER *batchBufferOut) // [out] Batch Buffer Out
{
MOS_STATUS eStatus;
PMHW_BATCH_BUFFER batchBuffer = nullptr;
PRENDERHAL_INTERFACE renderHal;
int32_t size;
uint32_t i;
uint32_t j;
uint32_t k;
int32_t freeIdx;
uint64_t kernelIds[CM_MAX_KERNELS_PER_TASK];
uint64_t kernelParamsIds[CM_MAX_KERNELS_PER_TASK];
CM_HAL_BB_DIRTY_STATUS bbDirtyStatus;
PCM_HAL_BB_ARGS bbcmArgs;
eStatus = MOS_STATUS_SUCCESS;
renderHal = state->renderHal;
freeIdx = CM_INVALID_INDEX;
bbDirtyStatus = CM_HAL_BB_CLEAN;
// Align the Batch Buffer size to power of 2
size = HalCm_GetPow2Aligned(state->taskParam->batchBufferSize);
MOS_ZeroMemory(&kernelIds, CM_MAX_KERNELS_PER_TASK * sizeof(uint64_t));
MOS_ZeroMemory(&kernelParamsIds, CM_MAX_KERNELS_PER_TASK * sizeof(uint64_t));
//Sanity check for batch buffer
if (size > CM_MAX_BB_SIZE)
{
eStatus = MOS_STATUS_EXCEED_MAX_BB_SIZE;
CM_ASSERTMESSAGE("Batch Buffer Size exeeceds Max '%d'", size);
goto finish;
}
for( i = 0; i < numKernels; ++i )
{
// remove upper 16 bits used for kernel binary re-use in GSH
kernelParamsIds[i] = ((kernels[i])->kernelId << 16 ) >> 16;
}
#if CM_BATCH_BUFFER_REUSE_ENABLE
bbDirtyStatus = CM_HAL_BB_CLEAN;
for (k = 0; k < numKernels; ++k)
{
if (kernels[k]->kernelThreadSpaceParam.bbDirtyStatus == CM_HAL_BB_DIRTY)
{
bbDirtyStatus = CM_HAL_BB_DIRTY;
break;
}
}
for (i = 0; i < (uint32_t)state->numBatchBuffers; i++)
{
batchBuffer = &state->batchBuffers[i];
CM_CHK_NULL_GOTOFINISH_MOSERROR(batchBuffer);
CM_CHK_NULL_GOTOFINISH_MOSERROR(batchBuffer->pPrivateData);
//if (!Mos_ResourceIsNull(&batchBuffer->OsResource) && (!batchBuffer->bBusy))
if (!Mos_ResourceIsNull(&batchBuffer->OsResource))
{
MOS_FillMemory(kernelIds, sizeof(uint64_t)*CM_MAX_KERNELS_PER_TASK, 0);
for (j = 0; j < numKernels; j ++)
{
kernelIds[j] = kernelParamsIds[j];
}
bbcmArgs = (PCM_HAL_BB_ARGS)batchBuffer->pPrivateData;
if (RtlEqualMemory(kernelIds, bbcmArgs->kernelIds, sizeof(uint64_t)*CM_MAX_KERNELS_PER_TASK))
{
if( batchBuffer->bBusy && bbDirtyStatus == CM_HAL_BB_DIRTY )
{
bbcmArgs->latest = false;
}
else if( bbcmArgs->latest == true )
{
break;
}
}
}
}
if (i < (uint32_t)state->numBatchBuffers)
{
CM_CHK_NULL_GOTOFINISH_MOSERROR(batchBuffer);
CM_CHK_NULL_GOTOFINISH_MOSERROR(batchBuffer->pPrivateData);
bbcmArgs = (PCM_HAL_BB_ARGS)batchBuffer->pPrivateData;
bbcmArgs->refCount ++;
batchBuffer->iCurrent = 0;
batchBuffer->dwSyncTag = 0;
batchBuffer->iRemaining = batchBuffer->iSize;
*batchBufferOut = batchBuffer;
eStatus = MOS_STATUS_SUCCESS;
goto finish;
}
#endif
for (i = 0; i < (uint32_t)state->numBatchBuffers; i++)
{
batchBuffer = &state->batchBuffers[i];
CM_CHK_NULL_GOTOFINISH_MOSERROR(batchBuffer);
// No holes in the array of batch buffers
if (Mos_ResourceIsNull(&batchBuffer->OsResource))
{
freeIdx = i;
break;
}
}
if (freeIdx == CM_INVALID_INDEX)
{
for (i = 0; i < (uint32_t)state->numBatchBuffers; i++)
{
batchBuffer = &state->batchBuffers[i];
CM_CHK_NULL_GOTOFINISH_MOSERROR(batchBuffer);
CM_CHK_NULL_GOTOFINISH_MOSERROR(batchBuffer->pPrivateData);
bbcmArgs = (PCM_HAL_BB_ARGS)batchBuffer->pPrivateData;
if (!batchBuffer->bBusy)
{
if (batchBuffer->iSize >= size)
{
batchBuffer->iCurrent = 0;
batchBuffer->iRemaining = batchBuffer->iSize;
batchBuffer->dwSyncTag = 0;
bbcmArgs->refCount = 1;
for (i = 0; i <numKernels; i ++)
{
bbcmArgs->kernelIds[i] = kernelParamsIds[i];
}
bbcmArgs->latest = true;
*batchBufferOut = batchBuffer;
eStatus = MOS_STATUS_SUCCESS;
goto finish;
}
if (freeIdx == CM_INVALID_INDEX)
{
freeIdx = i;
}
}
}
}
if (freeIdx == CM_INVALID_INDEX)
{
eStatus = MOS_STATUS_INVALID_PARAMETER;
CM_ASSERTMESSAGE("No batch buffer available");
goto finish;
}
batchBuffer = &state->batchBuffers[freeIdx];
CM_CHK_NULL_GOTOFINISH_MOSERROR(batchBuffer);
CM_CHK_NULL_GOTOFINISH_MOSERROR(batchBuffer->pPrivateData);
bbcmArgs = (PCM_HAL_BB_ARGS)batchBuffer->pPrivateData;
bbcmArgs->refCount = 1;
for (i = 0; i <numKernels; i ++)
{
bbcmArgs->kernelIds[i] = kernelParamsIds[i];
}
bbcmArgs->latest = true;
if (!Mos_ResourceIsNull(&batchBuffer->OsResource))
{
// Deallocate Batch Buffer
CM_CHK_MOSSTATUS_GOTOFINISH(renderHal->pfnFreeBB(renderHal, batchBuffer));
}
// Allocate Batch Buffer
CM_CHK_MOSSTATUS_GOTOFINISH(renderHal->pfnAllocateBB(renderHal, batchBuffer, size));
*batchBufferOut = batchBuffer;
finish:
return eStatus;
}
//*-----------------------------------------------------------------------------
//| Purpose: Parse the Kernel and populate the Task Param structure
//| Return: Result of the operation
//*-----------------------------------------------------------------------------
MOS_STATUS HalCm_ParseTask(
PCM_HAL_STATE state, // [in] Pointer to HAL CM state
PCM_HAL_EXEC_TASK_PARAM execParam) // [in] Pointer to Exec Task Param
{
MOS_STATUS eStatus;
PCM_HAL_TASK_PARAM taskParam;
PCM_HAL_KERNEL_PARAM kernelParam;
uint32_t hdrSize;
uint32_t totalThreads;
uint32_t krn;
uint32_t curbeOffset;
PMHW_VFE_SCOREBOARD scoreboardParams;
uint32_t hasThreadArg;
bool nonstallingScoreboardEnable;
CM_HAL_DEPENDENCY vfeDependencyInfo;
PCM_HAL_KERNEL_THREADSPACE_PARAM kernelTSParam;
uint32_t i, j, k;
uint8_t reuseBBUpdateMask;
bool bitIsSet;
PCM_HAL_MASK_AND_RESET dependencyMask;
uint32_t uSurfaceNumber;
uint32_t uSurfaceIndex;
bool threadArgExists;
eStatus = MOS_STATUS_SUCCESS;
curbeOffset = 0;
totalThreads = 0;
taskParam = state->taskParam;
taskParam->batchBufferSize = 0;
hasThreadArg = 0;
nonstallingScoreboardEnable = true;
reuseBBUpdateMask = 0;
bitIsSet = false;
threadArgExists = false;
hdrSize = state->renderHal->pHwSizes->dwSizeMediaObjectHeaderCmd;
taskParam->dependencyPattern = execParam->dependencyPattern;
taskParam->threadSpaceWidth = execParam->threadSpaceWidth;
taskParam->threadSpaceHeight = execParam->threadSpaceHeight;
taskParam->walkingPattern = execParam->walkingPattern;
taskParam->walkingParamsValid = execParam->walkingParamsValid;
taskParam->dependencyVectorsValid = execParam->dependencyVectorsValid;
if( taskParam->walkingParamsValid )
{
taskParam->walkingParams = execParam->walkingParams;
}
if( taskParam->dependencyVectorsValid )
{
taskParam->dependencyVectors = execParam->dependencyVectors;
}
taskParam->kernelDebugEnabled = (uint32_t)execParam->kernelDebugEnabled;
//GT-PIN
taskParam->surfEntryInfoArrays = execParam->surfEntryInfoArrays;
taskParam->surfacePerBT = 0;
taskParam->colorCountMinusOne = execParam->colorCountMinusOne;
taskParam->mediaWalkerGroupSelect = execParam->mediaWalkerGroupSelect;
if (execParam->threadCoordinates)
{
taskParam->threadCoordinates = execParam->threadCoordinates;
}
taskParam->dependencyMasks = execParam->dependencyMasks;
taskParam->syncBitmap = execParam->syncBitmap;
taskParam->conditionalEndBitmap = execParam->conditionalEndBitmap;
MOS_SecureMemcpy(taskParam->conditionalEndInfo, sizeof(taskParam->conditionalEndInfo), execParam->conditionalEndInfo, sizeof(execParam->conditionalEndInfo));
taskParam->numKernels = execParam->numKernels;
taskParam->taskConfig = execParam->taskConfig;
state->walkerParams.CmWalkerEnable = true;
state->renderHal->IsMDFLoad = (taskParam->taskConfig.turboBoostFlag == CM_TURBO_BOOST_ENABLE);
for (krn = 0; krn < execParam->numKernels; krn++)
{
if ((execParam->kernels[krn] == nullptr) ||
(execParam->kernelSizes[krn] == 0))
{
eStatus = MOS_STATUS_INVALID_PARAMETER;
CM_ASSERTMESSAGE("Invalid Kernel data");
goto finish;
}
kernelParam = (PCM_HAL_KERNEL_PARAM)execParam->kernels[krn];
PCM_INDIRECT_SURFACE_INFO indirectSurfaceInfo = kernelParam->indirectDataParam.surfaceInfo;
uSurfaceNumber = 0;
if (kernelParam->indirectDataParam.surfaceCount)
{
uSurfaceIndex = 0;
for (i = 0; i < kernelParam->indirectDataParam.surfaceCount; i++)
{
uSurfaceIndex = (indirectSurfaceInfo + i)->bindingTableIndex > uSurfaceIndex ? ((indirectSurfaceInfo + i)->bindingTableIndex + (indirectSurfaceInfo + i)->numBTIPerSurf - 1) : uSurfaceIndex;
uSurfaceNumber = uSurfaceNumber + (indirectSurfaceInfo + i)->numBTIPerSurf;
}
taskParam->surfacePerBT = taskParam->surfacePerBT > uSurfaceIndex ? taskParam->surfacePerBT : uSurfaceIndex;
}
uSurfaceNumber += kernelParam->numSurfaces;
taskParam->surfacePerBT = taskParam->surfacePerBT < uSurfaceNumber ?
uSurfaceNumber : taskParam->surfacePerBT;
// 26Z must be media object because by default it uses thread dependency mask
// if there is no thread payload and dependency is not WAVEFRONT26Z, check if walker can be used
if ( kernelParam->payloadSize == 0)
{
//per-kernel thread space is avaiable, and check it at first
if((kernelParam->kernelThreadSpaceParam.threadSpaceWidth != 0) &&
(kernelParam->kernelThreadSpaceParam.patternType != CM_WAVEFRONT26Z) &&
(kernelParam->kernelThreadSpaceParam.patternType != CM_WAVEFRONT26ZI) &&
(kernelParam->kernelThreadSpaceParam.threadCoordinates == nullptr))
{
kernelParam->walkerParams.cmWalkerEnable = true;
kernelParam->walkerParams.groupIdLoopSelect = execParam->mediaWalkerGroupSelect;
}
else if (kernelParam->kernelThreadSpaceParam.threadSpaceWidth == 0)
{
//Check per-task thread space setting
if (state->taskParam->threadCoordinates)
{
if (state->taskParam->threadCoordinates[krn] == nullptr)
{
kernelParam->walkerParams.cmWalkerEnable = true;
kernelParam->walkerParams.groupIdLoopSelect = execParam->mediaWalkerGroupSelect;
}
}
else
{
kernelParam->walkerParams.cmWalkerEnable = true;
kernelParam->walkerParams.groupIdLoopSelect = execParam->mediaWalkerGroupSelect;
}
}
}
//Media walker mode will be disabled if any kernel need use media object, we don't support mixed working modes
state->walkerParams.CmWalkerEnable &= kernelParam->walkerParams.cmWalkerEnable;
if (!state->walkerParams.CmWalkerEnable)
{
taskParam->batchBufferSize +=
kernelParam->numThreads * (hdrSize + MOS_MAX(kernelParam->payloadSize, 4));
}
totalThreads += kernelParam->numThreads;
}
taskParam->batchBufferSize += CM_EXTRA_BB_SPACE;
if (state->cmHalInterface->IsScoreboardParamNeeded())
{
scoreboardParams = &state->scoreboardParams;
scoreboardParams->ScoreboardMask = 0;
scoreboardParams->ScoreboardType = nonstallingScoreboardEnable;
// set VFE scoreboarding information from union of kernel dependency vectors
MOS_ZeroMemory(&vfeDependencyInfo, sizeof(CM_HAL_DEPENDENCY));
for (krn = 0; krn < execParam->numKernels; krn++)
{
kernelParam = execParam->kernels[krn];
kernelTSParam = &kernelParam->kernelThreadSpaceParam;
// calculate union dependency vector of all kernels with dependency
if (kernelTSParam->dependencyInfo.count || kernelTSParam->dependencyVectorsValid)
{
if (vfeDependencyInfo.count == 0)
{
if (kernelTSParam->dependencyInfo.count)
{
MOS_SecureMemcpy(&vfeDependencyInfo, sizeof(CM_HAL_DEPENDENCY), &kernelTSParam->dependencyInfo, sizeof(CM_HAL_DEPENDENCY));
}
else if (kernelTSParam->dependencyVectorsValid)
{
MOS_SecureMemcpy(&vfeDependencyInfo, sizeof(CM_HAL_DEPENDENCY), &kernelTSParam->dependencyVectors, sizeof(CM_HAL_DEPENDENCY));
}
kernelTSParam->globalDependencyMask = (1 << vfeDependencyInfo.count) - 1;
}
else
{
uint32_t count = 0;
CM_HAL_DEPENDENCY dependencyInfo;
if (kernelTSParam->dependencyVectorsValid)
{
count = kernelTSParam->dependencyVectors.count;
MOS_SecureMemcpy(&dependencyInfo.deltaX, sizeof(int32_t) * count, &kernelTSParam->dependencyVectors.deltaX, sizeof(int32_t) * count);
MOS_SecureMemcpy(&dependencyInfo.deltaY, sizeof(int32_t) * count, &kernelTSParam->dependencyVectors.deltaY, sizeof(int32_t) * count);
}
else
{
count = kernelTSParam->dependencyInfo.count;
MOS_SecureMemcpy(&dependencyInfo.deltaX, sizeof(int32_t) * count, &kernelTSParam->dependencyInfo.deltaX, sizeof(int32_t) * count);
MOS_SecureMemcpy(&dependencyInfo.deltaY, sizeof(int32_t) * count, &kernelTSParam->dependencyInfo.deltaY, sizeof(int32_t) * count);
}
for (j = 0; j < count; ++j)
{
for (k = 0; k < vfeDependencyInfo.count; ++k)
{
if ((dependencyInfo.deltaX[j] == vfeDependencyInfo.deltaX[k]) &&
(dependencyInfo.deltaY[j] == vfeDependencyInfo.deltaY[k]))
{
CM_HAL_SETBIT(kernelTSParam->globalDependencyMask, k);
break;
}
}
if (k == vfeDependencyInfo.count)
{
vfeDependencyInfo.deltaX[vfeDependencyInfo.count] = dependencyInfo.deltaX[j];
vfeDependencyInfo.deltaY[vfeDependencyInfo.count] = dependencyInfo.deltaY[j];
CM_HAL_SETBIT(kernelTSParam->globalDependencyMask, vfeDependencyInfo.count);
vfeDependencyInfo.count++;
}
}
}
}
reuseBBUpdateMask |= kernelTSParam->reuseBBUpdateMask;
}
if (vfeDependencyInfo.count > CM_HAL_MAX_DEPENDENCY_COUNT)
{
eStatus = MOS_STATUS_INVALID_PARAMETER;
CM_ASSERTMESSAGE("Union of kernel dependencies exceeds max dependency count (8)");
goto finish;
}
scoreboardParams->ScoreboardMask = (uint8_t)vfeDependencyInfo.count;
for (i = 0; i < scoreboardParams->ScoreboardMask; ++i)
{
scoreboardParams->ScoreboardDelta[i].x = vfeDependencyInfo.deltaX[i];
scoreboardParams->ScoreboardDelta[i].y = vfeDependencyInfo.deltaY[i];
}
//If no dependency defined in kernel data, then check per-task thread space setting
if (scoreboardParams->ScoreboardMask == 0)
{
if (taskParam->dependencyVectorsValid)
{
scoreboardParams->ScoreboardMask = (uint8_t)taskParam->dependencyVectors.count;
for (uint32_t i = 0; i < scoreboardParams->ScoreboardMask; ++i)
{
scoreboardParams->ScoreboardDelta[i].x = taskParam->dependencyVectors.deltaX[i];
scoreboardParams->ScoreboardDelta[i].y = taskParam->dependencyVectors.deltaY[i];
}
}
else
{
switch (taskParam->dependencyPattern)
{
case CM_NONE_DEPENDENCY:
break;
case CM_VERTICAL_WAVE:
scoreboardParams->ScoreboardMask = 1;
scoreboardParams->ScoreboardDelta[0].x = 0xF; // -1 in uint8_t:4
scoreboardParams->ScoreboardDelta[0].y = 0;
break;
case CM_HORIZONTAL_WAVE:
scoreboardParams->ScoreboardMask = 1;
scoreboardParams->ScoreboardDelta[0].x = 0;
scoreboardParams->ScoreboardDelta[0].y = 0xF; // -1 in uint8_t:4
break;
case CM_WAVEFRONT:
scoreboardParams->ScoreboardMask = 3;
scoreboardParams->ScoreboardDelta[0].x = 0xF; // -1 in uint8_t:4
scoreboardParams->ScoreboardDelta[0].y = 0;
scoreboardParams->ScoreboardDelta[1].x = 0xF; // -1 in uint8_t:4
scoreboardParams->ScoreboardDelta[1].y = 0xF; // -1 in uint8_t:4
scoreboardParams->ScoreboardDelta[2].x = 0;
scoreboardParams->ScoreboardDelta[2].y = 0xF; // -1 in uint8_t:4
break;
case CM_WAVEFRONT26:
scoreboardParams->ScoreboardMask = 4;
scoreboardParams->ScoreboardDelta[0].x = 0xF; // -1 in uint8_t:4
scoreboardParams->ScoreboardDelta[0].y = 0;
scoreboardParams->ScoreboardDelta[1].x = 0xF; // -1 in uint8_t:4
scoreboardParams->ScoreboardDelta[1].y = 0xF; // -1 in uint8_t:4
scoreboardParams->ScoreboardDelta[2].x = 0;
scoreboardParams->ScoreboardDelta[2].y = 0xF; // -1 in uint8_t:4
scoreboardParams->ScoreboardDelta[3].x = 1;
scoreboardParams->ScoreboardDelta[3].y = 0xF; // -1 in uint8_t:4
break;
case CM_WAVEFRONT26Z:
case CM_WAVEFRONT26ZIG:
scoreboardParams->ScoreboardMask = 5;
scoreboardParams->ScoreboardDelta[0].x = 0xF; // -1 in uint8_t:4
scoreboardParams->ScoreboardDelta[0].y = 1;
scoreboardParams->ScoreboardDelta[1].x = 0xF; // -1 in uint8_t:4
scoreboardParams->ScoreboardDelta[1].y = 0;
scoreboardParams->ScoreboardDelta[2].x = 0xF; // -1 in uint8_t:4
scoreboardParams->ScoreboardDelta[2].y = 0xF; // -1 in uint8_t:4
scoreboardParams->ScoreboardDelta[3].x = 0;
scoreboardParams->ScoreboardDelta[3].y = 0xF; // -1 in uint8_t:4
scoreboardParams->ScoreboardDelta[4].x = 1;
scoreboardParams->ScoreboardDelta[4].y = 0xF; // -1 in uint8_t:4
break;
case CM_WAVEFRONT26ZI:
scoreboardParams->ScoreboardMask = 7;
scoreboardParams->ScoreboardDelta[0].x = 0xF; // -1 in uint8_t:4
scoreboardParams->ScoreboardDelta[0].y = 1;
scoreboardParams->ScoreboardDelta[1].x = 0xE; // -2
scoreboardParams->ScoreboardDelta[1].y = 0;
scoreboardParams->ScoreboardDelta[2].x = 0xF; // -1 in uint8_t:4
scoreboardParams->ScoreboardDelta[2].y = 0;
scoreboardParams->ScoreboardDelta[3].x = 0xF; // -1 in uint8_t:4
scoreboardParams->ScoreboardDelta[3].y = 0xF; // -1 in uint8_t:4
scoreboardParams->ScoreboardDelta[4].x = 0;
scoreboardParams->ScoreboardDelta[4].y = 0xF; // -1 in uint8_t:4
scoreboardParams->ScoreboardDelta[5].x = 1;
scoreboardParams->ScoreboardDelta[5].y = 0xF; // -1 in uint8_t:4
scoreboardParams->ScoreboardDelta[6].x = 1;
scoreboardParams->ScoreboardDelta[6].y = 0;
break;
case CM_WAVEFRONT26X:
scoreboardParams->ScoreboardMask = 7;
scoreboardParams->ScoreboardDelta[0].x = 0xF;
scoreboardParams->ScoreboardDelta[0].y = 3;
scoreboardParams->ScoreboardDelta[1].x = 0xF;
scoreboardParams->ScoreboardDelta[1].y = 1;
scoreboardParams->ScoreboardDelta[2].x = 0xF;
scoreboardParams->ScoreboardDelta[2].y = 0xF;
scoreboardParams->ScoreboardDelta[3].x = 0;
scoreboardParams->ScoreboardDelta[3].y = 0xF;
scoreboardParams->ScoreboardDelta[4].x = 0;
scoreboardParams->ScoreboardDelta[4].y = 0xE;
scoreboardParams->ScoreboardDelta[5].x = 0;
scoreboardParams->ScoreboardDelta[5].y = 0xD;
scoreboardParams->ScoreboardDelta[6].x = 1;
scoreboardParams->ScoreboardDelta[6].y = 0xD;
break;
default:
taskParam->dependencyPattern = CM_NONE_DEPENDENCY;
break;
}
}
}
}
//Set size of surface binding table size
CM_SURFACE_BTI_INFO surfBTIInfo;
state->cmHalInterface->GetHwSurfaceBTIInfo(&surfBTIInfo);
taskParam->surfacePerBT += surfBTIInfo.normalSurfaceStart ;
// add one if kernel debugger is enabled
if (execParam->kernelDebugEnabled)
{
taskParam->surfacePerBT += CM_RESERVED_SURFACE_NUMBER_FOR_KERNEL_DEBUG;
}
//If global surface is used and current surface bt size less than the max index of reserved surfaces
//use set it as max bti size
if ((execParam->globalSurfaceUsed) && (taskParam->surfacePerBT < surfBTIInfo.reservedSurfaceEnd))
{
taskParam->surfacePerBT = CM_MAX_STATIC_SURFACE_STATES_PER_BT;
}
//Make sure surfacePerBT do not exceed CM_MAX_STATIC_SURFACE_STATES_PER_BT
taskParam->surfacePerBT = MOS_MIN(CM_MAX_STATIC_SURFACE_STATES_PER_BT, taskParam->surfacePerBT);
if( taskParam->dependencyMasks )
{
for (krn = 0; krn < execParam->numKernels; krn++)
{
kernelParam = execParam->kernels[krn];
dependencyMask = taskParam->dependencyMasks[krn];
if( dependencyMask )
{
for( i = 0; i < kernelParam->numThreads; ++i )
{
reuseBBUpdateMask |= dependencyMask[i].resetMask;
}
}
}
}
CM_HAL_CHECKBIT_IS_SET(bitIsSet, reuseBBUpdateMask, CM_NO_BATCH_BUFFER_REUSE_BIT_POS);
if( bitIsSet || reuseBBUpdateMask == 0 )
{
taskParam->reuseBBUpdateMask = 0;
}
else
{
taskParam->reuseBBUpdateMask = 1;
}
threadArgExists = HalCm_GetTaskHasThreadArg(execParam->kernels, execParam->numKernels);
// For media object with thread arg, only support up to CM_MAX_USER_THREADS (512*512) threads
// otherwise can support up to 262144 media object commands in batch buffer
if (!state->walkerParams.CmWalkerEnable) {
if (!threadArgExists)
{
if(totalThreads > CM_MAX_USER_THREADS_NO_THREADARG)
{
eStatus = MOS_STATUS_INVALID_PARAMETER;
CM_ASSERTMESSAGE(
"Total task threads '%d' exceeds max allowed threads '%d'",
totalThreads,
CM_MAX_USER_THREADS_NO_THREADARG);
goto finish;
}
}
else
{
if (totalThreads > CM_MAX_USER_THREADS)
{
eStatus = MOS_STATUS_INVALID_PARAMETER;
CM_ASSERTMESSAGE(
"Total task threads '%d' exceeds max allowed threads '%d'",
totalThreads,
CM_MAX_USER_THREADS);
goto finish;
}
}
}
taskParam->queueOption = execParam->queueOption;
finish:
return eStatus;
}
//*-----------------------------------------------------------------------------
//| Purpose: Parse the Kernel and populate the Task Param structure
//| Return: Result of the operation
//*-----------------------------------------------------------------------------
MOS_STATUS HalCm_ParseGroupTask(
PCM_HAL_STATE state, // [in] Pointer to HAL CM state
PCM_HAL_EXEC_GROUP_TASK_PARAM execGroupParam) // [in] Pointer to Exec Task Param
{
PCM_HAL_TASK_PARAM taskParam = state->taskParam;
MOS_STATUS eStatus = MOS_STATUS_SUCCESS;
PCM_HAL_KERNEL_PARAM kernelParam = nullptr;
uint32_t uSurfaceIndex;
taskParam->surfEntryInfoArrays = execGroupParam->surEntryInfoArrays; //GT-PIN
taskParam->batchBufferSize = 0;
taskParam->kernelDebugEnabled = (uint32_t)execGroupParam->kernelDebugEnabled;
taskParam->numKernels = execGroupParam->numKernels;
taskParam->syncBitmap = execGroupParam->syncBitmap;
taskParam->conditionalEndBitmap = execGroupParam->conditionalEndBitmap;
MOS_SecureMemcpy(taskParam->conditionalEndInfo, sizeof(taskParam->conditionalEndInfo),
execGroupParam->conditionalEndInfo, sizeof(execGroupParam->conditionalEndInfo));
taskParam->taskConfig = execGroupParam->taskConfig;
MOS_SecureMemcpy(taskParam->krnExecCfg, sizeof(taskParam->krnExecCfg),
execGroupParam->krnExecCfg, sizeof(execGroupParam->krnExecCfg));
for (uint32_t krn = 0; krn < execGroupParam->numKernels; krn ++)
{
kernelParam = execGroupParam->kernels[krn];
PCM_INDIRECT_SURFACE_INFO indirectSurfaceInfo = kernelParam->indirectDataParam.surfaceInfo;
uint32_t uSurfaceNumber = 0;
if (kernelParam->indirectDataParam.surfaceCount)
{
uSurfaceIndex = 0;
for (uint32_t i = 0; i < kernelParam->indirectDataParam.surfaceCount; i++)
{
uSurfaceIndex = (indirectSurfaceInfo + i)->bindingTableIndex > uSurfaceIndex ? (indirectSurfaceInfo + i)->bindingTableIndex : uSurfaceIndex;
uSurfaceNumber++;
}
taskParam->surfacePerBT = taskParam->surfacePerBT > uSurfaceIndex ? taskParam->surfacePerBT : uSurfaceIndex;
}
uSurfaceNumber += kernelParam->numSurfaces;
taskParam->surfacePerBT = taskParam->surfacePerBT < uSurfaceNumber ?
uSurfaceNumber : taskParam->surfacePerBT;
}
CM_SURFACE_BTI_INFO surfBTIInfo;
state->cmHalInterface->GetHwSurfaceBTIInfo(&surfBTIInfo);
taskParam->surfacePerBT += surfBTIInfo.normalSurfaceStart ;
// add one if kernel debugger is enabled
if (execGroupParam->kernelDebugEnabled)
{
taskParam->surfacePerBT += CM_RESERVED_SURFACE_NUMBER_FOR_KERNEL_DEBUG;
}
//If global surface is used and current surface bt size less than the max index of reserved surfaces
//use set it as max bti size
if ((execGroupParam->globalSurfaceUsed) &&
(taskParam->surfacePerBT < surfBTIInfo.reservedSurfaceEnd))
{
taskParam->surfacePerBT = CM_MAX_STATIC_SURFACE_STATES_PER_BT;
}
//Make sure surfacePerBT do not exceed CM_MAX_STATIC_SURFACE_STATES_PER_BT
taskParam->surfacePerBT = MOS_MIN(CM_MAX_STATIC_SURFACE_STATES_PER_BT, taskParam->surfacePerBT);
taskParam->queueOption = execGroupParam->queueOption;
return eStatus;
}
//*-----------------------------------------------------------------------------
//| Purpose: Parse the Kernel and populate the Hints Task Param structure
//| Return: Result of the operation
//*-----------------------------------------------------------------------------
MOS_STATUS HalCm_ParseHintsTask(
PCM_HAL_STATE state, // [in] Pointer to HAL CM state
PCM_HAL_EXEC_HINTS_TASK_PARAM execHintsParam)
{
MOS_STATUS eStatus;
PCM_HAL_TASK_PARAM taskParam;
PCM_HAL_KERNEL_PARAM kernelParam;
uint32_t hdrSize;
uint32_t totalThreads;
uint32_t krn;
uint32_t curbeOffset;
PMHW_VFE_SCOREBOARD scoreboardParams;
uint32_t hasThreadArg;
bool nonstallingScoreboardEnable;
bool bitIsSet;
uint8_t reuseBBUpdateMask;
bool threadArgExists;
eStatus = MOS_STATUS_SUCCESS;
krn = 0;
taskParam = state->taskParam;
nonstallingScoreboardEnable = true;
bitIsSet = false;
curbeOffset = 0;
hasThreadArg = 0;
totalThreads = 0;
reuseBBUpdateMask = 0;
threadArgExists = false;
hdrSize = state->renderHal->pHwSizes->dwSizeMediaObjectHeaderCmd;
scoreboardParams = &state->scoreboardParams;
for( krn = 0; krn < execHintsParam->numKernels; ++krn )
{
if ((execHintsParam->kernels[krn] == nullptr) ||
(execHintsParam->kernelSizes[krn] == 0))
{
eStatus = MOS_STATUS_INVALID_PARAMETER;
CM_ASSERTMESSAGE("Invalid Kernel data");
goto finish;
}
// Parse the kernel Param
kernelParam = execHintsParam->kernels[krn];
// if any kernel disables non-stalling, the non-stalling will be disabled
nonstallingScoreboardEnable &= (kernelParam->cmFlags & CM_KERNEL_FLAGS_NONSTALLING_SCOREBOARD) ? true : false;
if (!state->walkerParams.CmWalkerEnable)
{
taskParam->batchBufferSize +=
kernelParam->numThreads * (hdrSize + MOS_MAX(kernelParam->payloadSize, 4));
}
totalThreads += kernelParam->numThreads;
reuseBBUpdateMask |= kernelParam->kernelThreadSpaceParam.reuseBBUpdateMask;
}
CM_HAL_CHECKBIT_IS_SET(bitIsSet, reuseBBUpdateMask, CM_NO_BATCH_BUFFER_REUSE_BIT_POS);
if( bitIsSet || reuseBBUpdateMask == 0 )
{
taskParam->reuseBBUpdateMask = 0;
}
else
{
taskParam->reuseBBUpdateMask = 1;
}
taskParam->batchBufferSize += CM_EXTRA_BB_SPACE;
scoreboardParams->ScoreboardType = nonstallingScoreboardEnable;
threadArgExists = HalCm_GetTaskHasThreadArg(execHintsParam->kernels, execHintsParam->numKernels);
if (!state->walkerParams.CmWalkerEnable) {
if (!threadArgExists)
{
if(totalThreads > CM_MAX_USER_THREADS_NO_THREADARG)
{
eStatus = MOS_STATUS_INVALID_PARAMETER;
CM_ASSERTMESSAGE(
"Total task threads '%d' exceeds max allowed threads '%d'",
totalThreads,
CM_MAX_USER_THREADS_NO_THREADARG);
goto finish;
}
}
else
{
if (totalThreads > CM_MAX_USER_THREADS)
{
eStatus = MOS_STATUS_INVALID_PARAMETER;
CM_ASSERTMESSAGE(
"Total task threads '%d' exceeds max allowed threads '%d'",
totalThreads,
CM_MAX_USER_THREADS);
goto finish;
}
}
}
taskParam->queueOption = execHintsParam->queueOption;
finish:
return eStatus;
}
/*
** check to see if kernel entry is flaged as free or it is null
** used for combining
*/
bool bIsFree( PRENDERHAL_KRN_ALLOCATION kAlloc )
{
if (kAlloc== nullptr)
{
return false;
}
else
{
if (kAlloc->dwFlags != RENDERHAL_KERNEL_ALLOCATION_FREE)
{
return false;
}
}
return true;
}
/*
** local used supporting function
** setup correct values according to input and copy kernelBinary as needed
*/
void CmLoadKernel(PCM_HAL_STATE state,
PRENDERHAL_STATE_HEAP stateHeap,
PRENDERHAL_KRN_ALLOCATION kernelAllocation,
uint32_t sync,
uint32_t count,
PRENDERHAL_KERNEL_PARAM parameters,
PCM_HAL_KERNEL_PARAM kernelParam,
MHW_KERNEL_PARAM *mhwKernelParam,
bool isCloneEntry)
{
UNUSED(state);
if (mhwKernelParam)
{
kernelAllocation->iKID = -1;
kernelAllocation->iKUID = mhwKernelParam->iKUID;
kernelAllocation->iKCID = mhwKernelParam->iKCID;
kernelAllocation->dwSync = sync;
kernelAllocation->dwCount = count & 0xFFFFFFFF; // 28 bits
kernelAllocation->dwFlags = RENDERHAL_KERNEL_ALLOCATION_USED;
kernelAllocation->Params = *parameters;
kernelAllocation->pMhwKernelParam = mhwKernelParam;
if (!isCloneEntry)
{
// Copy kernel data
// Copy MovInstruction First
MOS_SecureMemcpy(stateHeap->pIshBuffer + kernelAllocation->dwOffset,
kernelParam->movInsDataSize,
kernelParam->movInsData,
kernelParam->movInsDataSize);
// Copy Cm Kernel Binary
MOS_SecureMemcpy(stateHeap->pIshBuffer + kernelAllocation->dwOffset + kernelParam->movInsDataSize,
kernelParam->kernelBinarySize - kernelParam->movInsDataSize,
kernelParam->kernelBinary,
kernelParam->kernelBinarySize - kernelParam->movInsDataSize);
// Padding bytes dummy instructions after kernel binary to resolve page fault issue
MOS_ZeroMemory(stateHeap->pIshBuffer + kernelAllocation->dwOffset + kernelParam->kernelBinarySize, CM_KERNEL_BINARY_PADDING_SIZE);
}
}
else
{
kernelAllocation->iKID = -1;
kernelAllocation->iKUID = -1;
kernelAllocation->iKCID = -1;
kernelAllocation->dwSync = 0;
kernelAllocation->dwCount = 0;
kernelAllocation->dwFlags = RENDERHAL_KERNEL_ALLOCATION_FREE;
kernelAllocation->pMhwKernelParam = nullptr;
kernelAllocation->cloneKernelParams.cloneKernelID = -1;
kernelAllocation->cloneKernelParams.isClone = false;
kernelAllocation->cloneKernelParams.isHeadKernel = false;
kernelAllocation->cloneKernelParams.kernelBinaryAllocID = -1;
kernelAllocation->cloneKernelParams.referenceCount = 0;
}
}
/*
** local used supporting function
** Try to find free entry which is big enough to load kernel binary
** If we cannot find one, then return fail, so we will delete more entries
*/
int32_t CmSearchFreeSlotSize(PCM_HAL_STATE state, MHW_KERNEL_PARAM *mhwKernelParam, bool isCloneEntry)
{
PRENDERHAL_STATE_HEAP stateHeap;
PRENDERHAL_KRN_ALLOCATION kernelAllocation;
int32_t kernelAllocationID;
int32_t returnVal = -1;
int32_t neededSize;
stateHeap = state->renderHal->pStateHeap;
kernelAllocation = stateHeap->pKernelAllocation;
if (isCloneEntry)
{
neededSize = CM_64BYTE;
}
else
{
neededSize = mhwKernelParam->iSize;
}
for (kernelAllocationID = 0;
kernelAllocationID < state->kernelNumInGsh;
kernelAllocationID++, kernelAllocation++)
{
if(kernelAllocation->dwFlags == RENDERHAL_KERNEL_ALLOCATION_FREE)
{
if(state->totalKernelSize[kernelAllocationID] >= neededSize)
{
// found free slot which is big enough
return kernelAllocationID;
}
}
}
// not found
return returnVal;
}
//*-----------------------------------------------------------------------------
//| Purpose: Updates the clone entries' head kernel binary allocation IDs
//| Function is called after kernel allocations are shifted due to combining neighboring free entries
//| Return: Result of the operation
//*-----------------------------------------------------------------------------
void HalCm_UpdateCloneKernel(PCM_HAL_STATE state,
uint32_t shiftPoint,
CM_SHIFT_DIRECTION shiftDirection,
uint32_t shiftFactor)
{
PRENDERHAL_STATE_HEAP stateHeap;
PRENDERHAL_KRN_ALLOCATION kernelAllocation;
int32_t allocationID;
stateHeap = state->renderHal->pStateHeap;
kernelAllocation = stateHeap->pKernelAllocation;
for (allocationID = 0; allocationID < state->kernelNumInGsh; allocationID++, kernelAllocation++)
{
kernelAllocation = &(stateHeap->pKernelAllocation[allocationID]);
if (kernelAllocation->cloneKernelParams.isClone && ((kernelAllocation->cloneKernelParams.kernelBinaryAllocID) > (int32_t)shiftPoint))
{
if (shiftDirection == CM_SHIFT_LEFT)
{
kernelAllocation->cloneKernelParams.kernelBinaryAllocID = kernelAllocation->cloneKernelParams.kernelBinaryAllocID + shiftFactor;
}
else
{
kernelAllocation->cloneKernelParams.kernelBinaryAllocID = kernelAllocation->cloneKernelParams.kernelBinaryAllocID - shiftFactor;
}
}
}
}
/*
** local used supporting function
** We found free slot and load kernel to this slot. There are 3 cases (see code)
*/
int32_t CmAddCurrentKernelToFreeSlot(PCM_HAL_STATE state,
int32_t slot,
PRENDERHAL_KERNEL_PARAM parameters,
PCM_HAL_KERNEL_PARAM kernelParam,
MHW_KERNEL_PARAM *mhwKernelParam,
CM_CLONE_TYPE cloneType,
int32_t headKernelAllocationID)
{
PRENDERHAL_STATE_HEAP stateHeap;
PRENDERHAL_KRN_ALLOCATION kernelAllocation, pKernelAllocationN;
int32_t hr = CM_SUCCESS;
int32_t i;
int32_t totalSize, tmpSize, dwOffset, neededSize;
bool adjust, isCloneEntry, isHeadKernel, isCloneAsHead, adjustHeadKernelID;
uint32_t tag;
stateHeap = state->renderHal->pStateHeap;
kernelAllocation = stateHeap->pKernelAllocation;
adjustHeadKernelID = false;
switch (cloneType)
{
case CM_CLONE_ENTRY:
{
neededSize = CM_64BYTE;
isCloneEntry = true;
isHeadKernel = false;
isCloneAsHead = false;
}
break;
case CM_HEAD_KERNEL:
{
neededSize = mhwKernelParam->iSize;
isHeadKernel = true;
isCloneEntry = false;
isCloneAsHead = false;
}
break;
case CM_CLONE_AS_HEAD_KERNEL:
{
neededSize = mhwKernelParam->iSize;
isHeadKernel = true;
isCloneEntry = false;
isCloneAsHead = true;
}
break;
case CM_NO_CLONE:
{
neededSize = mhwKernelParam->iSize;
isCloneEntry = false;
isHeadKernel = false;
isCloneAsHead = false;
}
break;
default:
{
hr = CM_FAILURE;
goto finish;
}
}
// to check if we have perfect size match
if(stateHeap->pKernelAllocation[slot].iSize == neededSize)
{
adjust = false;
}
else
{
adjust = true;
}
if ((state->kernelNumInGsh < state->cmDeviceParam.maxGshKernelEntries) && adjust)
{
// we have extra entry to add
// add new entry and pump index down below
int32_t lastKernel = state->kernelNumInGsh - 1;
for(i = lastKernel; i>slot; i--)
{
kernelAllocation = &stateHeap->pKernelAllocation[i];
pKernelAllocationN = &stateHeap->pKernelAllocation[i+1];
*pKernelAllocationN = *kernelAllocation;
state->totalKernelSize[i+1] = state->totalKernelSize[i];
}
if (lastKernel > slot)
{
// update the headKernelAllocationID if it was shifted
if (headKernelAllocationID > slot)
{
headKernelAllocationID++;
adjustHeadKernelID = true;
}
}
totalSize = state->totalKernelSize[slot];
tmpSize = neededSize;
dwOffset = stateHeap->pKernelAllocation[slot].dwOffset;
// now add new one
kernelAllocation = &stateHeap->pKernelAllocation[slot];
if(state->cbbEnabled)
{
tag = state->osInterface->pfnGetGpuStatusTag(state->osInterface,
state->osInterface->CurrentGpuContextOrdinal);
}
else
{
tag = stateHeap->dwNextTag;
}
CmLoadKernel(state, stateHeap, kernelAllocation, tag, stateHeap->dwAccessCounter, parameters, kernelParam, mhwKernelParam, isCloneEntry);
stateHeap->dwAccessCounter++;
kernelAllocation->iSize = tmpSize;
state->totalKernelSize[slot] = MOS_ALIGN_CEIL(tmpSize, 64);
// insert a new slot which is free with rest
tmpSize = MOS_ALIGN_CEIL(tmpSize, 64); // HW required 64 byte align
kernelAllocation = &stateHeap->pKernelAllocation[slot+1];
CmLoadKernel(state, stateHeap, kernelAllocation, 0, 0, parameters, kernelParam, nullptr, isCloneEntry);
kernelAllocation->dwOffset = dwOffset+tmpSize;
kernelAllocation->iSize = 0;
state->totalKernelSize[slot+1] = totalSize - tmpSize;
// added one more entry
state->kernelNumInGsh++;
kernelAllocation = &stateHeap->pKernelAllocation[slot];
if (isCloneEntry)
{
if (!stateHeap->pKernelAllocation[headKernelAllocationID].cloneKernelParams.isHeadKernel)
{
// ERROR thought kernel with allocation ID, headKernelAllocationID, was a head kernel, but it's not
hr = CM_FAILURE;
goto finish;
}
kernelAllocation->cloneKernelParams.dwOffsetForAllocID = dwOffset;
kernelAllocation->dwOffset = stateHeap->pKernelAllocation[headKernelAllocationID].dwOffset;
kernelAllocation->cloneKernelParams.isClone = true;
kernelAllocation->cloneKernelParams.kernelBinaryAllocID = headKernelAllocationID;
kernelAllocation->cloneKernelParams.cloneKernelID = stateHeap->pKernelAllocation[headKernelAllocationID].iKUID;
stateHeap->pKernelAllocation[headKernelAllocationID].cloneKernelParams.referenceCount = stateHeap->pKernelAllocation[headKernelAllocationID].cloneKernelParams.referenceCount + 1;
// update head kernel's count after updating the clone entry's count so that clone will be selected for deletion first
stateHeap->pKernelAllocation[headKernelAllocationID].dwCount = stateHeap->dwAccessCounter++;
}
else
{
kernelAllocation->dwOffset = dwOffset;
if (isHeadKernel)
{
kernelAllocation->cloneKernelParams.isHeadKernel = true;
if (isCloneAsHead)
{
kernelAllocation->cloneKernelParams.cloneKernelID = kernelParam->clonedKernelParam.kernelID;
}
}
}
if (lastKernel > slot)
{
HalCm_UpdateCloneKernel(state, slot, CM_SHIFT_LEFT, 1);
if (isCloneEntry && adjustHeadKernelID)
{
// if clone entry and already adjusted head kernel ID, then adjusted again in HalCm_UpdateCloneKernel, need to do only once
kernelAllocation->cloneKernelParams.kernelBinaryAllocID = kernelAllocation->cloneKernelParams.kernelBinaryAllocID - 1;
}
}
}
else if (state->kernelNumInGsh < state->cmDeviceParam.maxGshKernelEntries)
{
// no need to create a new entry since we have the same size
kernelAllocation = &stateHeap->pKernelAllocation[slot];
if(state->cbbEnabled)
{
tag = state->osInterface->pfnGetGpuStatusTag(state->osInterface,
state->osInterface->CurrentGpuContextOrdinal);
}
else
{
tag = stateHeap->dwNextTag;
}
CmLoadKernel(state, stateHeap, kernelAllocation, tag, stateHeap->dwAccessCounter, parameters, kernelParam, mhwKernelParam, isCloneEntry);
stateHeap->dwAccessCounter++;
// no change for kernelAllocation->dwOffset
kernelAllocation->iSize = neededSize;
state->totalKernelSize[slot] = MOS_ALIGN_CEIL(mhwKernelParam->iSize, 64);
if (isCloneEntry)
{
if (!stateHeap->pKernelAllocation[headKernelAllocationID].cloneKernelParams.isHeadKernel)
{
// ERROR thought kernel with allocation ID, headKernelAllocationID, was a head kernel, but it's not
hr = CM_FAILURE;
goto finish;
}
kernelAllocation->cloneKernelParams.dwOffsetForAllocID = kernelAllocation->dwOffset;
kernelAllocation->dwOffset = stateHeap->pKernelAllocation[headKernelAllocationID].dwOffset;
kernelAllocation->cloneKernelParams.isClone = true;
kernelAllocation->cloneKernelParams.kernelBinaryAllocID = headKernelAllocationID;
kernelAllocation->cloneKernelParams.cloneKernelID = stateHeap->pKernelAllocation[headKernelAllocationID].iKUID;
stateHeap->pKernelAllocation[headKernelAllocationID].cloneKernelParams.referenceCount = stateHeap->pKernelAllocation[headKernelAllocationID].cloneKernelParams.referenceCount + 1;
// update head kernel's count after updating the clone entry's count so that clone will be selected for deletion first
stateHeap->pKernelAllocation[headKernelAllocationID].dwCount = stateHeap->dwAccessCounter++;
}
else if (isHeadKernel)
{
kernelAllocation->cloneKernelParams.isHeadKernel = true;
if (isCloneAsHead)
{
kernelAllocation->cloneKernelParams.cloneKernelID = kernelParam->clonedKernelParam.kernelID;
}
}
}
else
{
// all slots are used, but we have one free which is big enough
// we may have fragmentation, but code is the same as above case
kernelAllocation = &stateHeap->pKernelAllocation[slot];
if(state->cbbEnabled)
{
tag = state->osInterface->pfnGetGpuStatusTag(state->osInterface, state->osInterface->CurrentGpuContextOrdinal);
}
else
{
tag = stateHeap->dwNextTag;
}
CmLoadKernel(state, stateHeap, kernelAllocation, tag, stateHeap->dwAccessCounter, parameters, kernelParam, mhwKernelParam, isCloneEntry);
stateHeap->dwAccessCounter++;
// kernelAllocation->iTotalSize is not changed, but we have smaller actual size
// no change for kernelAllocation->dwOffset
kernelAllocation->iSize = neededSize;
if (isCloneEntry)
{
if (!stateHeap->pKernelAllocation[headKernelAllocationID].cloneKernelParams.isHeadKernel)
{
// ERROR thought kernel with allocation ID, headKernelAllocationID, was a head kernel, but it's not
hr = CM_FAILURE;
goto finish;
}
kernelAllocation->cloneKernelParams.dwOffsetForAllocID = kernelAllocation->dwOffset;
kernelAllocation->dwOffset = stateHeap->pKernelAllocation[headKernelAllocationID].dwOffset;
kernelAllocation->cloneKernelParams.isClone = true;
kernelAllocation->cloneKernelParams.kernelBinaryAllocID = headKernelAllocationID;
kernelAllocation->cloneKernelParams.cloneKernelID = stateHeap->pKernelAllocation[headKernelAllocationID].iKUID;
stateHeap->pKernelAllocation[headKernelAllocationID].cloneKernelParams.referenceCount = stateHeap->pKernelAllocation[headKernelAllocationID].cloneKernelParams.referenceCount + 1;
// update head kernel's count after updating the clone entry's count so that clone will be selected for deletion first
stateHeap->pKernelAllocation[headKernelAllocationID].dwCount = stateHeap->dwAccessCounter++;
}
else if (isHeadKernel)
{
kernelAllocation->cloneKernelParams.isHeadKernel = true;
if (isCloneAsHead)
{
kernelAllocation->cloneKernelParams.cloneKernelID = kernelParam->clonedKernelParam.kernelID;
}
}
}
finish:
return hr;
}
/*----------------------------------------------------------------------------
| Name : HalCm_UnLoadKernel ( Replace RenderHal_UnloadKernel)
\---------------------------------------------------------------------------*/
int32_t HalCm_UnloadKernel(
PCM_HAL_STATE state,
PRENDERHAL_KRN_ALLOCATION kernelAllocation)
{
PRENDERHAL_INTERFACE renderHal = state->renderHal;
PRENDERHAL_STATE_HEAP stateHeap;
int32_t hr;
//---------------------------------------
CM_CHK_NULL_GOTOFINISH_CMERROR(renderHal);
CM_CHK_NULL_GOTOFINISH_CMERROR(renderHal->pStateHeap);
CM_CHK_NULL_GOTOFINISH_CMERROR(kernelAllocation);
//---------------------------------------
hr = CM_FAILURE;
stateHeap = renderHal->pStateHeap;
if (kernelAllocation->dwFlags == RENDERHAL_KERNEL_ALLOCATION_FREE)
{
goto finish;
}
CM_CHK_CMSTATUS_GOTOFINISH(HalCm_SyncKernel(state, kernelAllocation->dwSync));
// Unload kernel
if (kernelAllocation->pMhwKernelParam)
{
kernelAllocation->pMhwKernelParam->bLoaded = 0;
}
if (kernelAllocation->cloneKernelParams.isClone)
{
if (stateHeap->pKernelAllocation[kernelAllocation->cloneKernelParams.kernelBinaryAllocID].cloneKernelParams.isHeadKernel)
{
if ((stateHeap->pKernelAllocation[kernelAllocation->cloneKernelParams.kernelBinaryAllocID].cloneKernelParams.referenceCount) <= 0)
{
// ERROR
hr = CM_FAILURE;
goto finish;
}
}
else
{
// ERROR
hr = CM_FAILURE;
goto finish;
}
stateHeap->pKernelAllocation[kernelAllocation->cloneKernelParams.kernelBinaryAllocID].cloneKernelParams.referenceCount =
stateHeap->pKernelAllocation[kernelAllocation->cloneKernelParams.kernelBinaryAllocID].cloneKernelParams.referenceCount - 1;
// restore the dwOffset for this allocationID
kernelAllocation->dwOffset = kernelAllocation->cloneKernelParams.dwOffsetForAllocID;
}
else if (kernelAllocation->cloneKernelParams.isHeadKernel && kernelAllocation->cloneKernelParams.referenceCount != 0)
{
// ERROR, cloned kernel entries should have been selected for deletion before head kernel entry
hr = CM_FAILURE;
goto finish;
}
// Release kernel entry (Offset/size may be used for reallocation)
kernelAllocation->iKID = -1;
kernelAllocation->iKUID = -1;
kernelAllocation->iKCID = -1;
kernelAllocation->dwSync = 0;
kernelAllocation->dwFlags = RENDERHAL_KERNEL_ALLOCATION_FREE;
kernelAllocation->dwCount = 0;
kernelAllocation->pMhwKernelParam = nullptr;
kernelAllocation->cloneKernelParams.cloneKernelID = -1;
kernelAllocation->cloneKernelParams.isClone = false;
kernelAllocation->cloneKernelParams.isHeadKernel = false;
kernelAllocation->cloneKernelParams.kernelBinaryAllocID = -1;
kernelAllocation->cloneKernelParams.referenceCount = 0;
hr = CM_SUCCESS;
finish:
return hr;
}
/*----------------------------------------------------------------------------
| Name : HalCmw_TouchKernel ( Replace RenderHal_TouchKernel)
\---------------------------------------------------------------------------*/
int32_t HalCm_TouchKernel(
PCM_HAL_STATE state,
int32_t kernelAllocationID)
{
int32_t hr = CM_SUCCESS;
PRENDERHAL_STATE_HEAP stateHeap;
PRENDERHAL_KRN_ALLOCATION kernelAllocation;
PRENDERHAL_KRN_ALLOCATION headKernelAllocation;
uint32_t tag;
PRENDERHAL_INTERFACE renderHal = state->renderHal;
PMOS_INTERFACE osInterface = state->osInterface;
stateHeap = (renderHal) ? renderHal->pStateHeap : nullptr;
if (stateHeap == nullptr ||
stateHeap->pKernelAllocation == nullptr ||
kernelAllocationID < 0 ||
kernelAllocationID >= renderHal->StateHeapSettings.iKernelCount)
{
hr = CM_FAILURE;
goto finish;
}
// Update usage
kernelAllocation = &(stateHeap->pKernelAllocation[kernelAllocationID]);
if (kernelAllocation->dwFlags != RENDERHAL_KERNEL_ALLOCATION_FREE &&
kernelAllocation->dwFlags != RENDERHAL_KERNEL_ALLOCATION_LOCKED)
{
kernelAllocation->dwCount = stateHeap->dwAccessCounter++;
}
// Set sync tag, for deallocation control
if(state->cbbEnabled)
{
tag = osInterface->pfnGetGpuStatusTag(osInterface, osInterface->CurrentGpuContextOrdinal);
}
else
{
tag = stateHeap->dwNextTag;
}
kernelAllocation->dwSync = tag;
// if this kernel allocation is a cloned kernel, update the orig kernel sync tag and access counter
if (kernelAllocation->cloneKernelParams.isClone)
{
headKernelAllocation = &(stateHeap->pKernelAllocation[kernelAllocation->cloneKernelParams.kernelBinaryAllocID]);
if (headKernelAllocation->cloneKernelParams.referenceCount <= 0)
{
// ERROR
hr = CM_FAILURE;
goto finish;
}
headKernelAllocation->dwSync = tag;
headKernelAllocation->dwCount = stateHeap->dwAccessCounter++;
}
finish:
return hr;
}
/*
** Supporting function
** Delete oldest entry from table to free more space
** According to different cases, we will combine space with previous or next slot to get max space
*/
int32_t CmDeleteOldestKernel(PCM_HAL_STATE state, MHW_KERNEL_PARAM *mhwKernelParam)
{
PRENDERHAL_KRN_ALLOCATION kernelAllocation;
PRENDERHAL_INTERFACE renderHal = state->renderHal;;
PRENDERHAL_STATE_HEAP stateHeap = renderHal->pStateHeap;
UNUSED(state);
UNUSED(mhwKernelParam);
uint32_t oldest = 0;
uint32_t lastUsed;
int32_t kernelAllocationID, searchIndex = -1, index = -1;
int32_t alignedSize, shiftOffset;
int32_t hr = CM_SUCCESS;
kernelAllocation = stateHeap->pKernelAllocation;
// Search and deallocate oldest kernel (most likely this is optimal scheduling algorithm)
kernelAllocation = stateHeap->pKernelAllocation;
for (kernelAllocationID = 0;
kernelAllocationID < state->kernelNumInGsh;
kernelAllocationID++, kernelAllocation++)
{
// Skip unused entries
// Skip kernels flagged as locked (cannot be automatically deallocated)
if (kernelAllocation->dwFlags == RENDERHAL_KERNEL_ALLOCATION_FREE ||
kernelAllocation->dwFlags == RENDERHAL_KERNEL_ALLOCATION_LOCKED)
{
continue;
}
// Find kernel not used for the greater amount of time (measured in number of operations)
// Must not unload recently allocated kernels
lastUsed = (uint32_t)(stateHeap->dwAccessCounter - kernelAllocation->dwCount);
if (lastUsed > oldest)
{
searchIndex = kernelAllocationID;
oldest = lastUsed;
}
}
// Did not found any entry for deallocation, we get into a strange case!
if (searchIndex < 0)
{
CM_ASSERTMESSAGE("Failed to delete any slot from GSH. It is impossible.");
return CM_FAILURE;
}
if (stateHeap->pKernelAllocation[searchIndex].cloneKernelParams.isHeadKernel &&
(stateHeap->pKernelAllocation[searchIndex].cloneKernelParams.referenceCount != 0))
{
// ERROR, chose a head kernel for deletion but it still has clones pointing to it
return CM_FAILURE;
}
// Free kernel entry and states associated with the kernel (if any)
kernelAllocation = &stateHeap->pKernelAllocation[searchIndex];
if (HalCm_UnloadKernel(state, kernelAllocation) != CM_SUCCESS)
{
CM_ASSERTMESSAGE("Failed to load kernel - no space available in GSH.");
return CM_FAILURE;
}
// Let's check if we can merge searchIndex-1, searchIndex, searchIndex+1
index = searchIndex;
PRENDERHAL_KRN_ALLOCATION kAlloc0, kAlloc1, kAlloc2;
kAlloc0 = (index == 0)? nullptr : &stateHeap->pKernelAllocation[index-1];
kAlloc1 = &stateHeap->pKernelAllocation[index]; // free one
kAlloc2 = (index == state->cmDeviceParam.maxGshKernelEntries - 1) ? nullptr : &stateHeap->pKernelAllocation[index + 1];
if (bIsFree(kAlloc0) && bIsFree(kAlloc2))
{
// merge 3 into 1 slot and bump index after
stateHeap->pKernelAllocation[index-1].dwFlags = RENDERHAL_KERNEL_ALLOCATION_FREE;
state->totalKernelSize[index-1] += state->totalKernelSize[index] + state->totalKernelSize[index+1];
stateHeap->pKernelAllocation[index-1].iSize = 0;
// no change for stateHeap->pKernelAllocation[index-1].dwOffset
// copy the rest
for (int32_t i = index + 2; i<state->kernelNumInGsh; i++)
{
stateHeap->pKernelAllocation[i-2] = stateHeap->pKernelAllocation[i];
state->totalKernelSize[i-2] = state->totalKernelSize[i];
}
state->kernelNumInGsh -= 2;
if ( index == 0 )
HalCm_UpdateCloneKernel(state, 0, CM_SHIFT_RIGHT, 2);
else
HalCm_UpdateCloneKernel(state, index - 1, CM_SHIFT_RIGHT, 2);
}
else if (bIsFree(kAlloc0))
{
// merge before and current into 1 slot
stateHeap->pKernelAllocation[index-1].dwFlags = RENDERHAL_KERNEL_ALLOCATION_FREE;
state->totalKernelSize[index-1] += state->totalKernelSize[index];
stateHeap->pKernelAllocation[index-1].iSize = 0;
// no change for stateHeap->pKernelAllocation[index-1].dwOffset
for (int32_t i = index + 1; i<state->kernelNumInGsh; i++)
{
stateHeap->pKernelAllocation[i-1] = stateHeap->pKernelAllocation[i];
state->totalKernelSize[i-1] = state->totalKernelSize[i];
}
state->kernelNumInGsh -= 1;
if ( index == 0 )
HalCm_UpdateCloneKernel(state, 0, CM_SHIFT_RIGHT, 1);
else
HalCm_UpdateCloneKernel(state, index - 1, CM_SHIFT_RIGHT, 1);
}
else if (bIsFree(kAlloc2))
{
// kAlloc0 is not free, but it can be nullptr
// merge after and current into 1 slot
stateHeap->pKernelAllocation[index].dwFlags = RENDERHAL_KERNEL_ALLOCATION_FREE;
state->totalKernelSize[index] += state->totalKernelSize[index+1];
stateHeap->pKernelAllocation[index].iSize = 0;
if (kAlloc0)
{
// get free space starting point
alignedSize = MOS_ALIGN_CEIL(kAlloc0->iSize, 64);
shiftOffset = state->totalKernelSize[index-1] - alignedSize;
state->totalKernelSize[index-1] -= shiftOffset;
// no change for stateHeap->pKernelAllocation[index-1].iSize -= 0;
state->totalKernelSize[index] += shiftOffset;
stateHeap->pKernelAllocation[index].dwOffset -= shiftOffset;
}
for (int32_t i = index + 1; i<state->kernelNumInGsh; i++)
{
stateHeap->pKernelAllocation[i] = stateHeap->pKernelAllocation[i+1];
state->totalKernelSize[i] = state->totalKernelSize[i+1];
}
state->kernelNumInGsh -= 1;
if ( index == 0 )
HalCm_UpdateCloneKernel(state, 0, CM_SHIFT_RIGHT, 1);
else
HalCm_UpdateCloneKernel(state, index - 1, CM_SHIFT_RIGHT, 1);
}
else
{
// no merge
stateHeap->pKernelAllocation[index].dwFlags = RENDERHAL_KERNEL_ALLOCATION_FREE;
// no change for stateHeap->pKernelAllocation[index].iTotalSize;
stateHeap->pKernelAllocation[index].iSize = 0;
if(kAlloc0)
{
// get free space starting point
alignedSize = MOS_ALIGN_CEIL(kAlloc0->iSize, 64);
shiftOffset = state->totalKernelSize[index-1] - alignedSize;
state->totalKernelSize[index-1] -= shiftOffset;
// no change for stateHeap->pKernelAllocation[index-1].iSize -= 0;
state->totalKernelSize[index] += shiftOffset;
stateHeap->pKernelAllocation[index].dwOffset -= shiftOffset;
}
// no change for stateHeap->iNumKernels;
}
return hr;
}
/*----------------------------------------------------------------------------
| Name : HalCm_LoadKernel ( Replace RenderHal_LoadKernel)
\---------------------------------------------------------------------------*/
int32_t HalCm_LoadKernel(
PCM_HAL_STATE state,
PCM_HAL_KERNEL_PARAM kernelParam,
int32_t samplerCount,
PRENDERHAL_KRN_ALLOCATION &kernelAllocation)
{
PRENDERHAL_STATE_HEAP stateHeap;
PRENDERHAL_INTERFACE renderHal;
int32_t hr;
PRENDERHAL_KERNEL_PARAM parameters;
PMHW_KERNEL_PARAM mhwKernelParam;
int32_t kernelAllocationID; // Kernel allocation ID in GSH
int32_t kernelCacheID; // Kernel cache ID
int32_t kernelUniqueID; // Kernel unique ID
void *kernelPtr;
int32_t kernelSize;
int32_t searchIndex;
int32_t freeSlot;
bool isClonedKernel;
bool hasClones;
hr = CM_SUCCESS;
renderHal = state->renderHal;
stateHeap = (renderHal) ? renderHal->pStateHeap : nullptr;
kernelAllocationID = RENDERHAL_KERNEL_LOAD_FAIL;
mhwKernelParam = &(state->kernelParamsMhw);
parameters = &(state->kernelParamsRenderHal.Params);
// Validate parameters
if (stateHeap == nullptr ||
stateHeap->bIshLocked == false ||
stateHeap->pKernelAllocation == nullptr ||
kernelParam->kernelBinarySize == 0 ||
state->kernelNumInGsh > state->cmDeviceParam.maxGshKernelEntries)
{
CM_ASSERTMESSAGE("Failed to load kernel - invalid parameters.");
return CM_FAILURE;
}
isClonedKernel = kernelParam->clonedKernelParam.isClonedKernel;
hasClones = kernelParam->clonedKernelParam.hasClones;
parameters->Sampler_Count = samplerCount;
mhwKernelParam->iKUID = static_cast<int>( (kernelParam->kernelId >> 32) );
mhwKernelParam->iKCID = -1;
mhwKernelParam->pBinary = kernelParam->kernelBinary;
mhwKernelParam->iSize = kernelParam->kernelBinarySize + CM_KERNEL_BINARY_PADDING_SIZE;
// Kernel parameters
kernelPtr = mhwKernelParam->pBinary;
kernelSize = mhwKernelParam->iSize;
kernelUniqueID = mhwKernelParam->iKUID;
kernelCacheID = mhwKernelParam->iKCID;
// Check if kernel is already loaded; Search free allocation index
searchIndex = -1;
kernelAllocation = stateHeap->pKernelAllocation;
for (kernelAllocationID = 0;
kernelAllocationID < state->kernelNumInGsh;
kernelAllocationID++, kernelAllocation++)
{
if (kernelAllocation->iKUID == kernelUniqueID &&
kernelAllocation->iKCID == kernelCacheID)
{
// found match and Update kernel usage
hr = HalCm_TouchKernel(state, kernelAllocationID);
if (hr == CM_FAILURE)
{
goto finish;
}
// Increment reference counter
mhwKernelParam->bLoaded = 1;
// Record kernel allocation
kernelAllocation = &stateHeap->pKernelAllocation[kernelAllocationID];
goto finish;
}
}
if (isClonedKernel || hasClones)
{
hr = HalCm_InsertCloneKernel(state, kernelParam, kernelAllocation);
goto finish;
}
// here is the algorithm
// 1) search for free slot which is big enough to load current kerenel
// 2) if found slot, then add current kerenel
// 3) if we cannot find slot, we need to delete some entry (delete oldest first), after delete oldest entry
// we will loop over to step 1 until we get enough space.
// The algorithm won't fail except we load 1 kernel which is larger than 2MB
do
{
freeSlot = CmSearchFreeSlotSize(state, mhwKernelParam, false);
if (freeSlot >= 0)
{
// found free slot which is big enough to hold kernel
hr = CmAddCurrentKernelToFreeSlot(state, freeSlot, parameters, kernelParam, mhwKernelParam, CM_NO_CLONE, -1);
// update GSH states stateHeap->numKernels inside add function
break;
}
else
{
if (CmDeleteOldestKernel(state, mhwKernelParam) != CM_SUCCESS)
{
return CM_FAILURE;
}
}
} while(1);
mhwKernelParam->bLoaded = 1; // Increment reference counter
kernelAllocation = &stateHeap->pKernelAllocation[freeSlot]; // Record kernel allocation
finish:
return hr;
}
//*-----------------------------------------------------------------------------
//| Purpose: Loads cloned kernel entries and kernels with clones into free slot
//| Return: Result of the operation
//*-----------------------------------------------------------------------------
int32_t HalCm_InsertCloneKernel(
PCM_HAL_STATE state,
PCM_HAL_KERNEL_PARAM kernelParam,
PRENDERHAL_KRN_ALLOCATION &kernelAllocation)
{
int32_t hr = CM_SUCCESS;
int32_t kernelAllocationID; // Kernel allocation ID in GSH
uint32_t tag;
PMOS_INTERFACE osInterface = state->osInterface;
PMHW_KERNEL_PARAM mhwKernelParam = &(state->kernelParamsMhw);
int32_t freeSlot = -1;
PRENDERHAL_STATE_HEAP stateHeap = state->renderHal->pStateHeap;
kernelAllocation = state->renderHal->pStateHeap->pKernelAllocation;
for (kernelAllocationID = 0; kernelAllocationID < state->kernelNumInGsh;
kernelAllocationID++, kernelAllocation++)
{
if (kernelAllocation->cloneKernelParams.isHeadKernel)
{
if ((kernelAllocation->iKUID == kernelParam->clonedKernelParam.kernelID) || // original kernel that cloned from is already loaded as head
(kernelAllocation->cloneKernelParams.cloneKernelID == kernelParam->clonedKernelParam.kernelID) || // another clone from same original kernel is serving as the head
(kernelAllocation->cloneKernelParams.cloneKernelID == static_cast<int>(kernelParam->kernelId >> 32))) // clone is serving as the head and this is the original kernel
{
// found match, insert 64B dummy entry and set piKAID
do
{
// Before getting a free slot, update head kernel sync tag and count so head will not be selected for deletion
// then update head kernel count after inserting clone
// so that clone will be selected first for deletion (this is done in CmAddCurrentKernelToFreeSlot)
// update head kernel sync tag
if(state->cbbEnabled)
{
tag = osInterface->pfnGetGpuStatusTag(osInterface, osInterface->CurrentGpuContextOrdinal);
}
else
{
tag = state->renderHal->pStateHeap->dwNextTag;
}
kernelAllocation->dwSync = tag;
// update the head kernel count so it will not be selected for deletion
kernelAllocation->dwCount = state->renderHal->pStateHeap->dwAccessCounter++;
freeSlot = CmSearchFreeSlotSize(state, mhwKernelParam, true);
if (freeSlot >= 0)
{
// found free slot
hr = CmAddCurrentKernelToFreeSlot(state, freeSlot, &(state->kernelParamsRenderHal.Params),
kernelParam, &(state->kernelParamsMhw), CM_CLONE_ENTRY, kernelAllocationID);
goto finish;
}
else
{
if (CmDeleteOldestKernel(state, mhwKernelParam) != CM_SUCCESS)
{
hr = CM_FAILURE;
goto finish;
}
}
} while (1);
}
}
}
// didn't find a match, insert this kernel as the head kernel
do
{
freeSlot = CmSearchFreeSlotSize(state, mhwKernelParam, false);
if (freeSlot >= 0)
{
if (kernelParam->clonedKernelParam.isClonedKernel)
{
hr = CmAddCurrentKernelToFreeSlot(state, freeSlot, &(state->kernelParamsRenderHal.Params),
kernelParam, &(state->kernelParamsMhw), CM_CLONE_AS_HEAD_KERNEL, -1);
}
else
{
hr = CmAddCurrentKernelToFreeSlot(state, freeSlot, &(state->kernelParamsRenderHal.Params),
kernelParam, &(state->kernelParamsMhw), CM_HEAD_KERNEL, -1);
}
break;
}
else
{
if (CmDeleteOldestKernel(state, mhwKernelParam) != CM_SUCCESS)
{
hr = CM_FAILURE;
goto finish;
}
}
} while (1);
finish:
if (hr == CM_SUCCESS)
{
mhwKernelParam->bLoaded = 1;
kernelAllocation = &stateHeap->pKernelAllocation[freeSlot];
}
return hr;
}
//!
//! \brief Get offset to sampler state
//! \details Get offset to sampler state in General State Heap,
//! (Cm customized version of the RenderHal function which calculates
//! the sampler offset by MDF owned parameters).
//! \param PCM_HAL_STATE state
//! [in] Pointer to CM_HAL_STATE structure
//! \param PRENDERHAL_INTERFACE renderHal
//! [in] Pointer to RenderHal Interface
//! \param int mediaID
//! [in] Media ID associated with sampler
//! \param int samplerOffset
//! [in] sampler offset from the base of current kernel's sampler heap
//! \param int samplerBTI
//! [in] sampler BTI
//! \param unsigned long *pdwSamplerOffset
//! [out] optional; offset of sampler state from GSH base
//! \return MOS_STATUS
//!
MOS_STATUS HalCm_GetSamplerOffset(
PCM_HAL_STATE state,
PRENDERHAL_INTERFACE renderHal,
int mediaID,
unsigned int samplerOffset,
unsigned int samplerBTI,
PMHW_SAMPLER_STATE_PARAM samplerParam,
uint32_t *pdwSamplerOffset)
{
unsigned int tmpSamplerOffset = renderHal->pStateHeap->pCurMediaState->pDynamicState->Sampler3D.dwOffset +
state->taskParam->samplerOffsetsByKernel[mediaID] +
samplerOffset;
if (pdwSamplerOffset != nullptr)
{
*pdwSamplerOffset = tmpSamplerOffset;
}
if (samplerParam->SamplerType == MHW_SAMPLER_TYPE_3D)
{
samplerParam->Unorm.IndirectStateOffset = MOS_ALIGN_CEIL( renderHal->pStateHeap->pCurMediaState->pDynamicState->Sampler3D.dwOffset +
state->taskParam->samplerIndirectOffsetsByKernel[mediaID] +
samplerBTI * renderHal->pHwSizes->dwSizeSamplerIndirectState,
1 << MHW_SAMPLER_INDIRECT_SHIFT);
}
return MOS_STATUS_SUCCESS;
}
//!
//! \brief Setup Interface Descriptor
//! \details Set interface descriptor, (overriding RenderHal function),
//! (Cm customized version of the RenderHal function which set
//! dwSamplerOffset and dwSamplerCount by MDF owned parameters).
//! \param PCM_HAL_STATE state
//! [in] Pointer to CM_HAL_STATE structure
//! \param PRENDERHAL_INTERFACE renderHal
//! [in] Pointer to HW interface
//! \param PRENDERHAL_MEDIA_STATE mediaState
//! [in] Pointer to media state
//! \param PRENDERHAL_KRN_ALLOCATION kernelAllocation
//! [in] Pointer to kernel allocation
//! \param PRENDERHAL_INTERFACE_DESCRIPTOR_PARAMS interfaceDescriptorParams
//! [in] Pointer to interface descriptor parameters
//! \param PMHW_GPGPU_WALKER_PARAMS pGpGpuWalkerParams
//! [in] Pointer to gpgpu walker parameters
//! \return MOS_STATUS
//!
MOS_STATUS HalCm_SetupInterfaceDescriptor(
PCM_HAL_STATE state,
PRENDERHAL_INTERFACE renderHal,
PRENDERHAL_MEDIA_STATE mediaState,
PRENDERHAL_KRN_ALLOCATION kernelAllocation,
PRENDERHAL_INTERFACE_DESCRIPTOR_PARAMS interfaceDescriptorParams)
{
MOS_STATUS eStatus = MOS_STATUS_SUCCESS;
MHW_ID_ENTRY_PARAMS params;
PRENDERHAL_STATE_HEAP stateHeap;
PRENDERHAL_DYNAMIC_STATE dynamicState;
unsigned long mediaStateOffset;
//-----------------------------------------
MHW_RENDERHAL_CHK_NULL(renderHal);
MHW_RENDERHAL_CHK_NULL(renderHal->pMhwStateHeap);
MHW_RENDERHAL_CHK_NULL(mediaState);
MHW_RENDERHAL_CHK_NULL(mediaState->pDynamicState);
MHW_RENDERHAL_CHK_NULL(interfaceDescriptorParams);
//-----------------------------------------
// Get states, params
stateHeap = renderHal->pStateHeap;
dynamicState = mediaState->pDynamicState;
mediaStateOffset = dynamicState->memoryBlock.GetOffset();
params.dwMediaIdOffset = mediaStateOffset + dynamicState->MediaID.dwOffset;
params.iMediaId = interfaceDescriptorParams->iMediaID;
params.dwKernelOffset = kernelAllocation->dwOffset;
params.dwSamplerOffset = mediaStateOffset + dynamicState->Sampler3D.dwOffset + state->taskParam->samplerOffsetsByKernel[params.iMediaId];
params.dwSamplerCount = ( state->taskParam->samplerCountsByKernel[params.iMediaId] + 3 ) / 4;
params.dwSamplerCount = (params.dwSamplerCount > 4) ? 4 : params.dwSamplerCount;
params.dwBindingTableOffset = interfaceDescriptorParams->iBindingTableID * stateHeap->iBindingTableSize;
params.iCurbeOffset = interfaceDescriptorParams->iCurbeOffset;
params.iCurbeLength = interfaceDescriptorParams->iCurbeLength;
params.bBarrierEnable = interfaceDescriptorParams->blBarrierEnable;
params.bGlobalBarrierEnable = interfaceDescriptorParams->blGlobalBarrierEnable; //It's only applied for BDW+
params.dwNumberofThreadsInGPGPUGroup = interfaceDescriptorParams->iNumberThreadsInGroup;
params.dwSharedLocalMemorySize = renderHal->pfnEncodeSLMSize(renderHal, interfaceDescriptorParams->iSLMSize);
params.iCrsThdConDataRdLn = interfaceDescriptorParams->iCrsThrdConstDataLn;
params.memoryBlock = &dynamicState->memoryBlock;
MHW_RENDERHAL_CHK_STATUS(renderHal->pMhwStateHeap->AddInterfaceDescriptorData(¶ms));
dynamicState->MediaID.iCurrent++;
finish:
return eStatus;
}
/*----------------------------------------------------------------------------
| Name : HalCm_AllocateMediaID replace old RenderHal_AllocateMediaID
| Don't need touch kernel since we handle this a loadKernel time
|
| Purpose : Allocates an setup Interface Descriptor for Media Pipeline
|
| Arguments : [in] renderHal - Pointer to RenderHal interface structure
| [in] kernelParam - Pointer to Kernel parameters
| [in] pKernelAllocationID - Pointer to Kernel allocation
| [in] bindingTableID - Binding table ID
| [in] curbeOffset - Curbe offset (from CURBE base)
|
| Returns : Media Interface descriptor ID
| -1 if invalid parameters
| no Interface Descriptor entry available in GSH
|
| Comments : Kernel must be preloaded
| Curbe must be allocated using pfnAllocateCurbe
| Binding Table must be allocated using pfnAllocateBindingTable
\---------------------------------------------------------------------------*/
//!
//! \brief
//! \details
//! \param PRENDERHAL_INTERFACE renderHal
//| \param PCM_HAL_KERNEL_PARAM kernelParam
//| \param PRENDERHAL_KRN_ALLOCATION kernelAllocation
//| \param int32_t bindingTableID
//| \param int32_t curbeOffset
//! \return int32_t
//!
int32_t HalCm_AllocateMediaID(
PCM_HAL_STATE state,
PCM_HAL_KERNEL_PARAM kernelParam,
PRENDERHAL_KRN_ALLOCATION kernelAllocation,
int32_t bindingTableID,
int32_t curbeOffset)
{
PRENDERHAL_INTERFACE renderHal = state->renderHal;
PRENDERHAL_MEDIA_STATE curMediaState;
int32_t curbeSize, iCurbeCurrent;
int32_t interfaceDescriptor;
RENDERHAL_INTERFACE_DESCRIPTOR_PARAMS interfaceDescriptorParams;
interfaceDescriptor = -1;
// Obtain pointer and validate current media state
curMediaState = renderHal->pStateHeap->pCurMediaState;
if (state->dshEnabled)
{
if (curMediaState == nullptr || (state->dshEnabled && (curMediaState->pDynamicState == nullptr)))
{
CM_ASSERTMESSAGE("Invalid Media State.");
goto finish;
}
}
else
{
if (curMediaState == nullptr)
{
CM_ASSERTMESSAGE("Invalid Media State.");
goto finish;
}
}
// Validate kernel allocation (kernel must be pre-loaded into GSH)
if (!kernelAllocation ||
kernelAllocation->dwFlags == RENDERHAL_KERNEL_ALLOCATION_FREE ||
kernelAllocation->iSize == 0)
{
CM_ASSERTMESSAGE("Error: Invalid Kernel Allocation.");
goto finish;
}
// Check Curbe allocation (CURBE_Lenght is in 256-bit count -> convert to bytes)
curbeSize = kernelParam->curbeSizePerThread;
if (state->dshEnabled)
{
iCurbeCurrent = curMediaState->pDynamicState->Curbe.iCurrent;
}
else
{
iCurbeCurrent = curMediaState->iCurbeOffset;
}
if (curbeSize <= 0)
{
// Curbe is not used by the kernel
curbeSize = curbeOffset = 0;
}
// Validate Curbe Offset (curbe must be pre-allocated)
else if ( curbeOffset < 0 || // Not allocated
(curbeOffset & 0x1F) != 0 || // Invalid alignment
(curbeOffset + curbeSize) > iCurbeCurrent) // Invalid size
{
CM_ASSERTMESSAGE("Error: Invalid Curbe Allocation.");
goto finish;
}
// Try to reuse interface descriptor (for 2nd level buffer optimizations)
// Check if ID already in use by another kernel - must use a different ID
interfaceDescriptor = renderHal->pfnGetMediaID(renderHal, curMediaState, kernelAllocation);
if (interfaceDescriptor < 0)
{
CM_ASSERTMESSAGE("Error: No Interface Descriptor available.");
goto finish;
}
interfaceDescriptorParams.iMediaID = interfaceDescriptor;
interfaceDescriptorParams.iBindingTableID = bindingTableID;
//CURBE size and offset setting
//Media w/o group: only per-thread CURBE is used, CrossThread CURBE is not used.
//Media w/ group: should follow GPGPU walker setting, there is per-thread CURBE and cross-thread CURBE. But per-thread CURBE should be ZERO, and all should be cross-thread CURBE
//GPGPU: both per-thread CURBE and cross-thread CURBE need be set.
interfaceDescriptorParams.iCurbeOffset = curbeOffset;
if ((!kernelParam->gpgpuWalkerParams.gpgpuEnabled) && (kernelParam->kernelThreadSpaceParam.groupSelect == CM_MW_GROUP_NONE) && (state->taskParam->mediaWalkerGroupSelect == CM_MW_GROUP_NONE))
{ //Media pipe without group
interfaceDescriptorParams.iCurbeLength = kernelParam->curbeSizePerThread;
interfaceDescriptorParams.iCrsThrdConstDataLn = kernelParam->crossThreadConstDataLen; //should always be 0 in this case
interfaceDescriptorParams.iNumberThreadsInGroup = (kernelParam->numberThreadsInGroup > 0) ? kernelParam->numberThreadsInGroup : 1; // This field should not be set to 0 even if the barrier is disabled, since an accurate value is needed for proper pre-emption.
interfaceDescriptorParams.blGlobalBarrierEnable = false;
interfaceDescriptorParams.blBarrierEnable = false;
interfaceDescriptorParams.iSLMSize = 0;
}
else if ((!kernelParam->gpgpuWalkerParams.gpgpuEnabled) && ((kernelParam->kernelThreadSpaceParam.groupSelect != CM_MW_GROUP_NONE) || (state->taskParam->mediaWalkerGroupSelect != CM_MW_GROUP_NONE)))
{ //Media w/ group
interfaceDescriptorParams.iCurbeLength = 0; //No using per-thread CURBE
interfaceDescriptorParams.iCrsThrdConstDataLn = kernelParam->curbeSizePerThread; //treat all CURBE as cross-thread CURBE
interfaceDescriptorParams.iNumberThreadsInGroup = (kernelParam->numberThreadsInGroup > 0) ? kernelParam->numberThreadsInGroup : 1; // This field should not be set to 0 even if the barrier is disabled, since an accurate value is needed for proper pre-emption.
interfaceDescriptorParams.blBarrierEnable = (kernelParam->barrierMode != CM_NO_BARRIER) ? true : false;
interfaceDescriptorParams.blGlobalBarrierEnable = (kernelParam->barrierMode == CM_GLOBAL_BARRIER) ? true : false;
interfaceDescriptorParams.iSLMSize = kernelParam->slmSize;
}
else
{ //GPGPU pipe
interfaceDescriptorParams.iCurbeLength = kernelParam->curbeSizePerThread;
interfaceDescriptorParams.iCrsThrdConstDataLn = kernelParam->crossThreadConstDataLen;
interfaceDescriptorParams.iNumberThreadsInGroup = (kernelParam->numberThreadsInGroup > 0) ? kernelParam->numberThreadsInGroup : 1;
interfaceDescriptorParams.blBarrierEnable = (kernelParam->barrierMode != CM_NO_BARRIER) ? true : false;
interfaceDescriptorParams.blGlobalBarrierEnable = (kernelParam->barrierMode == CM_GLOBAL_BARRIER) ? true : false;
interfaceDescriptorParams.iSLMSize = kernelParam->slmSize;
}
if (state->useNewSamplerHeap == true)
{
HalCm_SetupInterfaceDescriptor(state, renderHal, curMediaState, kernelAllocation, &interfaceDescriptorParams);
}
else
{
// Setup Media ID entry - this call could be HW dependent
renderHal->pfnSetupInterfaceDescriptor(
renderHal,
curMediaState,
kernelAllocation,
&interfaceDescriptorParams);
}
finish:
return interfaceDescriptor;
}
bool isRenderTarget(PCM_HAL_STATE state, uint32_t index)
{
bool readSync = false;
readSync = state->umdSurf2DTable[index].readSyncs[state->osInterface->CurrentGpuContextOrdinal];
if (readSync)
return false;
else
return true;
}
int32_t HalCm_DSH_LoadKernelArray(
PCM_HAL_STATE state,
PCM_HAL_KERNEL_PARAM *kernelArray,
int32_t kernelCount,
PRENDERHAL_KRN_ALLOCATION *krnAllocation)
{
PRENDERHAL_INTERFACE renderHal;
PCM_HAL_KERNEL_PARAM kernel;
PMHW_STATE_HEAP_MEMORY_BLOCK memoryBlock; // Kernel memory block
int32_t totalSize; // Total size
uint32_t blockSize[CM_MAX_KERNELS_PER_TASK]; // Size of kernels to load
int32_t blockCount; // Number of kernels to load
MOS_STATUS eStatus = MOS_STATUS_SUCCESS;
int32_t hr = CM_FAILURE;
uint32_t currId, nextId;
renderHal = state->renderHal;
nextId = renderHal->pfnGetNextTrackerId(renderHal);
currId = renderHal->pfnGetCurrentTrackerId(renderHal);
state->criticalSectionDSH->Acquire();
do
{
blockCount = 0;
totalSize = 0;
// Obtain list of kernels already loaded, discard kernels loaded in older heaps.
// Calculate total size of kernels to be loaded, and get size of largest kernel.
for (int i = 0; i < kernelCount; i++)
{
// Find out if kernel is already allocated and loaded in ISH
kernel = kernelArray[i];
krnAllocation[i] = (PRENDERHAL_KRN_ALLOCATION)renderHal->pfnSearchDynamicKernel(renderHal, static_cast<int>((kernel->kernelId >> 32)), -1);
// Kernel is allocated - check if kernel is in current ISH
if (krnAllocation[i])
{
// Check if kernel is loaded
memoryBlock = krnAllocation[i]->pMemoryBlock;
if (memoryBlock)
{
// Kernel needs to be reloaded in current heap
if (memoryBlock->pStateHeap != renderHal->pMhwStateHeap->GetISHPointer() || state->forceKernelReload) //pInstructionStateHeaps
{
renderHal->pMhwStateHeap->FreeDynamicBlockDyn(MHW_ISH_TYPE, memoryBlock, currId);
krnAllocation[i]->pMemoryBlock = nullptr;
}
else
{
// Increment kernel usage count, used in kernel caching architecture
state->dshKernelCacheHit++;
krnAllocation[i]->dwCount++;
// Lock kernel to avoid removal while loading other kernels
krnAllocation[i]->dwFlags = RENDERHAL_KERNEL_ALLOCATION_LOCKED;
}
}
else if (krnAllocation[i]->dwFlags == RENDERHAL_KERNEL_ALLOCATION_REMOVED)
{
// This is a kernel that was unloaded and now needs to be reloaded
// Track how many times this "cache miss" happens to determine if the
// ISH is under pressure and needs to be expanded
state->dshKernelCacheMiss++;
}
}
else
{
// Assign kernel allocation for this kernel
krnAllocation[i] = renderHal->pfnAllocateDynamicKernel(renderHal, static_cast<int>((kernel->kernelId >> 32)), -1);
CM_CHK_NULL_GOTOFINISH_MOSERROR(krnAllocation[i]);
}
// Kernel is not loaded -> add to list of kernels to be loaded
if (krnAllocation[i]->pMemoryBlock == nullptr &&
krnAllocation[i]->dwFlags != RENDERHAL_KERNEL_ALLOCATION_LOADING)
{
// Increment amount of data that needs to be loaded in ISH (kernel already registered but unloaded)
blockSize[blockCount++] = kernel->kernelBinarySize + CM_KERNEL_BINARY_PADDING_SIZE;
totalSize += kernel->kernelBinarySize + CM_KERNEL_BINARY_PADDING_SIZE;
// Flag this kernel as loading - one single kernel instance is needed, not multiple!
// If the same kernel is used multiple times, avoid multiple reservations/loads
krnAllocation[i]->dwFlags = RENDERHAL_KERNEL_ALLOCATION_LOADING;
}
}
// Use Hit/Miss ratio to ignore eventual cache misses
// This code prevents ISH reallocation in case of eventual cache misses
while (state->dshKernelCacheHit >= HAL_CM_KERNEL_CACHE_HIT_TO_MISS_RATIO)
{
if (state->dshKernelCacheMiss > 0) state->dshKernelCacheMiss--;
state->dshKernelCacheHit -= HAL_CM_KERNEL_CACHE_HIT_TO_MISS_RATIO;
}
// Grow the kernel heap if too many kernels are being reloaded or there isn't enough room to load all kernels
if (state->dshKernelCacheMiss > HAL_CM_KERNEL_CACHE_MISS_THRESHOLD ||
renderHal->pfnRefreshDynamicKernels(renderHal, totalSize, blockSize, blockCount) != MOS_STATUS_SUCCESS)
{
renderHal->pfnExpandKernelStateHeap(renderHal, (uint32_t)totalSize);
state->dshKernelCacheHit = 0;
state->dshKernelCacheMiss = 0;
continue;
}
// blockSize/blockCount define a list of blocks that must be loaded in current ISH for the
// kernels not yet present. Pre-existing kernels are marked as bStatic to avoid being unloaded here
if (blockCount > 0)
{
// Allocate array of kernels
MHW_STATE_HEAP_DYNAMIC_ALLOC_PARAMS params;
params.piSizes = (int32_t*)blockSize;
params.iCount = blockCount;
params.dwAlignment = RENDERHAL_KERNEL_BLOCK_ALIGN;
params.bHeapAffinity = true; // heap affinity - load all kernels in the same heap
params.pHeapAffinity = renderHal->pMhwStateHeap->GetISHPointer(); // Select the active instruction heap
params.dwScratchSpace = 0;
params.bZeroAssignedMem = true;
params.bStatic = true;
params.bGrow = false;
// Try to allocate array of blocks; if it fails, we may need to clear some space or grow the heap!
memoryBlock = renderHal->pMhwStateHeap->AllocateDynamicBlockDyn(MHW_ISH_TYPE, ¶ms);
if (!memoryBlock)
{
// Reset flags
for (int i = 0; i < kernelCount; i++)
{
if (krnAllocation[i] && krnAllocation[i]->dwFlags == RENDERHAL_KERNEL_ALLOCATION_LOADING)
{
krnAllocation[i]->dwFlags = RENDERHAL_KERNEL_ALLOCATION_STALE;
}
}
if (renderHal->pfnRefreshDynamicKernels(renderHal, totalSize, blockSize, blockCount) != MOS_STATUS_SUCCESS)
{
renderHal->pfnExpandKernelStateHeap(renderHal, (uint32_t)totalSize);
}
continue;
}
// All blocks are allocated in ISH
// Setup kernel allocations, load kernel binaries
for (int32_t i = 0; i < kernelCount; i++)
{
// Load kernels in ISH
if (!krnAllocation[i]->pMemoryBlock)
{
PCM_HAL_KERNEL_PARAM kernelParam = kernelArray[i];
PRENDERHAL_KRN_ALLOCATION allocation = krnAllocation[i];
if (memoryBlock)
{
allocation->iKID = -1;
allocation->iKUID = static_cast<int>((kernelArray[i]->kernelId >> 32));
allocation->iKCID = -1;
allocation->dwSync = nextId;
allocation->dwOffset = memoryBlock->dwDataOffset;
allocation->iSize = kernelArray[i]->kernelBinarySize + CM_KERNEL_BINARY_PADDING_SIZE;
allocation->dwCount = 0;
allocation->dwFlags = RENDERHAL_KERNEL_ALLOCATION_USED;
allocation->Params = state->kernelParamsRenderHal.Params;
allocation->pMhwKernelParam = &state->kernelParamsMhw;
allocation->pMemoryBlock = memoryBlock;
// Copy kernel data
// Copy MovInstruction First
if (allocation->pMemoryBlock &&
allocation->pMemoryBlock->dwDataSize >= kernelParam->kernelBinarySize)
{
MOS_SecureMemcpy(allocation->pMemoryBlock->pDataPtr,
kernelParam->movInsDataSize,
kernelParam->movInsData,
kernelParam->movInsDataSize);
// Copy Cm Kernel Binary
MOS_SecureMemcpy(allocation->pMemoryBlock->pDataPtr + kernelParam->movInsDataSize,
kernelParam->kernelBinarySize - kernelParam->movInsDataSize,
kernelParam->kernelBinary,
kernelParam->kernelBinarySize - kernelParam->movInsDataSize);
// Padding bytes dummy instructions after kernel binary to resolve page fault issue
MOS_ZeroMemory(allocation->pMemoryBlock->pDataPtr + kernelParam->kernelBinarySize, CM_KERNEL_BINARY_PADDING_SIZE);
}
// Get next memory block returned as part of the array
memoryBlock = memoryBlock->pNext;
}
}
}
}
// Kernel load was successfull, or nothing else to load -
// Quit the kernel load loop
hr = CM_SUCCESS;
eStatus = MOS_STATUS_SUCCESS;
break;
} while (1);
finish:
if (eStatus == MOS_STATUS_SUCCESS)
{
for (int32_t i = 0; i < kernelCount; i++)
{
renderHal->pfnTouchDynamicKernel(renderHal, krnAllocation[i]);
}
}
state->criticalSectionDSH->Release();
return hr;
}
MOS_STATUS HalCm_DSH_GetDynamicStateConfiguration(
PCM_HAL_STATE state,
PRENDERHAL_DYNAMIC_MEDIA_STATE_PARAMS params,
uint32_t numKernels,
PCM_HAL_KERNEL_PARAM *kernels,
uint32_t *piCurbeOffsets)
{
PCM_HAL_KERNEL_PARAM cmKernel;
PRENDERHAL_INTERFACE renderHal = state->renderHal;
PRENDERHAL_KRN_ALLOCATION krnAllocation;
MOS_ZeroMemory(params, sizeof(RENDERHAL_DYNAMIC_MEDIA_STATE_PARAMS));
params->iMaxMediaIDs = numKernels;
for (uint32_t i = 0; i < numKernels; i++)
{
cmKernel = kernels[i];
// get max curbe size
int32_t curbeSize = MOS_ALIGN_CEIL(cmKernel->totalCurbeSize, state->renderHal->dwCurbeBlockAlign);
int32_t curbeOffset = piCurbeOffsets[i] + curbeSize;
params->iMaxCurbeOffset = MOS_MAX(params->iMaxCurbeOffset, curbeOffset);
params->iMaxCurbeSize += curbeSize;
// get max spill size
params->iMaxSpillSize = MOS_MAX(params->iMaxSpillSize, (int32_t)cmKernel->spillSize);
// check if kernel already used - increase Max Media ID to allow BB reuse logic
krnAllocation = renderHal->pfnSearchDynamicKernel(renderHal, static_cast<int>((cmKernel->kernelId >> 32)), -1);
if (krnAllocation)
{
params->iMaxMediaIDs = MOS_MAX(params->iMaxMediaIDs, krnAllocation->iKID + 1);
}
}
if (state->useNewSamplerHeap == true)
{
// Update offset to the base of first kernel and update count
// for 3D sampler, update indirect state information
unsigned int heapOffset = 0;
unsigned int sampler3DCount = 0;
MHW_SAMPLER_STATE_PARAM samplerParamMhw = {};
SamplerParam samplerParam = {};
samplerParamMhw.SamplerType = MHW_SAMPLER_TYPE_3D;
state->cmHalInterface->GetSamplerParamInfoForSamplerType(&samplerParamMhw, samplerParam);
for (unsigned int i = 0; i < numKernels; i++)
{
cmKernel = kernels[i];
std::list<SamplerParam> *sampler_heap = cmKernel->samplerHeap;
std::list<SamplerParam>::iterator iter;
heapOffset = MOS_ALIGN_CEIL(heapOffset, MHW_SAMPLER_STATE_ALIGN);
state->taskParam->samplerOffsetsByKernel[i] = heapOffset;
state->taskParam->samplerCountsByKernel[i] = sampler_heap->size();
if (sampler_heap->size() > 0)
{
heapOffset = heapOffset + sampler_heap->back().heapOffset + sampler_heap->back().size;
// 3D sampler needs indirect sampler heap, so calculates the required size
// and offset for indirect sampler heap.
unsigned int max3DCount = 0;
for (iter = sampler_heap->begin(); iter != sampler_heap->end(); ++iter)
{
if (iter->elementType == samplerParam.elementType)
{
if (iter->userDefinedBti == true)
{
max3DCount = iter->bti + 1;
}
else
{
max3DCount += 1;
}
}
}
heapOffset = MOS_ALIGN_CEIL(heapOffset, MHW_SAMPLER_STATE_ALIGN);
state->taskParam->samplerIndirectOffsetsByKernel[i] = heapOffset;
heapOffset += max3DCount * state->renderHal->pHwSizes->dwSizeSamplerIndirectState;
sampler3DCount += max3DCount;
}
}
// Temporary solution for DSH sampler heap assginment:
// Adjust sampler space for DSH, because the DSH use sampler count to
// allocate the space. However the mechanism is not correct. The sampler
// heap size is actually calculated by the maximum offset of the largest
// sampler type.
// So the offset of largest element plus the size of all of the largest
// element samplers should be equal to the maximum size. However we cannot
// do this because of the DSH's mechanism.
// To resolve this, we first let DSH allocate enough 3D samplers
// (because 3D samplers has indirect state), then just convert the rest of
// the heap to AVS. Here we only care about the size, not the correct
// number because we are going to calculate the offset by ourself.
// Since DSH allocation has some alignments inside, the actually size of the
// heap should be slightly larger, which should be OK.
samplerParamMhw.SamplerType = MHW_SAMPLER_TYPE_AVS;
state->cmHalInterface->GetSamplerParamInfoForSamplerType(&samplerParamMhw, samplerParam);
params->iMaxSamplerIndex3D = (sampler3DCount + numKernels - 1) / numKernels;
params->iMaxSamplerIndexAVS = ((heapOffset - sampler3DCount * (state->renderHal->pHwSizes->dwSizeSamplerState + state->renderHal->pHwSizes->dwSizeSamplerIndirectState)) + samplerParam.btiMultiplier * numKernels - 1) / (samplerParam.btiMultiplier * numKernels);
}
else
{
// Get total sampler count
// Initialize pointers to samplers and reset sampler index table
MOS_FillMemory(state->samplerIndexTable, state->cmDeviceParam.maxSamplerTableSize, CM_INVALID_INDEX);
params->iMaxSamplerIndex3D = CM_MAX_3D_SAMPLER_SIZE;
params->iMaxSamplerIndexAVS = CM_MAX_AVS_SAMPLER_SIZE;
params->iMaxSamplerIndexConv = 0;
params->iMaxSamplerIndexMisc = 0;
params->iMax8x8Tables = CM_MAX_AVS_SAMPLER_SIZE;
}
return MOS_STATUS_SUCCESS;
}
MOS_STATUS HalCm_DSH_UnregisterKernel(
PCM_HAL_STATE state,
uint64_t kernelId)
{
PRENDERHAL_INTERFACE renderHal = state->renderHal;
PRENDERHAL_KRN_ALLOCATION krnAllocation = renderHal->pfnSearchDynamicKernel(renderHal, static_cast<int>((kernelId >> 32)), -1);
if (krnAllocation)
{
state->criticalSectionDSH->Acquire();
renderHal->pfnUnregisterKernel(renderHal, krnAllocation);
state->criticalSectionDSH->Release();
}
return MOS_STATUS_SUCCESS;
}
//*-----------------------------------------------------------------------------
//| Purpose: Setup Sampler State
//| Returns: Result of the operation
//*-----------------------------------------------------------------------------
MOS_STATUS HalCm_SetupSamplerState(
PCM_HAL_STATE state,
PCM_HAL_KERNEL_PARAM kernelParam,
PCM_HAL_KERNEL_ARG_PARAM argParam,
PCM_HAL_INDEX_PARAM indexParam,
int32_t mediaID,
uint32_t threadIndex,
uint8_t *buffer)
{
MOS_STATUS eStatus;
PRENDERHAL_INTERFACE renderHal;
PMHW_SAMPLER_STATE_PARAM samplerParam;
uint8_t *src;
uint8_t *dst;
uint32_t index;
uint32_t samplerIndex = 0;
void *sampler = nullptr;
uint32_t samplerOffset = 0;
eStatus = MOS_STATUS_SUCCESS;
CM_CHK_NULL_GOTOFINISH_MOSERROR(state);
renderHal = state->renderHal;
if (indexParam->samplerIndexCount >= (uint32_t)renderHal->StateHeapSettings.iSamplers)
{
eStatus = MOS_STATUS_INVALID_PARAMETER;
CM_ASSERTMESSAGE(
"Exceeded Max samplers '%d'",
indexParam->samplerIndexCount);
goto finish;
}
// Get the Index to sampler array from the kernel data
//----------------------------------
CM_ASSERT(argParam->unitSize == sizeof(index));
//----------------------------------
src = argParam->firstValue + (threadIndex * argParam->unitSize);
index = *((uint32_t*)src);
// check to see if the data present for the sampler in the array
if (index >= state->cmDeviceParam.maxSamplerTableSize ||
!state->samplerTable[index].bInUse)
{
eStatus = MOS_STATUS_INVALID_PARAMETER;
CM_ASSERTMESSAGE(
"Invalid Sampler array index '%d'", index);
goto finish;
}
// Setup samplers
samplerParam = &state->samplerTable[index];
if (state->useNewSamplerHeap == true)
{
std::list<SamplerParam>::iterator iter;
for (iter = kernelParam->samplerHeap->begin(); iter != kernelParam->samplerHeap->end(); ++iter)
{
if ((iter->samplerTableIndex == index)&&(iter->regularBti == true))
{
break;
}
}
if (iter != kernelParam->samplerHeap->end())
{
samplerIndex = iter->bti;
}
else
{
// There must be incorrect internal logic
CM_ASSERTMESSAGE( "BTI calculation error in cm_hal\n");
return MOS_STATUS_UNKNOWN;
}
HalCm_GetSamplerOffset(state, renderHal, mediaID, iter->heapOffset, iter->bti, samplerParam, &samplerOffset);
}
else
{
// Check to see if sampler is already assigned
samplerIndex = state->samplerIndexTable[index];
if ((int)samplerIndex == CM_INVALID_INDEX)
{
switch (state->samplerTable[index].ElementType)
{
case MHW_Sampler2Elements:
{
unsigned int index = 0;
index = state->samplerStatistics.samplerIndexBase[MHW_Sampler2Elements];
while (state->samplerIndexTable[index] != CM_INVALID_INDEX)
{
index++;
}
samplerIndex = index;
state->samplerStatistics.samplerIndexBase[MHW_Sampler2Elements] = (index + 1);
break;
}
case MHW_Sampler4Elements:
{
unsigned int index = 0;
index = state->samplerStatistics.samplerIndexBase[MHW_Sampler4Elements];
while (state->samplerIndexTable[index] != CM_INVALID_INDEX)
{
index++;
}
samplerIndex = index;
state->samplerStatistics.samplerIndexBase[MHW_Sampler4Elements] = (index + 1);
break;
}
case MHW_Sampler8Elements:
{
unsigned int index = 0;
index = state->samplerStatistics.samplerIndexBase[MHW_Sampler8Elements];
while (state->samplerIndexTable[index] != CM_INVALID_INDEX)
{
index++;
}
samplerIndex = index;
state->samplerStatistics.samplerIndexBase[MHW_Sampler8Elements] = (index + 1);
break;
}
case MHW_Sampler64Elements:
{
unsigned int index = 0;
index = state->samplerStatistics.samplerIndexBase[MHW_Sampler64Elements];
while (state->samplerIndexTable[index] != CM_INVALID_INDEX)
{
index += index + 2;
}
samplerIndex = index;
state->samplerStatistics.samplerIndexBase[MHW_Sampler64Elements] = (index + 2);
break;
}
case MHW_Sampler128Elements:
{
unsigned int index = 0;
index = state->samplerStatistics.samplerIndexBase[MHW_Sampler128Elements];
while (state->samplerIndexTable[index] != CM_INVALID_INDEX)
{
index++;
}
samplerIndex = index;
state->samplerStatistics.samplerIndexBase[MHW_Sampler128Elements] = (index + 1);
break;
}
default:
CM_ASSERTMESSAGE("Invalid sampler type '%d'.", state->samplerTable[index].SamplerType);
break;
}
}
CM_CHK_MOSSTATUS_GOTOFINISH(renderHal->pfnGetSamplerOffsetAndPtr(
renderHal,
mediaID,
samplerIndex,
samplerParam,
&samplerOffset,
&sampler));
}
CM_CHK_MOSSTATUS_GOTOFINISH(renderHal->pMhwStateHeap->AddSamplerStateData(
samplerOffset,
&(renderHal->pStateHeap->pCurMediaState->pDynamicState->memoryBlock),
samplerParam));
state->samplerIndexTable[index] = (unsigned char)samplerIndex;
// Update the Batch Buffer
if (buffer)
{
dst = buffer + argParam->payloadOffset;
*((uint32_t*)dst) = samplerIndex;
}
finish:
return eStatus;
}
//*-----------------------------------------------------------------------------
//| Purpose: Setup Sampler State
//| Returns: Result of the operation
//*-----------------------------------------------------------------------------
MOS_STATUS HalCm_SetupSamplerStateWithBTIndex(
PCM_HAL_STATE state,
PCM_HAL_KERNEL_PARAM kernelParam,
PCM_HAL_SAMPLER_BTI_ENTRY samplerBTIEntry,
uint32_t samplerCount,
int32_t mediaID )
{
MOS_STATUS eStatus = MOS_STATUS_SUCCESS;
PRENDERHAL_INTERFACE renderHal;
PMHW_SAMPLER_STATE_PARAM samplerParam;
uint32_t index;
uint32_t samplerIndex;
void *sampler = nullptr;
uint32_t samplerOffset = 0;
renderHal = state->renderHal;
if (state->useNewSamplerHeap != true)
{
if (samplerCount >= (uint32_t)renderHal->StateHeapSettings.iSamplers)
{
eStatus = MOS_STATUS_INVALID_PARAMETER;
CM_ASSERTMESSAGE(
"Exceeded Max samplers '%d'",
samplerCount);
goto finish;
}
}
index = samplerBTIEntry[ samplerCount ].samplerIndex;
// check to see if the data present for the sampler in the array
if ( index >= state->cmDeviceParam.maxSamplerTableSize ||
!state->samplerTable[ index ].bInUse )
{
eStatus = MOS_STATUS_INVALID_PARAMETER;
CM_ASSERTMESSAGE(
"Invalid Sampler array index '%d'", index );
goto finish;
}
samplerIndex = samplerBTIEntry[ samplerCount ].samplerBTI;
// Setup samplers
samplerParam = &state->samplerTable[ index ];
if (state->useNewSamplerHeap == true)
{
std::list<SamplerParam>::iterator iter;
for (iter = kernelParam->samplerHeap->begin(); iter != kernelParam->samplerHeap->end(); ++iter)
{
if ((iter->samplerTableIndex == index) && (iter->bti == samplerIndex) && (iter->userDefinedBti == true))
{
break;
}
}
if (iter == kernelParam->samplerHeap->end())
{
// There must be incorrect internal logic
CM_ASSERTMESSAGE("BTI calculation error in cm_hal\n");
return MOS_STATUS_UNKNOWN;
}
HalCm_GetSamplerOffset(state, renderHal, mediaID, iter->heapOffset, iter->bti, samplerParam, &samplerOffset);
}
else
{
CM_CHK_MOSSTATUS_GOTOFINISH(renderHal->pfnGetSamplerOffsetAndPtr(renderHal, mediaID, samplerIndex, samplerParam, &samplerOffset, &sampler));
}
CM_CHK_MOSSTATUS_GOTOFINISH(renderHal->pMhwStateHeap->AddSamplerStateData(
samplerOffset,
&(renderHal->pStateHeap->pCurMediaState->pDynamicState->memoryBlock),
samplerParam));
finish:
return eStatus;
}
//*-----------------------------------------------------------------------------
//| Purpose: Setup Buffer surface State
//| Returns: Result of the operation
//*-----------------------------------------------------------------------------
MOS_STATUS HalCm_SetupBufferSurfaceState(
PCM_HAL_STATE state,
PCM_HAL_KERNEL_ARG_PARAM argParam,
PCM_HAL_INDEX_PARAM indexParam,
int32_t bindingTable,
int16_t globalSurface,
uint32_t threadIndex,
uint8_t *buffer)
{
MOS_STATUS eStatus;
RENDERHAL_SURFACE surface;
PMOS_SURFACE mosSurface;
RENDERHAL_SURFACE_STATE_PARAMS surfaceParam;
PRENDERHAL_INTERFACE renderHal;
PRENDERHAL_SURFACE_STATE_ENTRY surfaceEntry;
uint8_t *src;
uint8_t *dst;
uint32_t index;
uint32_t btIndex;
uint16_t memObjCtl;
uint32_t offsetSrc;
PRENDERHAL_STATE_HEAP stateHeap;
CM_SURFACE_BTI_INFO surfBTIInfo;
eStatus = MOS_STATUS_UNKNOWN;
renderHal = state->renderHal;
//GT-PIN
PCM_HAL_TASK_PARAM taskParam = state->taskParam;
// Get the Index to Buffer array from the kernel data
CM_ASSERT(argParam->unitSize == sizeof(index));
//Init surfBTIInfo
state->cmHalInterface->GetHwSurfaceBTIInfo(&surfBTIInfo);
src = argParam->firstValue + (threadIndex * argParam->unitSize);
index = *((uint32_t*)src) & CM_SURFACE_MASK;
if (index == CM_NULL_SURFACE)
{
if (buffer)
{
dst = buffer + argParam->payloadOffset;
*((uint32_t*)dst) = CM_NULL_SURFACE_BINDING_INDEX;
}
eStatus = MOS_STATUS_SUCCESS;
goto finish;
}
memObjCtl = state->bufferTable[index].memObjCtl;
if (!memObjCtl)
{
memObjCtl = CM_DEFAULT_CACHE_TYPE;
}
// check to see if index is valid
if (index >= state->cmDeviceParam.maxBufferTableSize ||
(state->bufferTable[index].size == 0))
{
eStatus = MOS_STATUS_INVALID_PARAMETER;
CM_ASSERTMESSAGE(
"Invalid Buffer surface array index '%d'", index);
goto finish;
}
// Check to see if buffer is already assigned
btIndex = state->btiBufferIndexTable[index].BTI.regularSurfIndex;
if (btIndex == ( unsigned char )CM_INVALID_INDEX || argParam->aliasCreated == true)
{
if (globalSurface < 0)
{
btIndex = HalCm_GetFreeBindingIndex(state, indexParam, 1);
}
else
{
btIndex = globalSurface + surfBTIInfo.reservedSurfaceStart; //CM_BINDING_START_INDEX_OF_GLOBAL_SURFACE(state);
if ( btIndex >= (surfBTIInfo.reservedSurfaceStart + CM_MAX_GLOBAL_SURFACE_NUMBER) ) {
eStatus = MOS_STATUS_INVALID_PARAMETER;
CM_ASSERTMESSAGE("Exceeded Max Global Surfaces '%d'", btIndex);
goto finish;
}
}
// Get Details of Buffer surface and fill the surface
CM_CHK_MOSSTATUS_GOTOFINISH(HalCm_GetSurfaceAndRegister(state, &surface, CM_ARGUMENT_SURFACEBUFFER, index, 0));
MOS_ZeroMemory(&surfaceParam, sizeof(surfaceParam));
// override the buffer offset and size if alias is used
mosSurface = &(surface.OsSurface);
if (state->bufferTable[index].surfaceStateEntry[argParam->aliasIndex / state->surfaceArraySize].surfaceStateSize)
{
mosSurface->dwWidth = state->bufferTable[index].surfaceStateEntry[argParam->aliasIndex / state->surfaceArraySize].surfaceStateSize;
mosSurface->dwOffset = state->bufferTable[index].surfaceStateEntry[argParam->aliasIndex / state->surfaceArraySize].surfaceStateOffset;
surface.rcSrc.right = mosSurface->dwWidth;
surface.rcDst.right = mosSurface->dwWidth;
}
// override the mocs value if it is set
if (state->bufferTable[index].surfaceStateEntry[argParam->aliasIndex / state->surfaceArraySize].surfaceStateMOCS)
{
memObjCtl = state->bufferTable[index].surfaceStateEntry[argParam->aliasIndex / state->surfaceArraySize].surfaceStateMOCS;
}
//Cache configurations
state->cmHalInterface->HwSetSurfaceMemoryObjectControl(memObjCtl, &surfaceParam);
// Set the bRenderTarget by default
surfaceParam.bRenderTarget = true;
// Setup Buffer surface
CM_CHK_MOSSTATUS_GOTOFINISH(renderHal->pfnSetupBufferSurfaceState(
renderHal,
&surface,
&surfaceParam,
&surfaceEntry));
// Bind the surface State
surfaceEntry->pSurface = &surface.OsSurface;
CM_ASSERT(((int32_t)btIndex) < renderHal->StateHeapSettings.iSurfacesPerBT + surfBTIInfo.normalSurfaceStart);
CM_CHK_MOSSTATUS_GOTOFINISH(renderHal->pfnBindSurfaceState(
renderHal,
bindingTable,
btIndex,
surfaceEntry));
if ((taskParam->surfEntryInfoArrays.kernelNum != 0) &&
(taskParam->surfEntryInfoArrays.surfEntryInfosArray != nullptr))
{
//GT-Pin
uint32_t dummy = 0;
CM_CHK_MOSSTATUS_GOTOFINISH(HalCm_GetSurfaceDetails(
state,
indexParam,
btIndex,
surface.OsSurface,
globalSurface,
nullptr,
dummy,
surfaceParam,
CM_ARGUMENT_SURFACEBUFFER));
}
// Update index to table
state->btiBufferIndexTable[ index ].BTI.regularSurfIndex = btIndex;
state->btiBufferIndexTable[ index ].nPlaneNumber = 1;
stateHeap = renderHal->pStateHeap;
offsetSrc = ( stateHeap->iCurSshBufferIndex * stateHeap->dwSshIntanceSize ) + // Points to the Base of Current SSH Buffer Instance
( stateHeap->iBindingTableOffset ) + // Moves the pointer to Base of Array of Binding Tables
( bindingTable * stateHeap->iBindingTableSize ) + // Moves the pointer to a Particular Binding Table
( btIndex * sizeof( uint32_t ) ); // Move the pointer to correct entry
state->btiBufferIndexTable[ index ].BTITableEntry.regularBtiEntryPosition = stateHeap->pSshBuffer + offsetSrc;
}
else
{
stateHeap = renderHal->pStateHeap;
// Get Offset to Current Binding Table
uint32_t offsetCurrentBTStart = ( stateHeap->iCurSshBufferIndex * stateHeap->dwSshIntanceSize ) + // Points to the Base of Current SSH Buffer Instance
( stateHeap->iBindingTableOffset ) + // Moves the pointer to Base of Array of Binding Tables
( bindingTable * stateHeap->iBindingTableSize ); // Moves the pointer to a Particular Binding Table
uint32_t *currentBTStart = ( uint32_t *)( stateHeap->pSshBuffer + offsetCurrentBTStart );
int nEntryIndex = (int) ((uint32_t*)( state->btiBufferIndexTable[ index ].BTITableEntry.regularBtiEntryPosition ) - currentBTStart);
if ( ( nEntryIndex < 0 ) || ( nEntryIndex >= renderHal->StateHeapSettings.iSurfacesPerBT ) )
{
uint32_t surfaceEntries = state->btiBufferIndexTable[ index ].nPlaneNumber;
if ( globalSurface < 0 )
{
btIndex = HalCm_GetFreeBindingIndex( state, indexParam, surfaceEntries );
}
else
{
btIndex = globalSurface + surfBTIInfo.reservedSurfaceStart;
if ( btIndex >= (surfBTIInfo.reservedSurfaceStart + CM_MAX_GLOBAL_SURFACE_NUMBER ) )
{
eStatus = MOS_STATUS_INVALID_PARAMETER;
CM_ASSERTMESSAGE( "Exceeded Max Global Surfaces '%d'", btIndex );
goto finish;
}
}
// Bind the surface State
CM_ASSERT( ( ( int32_t )btIndex ) < renderHal->StateHeapSettings.iSurfacesPerBT + surfBTIInfo.normalSurfaceStart);
// Get Offset to Current Binding Table
uint32_t offsetDst = offsetCurrentBTStart + ( btIndex * sizeof( uint32_t ) ); // Move the pointer to correct entry
uint32_t *bindingTableEntry = ( uint32_t *)( stateHeap->pSshBuffer + offsetDst );
MOS_SecureMemcpy( bindingTableEntry, sizeof( uint32_t ) * surfaceEntries, state->btiBufferIndexTable[ index ].BTITableEntry.regularBtiEntryPosition, sizeof( uint32_t ) * surfaceEntries );
// Update index to table
state->btiBufferIndexTable[ index ].BTI.regularSurfIndex = btIndex;
state->btiBufferIndexTable[ index ].BTITableEntry.regularBtiEntryPosition = bindingTableEntry;
}
}
// Update the Batch Buffer
if (buffer)
{
dst = buffer + argParam->payloadOffset;
*((uint32_t*)dst) = btIndex;
}
eStatus = MOS_STATUS_SUCCESS;
finish:
return eStatus;
}
//*-----------------------------------------------------------------------------
//| Purpose: Setup 3D surface State
//| Returns: Result of the operation
//*-----------------------------------------------------------------------------
MOS_STATUS HalCm_Setup3DSurfaceState(
PCM_HAL_STATE state,
PCM_HAL_KERNEL_ARG_PARAM argParam,
PCM_HAL_INDEX_PARAM indexParam,
int32_t bindingTable,
uint32_t threadIndex,
uint8_t *buffer)
{
MOS_STATUS eStatus;
PRENDERHAL_INTERFACE renderHal;
RENDERHAL_SURFACE surface;
RENDERHAL_SURFACE_STATE_PARAMS surfaceParam;
PRENDERHAL_SURFACE_STATE_ENTRY surfaceEntries[MHW_MAX_SURFACE_PLANES];
RENDERHAL_GET_SURFACE_INFO info;
uint8_t *src;
uint8_t *dst;
int32_t nSurfaceEntries;
uint32_t index;
uint32_t btIndex;
uint16_t memObjCtl;
uint32_t i;
uint32_t offsetSrc;
PRENDERHAL_STATE_HEAP stateHeap;
CM_SURFACE_BTI_INFO surfBTIInfo;
eStatus = MOS_STATUS_UNKNOWN;
renderHal = state->renderHal;
//GT-PIN
PCM_HAL_TASK_PARAM taskParam = state->taskParam;
state->cmHalInterface->GetHwSurfaceBTIInfo(&surfBTIInfo);
// Get the Index to 3dsurface array from the kernel data
CM_ASSERT(argParam->unitSize == sizeof(index));
src = argParam->firstValue + (threadIndex * argParam->unitSize);
index = *((uint32_t*)src) & CM_SURFACE_MASK;
if (index == CM_NULL_SURFACE)
{
if (buffer)
{
dst = buffer + argParam->payloadOffset;
*((uint32_t*)dst) = CM_NULL_SURFACE_BINDING_INDEX;
}
eStatus = MOS_STATUS_SUCCESS;
goto finish;
}
memObjCtl = state->surf3DTable[index].memObjCtl;
if (!memObjCtl)
{
memObjCtl = CM_DEFAULT_CACHE_TYPE;
}
// check to see if the data present for the 3d surface in the array
if ((index >= state->cmDeviceParam.max3DSurfaceTableSize) ||
Mos_ResourceIsNull(&state->surf3DTable[index].osResource))
{
eStatus = MOS_STATUS_INVALID_PARAMETER;
CM_ASSERTMESSAGE(
"Invalid 2D surface array index '%d'", index);
goto finish;
}
// Check to see if surface is already assigned
btIndex = state->bti3DIndexTable[index].BTI.regularSurfIndex;
if ( btIndex == ( unsigned char )CM_INVALID_INDEX )
{
uint32_t tempPlaneIndex = 0;
nSurfaceEntries = 0;
// Get Details of 3D surface and fill the surface
CM_CHK_MOSSTATUS_GOTOFINISH(HalCm_GetSurfaceAndRegister(state, &surface, CM_ARGUMENT_SURFACE3D, index, 0));
// Setup 3D surface
MOS_ZeroMemory(&surfaceParam, sizeof(surfaceParam));
surfaceParam.Type = renderHal->SurfaceTypeDefault;
surfaceParam.Boundary = RENDERHAL_SS_BOUNDARY_ORIGINAL;
surfaceParam.bRenderTarget = true;
//Cache configurations
state->cmHalInterface->HwSetSurfaceMemoryObjectControl(memObjCtl, &surfaceParam);
CM_CHK_MOSSTATUS_GOTOFINISH(renderHal->pfnSetupSurfaceState(
renderHal,
&surface,
&surfaceParam,
&nSurfaceEntries,
surfaceEntries,
nullptr));
MOS_ZeroMemory(&info, sizeof(RENDERHAL_GET_SURFACE_INFO));
CM_CHK_MOSSTATUS_GOTOFINISH(RenderHal_GetSurfaceInfo(
state->osInterface,
&info,
&surface.OsSurface));
btIndex = HalCm_GetFreeBindingIndex(state, indexParam, nSurfaceEntries);
for (i = 0; i < (uint32_t)nSurfaceEntries; i++)
{
// Bind the surface State
CM_CHK_MOSSTATUS_GOTOFINISH(renderHal->pfnBindSurfaceState(
renderHal,
bindingTable,
btIndex + i,
surfaceEntries[i]));
if ((taskParam->surfEntryInfoArrays.kernelNum != 0) &&
(taskParam->surfEntryInfoArrays.surfEntryInfosArray != nullptr))
{
CM_CHK_MOSSTATUS_GOTOFINISH(HalCm_GetSurfaceDetails(
state,
indexParam,
btIndex + i,
surface.OsSurface,
0,
surfaceEntries[i],
tempPlaneIndex,
surfaceParam,
CM_ARGUMENT_SURFACE3D));
}
}
// Update index to table
state->bti3DIndexTable[ index ].BTI.regularSurfIndex = btIndex;
state->bti3DIndexTable[ index ].nPlaneNumber = nSurfaceEntries;
stateHeap = renderHal->pStateHeap;
offsetSrc = ( stateHeap->iCurSshBufferIndex * stateHeap->dwSshIntanceSize ) + // Points to the Base of Current SSH Buffer Instance
( stateHeap->iBindingTableOffset ) + // Moves the pointer to Base of Array of Binding Tables
( bindingTable * stateHeap->iBindingTableSize ) + // Moves the pointer to a Particular Binding Table
( btIndex * sizeof( uint32_t ) ); // Move the pointer to correct entry
state->bti3DIndexTable[ index ].BTITableEntry.regularBtiEntryPosition = stateHeap->pSshBuffer + offsetSrc;
}
else
{
stateHeap = renderHal->pStateHeap;
// Get Offset to Current Binding Table
uint32_t offsetCurrentBTStart = ( stateHeap->iCurSshBufferIndex * stateHeap->dwSshIntanceSize ) + // Points to the Base of Current SSH Buffer Instance
( stateHeap->iBindingTableOffset ) + // Moves the pointer to Base of Array of Binding Tables
( bindingTable * stateHeap->iBindingTableSize ); // Moves the pointer to a Particular Binding Table
uint32_t *currentBTStart = ( uint32_t *)( stateHeap->pSshBuffer + offsetCurrentBTStart );
int nEntryIndex = (int)((uint32_t*)( state->bti3DIndexTable[ index ].BTITableEntry.regularBtiEntryPosition ) - currentBTStart);
if ( ( nEntryIndex < 0 ) || ( nEntryIndex >= renderHal->StateHeapSettings.iSurfacesPerBT ) )
{
nSurfaceEntries = state->bti3DIndexTable[ index ].nPlaneNumber;
btIndex = HalCm_GetFreeBindingIndex( state, indexParam, nSurfaceEntries );
// Bind the surface State
CM_ASSERT( ( ( int32_t )btIndex ) < renderHal->StateHeapSettings.iSurfacesPerBT + surfBTIInfo.normalSurfaceStart);
// Get Offset to Current Binding Table
uint32_t offsetDst = offsetCurrentBTStart + ( btIndex * sizeof( uint32_t ) ); // Move the pointer to correct entry
uint32_t *bindingTableEntry = ( uint32_t *)( stateHeap->pSshBuffer + offsetDst );
MOS_SecureMemcpy( bindingTableEntry, sizeof( uint32_t ) * nSurfaceEntries, state->bti3DIndexTable[ index ].BTITableEntry.regularBtiEntryPosition, sizeof( uint32_t ) * nSurfaceEntries );
// Update index to table
state->bti3DIndexTable[ index ].BTI.regularSurfIndex = btIndex;
state->bti3DIndexTable[ index ].BTITableEntry.regularBtiEntryPosition = bindingTableEntry;
}
}
// Update the Batch Buffer
if (buffer)
{
dst = buffer + argParam->payloadOffset;
*((uint32_t*)dst) = btIndex;
}
eStatus = MOS_STATUS_SUCCESS;
finish:
return eStatus;
}
/*----------------------------------------------------------------------------
| Purpose : Set's surface state interlaced settings
| Returns : dword value
\---------------------------------------------------------------------------*/
MOS_STATUS HalCm_HwSetSurfaceProperty(
PCM_HAL_STATE state,
CM_FRAME_TYPE frameType,
PRENDERHAL_SURFACE_STATE_PARAMS params)
{
MOS_STATUS eStatus = MOS_STATUS_SUCCESS;
switch (frameType)
{
case CM_FRAME:
params->bVertStride = 0;
params->bVertStrideOffs = 0;
break;
case CM_TOP_FIELD:
params->bVertStride = 1;
params->bVertStrideOffs = 0;
break;
case CM_BOTTOM_FIELD:
params->bVertStride = 1;
params->bVertStrideOffs = 1;
break;
default:
eStatus = MOS_STATUS_UNKNOWN;
}
return eStatus;
}
// A special treatment of NV12 format. Offset of the UV plane in an NV12 surface is adjusted, so
// this plane can be accessed as a separate R8G8 surface in kernels.
static bool UpdateSurfaceAliasPlaneOffset(
CM_HAL_SURFACE2D_SURFACE_STATE_PARAM *surfaceStateParam,
MOS_SURFACE *mosSurface)
{
if (Format_R8G8UN != surfaceStateParam->format
|| Format_NV12 != mosSurface->Format)
{
mosSurface->Format
= static_cast<MOS_FORMAT>(surfaceStateParam->format);
return false; // No need to update offset.
}
mosSurface->dwOffset = mosSurface->UPlaneOffset.iSurfaceOffset;
mosSurface->Format = Format_R8G8UN;
return false;
}
//*-----------------------------------------------------------------------------
//| Purpose: Setup 2D surface State
//| Returns: Result of the operation
//*-----------------------------------------------------------------------------
MOS_STATUS HalCm_Setup2DSurfaceStateBasic(
PCM_HAL_STATE state,
PCM_HAL_KERNEL_ARG_PARAM argParam,
PCM_HAL_INDEX_PARAM indexParam,
int32_t bindingTable,
uint32_t threadIndex,
bool pixelPitch,
uint8_t *buffer,
bool multipleBinding )
{
MOS_STATUS eStatus;
RENDERHAL_SURFACE renderHalSurface;
PMOS_SURFACE surface;
RENDERHAL_SURFACE_STATE_PARAMS surfaceParam;
PRENDERHAL_INTERFACE renderHal;
PRENDERHAL_SURFACE_STATE_ENTRY surfaceEntries[ MHW_MAX_SURFACE_PLANES ];
uint8_t *src;
uint8_t *dst;
int32_t nSurfaceEntries = 0;
uint32_t index;
uint32_t btIndex;
uint16_t memObjCtl;
uint32_t i;
uint32_t tempPlaneIndex = 0;
uint32_t offsetSrc;
PRENDERHAL_STATE_HEAP stateHeap;
PCM_HAL_SURFACE2D_SURFACE_STATE_PARAM surfStateParam = nullptr;
UNUSED(multipleBinding);
eStatus = MOS_STATUS_UNKNOWN;
renderHal = state->renderHal;
MOS_ZeroMemory(&renderHalSurface, sizeof(renderHalSurface));
surface = &renderHalSurface.OsSurface;
nSurfaceEntries = 0;
//GT-PIN
PCM_HAL_TASK_PARAM taskParam = state->taskParam;
// Get the Index to 2dsurface array from the kernel data
CM_ASSERT( argParam->unitSize == sizeof( index ) );
src = argParam->firstValue + ( threadIndex * argParam->unitSize );
index = *( ( uint32_t *)src ) & CM_SURFACE_MASK;
if ( index == CM_NULL_SURFACE )
{
if ( buffer )
{
dst = buffer + argParam->payloadOffset;
*( ( uint32_t *)dst ) = CM_NULL_SURFACE_BINDING_INDEX;
}
eStatus = MOS_STATUS_SUCCESS;
goto finish;
}
memObjCtl = state->umdSurf2DTable[index].memObjCtl;
if ( !memObjCtl )
{
memObjCtl = CM_DEFAULT_CACHE_TYPE;
}
// check to see if the data present for the 2d surface in the array
if ( index >= state->cmDeviceParam.max2DSurfaceTableSize ||
Mos_ResourceIsNull( &state->umdSurf2DTable[ index ].osResource ) )
{
eStatus = MOS_STATUS_INVALID_PARAMETER;
CM_ASSERTMESSAGE(
"Invalid 2D surface array index '%d'", index );
goto finish;
}
// Check to see if surface is already assigned
unsigned char nBTIRegularSurf, nBTISamplerSurf;
nBTIRegularSurf = state->bti2DIndexTable[ index ].BTI.regularSurfIndex;
nBTISamplerSurf = state->bti2DIndexTable[ index ].BTI.samplerSurfIndex;
if (((!pixelPitch && (nBTIRegularSurf != (unsigned char)CM_INVALID_INDEX)) || (pixelPitch && (nBTISamplerSurf != (unsigned char)CM_INVALID_INDEX))) && argParam->aliasCreated == false )
{
if ( pixelPitch )
{
btIndex = nBTISamplerSurf;
}
else
{
btIndex = nBTIRegularSurf;
}
stateHeap = renderHal->pStateHeap;
// Get Offset to Current Binding Table
uint32_t offsetCurrentBTStart = ( stateHeap->iCurSshBufferIndex * stateHeap->dwSshIntanceSize ) + // Points to the Base of Current SSH Buffer Instance
( stateHeap->iBindingTableOffset ) + // Moves the pointer to Base of Array of Binding Tables
( bindingTable * stateHeap->iBindingTableSize ); // Moves the pointer to a Particular Binding Table
uint32_t *currentBTStart = ( uint32_t *)( stateHeap->pSshBuffer + offsetCurrentBTStart );
int nEntryIndex = 0;
if ( pixelPitch )
{
nEntryIndex = (int)((uint32_t*)( state->bti2DIndexTable[ index ].BTITableEntry.samplerBtiEntryPosition ) - currentBTStart);
}
else
{
nEntryIndex = (int)((uint32_t*)( state->bti2DIndexTable[ index ].BTITableEntry.regularBtiEntryPosition ) - currentBTStart);
}
if ( ( nEntryIndex < 0 ) || ( nEntryIndex >= renderHal->StateHeapSettings.iSurfacesPerBT ) )
{
nSurfaceEntries = state->bti2DIndexTable[ index ].nPlaneNumber;
btIndex = HalCm_GetFreeBindingIndex( state, indexParam, nSurfaceEntries );
// Get Offset to Current Binding Table
uint32_t offsetDst = offsetCurrentBTStart + ( btIndex * sizeof( uint32_t ) ); // Move the pointer to correct entry
uint32_t *bindingTableEntry = ( uint32_t *)( stateHeap->pSshBuffer + offsetDst );
if ( pixelPitch )
{
MOS_SecureMemcpy( bindingTableEntry, sizeof( uint32_t ) * nSurfaceEntries, state->bti2DIndexTable[ index ].BTITableEntry.samplerBtiEntryPosition, sizeof( uint32_t ) * nSurfaceEntries );
}
else
{
MOS_SecureMemcpy( bindingTableEntry, sizeof( uint32_t ) * nSurfaceEntries, state->bti2DIndexTable[ index ].BTITableEntry.regularBtiEntryPosition, sizeof( uint32_t ) * nSurfaceEntries );
}
// update index to table
if ( pixelPitch )
{
state->bti2DIndexTable[ index ].BTI.samplerSurfIndex = btIndex;
state->bti2DIndexTable[ index ].BTITableEntry.samplerBtiEntryPosition = bindingTableEntry;
}
else
{
state->bti2DIndexTable[ index ].BTI.regularSurfIndex = btIndex;
state->bti2DIndexTable[ index ].BTITableEntry.regularBtiEntryPosition = bindingTableEntry;
}
}
// Update the Batch Buffer
if ( buffer )
{
dst = buffer + argParam->payloadOffset;
*( ( uint32_t *)dst ) = btIndex;
}
eStatus = MOS_STATUS_SUCCESS;
goto finish;
}
CM_CHK_MOSSTATUS_GOTOFINISH( HalCm_GetSurfaceAndRegister( state, &renderHalSurface, CM_ARGUMENT_SURFACE2D, index, pixelPitch ) );
// Setup 2D surface
MOS_ZeroMemory(&surfaceParam, sizeof(surfaceParam));
surfaceParam.Type = renderHal->SurfaceTypeDefault;
surfaceParam.Boundary = RENDERHAL_SS_BOUNDARY_ORIGINAL;
surfaceParam.bVertStride = 0;
surfaceParam.bVertStrideOffs = 0;
if (!pixelPitch) {
surfaceParam.bWidthInDword_UV = true;
surfaceParam.bWidthInDword_Y = true;
}
surfaceParam.bRenderTarget = isRenderTarget(state, index);
surfStateParam = &(state->umdSurf2DTable[index].surfaceStateParam[argParam->aliasIndex / state->surfaceArraySize]);
if (surfStateParam->width)
{
surface->dwWidth = surfStateParam->width;
}
if (surfStateParam->height)
{
surface->dwHeight = surfStateParam->height;
}
if (surfStateParam->depth)
{
surface->dwDepth = surfStateParam->depth;
}
if (surfStateParam->pitch)
{
surface->dwPitch= surfStateParam->pitch;
}
if (surfStateParam->format)
{
UpdateSurfaceAliasPlaneOffset(surfStateParam, surface);
}
if (surfStateParam->surfaceXOffset)
{
surface->YPlaneOffset.iXOffset = surfStateParam->surfaceXOffset;
if (surface->Format == Format_NV12)
{
surface->UPlaneOffset.iXOffset += surfStateParam->surfaceXOffset;
}
}
if (surfStateParam->surfaceYOffset)
{
surface->YPlaneOffset.iYOffset = surfStateParam->surfaceYOffset;
if (surface->Format == Format_NV12)
{
surface->UPlaneOffset.iYOffset += surfStateParam->surfaceYOffset/2;
}
}
if (surfStateParam->memoryObjectControl)
{
memObjCtl = surfStateParam->memoryObjectControl;
}
if(pixelPitch)
renderHalSurface.Rotation = state->umdSurf2DTable[index].rotationFlag;
//Cache configurations
state->cmHalInterface->HwSetSurfaceMemoryObjectControl(memObjCtl, &surfaceParam);
// interlace setting
HalCm_HwSetSurfaceProperty(state,
state->umdSurf2DTable[index].frameType,
&surfaceParam);
CM_CHK_MOSSTATUS_GOTOFINISH(renderHal->pfnSetupSurfaceState(
renderHal,
&renderHalSurface,
&surfaceParam,
&nSurfaceEntries,
surfaceEntries,
nullptr));
nSurfaceEntries = MOS_MIN( nSurfaceEntries, MHW_MAX_SURFACE_PLANES );
btIndex = HalCm_GetFreeBindingIndex(state, indexParam, nSurfaceEntries);
for (i = 0; i < (uint32_t)nSurfaceEntries; i++)
{
// Bind the surface State
CM_CHK_MOSSTATUS_GOTOFINISH(renderHal->pfnBindSurfaceState(
renderHal,
bindingTable,
btIndex + i,
surfaceEntries[i]));
if ((taskParam->surfEntryInfoArrays.kernelNum !=0) &&
(taskParam->surfEntryInfoArrays.surfEntryInfosArray != nullptr))
{
//GT-Pin
CM_CHK_MOSSTATUS_GOTOFINISH(HalCm_GetSurfaceDetails(
state,
indexParam,
btIndex + i,
*surface,
0,
surfaceEntries[i],
tempPlaneIndex,
surfaceParam,
CM_ARGUMENT_SURFACE2D));
}
}
// only update the reuse table for non-aliased surface
if ( argParam->aliasCreated == false )
{
state->bti2DIndexTable[ index ].nPlaneNumber = nSurfaceEntries;
// Get Offset to Current Binding Table
stateHeap = renderHal->pStateHeap;
offsetSrc = ( stateHeap->iCurSshBufferIndex * stateHeap->dwSshIntanceSize ) + // Points to the Base of Current SSH Buffer Instance
( stateHeap->iBindingTableOffset ) + // Moves the pointer to Base of Array of Binding Tables
( bindingTable * stateHeap->iBindingTableSize ) + // Moves the pointer to a Particular Binding Table
( btIndex * sizeof( uint32_t ) ); // Move the pointer to correct entry
if ( pixelPitch )
{
state->bti2DIndexTable[ index ].BTI.samplerSurfIndex = btIndex;
state->bti2DIndexTable[ index ].BTITableEntry.samplerBtiEntryPosition = stateHeap->pSshBuffer + offsetSrc;
}
else
{
state->bti2DIndexTable[ index ].BTI.regularSurfIndex = btIndex;
state->bti2DIndexTable[ index ].BTITableEntry.regularBtiEntryPosition = stateHeap->pSshBuffer + offsetSrc;
}
}
// Update the Batch Buffer
if (buffer)
{
dst = buffer + argParam->payloadOffset;
*((uint32_t*)dst) = btIndex;
}
// reset surface height and width
surface->dwWidth = state->umdSurf2DTable[index].width;
surface->dwHeight = state->umdSurf2DTable[index].height;
eStatus = MOS_STATUS_SUCCESS;
finish:
return eStatus;
}
MOS_STATUS HalCm_Setup2DSurfaceState(
PCM_HAL_STATE state,
PCM_HAL_KERNEL_ARG_PARAM argParam,
PCM_HAL_INDEX_PARAM indexParam,
int32_t bindingTable,
uint32_t threadIndex,
uint8_t *buffer)
{
MOS_STATUS eStatus;
//Binding surface based at the unit of dword
CM_CHK_MOSSTATUS_GOTOFINISH(HalCm_Setup2DSurfaceStateBasic(
state, argParam, indexParam, bindingTable, threadIndex, false, buffer, false));
eStatus = MOS_STATUS_SUCCESS;
finish:
return eStatus;
}
MOS_STATUS HalCm_Setup2DSurfaceSamplerState(
PCM_HAL_STATE state,
PCM_HAL_KERNEL_ARG_PARAM argParam,
PCM_HAL_INDEX_PARAM indexParam,
int32_t bindingTable,
uint32_t threadIndex,
uint8_t *buffer)
{
MOS_STATUS eStatus;
//Binding surface based at the unit of dword
CM_CHK_MOSSTATUS_GOTOFINISH(HalCm_Setup2DSurfaceStateBasic(
state, argParam, indexParam, bindingTable, threadIndex, true, buffer, false));
eStatus = MOS_STATUS_SUCCESS;
finish:
return eStatus;
}
//*-----------------------------------------------------------------------------
//| Purpose: Setup 2D surface State
//| Returns: Result of the operation
//*-----------------------------------------------------------------------------
MOS_STATUS HalCm_Setup2DSurfaceUPStateBasic(
PCM_HAL_STATE state,
PCM_HAL_KERNEL_ARG_PARAM argParam,
PCM_HAL_INDEX_PARAM indexParam,
int32_t bindingTable,
uint32_t threadIndex,
uint8_t *buffer,
bool pixelPitch)
{
MOS_STATUS eStatus;
RENDERHAL_SURFACE surface;
RENDERHAL_SURFACE_STATE_PARAMS surfaceParam;
PRENDERHAL_INTERFACE renderHal;
PRENDERHAL_SURFACE_STATE_ENTRY surfaceEntries[MHW_MAX_SURFACE_PLANES];
uint8_t *src;
uint8_t *dst;
int32_t nSurfaceEntries;
uint32_t index;
uint32_t btIndex;
uint16_t memObjCtl;
uint32_t i;
uint32_t offsetSrc;
PRENDERHAL_STATE_HEAP stateHeap;
eStatus = MOS_STATUS_UNKNOWN;
renderHal = state->renderHal;
//GT-PIN
PCM_HAL_TASK_PARAM taskParam = state->taskParam;
// Get the Index to sampler array from the kernel data
CM_ASSERT(argParam->unitSize == sizeof(index));
src = argParam->firstValue + (threadIndex * argParam->unitSize);
index = *((uint32_t*)src) & CM_SURFACE_MASK;
if (index == CM_NULL_SURFACE)
{
if (buffer)
{
dst = buffer + argParam->payloadOffset;
*((uint32_t*)dst) = CM_NULL_SURFACE_BINDING_INDEX;
}
eStatus = MOS_STATUS_SUCCESS;
goto finish;
}
memObjCtl = state->surf2DUPTable[index].memObjCtl;
if (!memObjCtl)
{
memObjCtl = CM_DEFAULT_CACHE_TYPE;
}
// check to see if the data present for the sampler in the array
if (index >= state->cmDeviceParam.max2DSurfaceUPTableSize ||
(state->surf2DUPTable[index].width == 0))
{
eStatus = MOS_STATUS_INVALID_PARAMETER;
CM_ASSERTMESSAGE(
"Invalid 2D SurfaceUP array index '%d'", index);
goto finish;
}
// Check to see if surface is already assigned
if ( pixelPitch )
{
btIndex = state->bti2DUPIndexTable[ index ].BTI.samplerSurfIndex;
}
else
{
btIndex = state->bti2DUPIndexTable[ index ].BTI.regularSurfIndex;
}
if ( btIndex == ( unsigned char )CM_INVALID_INDEX )
{
uint32_t tempPlaneIndex = 0;
// Get Details of 2DUP surface and fill the surface
CM_CHK_MOSSTATUS_GOTOFINISH(HalCm_GetSurfaceAndRegister(state, &surface, CM_ARGUMENT_SURFACE2D_UP, index, pixelPitch));
// Setup 2D surface
MOS_ZeroMemory(&surfaceParam, sizeof(surfaceParam));
surfaceParam.Type = renderHal->SurfaceTypeDefault;
surfaceParam.Boundary = RENDERHAL_SS_BOUNDARY_ORIGINAL;
if (!pixelPitch) {
surfaceParam.bWidthInDword_UV = true;
surfaceParam.bWidthInDword_Y = true;
}
surfaceParam.bRenderTarget = true;
//Cache configurations
state->cmHalInterface->HwSetSurfaceMemoryObjectControl(memObjCtl, &surfaceParam);
// interlace setting
HalCm_HwSetSurfaceProperty(state,
state->umdSurf2DTable[index].frameType,
&surfaceParam);
CM_CHK_MOSSTATUS_GOTOFINISH(renderHal->pfnSetupSurfaceState(
renderHal,
&surface,
&surfaceParam,
&nSurfaceEntries,
surfaceEntries,
nullptr));
//GT-PIN
btIndex = HalCm_GetFreeBindingIndex(state, indexParam, nSurfaceEntries);
for (i = 0; i < (uint32_t)nSurfaceEntries; i++)
{
// Bind the surface State
CM_CHK_MOSSTATUS_GOTOFINISH(renderHal->pfnBindSurfaceState(
renderHal,
bindingTable,
btIndex + i,
surfaceEntries[i]));
//GT-Pin
if ((taskParam->surfEntryInfoArrays.kernelNum != 0) &&
(taskParam->surfEntryInfoArrays.surfEntryInfosArray != nullptr))
{
CM_CHK_MOSSTATUS_GOTOFINISH(HalCm_GetSurfaceDetails(
state,
indexParam,
btIndex + i,
surface.OsSurface,
0,
surfaceEntries[i],
tempPlaneIndex,
surfaceParam,
CM_ARGUMENT_SURFACE2D_UP));
}
}
state->bti2DUPIndexTable[ index ].nPlaneNumber = nSurfaceEntries;
stateHeap = renderHal->pStateHeap;
offsetSrc = ( stateHeap->iCurSshBufferIndex * stateHeap->dwSshIntanceSize ) + // Points to the Base of Current SSH Buffer Instance
( stateHeap->iBindingTableOffset ) + // Moves the pointer to Base of Array of Binding Tables
( bindingTable * stateHeap->iBindingTableSize ) + // Moves the pointer to a Particular Binding Table
( btIndex * sizeof( uint32_t ) ); // Move the pointer to correct entry
if ( pixelPitch )
{
state->bti2DUPIndexTable[ index ].BTI.samplerSurfIndex = btIndex;
state->bti2DUPIndexTable[ index ].BTITableEntry.samplerBtiEntryPosition = stateHeap->pSshBuffer + offsetSrc;
}
else
{
state->bti2DUPIndexTable[ index ].BTI.regularSurfIndex = btIndex;
state->bti2DUPIndexTable[ index ].BTITableEntry.regularBtiEntryPosition = stateHeap->pSshBuffer + offsetSrc;
}
}
else
{
stateHeap = renderHal->pStateHeap;
// Get Offset to Current Binding Table
uint32_t offsetCurrentBTStart = ( stateHeap->iCurSshBufferIndex * stateHeap->dwSshIntanceSize ) + // Points to the Base of Current SSH Buffer Instance
( stateHeap->iBindingTableOffset ) + // Moves the pointer to Base of Array of Binding Tables
( bindingTable * stateHeap->iBindingTableSize ); // Moves the pointer to a Particular Binding Table
uint32_t *currentBTStart = ( uint32_t *)( stateHeap->pSshBuffer + offsetCurrentBTStart );
int nEntryIndex = 0;
if ( pixelPitch )
{
nEntryIndex = (int) ((uint32_t*)( state->bti2DUPIndexTable[ index ].BTITableEntry.samplerBtiEntryPosition ) - currentBTStart);
}
else
{
nEntryIndex = (int) ((uint32_t*)( state->bti2DUPIndexTable[ index ].BTITableEntry.regularBtiEntryPosition ) - currentBTStart);
}
if ( ( nEntryIndex < 0 ) || ( nEntryIndex >= renderHal->StateHeapSettings.iSurfacesPerBT ) )
{
uint32_t tmpSurfaceEntries = state->bti2DUPIndexTable[ index ].nPlaneNumber;
btIndex = HalCm_GetFreeBindingIndex( state, indexParam, tmpSurfaceEntries );
// Get Offset to Current Binding Table
uint32_t offsetDst = offsetCurrentBTStart + ( btIndex * sizeof( uint32_t ) ); // Move the pointer to correct entry
uint32_t *bindingTableEntry = ( uint32_t *)( stateHeap->pSshBuffer + offsetDst );
if ( pixelPitch )
{
MOS_SecureMemcpy( bindingTableEntry, sizeof( uint32_t ) * tmpSurfaceEntries, state->bti2DUPIndexTable[ index ].BTITableEntry.samplerBtiEntryPosition, sizeof( uint32_t ) * tmpSurfaceEntries );
}
else
{
MOS_SecureMemcpy( bindingTableEntry, sizeof( uint32_t ) * tmpSurfaceEntries, state->bti2DUPIndexTable[ index ].BTITableEntry.regularBtiEntryPosition, sizeof( uint32_t ) * tmpSurfaceEntries );
}
// update index to table
if ( pixelPitch )
{
state->bti2DUPIndexTable[ index ].BTI.samplerSurfIndex = btIndex;
state->bti2DUPIndexTable[ index ].BTITableEntry.samplerBtiEntryPosition = bindingTableEntry;
}
else
{
state->bti2DUPIndexTable[ index ].BTI.regularSurfIndex = btIndex;
state->bti2DUPIndexTable[ index ].BTITableEntry.regularBtiEntryPosition = bindingTableEntry;
}
}
}
// Update the Batch Buffer
if (buffer)
{
dst = buffer + argParam->payloadOffset;
*((uint32_t*)dst) = btIndex;
}
eStatus = MOS_STATUS_SUCCESS;
finish:
return eStatus;
}
MOS_STATUS HalCm_Setup2DSurfaceUPState(
PCM_HAL_STATE state,
PCM_HAL_KERNEL_ARG_PARAM argParam,
PCM_HAL_INDEX_PARAM indexParam,
int32_t bindingTable,
uint32_t threadIndex,
uint8_t *buffer)
{
MOS_STATUS eStatus;
//Binding surface based at the unit of dword
CM_CHK_MOSSTATUS_GOTOFINISH(HalCm_Setup2DSurfaceUPStateBasic(
state, argParam, indexParam, bindingTable, threadIndex, buffer, false));
eStatus = MOS_STATUS_SUCCESS;
finish:
return eStatus;
}
MOS_STATUS HalCm_Setup2DSurfaceUPSamplerState(
PCM_HAL_STATE state,
PCM_HAL_KERNEL_ARG_PARAM argParam,
PCM_HAL_INDEX_PARAM indexParam,
int32_t bindingTable,
uint32_t threadIndex,
uint8_t *buffer)
{
MOS_STATUS eStatus;
//Binding surface based at the unit of pixel
CM_CHK_MOSSTATUS_GOTOFINISH(HalCm_Setup2DSurfaceUPStateBasic(
state, argParam, indexParam, bindingTable, threadIndex, buffer, true));
eStatus = MOS_STATUS_SUCCESS;
finish:
return eStatus;
}
MOS_STATUS HalCm_SetupSpecificVmeSurfaceState(
PCM_HAL_STATE state,
PCM_HAL_INDEX_PARAM indexParam,
int32_t bindingTable,
uint32_t surfIndex,
uint32_t btIndex,
uint16_t memObjCtl,
uint32_t surfaceStateWidth,
uint32_t surfaceStateHeight)
{
MOS_STATUS eStatus;
RENDERHAL_SURFACE surface;
int32_t nSurfaceEntries = 0;
RENDERHAL_SURFACE_STATE_PARAMS surfaceParam;
PRENDERHAL_INTERFACE renderHal;
PRENDERHAL_SURFACE_STATE_ENTRY surfaceEntries[MHW_MAX_SURFACE_PLANES];
uint32_t tempPlaneIndex = 0;
PMOS_SURFACE mosSurface = nullptr;
eStatus = MOS_STATUS_UNKNOWN;
renderHal = state->renderHal;
nSurfaceEntries = 0;
PCM_HAL_TASK_PARAM taskParam = state->taskParam;
// Get Details of VME surface and fill the surface
CM_CHK_MOSSTATUS_GOTOFINISH(HalCm_GetSurfaceAndRegister(state, &surface, CM_ARGUMENT_VME_STATE, surfIndex, 0));
// Setup 2D surface
MOS_ZeroMemory(&surfaceParam, sizeof(surfaceParam));
surfaceParam.Type = renderHal->SurfaceTypeAdvanced;
surfaceParam.bRenderTarget = true;
surfaceParam.bWidthInDword_Y = false;
surfaceParam.bWidthInDword_UV = false;
surfaceParam.Boundary = RENDERHAL_SS_BOUNDARY_ORIGINAL;
surfaceParam.bVmeUse = true;
// Overwrite the width and height if specified
if (surfaceStateWidth && surfaceStateHeight)
{
mosSurface = &surface.OsSurface;
if (surfaceStateWidth > mosSurface->dwWidth || surfaceStateHeight > mosSurface->dwHeight)
{
CM_ASSERTMESSAGE("Error: VME surface state's resolution is larger than the original surface.");
eStatus = MOS_STATUS_INVALID_PARAMETER;
goto finish;
}
mosSurface->dwWidth = surfaceStateWidth;
mosSurface->dwHeight = surfaceStateHeight;
}
//Cache configurations
state->cmHalInterface->HwSetSurfaceMemoryObjectControl(memObjCtl, &surfaceParam);
CM_CHK_MOSSTATUS_GOTOFINISH(renderHal->pfnSetupSurfaceState(
renderHal,
&surface,
&surfaceParam,
&nSurfaceEntries,
surfaceEntries,
nullptr));
CM_ASSERT(nSurfaceEntries == 1);
{
// Bind the surface State
CM_CHK_MOSSTATUS_GOTOFINISH(renderHal->pfnBindSurfaceState(
renderHal,
bindingTable,
btIndex,
surfaceEntries[0]));
if ((taskParam->surfEntryInfoArrays.kernelNum != 0) &&
(taskParam->surfEntryInfoArrays.surfEntryInfosArray != nullptr))
{
CM_CHK_MOSSTATUS_GOTOFINISH(HalCm_GetSurfaceDetails(
state,
indexParam,
btIndex,
surface.OsSurface,
0,
surfaceEntries[0],
tempPlaneIndex,
surfaceParam,
CM_ARGUMENT_SURFACE2D));
}
}
state->bti2DIndexTable[ surfIndex ].BTI.vmeSurfIndex = btIndex;
eStatus = MOS_STATUS_SUCCESS;
finish:
return eStatus;
}
//*-----------------------------------------------------------------------------
//| Purpose: Setup VME surface State
//| Returns: Result of the operation
//*-----------------------------------------------------------------------------
MOS_STATUS HalCm_SetupVmeSurfaceState(
PCM_HAL_STATE state,
PCM_HAL_KERNEL_ARG_PARAM argParam,
PCM_HAL_INDEX_PARAM indexParam,
int32_t bindingTable,
uint32_t threadIndex,
uint8_t *buffer)
{
MOS_STATUS eStatus;
PRENDERHAL_INTERFACE renderHal;
PCM_HAL_VME_ARG_VALUE vmeSrc;
uint8_t *dst;
uint32_t index[CM_MAX_VME_BINDING_INDEX_1];
uint16_t memObjCtl[CM_MAX_VME_BINDING_INDEX_1];
uint32_t fwSurfCount = 0;
uint32_t bwSurfCount = 0;
bool alreadyBind = true;
uint32_t surfPairNum;
uint32_t idx;
uint32_t curBTIndex;
uint32_t btIndex;
uint32_t surfaceStateWidth = 0;
uint32_t surfaceStateHeight = 0;
uint32_t *fPtr = nullptr;
uint32_t *bPtr = nullptr;
uint32_t *refSurfaces = nullptr;
eStatus = MOS_STATUS_UNKNOWN;
renderHal = state->renderHal;
btIndex = 0;
MOS_ZeroMemory(memObjCtl, CM_MAX_VME_BINDING_INDEX_1*sizeof(uint16_t));
MOS_ZeroMemory(index, CM_MAX_VME_BINDING_INDEX_1*sizeof(uint32_t));
CM_ASSERT(argParam->unitSize <= sizeof(uint32_t)*(CM_MAX_VME_BINDING_INDEX_1 + 2));
CM_ASSERT(threadIndex == 0); // VME surface is not allowed in thread arg
vmeSrc = (PCM_HAL_VME_ARG_VALUE)argParam->firstValue;
fwSurfCount = vmeSrc->fwRefNum;
bwSurfCount = vmeSrc->bwRefNum;
refSurfaces = findRefInVmeArg(vmeSrc);
index[0] = vmeSrc->curSurface & CM_SURFACE_MASK;
// check to see if index[0] is valid
if (index[0] == CM_NULL_SURFACE)
{
if (buffer)
{
dst = buffer + argParam->payloadOffset;
*((uint32_t*)dst) = CM_NULL_SURFACE_BINDING_INDEX;
}
eStatus = MOS_STATUS_SUCCESS;
goto finish;
}
if (index[0] >= state->cmDeviceParam.max2DSurfaceTableSize ||
Mos_ResourceIsNull(&state->umdSurf2DTable[index[0]].osResource))
{
eStatus = MOS_STATUS_INVALID_PARAMETER;
CM_ASSERTMESSAGE(
"Invalid 2D surface array index '%d'", index[0]);
goto finish;
}
memObjCtl[0] = state->umdSurf2DTable[index[0]].memObjCtl;
if (!memObjCtl[0])
{
memObjCtl[0] = CM_DEFAULT_CACHE_TYPE;
}
for (idx = 0; idx < (vmeSrc->fwRefNum + vmeSrc->bwRefNum); idx++)
{
index[idx + 1] = refSurfaces[idx] & CM_SURFACE_MASK;
memObjCtl[idx + 1] = state->umdSurf2DTable[index[idx + 1]].memObjCtl;
if (!memObjCtl[idx + 1])
{
memObjCtl[idx + 1] = CM_DEFAULT_CACHE_TYPE;
}
}
surfaceStateWidth = vmeSrc->surfStateParam.surfaceStateWidth;
surfaceStateHeight = vmeSrc->surfStateParam.surfaceStateHeight;
fPtr = index + 1;
bPtr = index + 1 + fwSurfCount;
//Max surface pair number
surfPairNum = fwSurfCount > bwSurfCount ? fwSurfCount : bwSurfCount;
btIndex = curBTIndex = HalCm_GetFreeBindingIndex(state, indexParam, surfPairNum*2 + 1);
HalCm_SetupSpecificVmeSurfaceState(state, indexParam, bindingTable, index[0], curBTIndex, memObjCtl[0], surfaceStateWidth, surfaceStateHeight);
curBTIndex++;
//Setup surface states interleavely for backward and forward surfaces pairs.
for (idx = 0; idx < surfPairNum; idx++)
{
if (idx < fwSurfCount)
{
HalCm_SetupSpecificVmeSurfaceState(state, indexParam, bindingTable, fPtr[idx], curBTIndex, memObjCtl[idx + 1], surfaceStateWidth, surfaceStateHeight);
}
curBTIndex++;
if (idx < bwSurfCount)
{
HalCm_SetupSpecificVmeSurfaceState(state, indexParam, bindingTable, bPtr[idx], curBTIndex, memObjCtl[idx+ 1 + fwSurfCount], surfaceStateWidth, surfaceStateHeight);
}
curBTIndex++;
}
// Update the Batch Buffer
if (buffer)
{
dst = buffer + argParam->payloadOffset;
*((uint32_t*)dst) = btIndex;
}
eStatus = MOS_STATUS_SUCCESS;
finish:
return eStatus;
}
//*-----------------------------------------------------------------------------
//| Purpose: Setup VME surface State
//| Returns: Result of the operation
//*-----------------------------------------------------------------------------
MOS_STATUS HalCm_SetupSampler8x8SurfaceState(
PCM_HAL_STATE state,
PCM_HAL_KERNEL_ARG_PARAM argParam,
PCM_HAL_INDEX_PARAM indexParam,
int32_t bindingTable,
uint32_t threadIndex,
uint8_t *buffer)
{
MOS_STATUS eStatus;
RENDERHAL_SURFACE surface;
RENDERHAL_SURFACE_STATE_PARAMS surfaceParam;
PRENDERHAL_INTERFACE renderHal;
PRENDERHAL_SURFACE_STATE_ENTRY surfaceEntries[MHW_MAX_SURFACE_PLANES];
uint8_t *src;
uint8_t *dst;
int32_t nSurfaceEntries;
uint32_t index;
uint16_t memObjCtl;
int32_t i;
uint32_t btIndex;
uint32_t tempPlaneIndex = 0;
uint32_t offsetSrc;
PRENDERHAL_STATE_HEAP stateHeap;
eStatus = MOS_STATUS_UNKNOWN;
renderHal = state->renderHal;
PCM_HAL_TASK_PARAM taskParam = state->taskParam;
nSurfaceEntries = 0;
CM_ASSERT(argParam->unitSize == sizeof(uint32_t));
src = argParam->firstValue + (threadIndex * argParam->unitSize);
index = *((uint32_t*)src) & CM_SURFACE_MASK;
if (index == CM_NULL_SURFACE)
{
if (buffer)
{
dst = buffer + argParam->payloadOffset;
*((uint32_t*)dst) = CM_NULL_SURFACE_BINDING_INDEX;
}
eStatus = MOS_STATUS_SUCCESS;
goto finish;
}
memObjCtl = state->umdSurf2DTable[index].memObjCtl;
if (!memObjCtl)
{
memObjCtl = CM_DEFAULT_CACHE_TYPE;
}
// check to see if index is valid
if (index >= state->cmDeviceParam.max2DSurfaceTableSize ||
Mos_ResourceIsNull(&state->umdSurf2DTable[index].osResource))
{
eStatus = MOS_STATUS_INVALID_PARAMETER;
CM_ASSERTMESSAGE(
"Invalid 2D surface array index '%d'", index);
goto finish;
}
renderHal->bEnableP010SinglePass = state->cmHalInterface->IsP010SinglePassSupported();
btIndex = state->bti2DIndexTable[ index ].BTI.sampler8x8SurfIndex;
if ( btIndex == ( unsigned char )CM_INVALID_INDEX )
{
// Get Details of Sampler8x8 surface and fill the surface
CM_CHK_MOSSTATUS_GOTOFINISH( HalCm_GetSurfaceAndRegister( state, &surface, argParam->kind, index, 0 ) );
// Setup surface
MOS_ZeroMemory( &surfaceParam, sizeof( surfaceParam ) );
surfaceParam.Type = renderHal->SurfaceTypeAdvanced;
surfaceParam.bRenderTarget = true;
surfaceParam.bWidthInDword_Y = false;
surfaceParam.bWidthInDword_UV = false;
surfaceParam.Boundary = RENDERHAL_SS_BOUNDARY_ORIGINAL;
surfaceParam.bVASurface = ( argParam->kind == CM_ARGUMENT_SURFACE_SAMPLER8X8_VA ) ? 1 : 0;
surfaceParam.AddressControl = argParam->nCustomValue;
//Set memory object control
state->cmHalInterface->HwSetSurfaceMemoryObjectControl(memObjCtl, &surfaceParam);
surface.Rotation = state->umdSurf2DTable[index].rotationFlag;
surface.ChromaSiting = state->umdSurf2DTable[index].chromaSiting;
nSurfaceEntries = 0;
// interlace setting
HalCm_HwSetSurfaceProperty(state,
state->umdSurf2DTable[index].frameType,
&surfaceParam);
CM_CHK_MOSSTATUS_GOTOFINISH( renderHal->pfnSetupSurfaceState(
renderHal,
&surface,
&surfaceParam,
&nSurfaceEntries,
surfaceEntries,
nullptr ) );
CM_ASSERT( nSurfaceEntries == 1 );
btIndex = HalCm_GetFreeBindingIndex( state, indexParam, nSurfaceEntries );
for ( i = 0; i < nSurfaceEntries; i++ )
{
// Bind the surface State
CM_CHK_MOSSTATUS_GOTOFINISH( renderHal->pfnBindSurfaceState(
renderHal,
bindingTable,
btIndex + i,
surfaceEntries[ i ] ) );
if ( ( taskParam->surfEntryInfoArrays.kernelNum != 0 ) &&
( taskParam->surfEntryInfoArrays.surfEntryInfosArray != nullptr ) )
{
CM_CHK_MOSSTATUS_GOTOFINISH( HalCm_GetSurfaceDetails(
state,
indexParam,
btIndex + i,
surface.OsSurface,
0,
surfaceEntries[ i ],
tempPlaneIndex,
surfaceParam,
CM_ARGUMENT_SURFACE2D ) );
}
}
stateHeap = renderHal->pStateHeap;
offsetSrc = ( stateHeap->iCurSshBufferIndex * stateHeap->dwSshIntanceSize ) + // Points to the Base of Current SSH Buffer Instance
( stateHeap->iBindingTableOffset ) + // Moves the pointer to Base of Array of Binding Tables
( bindingTable * stateHeap->iBindingTableSize ) + // Moves the pointer to a Particular Binding Table
( btIndex * sizeof( uint32_t ) ); // Move the pointer to correct entry
state->bti2DIndexTable[ index ].nPlaneNumber = nSurfaceEntries;
state->bti2DIndexTable[ index ].BTITableEntry.sampler8x8BtiEntryPosition = stateHeap->pSshBuffer + offsetSrc;
state->bti2DIndexTable[ index ].BTI.sampler8x8SurfIndex = btIndex;
}
else
{
stateHeap = renderHal->pStateHeap;
// Get Offset to Current Binding Table
uint32_t offsetCurrentBTStart = ( stateHeap->iCurSshBufferIndex * stateHeap->dwSshIntanceSize ) + // Points to the Base of Current SSH Buffer Instance
( stateHeap->iBindingTableOffset ) + // Moves the pointer to Base of Array of Binding Tables
( bindingTable * stateHeap->iBindingTableSize ); // Moves the pointer to a Particular Binding Table
uint32_t *currentBTStart = ( uint32_t *)( stateHeap->pSshBuffer + offsetCurrentBTStart );
int nEntryIndex = 0;
nEntryIndex = ( int )( ( uint32_t *)( state->bti2DIndexTable[ index ].BTITableEntry.sampler8x8BtiEntryPosition ) - currentBTStart );
if ( ( nEntryIndex < 0 ) || ( nEntryIndex >= renderHal->StateHeapSettings.iSurfacesPerBT ) )
{
uint32_t tmpSurfaceEntries = state->bti2DIndexTable[ index ].nPlaneNumber;
btIndex = HalCm_GetFreeBindingIndex( state, indexParam, tmpSurfaceEntries );
// Get Offset to Current Binding Table
uint32_t offsetDst = offsetCurrentBTStart + ( btIndex * sizeof( uint32_t ) ); // Move the pointer to correct entry
uint32_t *bindingTableEntry = ( uint32_t *)( stateHeap->pSshBuffer + offsetDst );
MOS_SecureMemcpy( bindingTableEntry, sizeof( uint32_t ) * tmpSurfaceEntries, state->bti2DIndexTable[ index ].BTITableEntry.sampler8x8BtiEntryPosition, sizeof( uint32_t ) * tmpSurfaceEntries );
// update index to table
state->bti2DIndexTable[ index ].BTI.sampler8x8SurfIndex = btIndex;
state->bti2DIndexTable[ index ].BTITableEntry.sampler8x8BtiEntryPosition = bindingTableEntry;
}
}
// Update the Batch Buffer
if ( buffer )
{
dst = buffer + argParam->payloadOffset;
*( ( uint32_t *)dst ) = state->bti2DIndexTable[ index ].BTI.sampler8x8SurfIndex;
}
eStatus = MOS_STATUS_SUCCESS;
finish:
renderHal->bEnableP010SinglePass = false;
return eStatus;
}
//*-----------------------------------------------------------------------------
//| Purpose: Setup State Buffer surface State
//| Returns: Result of the operation
//*-----------------------------------------------------------------------------
MOS_STATUS HalCm_SetupStateBufferSurfaceState(
PCM_HAL_STATE state,
PCM_HAL_KERNEL_ARG_PARAM argParam,
PCM_HAL_INDEX_PARAM indexParam,
int32_t bindingTable,
uint32_t threadIndex,
uint8_t *buffer )
{
MOS_STATUS eStatus = MOS_STATUS_SUCCESS;
PRENDERHAL_INTERFACE renderHal;
RENDERHAL_SURFACE_STATE_PARAMS surfaceParam;
RENDERHAL_SURFACE renderhalSurface;
PRENDERHAL_SURFACE_STATE_ENTRY surfaceEntry;
uint32_t btIndex;
CM_SURFACE_BTI_INFO surfBTIInfo;
uint16_t memObjCtl;
state->cmHalInterface->GetHwSurfaceBTIInfo( &surfBTIInfo );
uint32_t surfIndex = reinterpret_cast< uint32_t *>( argParam->firstValue )[ 0 ];
surfIndex = surfIndex & CM_SURFACE_MASK;
memObjCtl = state->bufferTable[ surfIndex ].memObjCtl;
btIndex = HalCm_GetFreeBindingIndex( state, indexParam, 1 );
renderHal = state->renderHal;
MOS_ZeroMemory( &renderhalSurface, sizeof( renderhalSurface ) );
// Get Details of Sampler8x8 surface and fill the surface
CM_CHK_MOSSTATUS_GOTOFINISH( HalCm_GetSurfaceAndRegister( state, &renderhalSurface, argParam->kind, surfIndex, 0 ) );
MOS_ZeroMemory( &surfaceParam, sizeof( surfaceParam ) );
// Set the bRenderTarget by default
surfaceParam.bRenderTarget = true;
//Cache configurations default
state->cmHalInterface->HwSetSurfaceMemoryObjectControl( memObjCtl, &surfaceParam );
// Setup Buffer surface
CM_CHK_MOSSTATUS_GOTOFINISH( renderHal->pfnSetupBufferSurfaceState(
renderHal,
&renderhalSurface,
&surfaceParam,
&surfaceEntry ) );
// Bind the surface State
surfaceEntry->pSurface = &renderhalSurface.OsSurface;
CM_ASSERT( ( ( int32_t )btIndex ) < renderHal->StateHeapSettings.iSurfacesPerBT + surfBTIInfo.normalSurfaceStart );
CM_CHK_MOSSTATUS_GOTOFINISH( renderHal->pfnBindSurfaceState(
renderHal,
bindingTable,
btIndex,
surfaceEntry ) );
if ( buffer )
{
*( ( uint32_t *)( buffer + argParam->payloadOffset ) ) = btIndex;
}
finish:
return eStatus;
}
//------------------------------------------------------------------------------
//| Purpose: Get usr defined threadcount / threadgroup
//| Returns: Result of the operation
//------------------------------------------------------------------------------
MOS_STATUS HalCm_GetMaxThreadCountPerThreadGroup(
PCM_HAL_STATE state, // [in] Pointer to CM State
uint32_t *threadsPerThreadGroup) // [out] Pointer to threadsPerThreadGroup
{
MOS_STATUS eStatus = MOS_STATUS_SUCCESS;
CM_PLATFORM_INFO platformInfo;
MOS_ZeroMemory(&platformInfo, sizeof(CM_PLATFORM_INFO));
CM_CHK_MOSSTATUS_GOTOFINISH( state->pfnGetPlatformInfo( state, &platformInfo, false) );
if (platformInfo.numMaxEUsPerPool)
{
*threadsPerThreadGroup = (platformInfo.numHWThreadsPerEU) * (platformInfo.numMaxEUsPerPool);
}
else
{
*threadsPerThreadGroup = (platformInfo.numHWThreadsPerEU) * (platformInfo.numEUsPerSubSlice);
}
finish:
return eStatus;
}
//*-----------------------------------------------------------------------------
//| Purpose: Decodes hints to get number and size of kernel groups
//| Returns: Result of the operation
//*-----------------------------------------------------------------------------
MOS_STATUS HalCm_GetNumKernelsPerGroup(
uint8_t hintsBits,
uint32_t numKernels,
uint32_t *numKernelsPerGroup,
uint32_t *numKernelGroups,
uint32_t *remapKernelToGroup,
uint32_t *remapGroupToKernel
)
{
MOS_STATUS eStatus = MOS_STATUS_SUCCESS;
uint32_t currGrp = 0;
uint32_t i = 0;
// first group at least has one kernel
numKernelsPerGroup[currGrp]++;
remapGroupToKernel[currGrp] = 0;
for( i = 0; i < numKernels - 1; ++i )
{
if( (hintsBits & CM_HINTS_LEASTBIT_MASK) == CM_HINTS_LEASTBIT_MASK )
{
currGrp++;
*numKernelGroups = *numKernelGroups + 1;
remapGroupToKernel[currGrp] = i + 1;
}
numKernelsPerGroup[currGrp]++;
hintsBits >>= 1;
remapKernelToGroup[i+1] = currGrp;
}
return eStatus;
}
//*-----------------------------------------------------------------------------
//| Purpose: Gets information about max parallelism graphs
//| numThreadsOnSides based on formula to sum 1 to n: (n(n+1))/2
//| Returns: Result of the operation
//*-----------------------------------------------------------------------------
MOS_STATUS HalCm_GetParallelGraphInfo(
uint32_t maximum,
uint32_t numThreads,
uint32_t width,
uint32_t height,
PCM_HAL_PARALLELISM_GRAPH_INFO graphInfo,
CM_DEPENDENCY_PATTERN pattern,
bool noDependencyCase)
{
MOS_STATUS eStatus = MOS_STATUS_SUCCESS;
uint32_t numThreadsOnSides = 0;
uint32_t numMaxRepeat = 0;
uint32_t numSteps = 0;
switch( pattern )
{
case CM_NONE_DEPENDENCY:
if (noDependencyCase)
{
maximum = 1;
numMaxRepeat = width * height;
numSteps = width * height;
}
// do nothing will depend on other kernels
break;
case CM_VERTICAL_WAVE:
numMaxRepeat = width;
numSteps = width;
break;
case CM_HORIZONTAL_WAVE:
numMaxRepeat = height;
numSteps = height;
break;
case CM_WAVEFRONT:
numThreadsOnSides = ( maximum - 1 ) * maximum;
numMaxRepeat = (numThreads - numThreadsOnSides ) / maximum;
numSteps = ( maximum - 1) * 2 + numMaxRepeat;
break;
case CM_WAVEFRONT26:
numThreadsOnSides = ( maximum - 1 ) * maximum * 2;
numMaxRepeat = (numThreads - numThreadsOnSides ) / maximum;
numSteps = ( (maximum - 1) * 2 ) * 2 + numMaxRepeat;
break;
case CM_WAVEFRONT26Z:
// do nothing already set outside of this function
break;
default:
eStatus = MOS_STATUS_INVALID_PARAMETER;
CM_ASSERTMESSAGE("Unsupported dependency pattern for EnqueueWithHints");
goto finish;
}
graphInfo->maxParallelism = maximum;
graphInfo->numMaxRepeat = numMaxRepeat;
graphInfo->numSteps = numSteps;
finish:
return eStatus;
}
//*-----------------------------------------------------------------------------
//| Purpose: Sets dispatch pattern based on max parallelism for media objects
//| Returns: Result of the operation
//*-----------------------------------------------------------------------------
MOS_STATUS HalCm_SetDispatchPattern(
CM_HAL_PARALLELISM_GRAPH_INFO graphInfo,
CM_DEPENDENCY_PATTERN pattern,
uint32_t *dispatchFreq
)
{
MOS_STATUS eStatus = MOS_STATUS_SUCCESS;
uint32_t i = 0;
uint32_t j = 0;
uint32_t k = 0;
switch( pattern )
{
case CM_NONE_DEPENDENCY:
break;
case CM_HORIZONTAL_WAVE:
case CM_VERTICAL_WAVE:
for( i = 0; i < graphInfo.numSteps; ++i )
{
dispatchFreq[i] = graphInfo.maxParallelism;
}
break;
case CM_WAVEFRONT:
for( i = 1; i < graphInfo.maxParallelism; ++i )
{
dispatchFreq[i-1] = i;
}
for( j = 0; j < graphInfo.numMaxRepeat; ++i, ++j )
{
dispatchFreq[i-1] = graphInfo.maxParallelism;
}
for( j = graphInfo.maxParallelism - 1; i <= graphInfo.numSteps; ++i, --j )
{
dispatchFreq[i-1] = j;
}
break;
case CM_WAVEFRONT26:
for( i = 1, j = 0; i < graphInfo.maxParallelism; ++i, j +=2 )
{
dispatchFreq[j] = i;
dispatchFreq[j+1] = i;
}
for( k = 0; k < graphInfo.numMaxRepeat; ++k, ++j)
{
dispatchFreq[j] = graphInfo.maxParallelism;
}
for( i = graphInfo.maxParallelism - 1; j < graphInfo.numSteps; j +=2, --i )
{
dispatchFreq[j] = i;
dispatchFreq[j+1] = i;
}
break;
case CM_WAVEFRONT26Z:
break;
default:
eStatus = MOS_STATUS_INVALID_PARAMETER;
CM_ASSERTMESSAGE("Unsupported dependency pattern for EnqueueWithHints");
goto finish;
}
finish:
return eStatus;
}
//*-----------------------------------------------------------------------------
//| Purpose: Sets dispatch frequency for kernel group based on number of steps
//| Returns: Result of the operation
//*-----------------------------------------------------------------------------
MOS_STATUS HalCm_SetKernelGrpFreqDispatch(
PCM_HAL_PARALLELISM_GRAPH_INFO graphInfo,
PCM_HAL_KERNEL_GROUP_INFO groupInfo,
uint32_t numKernelGroups,
uint32_t *minSteps)
{
MOS_STATUS eStatus = MOS_STATUS_SUCCESS;
uint32_t i = 0;
uint32_t j = 0;
uint32_t tmpSteps = 0;
uint32_t kerIndex = 0;
for( i = 0; i < numKernelGroups; ++i)
{
for( j = 0; j < groupInfo[i].numKernelsInGroup; ++j )
{
tmpSteps += graphInfo[kerIndex].numSteps;
kerIndex++;
}
if ( tmpSteps )
{
*minSteps = MOS_MIN(*minSteps, tmpSteps);
groupInfo[i].numStepsInGrp = tmpSteps;
}
tmpSteps = 0;
}
for( i = 0; i < numKernelGroups; ++i )
{
groupInfo[i].freqDispatch = (uint32_t)ceil( (groupInfo[i].numStepsInGrp / (double)*minSteps) );
}
return eStatus;
}
//*-----------------------------------------------------------------------------
//| Purpose: Sets dispatch pattern for kernel with no dependency based on
//| the minimum number of steps calculated from kernels with dependency
//| Returns: Result of the operation
//*-----------------------------------------------------------------------------
MOS_STATUS HalCm_SetNoDependKernelDispatchPattern(
uint32_t numThreads,
uint32_t minSteps,
uint32_t *dispatchFreq)
{
MOS_STATUS eStatus = MOS_STATUS_SUCCESS;
uint32_t i = 0;
uint32_t numEachStep = 0;
uint32_t total = 0;
numEachStep = numThreads / minSteps;
for( i = 0; i < minSteps; ++i )
{
dispatchFreq[i] = numEachStep;
total += numEachStep;
}
while( total != numThreads )
{
// dispatch more at beginning
i = 0;
dispatchFreq[i]++;
total++;
i++;
}
return eStatus;
}
MOS_STATUS HalCm_FinishStatesForKernel(
PCM_HAL_STATE state, // [in] Pointer to CM State
PRENDERHAL_MEDIA_STATE mediaState,
PMHW_BATCH_BUFFER batchBuffer, // [in] Pointer to Batch Buffer
int32_t taskId, // [in] Task ID
PCM_HAL_KERNEL_PARAM kernelParam,
int32_t kernelIndex,
PCM_HAL_INDEX_PARAM indexParam,
int32_t bindingTable,
int32_t mediaID,
PRENDERHAL_KRN_ALLOCATION krnAllocation
)
{
MOS_STATUS eStatus = MOS_STATUS_SUCCESS;
PCM_HAL_TASK_PARAM taskParam = state->taskParam;
PRENDERHAL_INTERFACE renderHal = state->renderHal;
PCM_HAL_WALKER_PARAMS mediaWalkerParams = &kernelParam->walkerParams;
PCM_GPGPU_WALKER_PARAMS perKernelGpGpuWalkerParams = &kernelParam->gpgpuWalkerParams;
PCM_HAL_SCOREBOARD threadCoordinates = nullptr;
PCM_HAL_MASK_AND_RESET dependencyMask = nullptr;
bool enableThreadSpace = false;
bool enableKernelThreadSpace = false;
PCM_HAL_SCOREBOARD kernelThreadCoordinates = nullptr;
UNUSED(taskId);
MHW_MEDIA_OBJECT_PARAMS mediaObjectParam;
PCM_HAL_KERNEL_ARG_PARAM argParam;
MHW_PIPE_CONTROL_PARAMS pipeControlParam;
uint32_t i;
uint32_t hdrSize;
uint32_t aIndex;
uint32_t tIndex;
uint32_t index;
//GT-PIN
taskParam->curKernelIndex = kernelIndex;
CmSafeMemSet(&mediaObjectParam, 0, sizeof(MHW_MEDIA_OBJECT_PARAMS));
if (perKernelGpGpuWalkerParams->gpgpuEnabled)
{
// GPGPU_WALKER, just update ID here. other fields are already filled.
perKernelGpGpuWalkerParams->interfaceDescriptorOffset = mediaID;// mediaObjectParam.dwInterfaceDescriptorOffset;
}
else if (mediaWalkerParams->cmWalkerEnable)
{
// Media walker, just update ID here. other fields are already filled.
mediaWalkerParams->interfaceDescriptorOffset = mediaID;
}
else
{
// MEDIA_OBJECT
mediaObjectParam.dwInterfaceDescriptorOffset = mediaID;
hdrSize = renderHal->pHwSizes->dwSizeMediaObjectHeaderCmd;
if (kernelParam->indirectDataParam.indirectDataSize)
{
mediaObjectParam.dwInlineDataSize = 0;
}
else
{
mediaObjectParam.dwInlineDataSize = MOS_MAX(kernelParam->payloadSize, 4);
}
if (taskParam->threadCoordinates)
{
threadCoordinates = taskParam->threadCoordinates[kernelIndex];
if (threadCoordinates)
{
enableThreadSpace = true;
}
}
else if (kernelParam->kernelThreadSpaceParam.threadCoordinates)
{
kernelThreadCoordinates = kernelParam->kernelThreadSpaceParam.threadCoordinates;
if (kernelThreadCoordinates)
{
enableKernelThreadSpace = true;
}
}
if (taskParam->dependencyMasks)
{
dependencyMask = taskParam->dependencyMasks[kernelIndex];
}
CM_CHK_NULL_GOTOFINISH_MOSERROR( batchBuffer );
uint8_t inlineData[CM_MAX_THREAD_PAYLOAD_SIZE];
uint8_t *cmdInline = inlineData;
uint32_t cmdSize = mediaObjectParam.dwInlineDataSize + hdrSize;
// Setup states for arguments and threads
if (((PCM_HAL_BB_ARGS)batchBuffer->pPrivateData)->refCount > 1)
{
uint8_t *bBuffer = batchBuffer->pData + batchBuffer->iCurrent;
for (aIndex = 0; aIndex < kernelParam->numArgs; aIndex++)
{
argParam = &kernelParam->argParams[aIndex];
if ((kernelParam->cmFlags & CM_KERNEL_FLAGS_CURBE) && !argParam->perThread)
{
continue;
}
for (tIndex = 0; tIndex < kernelParam->numThreads; tIndex++)
{
index = tIndex * argParam->perThread;
//-----------------------------------------------------
CM_ASSERT(argParam->payloadOffset < kernelParam->payloadSize);
//-----------------------------------------------------
switch(argParam->kind)
{
case CM_ARGUMENT_GENERAL:
break;
case CM_ARGUMENT_SAMPLER:
CM_CHK_MOSSTATUS_GOTOFINISH(HalCm_SetupSamplerState(
state, kernelParam, argParam, indexParam, mediaID, index, nullptr));
break;
case CM_ARGUMENT_SURFACEBUFFER:
CM_CHK_MOSSTATUS_GOTOFINISH(HalCm_SetupBufferSurfaceState(
state, argParam, indexParam, bindingTable, -1, index, nullptr));
break;
case CM_ARGUMENT_SURFACE2D_UP:
CM_CHK_MOSSTATUS_GOTOFINISH(HalCm_Setup2DSurfaceUPState(
state, argParam, indexParam, bindingTable, index, nullptr));
break;
case CM_ARGUMENT_SURFACE2DUP_SAMPLER:
CM_CHK_MOSSTATUS_GOTOFINISH(HalCm_Setup2DSurfaceUPSamplerState(
state, argParam, indexParam, bindingTable, index, nullptr));
break;
case CM_ARGUMENT_SURFACE2D_SAMPLER:
CM_CHK_MOSSTATUS_GOTOFINISH(HalCm_Setup2DSurfaceSamplerState(
state, argParam, indexParam, bindingTable, 0, nullptr));
break;
case CM_ARGUMENT_SURFACE2D:
CM_CHK_MOSSTATUS_GOTOFINISH(HalCm_Setup2DSurfaceState(
state, argParam, indexParam, bindingTable, index, nullptr));
break;
case CM_ARGUMENT_SURFACE3D:
CM_CHK_MOSSTATUS_GOTOFINISH(HalCm_Setup3DSurfaceState(
state, argParam, indexParam, bindingTable, index, nullptr));
break;
case CM_ARGUMENT_SURFACE_VME:
CM_CHK_MOSSTATUS_GOTOFINISH(HalCm_SetupVmeSurfaceState(
state, argParam, indexParam, bindingTable, 0, nullptr));
break;
case CM_ARGUMENT_SURFACE_SAMPLER8X8_AVS:
case CM_ARGUMENT_SURFACE_SAMPLER8X8_VA:
CM_CHK_MOSSTATUS_GOTOFINISH(HalCm_SetupSampler8x8SurfaceState(
state, argParam, indexParam, bindingTable, 0, nullptr));
break;
default:
eStatus = MOS_STATUS_INVALID_PARAMETER;
CM_ASSERTMESSAGE(
"Argument kind '%d' is not supported", argParam->kind);
goto finish;
}
}
if( dependencyMask )
{
if( dependencyMask[tIndex].resetMask == CM_RESET_DEPENDENCY_MASK )
{
MOS_SecureMemcpy(bBuffer + (CM_SCOREBOARD_MASK_POS_IN_MEDIA_OBJECT_CMD*sizeof(uint32_t)),
sizeof(uint8_t), &dependencyMask[tIndex].mask, sizeof(uint8_t));
}
}
batchBuffer->iCurrent += cmdSize;
bBuffer += cmdSize;
}
}
else
{
//Insert synchronization if needed (PIPE_CONTROL)
// 1. synchronization is set
// 2. the next kernel has dependency pattern
if((kernelIndex > 0) && ((taskParam->syncBitmap & ((uint64_t)1 << (kernelIndex-1))) || (kernelParam->kernelThreadSpaceParam.patternType != CM_NONE_DEPENDENCY)))
{
pipeControlParam = g_cRenderHal_InitPipeControlParams;
pipeControlParam.presDest = nullptr;
pipeControlParam.dwFlushMode = MHW_FLUSH_CUSTOM; // Use custom flags
pipeControlParam.dwPostSyncOp = MHW_FLUSH_NOWRITE;
pipeControlParam.bDisableCSStall = false;
pipeControlParam.bTlbInvalidate = false;
pipeControlParam.bFlushRenderTargetCache = true;
pipeControlParam.bInvalidateTextureCache = true;
renderHal->pMhwMiInterface->AddPipeControl(nullptr, batchBuffer, &pipeControlParam);
}
uint8_t *bBuffer = batchBuffer->pData + batchBuffer->iCurrent;
for (tIndex = 0; tIndex < kernelParam->numThreads; tIndex++)
{
if (enableThreadSpace)
{
mediaObjectParam.VfeScoreboard.ScoreboardEnable = (state->scoreboardParams.ScoreboardMask==0) ? 0:1;
mediaObjectParam.VfeScoreboard.Value[0] = threadCoordinates[tIndex].x;
mediaObjectParam.VfeScoreboard.Value[1] = threadCoordinates[tIndex].y;
mediaObjectParam.VfeScoreboard.ScoreboardColor = threadCoordinates[tIndex].color;
mediaObjectParam.dwSliceDestinationSelect = threadCoordinates[tIndex].sliceSelect;
mediaObjectParam.dwHalfSliceDestinationSelect = threadCoordinates[tIndex].subSliceSelect;
if( !dependencyMask )
{
mediaObjectParam.VfeScoreboard.ScoreboardMask = (1 << state->scoreboardParams.ScoreboardMask)-1;
}
else
{
mediaObjectParam.VfeScoreboard.ScoreboardMask = dependencyMask[tIndex].mask;
}
}
else if (enableKernelThreadSpace)
{
mediaObjectParam.VfeScoreboard.ScoreboardEnable = (state->scoreboardParams.ScoreboardMask == 0) ? 0 : 1;
mediaObjectParam.VfeScoreboard.Value[0] = kernelThreadCoordinates[tIndex].x;
mediaObjectParam.VfeScoreboard.Value[1] = kernelThreadCoordinates[tIndex].y;
mediaObjectParam.VfeScoreboard.ScoreboardColor = kernelThreadCoordinates[tIndex].color;
mediaObjectParam.dwSliceDestinationSelect = kernelThreadCoordinates[tIndex].sliceSelect;
mediaObjectParam.dwHalfSliceDestinationSelect = kernelThreadCoordinates[tIndex].subSliceSelect;
if (!dependencyMask)
{
mediaObjectParam.VfeScoreboard.ScoreboardMask = (1 << state->scoreboardParams.ScoreboardMask) - 1;
}
else
{
mediaObjectParam.VfeScoreboard.ScoreboardMask = dependencyMask[tIndex].mask;
}
}
else
{
mediaObjectParam.VfeScoreboard.Value[0] = tIndex % taskParam->threadSpaceWidth;
mediaObjectParam.VfeScoreboard.Value[1] = tIndex / taskParam->threadSpaceWidth;
}
for (aIndex = 0; aIndex < kernelParam->numArgs; aIndex++)
{
argParam = &kernelParam->argParams[aIndex];
index = tIndex * argParam->perThread;
if ((kernelParam->cmFlags & CM_KERNEL_FLAGS_CURBE) && !argParam->perThread)
{
continue;
}
//-----------------------------------------------------
CM_ASSERT(argParam->payloadOffset < kernelParam->payloadSize);
//-----------------------------------------------------
switch(argParam->kind)
{
case CM_ARGUMENT_GENERAL:
MOS_SecureMemcpy(
cmdInline + argParam->payloadOffset,
argParam->unitSize,
argParam->firstValue + index * argParam->unitSize,
argParam->unitSize);
break;
case CM_ARGUMENT_SAMPLER:
CM_CHK_MOSSTATUS_GOTOFINISH(HalCm_SetupSamplerState(
state, kernelParam, argParam, indexParam, mediaID, index, cmdInline));
break;
case CM_ARGUMENT_SURFACEBUFFER:
CM_CHK_MOSSTATUS_GOTOFINISH(HalCm_SetupBufferSurfaceState(
state, argParam, indexParam, bindingTable, -1, index, cmdInline));
break;
case CM_ARGUMENT_SURFACE2D_UP:
CM_CHK_MOSSTATUS_GOTOFINISH(HalCm_Setup2DSurfaceUPState(
state, argParam, indexParam, bindingTable, index, cmdInline));
break;
case CM_ARGUMENT_SURFACE2DUP_SAMPLER:
CM_CHK_MOSSTATUS_GOTOFINISH(HalCm_Setup2DSurfaceUPSamplerState(
state, argParam, indexParam, bindingTable, index, cmdInline));
break;
case CM_ARGUMENT_SURFACE2D_SAMPLER:
CM_CHK_MOSSTATUS_GOTOFINISH(HalCm_Setup2DSurfaceSamplerState(
state, argParam, indexParam, bindingTable, index, cmdInline));
break;
case CM_ARGUMENT_SURFACE2D:
CM_CHK_MOSSTATUS_GOTOFINISH(HalCm_Setup2DSurfaceState(
state, argParam, indexParam, bindingTable, index, cmdInline));
break;
case CM_ARGUMENT_SURFACE3D:
CM_CHK_MOSSTATUS_GOTOFINISH(HalCm_Setup3DSurfaceState(
state, argParam, indexParam, bindingTable, index, cmdInline));
break;
case CM_ARGUMENT_SURFACE_VME:
CM_CHK_MOSSTATUS_GOTOFINISH(HalCm_SetupVmeSurfaceState(
state, argParam, indexParam, bindingTable, 0, cmdInline));
break;
case CM_ARGUMENT_SURFACE_SAMPLER8X8_AVS:
case CM_ARGUMENT_SURFACE_SAMPLER8X8_VA:
CM_CHK_MOSSTATUS_GOTOFINISH(HalCm_SetupSampler8x8SurfaceState(
state, argParam, indexParam, bindingTable, 0, cmdInline));
break;
default:
eStatus = MOS_STATUS_INVALID_PARAMETER;
CM_ASSERTMESSAGE(
"Argument kind '%d' is not supported", argParam->kind);
goto finish;
}
}
mediaObjectParam.pInlineData = inlineData;
state->renderHal->pMhwRenderInterface->AddMediaObject(nullptr, batchBuffer, &mediaObjectParam);
}
}
}
for (i = 0; i < CM_MAX_GLOBAL_SURFACE_NUMBER; i++) {
if ((kernelParam->globalSurface[i] & CM_SURFACE_MASK) != CM_NULL_SURFACE)
{
CM_HAL_KERNEL_ARG_PARAM tempArgParam;
argParam = &tempArgParam;
tempArgParam.kind = CM_ARGUMENT_SURFACEBUFFER;
tempArgParam.payloadOffset = 0;
tempArgParam.unitCount = 1;
tempArgParam.unitSize = sizeof(uint32_t);
tempArgParam.perThread = false;
tempArgParam.firstValue = (uint8_t*)&kernelParam->globalSurface[i];
tempArgParam.aliasIndex = 0;
tempArgParam.aliasCreated = false;
CM_CHK_MOSSTATUS_GOTOFINISH(HalCm_SetupBufferSurfaceState(
state, argParam, indexParam, bindingTable, (int16_t)i, 0, nullptr));
}
}
// set number of samplers
krnAllocation->Params.Sampler_Count = indexParam->samplerIndexCount;
// add SIP surface
if (kernelParam->kernelDebugEnabled)
{
CM_CHK_MOSSTATUS_GOTOFINISH(HalCm_SetupSipSurfaceState(state, indexParam, bindingTable));
}
finish:
return eStatus;
}
//*-----------------------------------------------------------------------------
//| Purpose: Finishes setting up HW states for the kernel
//| Used by EnqueueWithHints
//| Returns: Result of the operation
//*-----------------------------------------------------------------------------
MOS_STATUS HalCm_FinishStatesForKernelMix(
PCM_HAL_STATE state,
PMHW_BATCH_BUFFER batchBuffer,
int32_t taskId,
PCM_HAL_KERNEL_PARAM* cmExecKernels,
PCM_HAL_INDEX_PARAM indexParams,
int32_t *bindingTableEntries,
int32_t *mediaIds,
PRENDERHAL_KRN_ALLOCATION *krnAllocations,
uint32_t numKernels,
uint32_t hints,
bool lastTask)
{
MOS_STATUS eStatus = MOS_STATUS_SUCCESS;
PRENDERHAL_INTERFACE renderHal = state->renderHal;
PMHW_MEDIA_OBJECT_PARAMS mediaObjectParams = nullptr;
PCM_HAL_KERNEL_PARAM* kernelParams = nullptr;
PCM_HAL_KERNEL_ARG_PARAM* argParams = nullptr;
PCM_HAL_BB_ARGS bbCmArgs = nullptr;
PMHW_VFE_SCOREBOARD scoreboardParams = nullptr;
PCM_HAL_PARALLELISM_GRAPH_INFO parallelGraphInfo = nullptr;
PCM_HAL_KERNEL_ARG_PARAM argParam = nullptr;
PCM_HAL_KERNEL_SUBSLICE_INFO kernelsSliceInfo = nullptr;
PCM_HAL_KERNEL_THREADSPACE_PARAM kernelTSParam = nullptr;
PCM_HAL_KERNEL_GROUP_INFO groupInfo = nullptr;
CM_HAL_DEPENDENCY vfeDependencyInfo ;
CM_PLATFORM_INFO platformInfo ;
CM_GT_SYSTEM_INFO systemInfo ;
CM_HAL_SCOREBOARD_XY_MASK threadCoordinates ;
uint32_t **dependRemap = nullptr;
uint32_t **dispatchFreq = nullptr;
uint8_t **cmdInline = nullptr;
uint32_t *cmdSizes = nullptr;
uint32_t *remapKrnToGrp = nullptr;
uint32_t *remapGrpToKrn = nullptr;
uint32_t *numKernelsPerGrp = nullptr;
uint8_t *kernelScoreboardMask = nullptr;
uint8_t hintsBits = 0;
uint8_t tmpThreadScoreboardMask = 0;
uint8_t scoreboardMask = 0;
bool singleSubSlice = false;
bool enableThreadSpace = false;
bool kernelFound = false;
bool updateCurrKernel = false;
bool noDependencyCase = false;
bool sufficientSliceInfo = true;
uint32_t adjustedYCoord = 0;
uint32_t numKernelGroups = CM_HINTS_DEFAULT_NUM_KERNEL_GRP;
uint32_t totalNumThreads = 0;
uint32_t hdrSize = 0;
uint32_t i = 0;
uint32_t j = 0;
uint32_t k = 0;
uint32_t tmp = 0;
uint32_t tmp1 = 0;
uint32_t loopCount = 0;
uint32_t aIndex = 0;
uint32_t index = 0;
uint32_t totalReqSubSlices = 0;
uint32_t difference = 0;
uint32_t curKernel = 0;
uint32_t numSet = 0;
uint32_t numSubSlicesEnabled = 0;
uint32_t sliceIndex = 0;
uint32_t tmpNumSubSlice = 0;
uint32_t tmpNumKernelsPerGrp = 0;
uint32_t maximum = 0;
uint32_t count = 0;
uint32_t numDispatched = 0;
uint32_t tmpIndex = 0;
uint32_t numStepsDispatched = 0;
uint32_t minSteps = UINT_MAX;
uint32_t grpId = 0;
uint32_t allocSize = 0;
uint32_t currentKernel = 0;
uint32_t roundRobinCount = 0;
uint32_t numTasks = 0;
uint32_t extraSWThreads = 0;
UNUSED(taskId);
CM_CHK_NULL_GOTOFINISH_MOSERROR(batchBuffer);
MOS_ZeroMemory(&threadCoordinates, sizeof(CM_HAL_SCOREBOARD_XY_MASK));
MOS_ZeroMemory(&vfeDependencyInfo, sizeof(CM_HAL_DEPENDENCY));
MOS_ZeroMemory(&platformInfo, sizeof(CM_PLATFORM_INFO));
MOS_ZeroMemory(&systemInfo, sizeof(CM_GT_SYSTEM_INFO));
mediaObjectParams = (PMHW_MEDIA_OBJECT_PARAMS)MOS_AllocAndZeroMemory(sizeof(MHW_MEDIA_OBJECT_PARAMS)*numKernels);
kernelParams = (PCM_HAL_KERNEL_PARAM*)MOS_AllocAndZeroMemory(sizeof(PCM_HAL_KERNEL_PARAM)*numKernels);
argParams = (PCM_HAL_KERNEL_ARG_PARAM*)MOS_AllocAndZeroMemory(sizeof(PCM_HAL_KERNEL_ARG_PARAM)*numKernels);
cmdInline = (uint8_t**)MOS_AllocAndZeroMemory(sizeof(uint8_t*)*numKernels);
cmdSizes = (uint32_t*)MOS_AllocAndZeroMemory(sizeof(uint32_t)*numKernels);
remapKrnToGrp = (uint32_t*)MOS_AllocAndZeroMemory(sizeof(uint32_t)*numKernels);
remapGrpToKrn = (uint32_t*)MOS_AllocAndZeroMemory(sizeof(uint32_t)*numKernels);
kernelScoreboardMask = (uint8_t*)MOS_AllocAndZeroMemory(sizeof(uint8_t)*numKernels);
dependRemap = (uint32_t**)MOS_AllocAndZeroMemory(sizeof(uint32_t*)*numKernels);
parallelGraphInfo = (PCM_HAL_PARALLELISM_GRAPH_INFO)MOS_AllocAndZeroMemory(sizeof(CM_HAL_PARALLELISM_GRAPH_INFO)*numKernels);
dispatchFreq = (uint32_t**)MOS_AllocAndZeroMemory(sizeof(uint32_t*)*numKernels);
numKernelsPerGrp = (uint32_t*)MOS_AllocAndZeroMemory(sizeof(uint32_t)*numKernels);
if( !mediaObjectParams || !kernelParams || !argParams ||
!cmdInline || !cmdSizes ||
!remapKrnToGrp || !remapGrpToKrn || !kernelScoreboardMask || !dependRemap ||
!parallelGraphInfo || !dispatchFreq || !numKernelsPerGrp )
{
eStatus = MOS_STATUS_INVALID_PARAMETER;
CM_ASSERTMESSAGE("Memory allocation failed in EnqueueWithHints");
goto finish;
}
state->euSaturationEnabled = true;
hintsBits = (hints & CM_HINTS_MASK_KERNEL_GROUPS) >> CM_HINTS_NUM_BITS_WALK_OBJ;
CM_CHK_MOSSTATUS_GOTOFINISH(HalCm_GetNumKernelsPerGroup(hintsBits, numKernels, numKernelsPerGrp,
&numKernelGroups, remapKrnToGrp, remapGrpToKrn));
kernelsSliceInfo = (PCM_HAL_KERNEL_SUBSLICE_INFO)MOS_AllocAndZeroMemory(sizeof(CM_HAL_KERNEL_SUBSLICE_INFO)*numKernelGroups);
groupInfo = (PCM_HAL_KERNEL_GROUP_INFO)MOS_AllocAndZeroMemory(sizeof(CM_HAL_KERNEL_GROUP_INFO)*numKernelGroups);
if( !kernelsSliceInfo || !groupInfo )
{
eStatus = MOS_STATUS_INVALID_PARAMETER;
CM_ASSERTMESSAGE("Memory allocation failed in EnqueueWithHints");
goto finish;
}
for( i = 0; i < numKernelGroups; ++i)
{
groupInfo[i].numKernelsInGroup = numKernelsPerGrp[i];
}
hdrSize = renderHal->pHwSizes->dwSizeMediaObjectHeaderCmd;
for ( i = 0; i < numKernels; ++i )
{
kernelParams[i] = cmExecKernels[i];
mediaObjectParams[i].dwInterfaceDescriptorOffset = mediaIds[i];
mediaObjectParams[i].dwInlineDataSize = MOS_MAX(kernelParams[i]->payloadSize, 4);
cmdInline[i] = (uint8_t*)MOS_AllocAndZeroMemory(sizeof(uint8_t) * 1024);
cmdSizes[i] = mediaObjectParams[i].dwInlineDataSize + hdrSize;
totalNumThreads += kernelParams[i]->numThreads;
}
numTasks = ( hints & CM_HINTS_MASK_NUM_TASKS ) >> CM_HINTS_NUM_BITS_TASK_POS;
if( numTasks > 1 )
{
if( lastTask )
{
extraSWThreads = totalNumThreads % numTasks;
}
totalNumThreads = (totalNumThreads / numTasks) + extraSWThreads;
}
for( i = 0; i < numKernels; ++i )
{
dependRemap[i] = (uint32_t*)MOS_AllocAndZeroMemory(sizeof(uint32_t) * CM_HAL_MAX_DEPENDENCY_COUNT);
for( k = 0; k < CM_HAL_MAX_DEPENDENCY_COUNT; ++k )
{
// initialize each index to map to itself
dependRemap[i][k] = k;
}
}
for( i = 0; i < numKernels; ++i )
{
kernelTSParam = &kernelParams[i]->kernelThreadSpaceParam;
// calculate union dependency vector of all kernels with dependency
if( kernelTSParam->dependencyInfo.count )
{
if( vfeDependencyInfo.count == 0 )
{
MOS_SecureMemcpy(&vfeDependencyInfo, sizeof(CM_HAL_DEPENDENCY), &kernelTSParam->dependencyInfo, sizeof(CM_HAL_DEPENDENCY));
kernelScoreboardMask[i] = ( 1 << vfeDependencyInfo.count ) - 1;
}
else
{
for( j = 0; j < kernelTSParam->dependencyInfo.count; ++j )
{
for( k = 0; k < vfeDependencyInfo.count; ++k )
{
if( (kernelTSParam->dependencyInfo.deltaX[j] == vfeDependencyInfo.deltaX[k]) &&
(kernelTSParam->dependencyInfo.deltaY[j] == vfeDependencyInfo.deltaY[k]) )
{
CM_HAL_SETBIT(kernelScoreboardMask[i], k);
dependRemap[i][j] = k;
break;
}
}
if ( k == vfeDependencyInfo.count )
{
vfeDependencyInfo.deltaX[vfeDependencyInfo.count] = kernelTSParam->dependencyInfo.deltaX[j];
vfeDependencyInfo.deltaY[vfeDependencyInfo.count] = kernelTSParam->dependencyInfo.deltaY[j];
CM_HAL_SETBIT(kernelScoreboardMask[i], vfeDependencyInfo.count);
vfeDependencyInfo.count++;
dependRemap[i][j] = k;
}
}
}
}
} // for num kernels
if( vfeDependencyInfo.count > CM_HAL_MAX_DEPENDENCY_COUNT )
{
eStatus = MOS_STATUS_INVALID_PARAMETER;
CM_ASSERTMESSAGE("Union of kernel dependencies exceeds max dependency count (8)");
goto finish;
}
// set VFE scoreboarding information from union of kernel dependency vectors
scoreboardParams = &state->scoreboardParams;
scoreboardParams->ScoreboardMask = (uint8_t)vfeDependencyInfo.count;
for( i = 0; i < scoreboardParams->ScoreboardMask; ++i )
{
scoreboardParams->ScoreboardDelta[i].x = vfeDependencyInfo.deltaX[i];
scoreboardParams->ScoreboardDelta[i].y = vfeDependencyInfo.deltaY[i];
}
if (vfeDependencyInfo.count == 0)
{
noDependencyCase = true;
}
CM_CHK_MOSSTATUS_GOTOFINISH(state->pfnGetPlatformInfo(state, &platformInfo, true));
singleSubSlice = (platformInfo.numSubSlices == 1) ? true : false;
CM_CHK_MOSSTATUS_GOTOFINISH(state->pfnGetGTSystemInfo(state, &systemInfo));
if( !singleSubSlice )
{
for( i = 0; i < numKernelGroups; ++i )
{
tmpNumKernelsPerGrp = numKernelsPerGrp[i];
for( j = 0; j < tmpNumKernelsPerGrp; ++j )
{
kernelTSParam = &kernelParams[count]->kernelThreadSpaceParam;
switch( kernelTSParam->patternType )
{
case CM_NONE_DEPENDENCY:
maximum = kernelParams[count]->numThreads;
break;
case CM_WAVEFRONT:
maximum = MOS_MIN(kernelTSParam->threadSpaceWidth, kernelTSParam->threadSpaceHeight);
break;
case CM_WAVEFRONT26:
maximum = MOS_MIN( ((kernelTSParam->threadSpaceWidth + 1) >> 1), kernelTSParam->threadSpaceHeight);
break;
case CM_VERTICAL_WAVE:
maximum = kernelTSParam->threadSpaceHeight;
break;
case CM_HORIZONTAL_WAVE:
maximum = kernelTSParam->threadSpaceWidth;
break;
case CM_WAVEFRONT26Z:
maximum = MOS_MIN( ((kernelTSParam->threadSpaceWidth - 1) >> 1), kernelTSParam->threadSpaceHeight);
break;
default:
eStatus = MOS_STATUS_INVALID_PARAMETER;
CM_ASSERTMESSAGE("Unsupported dependency pattern for EnqueueWithHints");
goto finish;
}
if( kernelTSParam->patternType != CM_WAVEFRONT26Z )
{
CM_CHK_MOSSTATUS_GOTOFINISH(HalCm_GetParallelGraphInfo(maximum, kernelParams[count]->numThreads,
kernelTSParam->threadSpaceWidth, kernelTSParam->threadSpaceHeight,
¶llelGraphInfo[count], kernelTSParam->patternType, noDependencyCase));
}
else
{
parallelGraphInfo[count].numSteps = kernelTSParam->dispatchInfo.numWaves;
}
if( kernelTSParam->patternType != CM_NONE_DEPENDENCY )
{
dispatchFreq[count] = (uint32_t*)MOS_AllocAndZeroMemory(sizeof(uint32_t)*parallelGraphInfo[count].numSteps);
if( !dispatchFreq[count] )
{
eStatus = MOS_STATUS_INVALID_PARAMETER;
CM_ASSERTMESSAGE("Memory allocation failed for EnqueueWithHints");
goto finish;
}
if( kernelTSParam->patternType != CM_WAVEFRONT26Z )
{
CM_CHK_MOSSTATUS_GOTOFINISH(HalCm_SetDispatchPattern(parallelGraphInfo[count], kernelTSParam->patternType, dispatchFreq[count]));
}
else
{
MOS_SecureMemcpy(dispatchFreq[count], sizeof(uint32_t)*parallelGraphInfo[count].numSteps,
kernelTSParam->dispatchInfo.numThreadsInWave, sizeof(uint32_t)*parallelGraphInfo[count].numSteps);
}
}
if (!noDependencyCase)
{
tmpNumSubSlice =
(maximum / (platformInfo.numEUsPerSubSlice * platformInfo.numHWThreadsPerEU)) + 1;
if (tmpNumSubSlice > platformInfo.numSubSlices)
{
tmpNumSubSlice = platformInfo.numSubSlices - 1;
}
if (tmpNumSubSlice > kernelsSliceInfo[i].numSubSlices)
{
kernelsSliceInfo[i].numSubSlices = tmpNumSubSlice;
}
}
else
{
kernelsSliceInfo[i].numSubSlices = platformInfo.numSubSlices;
}
count++;
}
}
if (!noDependencyCase)
{
for (i = 0; i < numKernelGroups; ++i)
{
totalReqSubSlices += kernelsSliceInfo[i].numSubSlices;
}
// adjust if requested less or more subslices than architecture has
if (totalReqSubSlices < platformInfo.numSubSlices)
{
// want to add subslices starting from K0
difference = platformInfo.numSubSlices - totalReqSubSlices;
tmp = tmp1 = 0;
for (i = 0; i < difference; ++i)
{
tmp = tmp1 % numKernelGroups;
kernelsSliceInfo[tmp].numSubSlices++;
totalReqSubSlices++;
tmp1++;
}
}
else if (totalReqSubSlices > platformInfo.numSubSlices)
{
// want to subtract subslices starting from last kernel
difference = totalReqSubSlices - platformInfo.numSubSlices;
tmp = 0;
tmp1 = numKernelGroups - 1;
for (i = numKernelGroups - 1, j = 0; j < difference; --i, ++j)
{
tmp = tmp1 % numKernelGroups;
kernelsSliceInfo[tmp].numSubSlices--;
totalReqSubSlices--;
tmp1 += numKernelGroups - 1;
}
}
if (totalReqSubSlices != platformInfo.numSubSlices)
{
eStatus = MOS_STATUS_INVALID_PARAMETER;
CM_ASSERTMESSAGE("Total requested sub-slices does not match platform's number of sub-slices");
goto finish;
}
}
for(i = 0; i < numKernelGroups; ++i)
{
kernelsSliceInfo[i].destination = (PCM_HAL_KERNEL_SLICE_SUBSLICE)MOS_AllocAndZeroMemory(sizeof(CM_HAL_KERNEL_SLICE_SUBSLICE)*kernelsSliceInfo[i].numSubSlices);
if( !kernelsSliceInfo[i].destination )
{
eStatus = MOS_STATUS_INVALID_PARAMETER;
CM_ASSERTMESSAGE("Memory allocation failed in EnqueueWithHints");
goto finish;
}
}
// set slice, subslice for each kernel group
if (systemInfo.isSliceInfoValid)
{
for (i = 0; i < systemInfo.numMaxSlicesSupported; ++i)
{
for (j = 0; j < (systemInfo.numMaxSubSlicesSupported / systemInfo.numMaxSlicesSupported); ++j)
{
if (systemInfo.sliceInfo[i].SubSliceInfo[j].Enabled && systemInfo.sliceInfo[i].Enabled)
{
if (curKernel < numKernelGroups)
{
if (kernelsSliceInfo[curKernel].numSubSlices == numSet)
{
curKernel++;
numSet = 0;
}
}
if (curKernel < numKernelGroups)
{
kernelsSliceInfo[curKernel].destination[numSet].slice = i;
kernelsSliceInfo[curKernel].destination[numSet].subSlice = j;
numSet++;
}
numSubSlicesEnabled++;
}
}
}
if (numSubSlicesEnabled != platformInfo.numSubSlices)
{
// not enough slice information, do not assign sub-slice destination
sufficientSliceInfo = false;
}
}
// set freq dispatch ratio for each group
CM_CHK_MOSSTATUS_GOTOFINISH(HalCm_SetKernelGrpFreqDispatch(parallelGraphInfo, groupInfo, numKernelGroups, &minSteps));
// set dispatch pattern for kernel with no dependency
for( i = 0; i < numKernels; ++i )
{
if( kernelParams[i]->kernelThreadSpaceParam.patternType == CM_NONE_DEPENDENCY )
{
grpId = remapKrnToGrp[i];
allocSize = 0;
if( groupInfo[grpId].freqDispatch == 0 )
{
allocSize = minSteps;
groupInfo[grpId].freqDispatch = 1;
}
else
{
allocSize = minSteps * groupInfo[grpId].freqDispatch;
groupInfo[grpId].freqDispatch = groupInfo[grpId].freqDispatch * 2;
}
dispatchFreq[i] = (uint32_t*)MOS_AllocAndZeroMemory(sizeof(uint32_t)*allocSize);
if( !dispatchFreq[i] )
{
eStatus = MOS_STATUS_INVALID_PARAMETER;
CM_ASSERTMESSAGE("Memory allocation failed in EnqueueWithHints");
goto finish;
}
CM_CHK_MOSSTATUS_GOTOFINISH(HalCm_SetNoDependKernelDispatchPattern(kernelParams[i]->numThreads,
allocSize, dispatchFreq[i]));
}
}
}
CM_CHK_NULL_GOTOFINISH_MOSERROR(batchBuffer->pPrivateData);
bbCmArgs = (PCM_HAL_BB_ARGS) batchBuffer->pPrivateData;
if( bbCmArgs->refCount > 1 )
{
uint8_t *bBuffer = batchBuffer->pData + batchBuffer->iCurrent;
updateCurrKernel = false;
for( i = 0; i < totalNumThreads; ++i )
{
if( !singleSubSlice )
{
if( (dispatchFreq[currentKernel][state->hintIndexes.dispatchIndexes[currentKernel]] == numDispatched) ||
(state->hintIndexes.kernelIndexes[currentKernel] >= kernelParams[currentKernel]->numThreads) )
{
numDispatched = 0;
numStepsDispatched++;
state->hintIndexes.dispatchIndexes[currentKernel]++;
if( state->hintIndexes.kernelIndexes[currentKernel] >= kernelParams[currentKernel]->numThreads )
{
updateCurrKernel = true;
groupInfo[remapKrnToGrp[currentKernel]].numKernelsFinished++;
if( groupInfo[remapKrnToGrp[currentKernel]].numKernelsFinished ==
groupInfo[remapKrnToGrp[currentKernel]].numKernelsInGroup )
{
groupInfo[remapKrnToGrp[currentKernel]].groupFinished = 1;
}
else
{
remapGrpToKrn[tmpIndex]++;
}
}
if( (groupInfo[remapKrnToGrp[currentKernel]].freqDispatch == numStepsDispatched) ||
updateCurrKernel )
{
numStepsDispatched = 0;
roundRobinCount++;
tmpIndex = roundRobinCount % numKernelGroups;
if( groupInfo[tmpIndex].groupFinished )
{
loopCount = 0;
while( (loopCount < numKernelGroups) && (!kernelFound) )
{
roundRobinCount++;
tmpIndex = roundRobinCount % numKernelGroups;
if( state->hintIndexes.kernelIndexes[remapGrpToKrn[tmpIndex]] < kernelParams[remapGrpToKrn[tmpIndex]]->numThreads )
{
kernelFound = true;
}
loopCount++;
}
if( !kernelFound )
{
// Error shouldn't be here
// if still in for loop totalNumThreads, needs to be a kernel with threads left
eStatus = MOS_STATUS_UNKNOWN;
CM_ASSERTMESSAGE("Couldn't find kernel with threads left for EnqueueWithHints");
goto finish;
}
}
currentKernel = remapGrpToKrn[tmpIndex];
}
}
}
else
{
if( state->hintIndexes.kernelIndexes[currentKernel] >= kernelParams[currentKernel]->numThreads )
{
currentKernel++;
}
}
if( kernelParams[currentKernel]->kernelThreadSpaceParam.threadCoordinates )
{
threadCoordinates.y = kernelParams[currentKernel]->kernelThreadSpaceParam.threadCoordinates[state->hintIndexes.kernelIndexes[currentKernel]].y;
threadCoordinates.mask = kernelParams[currentKernel]->kernelThreadSpaceParam.threadCoordinates[state->hintIndexes.kernelIndexes[currentKernel]].mask;
enableThreadSpace = true;
threadCoordinates.resetMask = kernelParams[currentKernel]->kernelThreadSpaceParam.threadCoordinates[state->hintIndexes.kernelIndexes[currentKernel]].resetMask;
}
if( enableThreadSpace )
{
if( threadCoordinates.mask != CM_DEFAULT_THREAD_DEPENDENCY_MASK )
{
tmpThreadScoreboardMask = kernelScoreboardMask[currentKernel];
// do the remapping
for( k = 0; k < kernelParams[currentKernel]->kernelThreadSpaceParam.dependencyInfo.count; ++k )
{
if( (threadCoordinates.mask & CM_HINTS_LEASTBIT_MASK) == 0 )
{
CM_HAL_UNSETBIT(tmpThreadScoreboardMask, dependRemap[currentKernel][k]);
}
threadCoordinates.mask = threadCoordinates.mask >> 1;
}
scoreboardMask = tmpThreadScoreboardMask;
}
else
{
scoreboardMask = kernelScoreboardMask[currentKernel];
}
}
else
{
threadCoordinates.y = state->hintIndexes.kernelIndexes[currentKernel] / kernelParams[currentKernel]->kernelThreadSpaceParam.threadSpaceWidth;
scoreboardMask = kernelScoreboardMask[currentKernel];
}
adjustedYCoord = 0;
if( currentKernel > 0 )
{
// if not first kernel, and has dependency,
// and along scoreboard border top need to mask out dependencies with y < 0
if( kernelScoreboardMask[currentKernel] )
{
if( threadCoordinates.y == 0 )
{
for( k = 0; k < vfeDependencyInfo.count; ++k )
{
if( vfeDependencyInfo.deltaY[k] < 0 )
{
CM_HAL_UNSETBIT(scoreboardMask, k);
}
}
}
}
}
if( currentKernel < numKernels - 1 )
{
// if not last kernel, and has dependency,
// along scoreboard border bottom need to mask out dependencies with y > 0
if( kernelScoreboardMask[currentKernel] )
{
if( threadCoordinates.y == (kernelParams[currentKernel]->kernelThreadSpaceParam.threadSpaceHeight - 1))
{
for( k = 0; k < vfeDependencyInfo.count; ++k)
{
if( vfeDependencyInfo.deltaY[k] > 0 )
{
CM_HAL_UNSETBIT(scoreboardMask, k);
}
}
}
}
}
for( aIndex = 0; aIndex < kernelParams[currentKernel]->numArgs; aIndex++ )
{
argParams[currentKernel] = &kernelParams[currentKernel]->argParams[aIndex];
index = state->hintIndexes.kernelIndexes[currentKernel] * argParams[currentKernel]->perThread;
if( (kernelParams[currentKernel]->cmFlags & CM_KERNEL_FLAGS_CURBE) && !argParams[currentKernel]->perThread )
{
continue;
}
CM_ASSERT(argParams[currentKernel]->payloadOffset < kernelParams[currentKernel]->payloadSize);
switch(argParams[currentKernel]->kind)
{
case CM_ARGUMENT_GENERAL:
break;
case CM_ARGUMENT_SAMPLER:
CM_CHK_MOSSTATUS_GOTOFINISH(HalCm_SetupSamplerState(
state, kernelParams[currentKernel], argParams[currentKernel], &indexParams[currentKernel],
mediaIds[currentKernel], index, nullptr));
break;
case CM_ARGUMENT_SURFACEBUFFER:
CM_CHK_MOSSTATUS_GOTOFINISH(HalCm_SetupBufferSurfaceState(
state, argParams[currentKernel], &indexParams[currentKernel],
bindingTableEntries[currentKernel], -1, index, nullptr));
break;
case CM_ARGUMENT_SURFACE2D_UP:
CM_CHK_MOSSTATUS_GOTOFINISH(HalCm_Setup2DSurfaceUPState(
state, argParams[currentKernel], &indexParams[currentKernel],
bindingTableEntries[currentKernel], index, nullptr));
break;
case CM_ARGUMENT_SURFACE2DUP_SAMPLER:
CM_CHK_MOSSTATUS_GOTOFINISH(HalCm_Setup2DSurfaceUPSamplerState(
state, argParams[currentKernel], &indexParams[currentKernel],
bindingTableEntries[currentKernel], index, nullptr));
break;
case CM_ARGUMENT_SURFACE2D_SAMPLER:
CM_CHK_MOSSTATUS_GOTOFINISH(HalCm_Setup2DSurfaceSamplerState(
state, argParams[currentKernel], &indexParams[currentKernel],
bindingTableEntries[currentKernel], 0, nullptr));
break;
case CM_ARGUMENT_SURFACE2D:
CM_CHK_MOSSTATUS_GOTOFINISH(HalCm_Setup2DSurfaceState(
state, argParams[currentKernel], &indexParams[currentKernel],
bindingTableEntries[currentKernel], index, nullptr));
break;
case CM_ARGUMENT_SURFACE3D:
CM_CHK_MOSSTATUS_GOTOFINISH(HalCm_Setup3DSurfaceState(
state, argParams[currentKernel], &indexParams[currentKernel],
bindingTableEntries[currentKernel], index, nullptr));
break;
case CM_ARGUMENT_SURFACE_VME:
CM_CHK_MOSSTATUS_GOTOFINISH(HalCm_SetupVmeSurfaceState(
state, argParams[currentKernel], &indexParams[currentKernel],
bindingTableEntries[currentKernel], 0, nullptr));
break;
case CM_ARGUMENT_SURFACE_SAMPLER8X8_VA:
case CM_ARGUMENT_SURFACE_SAMPLER8X8_AVS:
CM_CHK_MOSSTATUS_GOTOFINISH(HalCm_SetupSampler8x8SurfaceState(
state, argParams[currentKernel], &indexParams[currentKernel],
bindingTableEntries[currentKernel], 0, nullptr));
break;
default:
eStatus = MOS_STATUS_INVALID_PARAMETER;
CM_ASSERTMESSAGE(
"Argument kind '%d' is not supported", argParams[currentKernel]->kind);
goto finish;
} // switch argKind
} // for numArgs
if( threadCoordinates.resetMask == CM_RESET_DEPENDENCY_MASK )
{
MOS_SecureMemcpy(bBuffer + (CM_SCOREBOARD_MASK_POS_IN_MEDIA_OBJECT_CMD*sizeof(uint32_t)),
sizeof(uint8_t), &scoreboardMask, sizeof(uint8_t));
}
batchBuffer->iCurrent += cmdSizes[currentKernel];
bBuffer += cmdSizes[currentKernel];
state->hintIndexes.kernelIndexes[currentKernel]++;
enableThreadSpace = false;
kernelFound = false;
updateCurrKernel = false;
numDispatched++;
} // for totalNumThreads
} // if uiRefCount > 1
else
{
uint8_t *bBuffer = batchBuffer->pData + batchBuffer->iCurrent;
updateCurrKernel = false;
for( i = 0; i < totalNumThreads; ++i)
{
if( !singleSubSlice )
{
if( (dispatchFreq[currentKernel][state->hintIndexes.dispatchIndexes[currentKernel]] == numDispatched) ||
(state->hintIndexes.kernelIndexes[currentKernel] >= kernelParams[currentKernel]->numThreads) )
{
numDispatched = 0;
numStepsDispatched++;
state->hintIndexes.dispatchIndexes[currentKernel]++;
if( state->hintIndexes.kernelIndexes[currentKernel] >= kernelParams[currentKernel]->numThreads )
{
updateCurrKernel = true;
groupInfo[remapKrnToGrp[currentKernel]].numKernelsFinished++;
if( groupInfo[remapKrnToGrp[currentKernel]].numKernelsFinished ==
groupInfo[remapKrnToGrp[currentKernel]].numKernelsInGroup )
{
groupInfo[remapKrnToGrp[currentKernel]].groupFinished = 1;
}
else
{
remapGrpToKrn[tmpIndex]++;
}
}
if( (groupInfo[remapKrnToGrp[currentKernel]].freqDispatch == numStepsDispatched) ||
updateCurrKernel )
{
numStepsDispatched = 0;
roundRobinCount++;
tmpIndex = roundRobinCount % numKernelGroups;
if( groupInfo[tmpIndex].groupFinished )
{
loopCount = 0;
while( (loopCount < numKernelGroups) && (!kernelFound) )
{
roundRobinCount++;
tmpIndex = roundRobinCount % numKernelGroups;
if( state->hintIndexes.kernelIndexes[remapGrpToKrn[tmpIndex]] < kernelParams[remapGrpToKrn[tmpIndex]]->numThreads )
{
kernelFound = true;
}
loopCount++;
}
if( !kernelFound )
{
// Error shouldn't be here
// if still in for loop totalNumThreads, needs to be a kernel with threads left
eStatus = MOS_STATUS_UNKNOWN;
CM_ASSERTMESSAGE("Couldn't find kernel with threads left for EnqueueWithHints");
goto finish;
}
}
currentKernel = remapGrpToKrn[tmpIndex];
}
}
}
else
{
if( state->hintIndexes.kernelIndexes[currentKernel] >= kernelParams[currentKernel]->numThreads )
{
currentKernel++;
}
}
if( kernelParams[currentKernel]->kernelThreadSpaceParam.threadCoordinates )
{
threadCoordinates.x = kernelParams[currentKernel]->kernelThreadSpaceParam.threadCoordinates[state->hintIndexes.kernelIndexes[currentKernel]].x;
threadCoordinates.y = kernelParams[currentKernel]->kernelThreadSpaceParam.threadCoordinates[state->hintIndexes.kernelIndexes[currentKernel]].y;
threadCoordinates.mask = kernelParams[currentKernel]->kernelThreadSpaceParam.threadCoordinates[state->hintIndexes.kernelIndexes[currentKernel]].mask;
enableThreadSpace = true;
}
mediaObjectParams[currentKernel].VfeScoreboard.ScoreboardEnable =
(kernelParams[currentKernel]->kernelThreadSpaceParam.dependencyInfo.count == 0) ? 0:1;
if( !singleSubSlice && systemInfo.isSliceInfoValid && sufficientSliceInfo )
{
sliceIndex = kernelsSliceInfo[remapKrnToGrp[currentKernel]].counter % kernelsSliceInfo[remapKrnToGrp[currentKernel]].numSubSlices;
mediaObjectParams[currentKernel].dwSliceDestinationSelect = kernelsSliceInfo[remapKrnToGrp[currentKernel]].destination[sliceIndex].slice;
mediaObjectParams[currentKernel].dwHalfSliceDestinationSelect = kernelsSliceInfo[remapKrnToGrp[currentKernel]].destination[sliceIndex].subSlice;
mediaObjectParams[currentKernel].bForceDestination = true;
kernelsSliceInfo[remapKrnToGrp[currentKernel]].counter++;
}
if( enableThreadSpace )
{
mediaObjectParams[currentKernel].VfeScoreboard.Value[0] = threadCoordinates.x;
mediaObjectParams[currentKernel].VfeScoreboard.Value[1] = threadCoordinates.y;
if( threadCoordinates.mask != CM_DEFAULT_THREAD_DEPENDENCY_MASK )
{
tmpThreadScoreboardMask = kernelScoreboardMask[currentKernel];
// do the remapping
for( k = 0; k < kernelParams[currentKernel]->kernelThreadSpaceParam.dependencyInfo.count; ++k )
{
if( (threadCoordinates.mask & CM_HINTS_LEASTBIT_MASK) == 0 )
{
CM_HAL_UNSETBIT(tmpThreadScoreboardMask, dependRemap[currentKernel][k]);
}
threadCoordinates.mask = threadCoordinates.mask >> 1;
}
mediaObjectParams[currentKernel].VfeScoreboard.ScoreboardMask = tmpThreadScoreboardMask;
}
else
{
mediaObjectParams[currentKernel].VfeScoreboard.ScoreboardMask = kernelScoreboardMask[currentKernel];
}
}
else
{
mediaObjectParams[currentKernel].VfeScoreboard.Value[0] = state->hintIndexes.kernelIndexes[currentKernel] %
kernelParams[currentKernel]->kernelThreadSpaceParam.threadSpaceWidth;
mediaObjectParams[currentKernel].VfeScoreboard.Value[1] = state->hintIndexes.kernelIndexes[currentKernel] /
kernelParams[currentKernel]->kernelThreadSpaceParam.threadSpaceWidth;
mediaObjectParams[currentKernel].VfeScoreboard.ScoreboardMask = kernelScoreboardMask[currentKernel];
}
adjustedYCoord = 0;
// adjust y coordinate for kernels after the first one
if( currentKernel > 0 )
{
// if not first kernel, and has dependency,
// and along scoreboard border need to mask out dependencies with y < 0
if( kernelScoreboardMask[currentKernel] )
{
if (mediaObjectParams[currentKernel].VfeScoreboard.Value[1] == 0)
{
for( k = 0; k < vfeDependencyInfo.count; ++k )
{
if( vfeDependencyInfo.deltaY[k] < 0 )
{
CM_HAL_UNSETBIT(mediaObjectParams[currentKernel].VfeScoreboard.ScoreboardMask, k);
}
}
}
}
for( j = currentKernel; j > 0; --j )
{
adjustedYCoord += kernelParams[j-1]->kernelThreadSpaceParam.threadSpaceHeight;
}
}
if( currentKernel < numKernels - 1 )
{
// if not last kernel, and has dependency,
// along scoreboard border bottom need to mask out dependencies with y > 0
if( kernelScoreboardMask[currentKernel] )
{
if (mediaObjectParams[currentKernel].VfeScoreboard.Value[1] ==
(kernelParams[currentKernel]->kernelThreadSpaceParam.threadSpaceHeight - 1))
{
for( k = 0; k < vfeDependencyInfo.count; ++k )
{
if( vfeDependencyInfo.deltaY[k] > 0 )
{
CM_HAL_UNSETBIT(mediaObjectParams[currentKernel].VfeScoreboard.ScoreboardMask, k);
}
}
}
}
}
mediaObjectParams[currentKernel].VfeScoreboard.Value[1] =
mediaObjectParams[currentKernel].VfeScoreboard.Value[1] + adjustedYCoord;
for( aIndex = 0; aIndex < kernelParams[currentKernel]->numArgs; aIndex++ )
{
argParams[currentKernel] = &kernelParams[currentKernel]->argParams[aIndex];
index = state->hintIndexes.kernelIndexes[currentKernel] * argParams[currentKernel]->perThread;
if( (kernelParams[currentKernel]->cmFlags & CM_KERNEL_FLAGS_CURBE) && !argParams[currentKernel]->perThread )
{
continue;
}
CM_ASSERT(argParams[currentKernel]->payloadOffset < kernelParams[currentKernel]->payloadSize);
switch(argParams[currentKernel]->kind)
{
case CM_ARGUMENT_GENERAL:
MOS_SecureMemcpy(
cmdInline[currentKernel] + argParams[currentKernel]->payloadOffset,
argParams[currentKernel]->unitSize,
argParams[currentKernel]->firstValue + index * argParams[currentKernel]->unitSize,
argParams[currentKernel]->unitSize);
break;
case CM_ARGUMENT_SAMPLER:
CM_CHK_MOSSTATUS_GOTOFINISH(HalCm_SetupSamplerState(
state, kernelParams[currentKernel], argParams[currentKernel], &indexParams[currentKernel],
mediaIds[currentKernel], index, cmdInline[currentKernel]));
break;
case CM_ARGUMENT_SURFACEBUFFER:
CM_CHK_MOSSTATUS_GOTOFINISH(HalCm_SetupBufferSurfaceState(
state, argParams[currentKernel], &indexParams[currentKernel],
bindingTableEntries[currentKernel], -1, index, cmdInline[currentKernel]));
break;
case CM_ARGUMENT_SURFACE2D_UP:
CM_CHK_MOSSTATUS_GOTOFINISH(HalCm_Setup2DSurfaceUPState(
state, argParams[currentKernel], &indexParams[currentKernel],
bindingTableEntries[currentKernel], index, cmdInline[currentKernel]));
break;
case CM_ARGUMENT_SURFACE2DUP_SAMPLER:
CM_CHK_MOSSTATUS_GOTOFINISH(HalCm_Setup2DSurfaceUPSamplerState(
state, argParams[currentKernel], &indexParams[currentKernel],
bindingTableEntries[currentKernel], index, cmdInline[currentKernel]));
break;
case CM_ARGUMENT_SURFACE2D_SAMPLER:
CM_CHK_MOSSTATUS_GOTOFINISH(HalCm_Setup2DSurfaceSamplerState(
state, argParams[currentKernel], &indexParams[currentKernel],
bindingTableEntries[currentKernel], index, cmdInline[currentKernel]));
break;
case CM_ARGUMENT_SURFACE2D:
CM_CHK_MOSSTATUS_GOTOFINISH(HalCm_Setup2DSurfaceState(
state, argParams[currentKernel], &indexParams[currentKernel],
bindingTableEntries[currentKernel], index, cmdInline[currentKernel]));
break;
case CM_ARGUMENT_SURFACE3D:
CM_CHK_MOSSTATUS_GOTOFINISH(HalCm_Setup3DSurfaceState(
state, argParams[currentKernel], &indexParams[currentKernel],
bindingTableEntries[currentKernel], index, cmdInline[currentKernel]));
break;
case CM_ARGUMENT_SURFACE_VME:
CM_CHK_MOSSTATUS_GOTOFINISH(HalCm_SetupVmeSurfaceState(
state, argParams[currentKernel], &indexParams[currentKernel],
bindingTableEntries[currentKernel], 0, cmdInline[currentKernel]));
break;
case CM_ARGUMENT_SURFACE_SAMPLER8X8_VA:
case CM_ARGUMENT_SURFACE_SAMPLER8X8_AVS:
CM_CHK_MOSSTATUS_GOTOFINISH(HalCm_SetupSampler8x8SurfaceState(
state, argParams[currentKernel], &indexParams[currentKernel],
bindingTableEntries[currentKernel], 0, cmdInline[currentKernel]));
break;
default:
eStatus = MOS_STATUS_INVALID_PARAMETER;
CM_ASSERTMESSAGE(
"Argument kind '%d' is not supported", argParams[currentKernel]->kind);
goto finish;
}
}
mediaObjectParams[currentKernel].pInlineData = cmdInline[currentKernel];
state->renderHal->pMhwRenderInterface->AddMediaObject(nullptr, batchBuffer, &mediaObjectParams[currentKernel]);
state->hintIndexes.kernelIndexes[currentKernel]++;
enableThreadSpace = false;
kernelFound = false;
updateCurrKernel = false;
numDispatched++;
} // for totalNumThreads
} // else refCount <= 1
// setup global surfaces
for( j = 0; j < numKernels; ++j )
{
for( i = 0; i < CM_MAX_GLOBAL_SURFACE_NUMBER; ++i )
{
if(( kernelParams[j]->globalSurface[i] & CM_SURFACE_MASK) != CM_NULL_SURFACE)
{
CM_HAL_KERNEL_ARG_PARAM tmpArgParam;
argParam = &tmpArgParam;
tmpArgParam.kind = CM_ARGUMENT_SURFACEBUFFER;
tmpArgParam.payloadOffset = 0;
tmpArgParam.unitCount = 1;
tmpArgParam.unitSize = sizeof(uint32_t);
tmpArgParam.perThread = false;
tmpArgParam.firstValue = (uint8_t*)&kernelParams[j]->globalSurface[i];
CM_CHK_MOSSTATUS_GOTOFINISH(HalCm_SetupBufferSurfaceState(
state, argParam, &indexParams[j], bindingTableEntries[j],
(int16_t)i, 0, nullptr));
}
}
// set number of samplers
krnAllocations[j]->Params.Sampler_Count = indexParams[j].samplerIndexCount;
}
// check to make sure we did all threads for all kernels
if (numTasks <= 1 || lastTask )
{
for( i = 0; i < numKernels; ++i )
{
if( state->hintIndexes.kernelIndexes[i] < kernelParams[i]->numThreads )
{
eStatus = MOS_STATUS_INVALID_PARAMETER;
CM_ASSERTMESSAGE("Not all threads for all kernels were put into batch buffer");
goto finish;
}
}
}
if ( lastTask )
{
MOS_ZeroMemory(&state->hintIndexes.kernelIndexes, sizeof(uint32_t) * CM_MAX_TASKS_EU_SATURATION);
MOS_ZeroMemory(&state->hintIndexes.dispatchIndexes, sizeof(uint32_t) * CM_MAX_TASKS_EU_SATURATION);
}
finish:
// free memory
if( mediaObjectParams ) MOS_FreeMemory(mediaObjectParams);
if( kernelParams ) MOS_FreeMemory(kernelParams);
if( argParams ) MOS_FreeMemory(argParams);
if( cmdSizes ) MOS_FreeMemory(cmdSizes);
if( remapKrnToGrp ) MOS_FreeMemory(remapKrnToGrp);
if( remapGrpToKrn ) MOS_FreeMemory(remapGrpToKrn);
if( kernelScoreboardMask ) MOS_FreeMemory(kernelScoreboardMask);
if( parallelGraphInfo ) MOS_FreeMemory(parallelGraphInfo);
if( numKernelsPerGrp ) MOS_FreeMemory(numKernelsPerGrp);
if( groupInfo ) MOS_FreeMemory(groupInfo);
if( cmdInline )
{
for( i = 0; i < numKernels; ++i )
{
if( cmdInline[i] )
MOS_FreeMemory(cmdInline[i]);
}
MOS_FreeMemory(cmdInline);
}
if( kernelsSliceInfo )
{
for( i = 0; i < numKernelGroups; ++i )
{
if( kernelsSliceInfo[i].destination )
MOS_FreeMemory(kernelsSliceInfo[i].destination);
}
MOS_FreeMemory(kernelsSliceInfo);
}
if( dependRemap )
{
for( i = 0; i < numKernels; ++i )
{
if( dependRemap[i] )
MOS_FreeMemory(dependRemap[i]);
}
MOS_FreeMemory(dependRemap);
}
if( dispatchFreq )
{
for( i = 0; i < numKernels; ++i )
{
if( dispatchFreq[i] )
MOS_FreeMemory(dispatchFreq[i]);
}
MOS_FreeMemory(dispatchFreq);
}
return eStatus;
}
uint32_t HalCm_ThreadsNumberPerGroup_MW(PCM_HAL_WALKER_PARAMS walkerParams)
{
int localInnerCount = 0, localMidCount = 0, localOuterCount = 0, globalInnerCount = 0, globalOuterCount = 0;
int localInnerCountMax = 0, localMidCountMax = 0, localOuterCountMax = 0, globalInnerCountMax = 0;
int midX = 0, midY = 0, midStep = 0;
int outerX = 0, outerY = 0;
int localInnerX = 0, localInnerY = 0;
int blockSizeX = 0, blockSizeY = 0;
//int x, y;
int localLoopExecCount = walkerParams->localLoopExecCount;
int globalLoopExecCount = walkerParams->globalLoopExecCount;
int globalresX = walkerParams->globalResolution.x, globalresY = walkerParams->globalResolution.y;
int globalOuterX = walkerParams->globalStart.x, globalOuterY = walkerParams->globalStart.y;
int globalOuterStepX = walkerParams->globalOutlerLoopStride.x, globalOuterStepY = walkerParams->globalOutlerLoopStride.y;
int globalInnerStepX = walkerParams->globalInnerLoopUnit.x, globalInnerStepY = walkerParams->globalInnerLoopUnit.y;
int middleStepX = walkerParams->midLoopUnitX, middleStepY = walkerParams->midLoopUnitY, extraSteps = walkerParams->middleLoopExtraSteps;
int localblockresX = walkerParams->blockResolution.x, localblockresY = walkerParams->blockResolution.y;
int localStartX = walkerParams->localStart.x, localStartY = walkerParams->localStart.y;
int localOuterStepX = walkerParams->localOutLoopStride.x, localOuterStepY = walkerParams->localOutLoopStride.y;
int localInnerStepX = walkerParams->localInnerLoopUnit.x, localInnerStepY = walkerParams->localInnerLoopUnit.y;
uint32_t threadsNumberPergroup = 0;
//do global_outer_looper initialization
while (((globalOuterX >= globalresX) && (globalInnerStepX < 0)) ||
((globalOuterX + localblockresX) < 0) && (globalInnerStepX > 0) ||
((globalOuterY >= globalresY) && (globalInnerStepY < 0)) ||
((globalOuterX + localblockresY) < 0) && (globalInnerStepY > 0))
{
globalOuterX += globalInnerStepX;
globalOuterY += globalInnerStepY;
}
//global_ouer_loop_in_bounds()
while ((globalOuterX < globalresX) &&
(globalOuterY < globalresY) &&
(globalOuterX + localblockresX > 0) &&
(globalOuterY + localblockresY > 0) &&
(globalOuterCount <= globalLoopExecCount))
{
int globalInnerX = globalOuterX;
int globalInnerY = globalOuterY;
if (globalInnerCountMax < globalInnerCount)
{
globalInnerCountMax = globalInnerCount;
}
globalInnerCount = 0;
//global_inner_loop_in_bounds()
while ((globalInnerX < globalresX) &&
(globalInnerY < globalresY) &&
(globalInnerX + localblockresX > 0) &&
(globalInnerY + localblockresY > 0))
{
int globalInnerXCopy = globalInnerX;
int globalInnerYCopy = globalInnerY;
if (globalInnerX < 0)
globalInnerXCopy = 0;
if (globalInnerY < 0)
globalInnerYCopy = 0;
if (globalInnerX < 0)
blockSizeX = localblockresX + globalInnerX;
else if ((globalresX - globalInnerX) < localblockresX)
blockSizeX = globalresX - globalInnerX;
else
blockSizeX = localblockresX;
if (globalInnerY < 0)
blockSizeY = localblockresY + globalInnerY;
else if ((globalresY - globalInnerY) < localblockresY)
blockSizeY = globalresY - globalInnerY;
else
blockSizeY = localblockresY;
outerX = localStartX;
outerY = localStartY;
if (localOuterCountMax < localOuterCount)
{
localOuterCountMax = localOuterCount;
}
localOuterCount = 0;
while ((outerX >= blockSizeX && localInnerStepX < 0) ||
(outerX < 0 && localInnerStepX > 0) ||
(outerY >= blockSizeY && localInnerStepY < 0) ||
(outerY < 0 && localInnerStepY > 0))
{
outerX += localInnerStepX;
outerY += localInnerStepY;
}
//local_outer_loop_in_bounds()
while ((outerX < blockSizeX) &&
(outerY < blockSizeY) &&
(outerX >= 0) &&
(outerY >= 0) &&
(localOuterCount <= localLoopExecCount))
{
midX = outerX;
midY = outerY;
midStep = 0;
if (localMidCountMax < localMidCount)
{
localMidCountMax = localMidCount;
}
localMidCount = 0;
//local_middle_steps_remaining()
while ((midStep <= extraSteps) &&
(midX < blockSizeX) &&
(midY < blockSizeY) &&
(midX >= 0) &&
(midY >= 0))
{
localInnerX = midX;
localInnerY = midY;
if (localInnerCountMax < localInnerCount)
{
localInnerCountMax = localInnerCount;
}
localInnerCount = 0;
//local_inner_loop_shrinking()
while ((localInnerX < blockSizeX) &&
(localInnerY < blockSizeY) &&
(localInnerX >= 0) &&
(localInnerY >= 0))
{
//x = localInnerX + globalInnerXCopy;
//y = localInnerY + globalInnerYCopy;
localInnerCount ++;
localInnerX += localInnerStepX;
localInnerY += localInnerStepY;
}
localMidCount++;
midStep++;
midX += middleStepX;
midY += middleStepY;
}
localOuterCount += 1;
outerX += localOuterStepX;
outerY += localOuterStepY;
while ((outerX >= blockSizeX && localInnerStepX < 0) ||
(outerX <0 && localInnerStepX > 0) ||
(outerY >= blockSizeY && localInnerStepY < 0) ||
(outerY <0 && localInnerStepY > 0))
{
outerX += localInnerStepX;
outerY += localInnerStepY;
}
}
globalInnerCount++;
globalInnerX += globalInnerStepX;
globalInnerY += globalInnerStepY;
}
globalOuterCount += 1;
globalOuterX += globalOuterStepX;
globalOuterY += globalOuterStepY;
while (((globalOuterX >= globalresX) && (globalInnerStepX < 0)) ||
((globalOuterX + localblockresX) < 0) && (globalInnerStepX > 0) ||
((globalOuterY >= globalresY) && (globalInnerStepY < 0)) ||
((globalOuterX + localblockresY) < 0) && (globalInnerStepY > 0))
{
globalOuterX += globalInnerStepX;
globalOuterY += globalInnerStepY;
}
}
switch (walkerParams->groupIdLoopSelect)
{
case CM_MW_GROUP_COLORLOOP:
threadsNumberPergroup = walkerParams->colorCountMinusOne + 1;
break;
case CM_MW_GROUP_INNERLOCAL:
threadsNumberPergroup = localInnerCount * (walkerParams->colorCountMinusOne + 1);
break;
case CM_MW_GROUP_MIDLOCAL:
threadsNumberPergroup = localMidCount * localInnerCount * (walkerParams->colorCountMinusOne + 1);
break;
case CM_MW_GROUP_OUTERLOCAL:
threadsNumberPergroup = localOuterCount * localMidCount * localInnerCount * (walkerParams->colorCountMinusOne + 1);
break;
case CM_MW_GROUP_INNERGLOBAL:
threadsNumberPergroup = globalInnerCount * localOuterCount * localMidCount * localInnerCount * (walkerParams->colorCountMinusOne + 1);
break;
default:
threadsNumberPergroup = globalOuterCount * globalInnerCount * localOuterCount * localMidCount * localInnerCount * (walkerParams->colorCountMinusOne + 1);
break;
}
return threadsNumberPergroup;
}
MOS_STATUS HalCm_SetupMediaWalkerParams(
PCM_HAL_STATE state,
PCM_HAL_KERNEL_PARAM kernelParam)
{
MOS_STATUS eStatus = MOS_STATUS_SUCCESS;
PCM_HAL_TASK_PARAM taskParam = state->taskParam;
PCM_HAL_WALKER_PARAMS walkerParams = &kernelParam->walkerParams;
//Using global walker enable flag
walkerParams->cmWalkerEnable = state->walkerParams.CmWalkerEnable;
if (walkerParams->cmWalkerEnable)
{
// MEDIA_WALKER
CM_HAL_KERNEL_THREADSPACE_PARAM kernelThreadSpace;
if (kernelParam->kernelThreadSpaceParam.threadSpaceWidth)
{
kernelThreadSpace.threadSpaceWidth = kernelParam->kernelThreadSpaceParam.threadSpaceWidth;
kernelThreadSpace.threadSpaceHeight = kernelParam->kernelThreadSpaceParam.threadSpaceHeight;
kernelThreadSpace.patternType = kernelParam->kernelThreadSpaceParam.patternType;
kernelThreadSpace.walkingPattern = kernelParam->kernelThreadSpaceParam.walkingPattern;
kernelThreadSpace.groupSelect = kernelParam->kernelThreadSpaceParam.groupSelect;
kernelThreadSpace.colorCountMinusOne = kernelParam->kernelThreadSpaceParam.colorCountMinusOne;
}
else
{
kernelThreadSpace.threadSpaceWidth = (uint16_t)taskParam->threadSpaceWidth;
kernelThreadSpace.threadSpaceHeight = (uint16_t)taskParam->threadSpaceHeight;
kernelThreadSpace.patternType = taskParam->dependencyPattern;
kernelThreadSpace.walkingPattern = taskParam->walkingPattern;
kernelThreadSpace.groupSelect = taskParam->mediaWalkerGroupSelect;
kernelThreadSpace.colorCountMinusOne = taskParam->colorCountMinusOne;
}
// check for valid thread space width and height here since different from media object
if (kernelThreadSpace.threadSpaceWidth > state->cmHalInterface->GetMediaWalkerMaxThreadWidth())
{
CM_ASSERTMESSAGE("Error: Exceeds the maximum thread space width.");
eStatus = MOS_STATUS_INVALID_PARAMETER;
goto finish;
}
if (kernelThreadSpace.threadSpaceHeight > state->cmHalInterface->GetMediaWalkerMaxThreadHeight())
{
CM_ASSERTMESSAGE("Error: Exceeds the maximum thread space height.");
eStatus = MOS_STATUS_INVALID_PARAMETER;
goto finish;
}
//walkerParams->InterfaceDescriptorOffset = mediaID;// mediaObjectParam.dwInterfaceDescriptorOffset;
walkerParams->inlineDataLength = MOS_ALIGN_CEIL(kernelParam->indirectDataParam.indirectDataSize, 4);
walkerParams->inlineData = kernelParam->indirectDataParam.indirectData;
walkerParams->colorCountMinusOne = kernelThreadSpace.colorCountMinusOne;// taskParam->ColorCountMinusOne;
walkerParams->groupIdLoopSelect = (uint32_t)kernelThreadSpace.groupSelect;
CM_WALKING_PATTERN walkPattern = kernelThreadSpace.walkingPattern;
switch (kernelThreadSpace.patternType)
{
case CM_NONE_DEPENDENCY:
break;
case CM_HORIZONTAL_WAVE:
walkPattern = CM_WALK_HORIZONTAL;
break;
case CM_VERTICAL_WAVE:
walkPattern = CM_WALK_VERTICAL;
break;
case CM_WAVEFRONT:
walkPattern = CM_WALK_WAVEFRONT;
break;
case CM_WAVEFRONT26:
walkPattern = CM_WALK_WAVEFRONT26;
break;
case CM_WAVEFRONT26X:
if (kernelThreadSpace.threadSpaceWidth > 1)
{
walkPattern = CM_WALK_WAVEFRONT26X;
}
else
{
walkPattern = CM_WALK_DEFAULT;
}
break;
case CM_WAVEFRONT26ZIG:
if (kernelThreadSpace.threadSpaceWidth > 2)
{
walkPattern = CM_WALK_WAVEFRONT26ZIG;
}
else
{
walkPattern = CM_WALK_DEFAULT;
}
break;
default:
CM_ASSERTMESSAGE("Error: Invalid walking pattern.");
walkPattern = CM_WALK_DEFAULT;
break;
}
if (taskParam->walkingParamsValid)
{
CM_CHK_MOSSTATUS_GOTOFINISH(state->cmHalInterface->SetMediaWalkerParams
(taskParam->walkingParams, walkerParams));
if (walkPattern == CM_WALK_HORIZONTAL || walkPattern == CM_WALK_DEFAULT)
{
walkerParams->localEnd.x = walkerParams->blockResolution.x - 1;
}
else if (walkPattern == CM_WALK_VERTICAL)
{
walkerParams->localEnd.y = walkerParams->blockResolution.y - 1;
}
}
else if (kernelParam->kernelThreadSpaceParam.walkingParamsValid)
{
CM_CHK_MOSSTATUS_GOTOFINISH(state->cmHalInterface->SetMediaWalkerParams(
kernelParam->kernelThreadSpaceParam.walkingParams, walkerParams));
if (walkPattern == CM_WALK_HORIZONTAL || walkPattern == CM_WALK_DEFAULT)
{
walkerParams->localEnd.x = walkerParams->blockResolution.x - 1;
}
else if (walkPattern == CM_WALK_VERTICAL)
{
walkerParams->localEnd.y = walkerParams->blockResolution.y - 1;
}
}
else
{
//Local loop parameters
walkerParams->blockResolution.x = kernelThreadSpace.threadSpaceWidth;
walkerParams->blockResolution.y = kernelThreadSpace.threadSpaceHeight;
walkerParams->localStart.x = 0;
walkerParams->localStart.y = 0;
walkerParams->localEnd.x = 0;
walkerParams->localEnd.y = 0;
walkerParams->globalLoopExecCount = 1;
walkerParams->midLoopUnitX = 0;
walkerParams->midLoopUnitY = 0;
walkerParams->middleLoopExtraSteps = 0;
// account for odd Height/Width for 26x and 26Zig
uint16_t adjHeight = ((kernelThreadSpace.threadSpaceHeight + 1) >> 1) << 1;
uint16_t adjWidth = ((kernelThreadSpace.threadSpaceWidth + 1) >> 1) << 1;
uint32_t maxThreadWidth = state->cmHalInterface->GetMediaWalkerMaxThreadWidth();
switch (walkPattern)
{
case CM_WALK_DEFAULT:
case CM_WALK_HORIZONTAL:
if (kernelThreadSpace.threadSpaceWidth == kernelParam->numThreads &&
kernelThreadSpace.threadSpaceHeight == 1)
{
walkerParams->blockResolution.x = MOS_MIN(kernelParam->numThreads, maxThreadWidth);
walkerParams->blockResolution.y = 1 + kernelParam->numThreads / maxThreadWidth;
}
walkerParams->localLoopExecCount = walkerParams->blockResolution.y - 1;
walkerParams->localOutLoopStride.x = 0;
walkerParams->localOutLoopStride.y = 1;
walkerParams->localInnerLoopUnit.x = 1;
walkerParams->localInnerLoopUnit.y = 0;
walkerParams->localEnd.x = walkerParams->blockResolution.x - 1;
break;
case CM_WALK_WAVEFRONT:
walkerParams->localLoopExecCount = kernelThreadSpace.threadSpaceWidth + (kernelThreadSpace.threadSpaceHeight - 1) * 1 - 1;
walkerParams->localOutLoopStride.x = 1;
walkerParams->localOutLoopStride.y = 0;
walkerParams->localInnerLoopUnit.x = 0xFFFF; // -1 in uint32_t:16
walkerParams->localInnerLoopUnit.y = 1;
break;
case CM_WALK_WAVEFRONT26:
walkerParams->localLoopExecCount = kernelThreadSpace.threadSpaceWidth + (kernelThreadSpace.threadSpaceHeight - 1) * 2 - 1;
walkerParams->localOutLoopStride.x = 1;
walkerParams->localOutLoopStride.y = 0;
walkerParams->localInnerLoopUnit.x = 0xFFFE; // -2 in uint32_t:16
walkerParams->localInnerLoopUnit.y = 1;
break;
case CM_WALK_WAVEFRONT26X:
case CM_WALK_WAVEFRONT26XALT:
walkerParams->localLoopExecCount = 0x7ff;
walkerParams->globalLoopExecCount = 0;
walkerParams->localOutLoopStride.x = 1;
walkerParams->localOutLoopStride.y = 0;
walkerParams->localInnerLoopUnit.x = 0xFFFE; // -2 in uint32_t:16
walkerParams->localInnerLoopUnit.y = 2;
walkerParams->middleLoopExtraSteps = 1;
walkerParams->midLoopUnitX = 0;
walkerParams->midLoopUnitY = 1;
break;
case CM_WALK_WAVEFRONT26ZIG:
walkerParams->localLoopExecCount = 1;
walkerParams->globalLoopExecCount = (adjHeight / 2 - 1) * 2 + (adjWidth / 2) - 1;
walkerParams->localOutLoopStride.x = 0;
walkerParams->localOutLoopStride.y = 1;
walkerParams->localInnerLoopUnit.x = 1;
walkerParams->localInnerLoopUnit.y = 0;
walkerParams->blockResolution.x = 2;
walkerParams->blockResolution.y = 2;
walkerParams->localEnd.x = walkerParams->blockResolution.x - 1;
break;
case CM_WALK_VERTICAL:
walkerParams->localLoopExecCount = walkerParams->blockResolution.x - 1;
walkerParams->localOutLoopStride.x = 1;
walkerParams->localOutLoopStride.y = 0;
walkerParams->localInnerLoopUnit.x = 0;
walkerParams->localInnerLoopUnit.y = 1;
walkerParams->localEnd.y = walkerParams->blockResolution.y - 1;
break;
case CM_WALK_WAVEFRONT45D:
walkerParams->localLoopExecCount = 0x7ff;
walkerParams->globalLoopExecCount = 0x7ff;
walkerParams->localStart.x = kernelThreadSpace.threadSpaceWidth;
walkerParams->localOutLoopStride.x = 1;
walkerParams->localOutLoopStride.y = 0;
walkerParams->localInnerLoopUnit.x = 0xFFFF; // -1 in uint32_t:16
walkerParams->localInnerLoopUnit.y = 1;
break;
case CM_WALK_WAVEFRONT45XD_2:
walkerParams->localLoopExecCount = 0x7ff;
walkerParams->globalLoopExecCount = 0x7ff;
// Local
walkerParams->localStart.x = kernelThreadSpace.threadSpaceWidth;
walkerParams->localOutLoopStride.x = 1;
walkerParams->localOutLoopStride.y = 0;
walkerParams->localInnerLoopUnit.x = 0xFFFF; // -1 in uint32_t:16
walkerParams->localInnerLoopUnit.y = 2;
// Mid
walkerParams->middleLoopExtraSteps = 1;
walkerParams->midLoopUnitX = 0;
walkerParams->midLoopUnitY = 1;
break;
case CM_WALK_WAVEFRONT26D:
walkerParams->localLoopExecCount = 0x7ff;
walkerParams->globalLoopExecCount = 0x7ff;
walkerParams->localStart.x = kernelThreadSpace.threadSpaceWidth;
walkerParams->localOutLoopStride.x = 1;
walkerParams->localOutLoopStride.y = 0;
walkerParams->localInnerLoopUnit.x = 0xFFFE; // -2 in uint32_t:16
walkerParams->localInnerLoopUnit.y = 1;
break;
case CM_WALK_WAVEFRONT26XD:
walkerParams->localLoopExecCount = 0x7ff;
walkerParams->globalLoopExecCount = 0x7ff;
// Local
walkerParams->localStart.x = kernelThreadSpace.threadSpaceWidth;
walkerParams->localOutLoopStride.x = 1;
walkerParams->localOutLoopStride.y = 0;
walkerParams->localInnerLoopUnit.x = 0xFFFE; // -2 in uint32_t:16
walkerParams->localInnerLoopUnit.y = 2;
// Mid
walkerParams->middleLoopExtraSteps = 1;
walkerParams->midLoopUnitX = 0;
walkerParams->midLoopUnitY = 1;
break;
default:
walkerParams->localLoopExecCount = MOS_MIN(kernelParam->numThreads, 0x3FF);
walkerParams->localOutLoopStride.x = 0;
walkerParams->localOutLoopStride.y = 1;
walkerParams->localInnerLoopUnit.x = 1;
walkerParams->localInnerLoopUnit.y = 0;
break;
}
//Global loop parameters: execution count, resolution and strides
//Since no global loop, global resolution equals block resolution.
walkerParams->globalStart.x = 0;
walkerParams->globalStart.y = 0;
walkerParams->globalOutlerLoopStride.y = 0;
if (walkPattern == CM_WALK_WAVEFRONT26ZIG)
{
walkerParams->globalResolution.x = kernelThreadSpace.threadSpaceWidth;
walkerParams->globalResolution.y = kernelThreadSpace.threadSpaceHeight;
walkerParams->globalOutlerLoopStride.x = 2;
walkerParams->globalInnerLoopUnit.x = 0xFFFC;
walkerParams->globalInnerLoopUnit.y = 2;
}
else
{
walkerParams->globalResolution.x = walkerParams->blockResolution.x;
walkerParams->globalResolution.y = walkerParams->blockResolution.y;
walkerParams->globalOutlerLoopStride.x = walkerParams->globalResolution.x;
walkerParams->globalInnerLoopUnit.x = 0;
walkerParams->globalInnerLoopUnit.y = walkerParams->globalResolution.y;
}
}
//Need calculate number threads per group for media walker, the minimum value is 1
if (kernelThreadSpace.groupSelect > CM_MW_GROUP_NONE)
{
kernelParam->numberThreadsInGroup = HalCm_ThreadsNumberPerGroup_MW(walkerParams);
}
else
{
kernelParam->numberThreadsInGroup = 1;
}
}
finish:
return eStatus;
}
MOS_STATUS HalCm_AcquireSamplerStatistics(PCM_HAL_STATE state)
{
MOS_STATUS eStatus = MOS_STATUS_SUCCESS;
uint32_t i = 0;
unsigned int maxBTIindex[MAX_ELEMENT_TYPE_COUNT] = {0}; //tempoary variable, it will hold the max BTI index in each element type
/* enumerate through the samplerTable for the one in use, then count and analyze */
for (i = 0; i < state->cmDeviceParam.maxSamplerTableSize; i++) { //state->CmDeviceParam.iMaxSamplerTableSize;
if (state->samplerTable[i].bInUse) {
uint32_t samplerIndex = state->samplerIndexTable[i];
if (samplerIndex != CM_INVALID_INDEX) {
MHW_SAMPLER_ELEMENT_TYPE elementType = state->samplerTable[i].ElementType;
maxBTIindex[elementType] = (maxBTIindex[elementType] > samplerIndex) ? maxBTIindex[elementType] : samplerIndex;
}
else
state->samplerStatistics.samplerCount[state->samplerTable[i].ElementType]++;
}
}
int tempbase=0;
state->samplerStatistics.samplerIndexBase[MHW_Sampler2Elements]
= (state->samplerStatistics.samplerCount[MHW_Sampler2Elements]) ? 0 : -1;
tempbase
= state->samplerStatistics.samplerIndexBase[MHW_Sampler2Elements];
state->samplerStatistics.samplerIndexBase[MHW_Sampler4Elements]
= (state->samplerStatistics.samplerCount[MHW_Sampler4Elements]) ?
((tempbase == -1) ? 0 : INDEX_ALIGN(state->samplerStatistics.samplerCount[MHW_Sampler2Elements], 2, 4))
: tempbase;
tempbase
= state->samplerStatistics.samplerIndexBase[MHW_Sampler4Elements];
state->samplerStatistics.samplerIndexBase[MHW_Sampler8Elements]
= (state->samplerStatistics.samplerCount[MHW_Sampler8Elements]) ?
((tempbase == -1) ? 0 : INDEX_ALIGN(state->samplerStatistics.samplerCount[MHW_Sampler4Elements], 4, 8))
: tempbase;
tempbase
= state->samplerStatistics.samplerIndexBase[MHW_Sampler8Elements];
state->samplerStatistics.samplerIndexBase[MHW_Sampler64Elements]
= (state->samplerStatistics.samplerCount[MHW_Sampler64Elements]) ?
((tempbase == -1) ? 0 : INDEX_ALIGN(state->samplerStatistics.samplerCount[MHW_Sampler8Elements], 8, 64))
: tempbase;
tempbase
= state->samplerStatistics.samplerIndexBase[MHW_Sampler64Elements];
state->samplerStatistics.samplerIndexBase[MHW_Sampler128Elements]
= (state->samplerStatistics.samplerCount[MHW_Sampler128Elements]) ?
((tempbase == -1) ? 0 : INDEX_ALIGN(state->samplerStatistics.samplerCount[MHW_Sampler64Elements], 64, 128))
: tempbase;
/* There are Sampler BTI, next step needs to consider it during calculate the base */
for (int k = MHW_Sampler2Elements; k < MHW_Sampler128Elements; k++) {
if (state->samplerStatistics.samplerIndexBase[k + 1] < maxBTIindex[k])
state->samplerStatistics.samplerIndexBase[k + 1] = maxBTIindex[k];
}
return eStatus;
}
//*-----------------------------------------------------------------------------
//| Purpose: Initial setup of HW states for the kernel
//| Returns: Result of the operation
//*-----------------------------------------------------------------------------
MOS_STATUS HalCm_SetupStatesForKernelInitial(
PCM_HAL_STATE state,
PRENDERHAL_MEDIA_STATE mediaState,
PMHW_BATCH_BUFFER batchBuffer,
int32_t taskId,
PCM_HAL_KERNEL_PARAM kernelParam,
PCM_HAL_INDEX_PARAM indexParam,
uint32_t kernelCurbeOffset,
int32_t& bindingTable,
int32_t& mediaID,
PRENDERHAL_KRN_ALLOCATION &krnAllocation)
{
MOS_STATUS eStatus = MOS_STATUS_SUCCESS;
PRENDERHAL_INTERFACE renderHal = state->renderHal;
PRENDERHAL_STATE_HEAP stateHeap = renderHal->pStateHeap;
PCM_INDIRECT_SURFACE_INFO indirectSurfaceInfo = kernelParam->indirectDataParam.surfaceInfo;
PCM_GPGPU_WALKER_PARAMS perKernelGpGpuWalkerParames = &kernelParam->gpgpuWalkerParams;
UNUSED(batchBuffer);
UNUSED(taskId);
MHW_MEDIA_OBJECT_PARAMS mediaObjectParam;
PCM_HAL_KERNEL_ARG_PARAM argParam;
uint32_t hdrSize;
uint32_t index;
uint32_t value;
uint32_t btIndex;
uint32_t surfIndex;
uint32_t aIndex;
uint32_t idZ;
uint32_t idY;
uint32_t idX;
uint32_t localIdIndex;
CM_SURFACE_BTI_INFO surfBTIInfo;
bool vmeUsed = false;
CM_PLATFORM_INFO platformInfo;
localIdIndex = kernelParam->localIdIndex;
state->cmHalInterface->GetHwSurfaceBTIInfo(&surfBTIInfo);
HalCm_PreSetBindingIndex(indexParam, CM_NULL_SURFACE_BINDING_INDEX, CM_NULL_SURFACE_BINDING_INDEX);
HalCm_PreSetBindingIndex(indexParam, surfBTIInfo.reservedSurfaceStart,
surfBTIInfo.reservedSurfaceStart + CM_MAX_GLOBAL_SURFACE_NUMBER - 1);
if (kernelParam->indirectDataParam.surfaceCount)
{
for (index = 0; index < kernelParam->indirectDataParam.surfaceCount; index++)
{
value = (indirectSurfaceInfo + index)->bindingTableIndex;
HalCm_PreSetBindingIndex(indexParam, value, value);
}
}
// Get the binding table for this kernel
CM_CHK_MOSSTATUS_GOTOFINISH(renderHal->pfnAssignBindingTable(renderHal, &bindingTable));
if (state->dshEnabled)
{
// Kernels are already pre-loaded in GSH
// krnAllocation is the head of a linked list
if (!krnAllocation)
{
CM_ASSERTMESSAGE("Error: Invalid kernel allocation.");
goto finish;
}
}
else
{
// Load the Kernel to GSH
CM_CHK_MOSSTATUS_GOTOFINISH(HalCm_LoadKernel(
state,
kernelParam,
0,
krnAllocation));
}
// initialize curbe buffer
if (kernelParam->totalCurbeSize > 0)
{
// Update Curbe offset after curbe load command
if (state->dshEnabled)
{
mediaState->pDynamicState->Curbe.iCurrent += MOS_ALIGN_CEIL(kernelParam->totalCurbeSize, state->renderHal->dwCurbeBlockAlign);
}
else
{
mediaState->iCurbeOffset += MOS_ALIGN_CEIL(kernelParam->totalCurbeSize, state->renderHal->dwCurbeBlockAlign);
}
}
//Setup media walker parameters if it is
CM_CHK_MOSSTATUS_GOTOFINISH(HalCm_SetupMediaWalkerParams(state, kernelParam));
// Allocate Interface Descriptor
mediaID = HalCm_AllocateMediaID(
state,
kernelParam,
krnAllocation,
bindingTable,
kernelCurbeOffset);
if (mediaID < 0)
{
eStatus = MOS_STATUS_INVALID_PARAMETER;
CM_ASSERTMESSAGE("Unable to get Media ID");
goto finish;
}
// Setup the Media object
hdrSize = renderHal->pHwSizes->dwSizeMediaObjectHeaderCmd;
mediaObjectParam.dwInterfaceDescriptorOffset = mediaID;
if (kernelParam->indirectDataParam.indirectDataSize)
{
mediaObjectParam.dwInlineDataSize = 0;
}
else
{
mediaObjectParam.dwInlineDataSize = MOS_MAX(kernelParam->payloadSize, 4);
}
// set surface state and binding table
if (kernelParam->indirectDataParam.surfaceCount)
{
for (index = 0; index < kernelParam->indirectDataParam.surfaceCount; index++)
{
btIndex = (indirectSurfaceInfo + index)->bindingTableIndex;
surfIndex = (indirectSurfaceInfo + index)->surfaceIndex;
switch ((indirectSurfaceInfo + index)->kind)
{
case CM_ARGUMENT_SURFACEBUFFER:
CM_CHK_MOSSTATUS_GOTOFINISH(HalCm_SetupBufferSurfaceStateWithBTIndex(
state, bindingTable, surfIndex, btIndex, 0));
break;
case CM_ARGUMENT_SURFACE2D:
CM_CHK_MOSSTATUS_GOTOFINISH(HalCm_Setup2DSurfaceStateWithBTIndex(
state, bindingTable, surfIndex, btIndex, 0));
break;
case CM_ARGUMENT_SURFACE2D_UP:
CM_CHK_MOSSTATUS_GOTOFINISH(HalCm_Setup2DSurfaceUPStateWithBTIndex(
state, bindingTable, surfIndex, btIndex, 0));
break;
case CM_ARGUMENT_SURFACE2D_SAMPLER:
CM_CHK_MOSSTATUS_GOTOFINISH(HalCm_Setup2DSurfaceStateWithBTIndex(
state, bindingTable, surfIndex, btIndex, 1));
break;
case CM_ARGUMENT_SURFACE2DUP_SAMPLER:
CM_CHK_MOSSTATUS_GOTOFINISH(HalCm_Setup2DSurfaceUPStateWithBTIndex(
state, bindingTable, surfIndex, btIndex, 1));
break;
case CM_ARGUMENT_SURFACE_SAMPLER8X8_AVS:
case CM_ARGUMENT_SURFACE_SAMPLER8X8_VA:
CM_CHK_MOSSTATUS_GOTOFINISH(HalCm_SetupSampler8x8SurfaceStateWithBTIndex(
state, bindingTable, surfIndex, btIndex, 0, (CM_HAL_KERNEL_ARG_KIND)(indirectSurfaceInfo + index)->kind, 0));
break;
case CM_ARGUMENT_SURFACE3D:
CM_CHK_MOSSTATUS_GOTOFINISH(HalCm_Setup3DSurfaceStateWithBTIndex(
state, bindingTable, surfIndex, btIndex));
break;
default:
eStatus = MOS_STATUS_INVALID_PARAMETER;
CM_ASSERTMESSAGE("Indirect Data surface kind is not supported");
goto finish;
}
}
}
// set sampler bti
if (kernelParam->samplerBTIParam.samplerCount > 0)
{
for (uint32_t i = 0; i < kernelParam->samplerBTIParam.samplerCount; i++)
{
HalCm_SetupSamplerStateWithBTIndex(state, kernelParam, &kernelParam->samplerBTIParam.samplerInfo[0], i, mediaID);
}
}
if ( ( kernelParam->curbeSizePerThread > 0 ) && ( kernelParam->stateBufferType == CM_STATE_BUFFER_NONE ) )
{
uint8_t data[CM_MAX_THREAD_PAYLOAD_SIZE + 32];
uint8_t curbe[CM_MAX_CURBE_SIZE_PER_TASK + 32];
MOS_ZeroMemory(data, sizeof(data));
MOS_ZeroMemory(curbe, sizeof(curbe));
for (aIndex = 0; aIndex < kernelParam->numArgs; aIndex++)
{
argParam = &kernelParam->argParams[aIndex];
if (argParam->perThread || argParam->isNull)
{
continue;
}
switch (argParam->kind)
{
case CM_ARGUMENT_GENERAL:
case CM_ARGUMENT_IMPLICT_GROUPSIZE:
case CM_ARGUMENT_IMPLICT_LOCALSIZE:
case CM_ARGUMENT_IMPLICIT_LOCALID:
case CM_ARGUMENT_GENERAL_DEPVEC:
HalCm_SetArgData(argParam, 0, data);
break;
case CM_ARGUMENT_SAMPLER:
CM_CHK_MOSSTATUS_GOTOFINISH(HalCm_SetupSamplerState(
state, kernelParam, argParam, indexParam, mediaID, 0, data));
break;
case CM_ARGUMENT_SURFACEBUFFER:
CM_CHK_MOSSTATUS_GOTOFINISH(HalCm_SetupBufferSurfaceState(
state, argParam, indexParam, bindingTable, -1, 0, data));
break;
case CM_ARGUMENT_SURFACE2D_UP:
CM_CHK_MOSSTATUS_GOTOFINISH(HalCm_Setup2DSurfaceUPState(
state, argParam, indexParam, bindingTable, 0, data));
break;
case CM_ARGUMENT_SURFACE2DUP_SAMPLER:
CM_CHK_MOSSTATUS_GOTOFINISH(HalCm_Setup2DSurfaceUPSamplerState(
state, argParam, indexParam, bindingTable, 0, data));
break;
case CM_ARGUMENT_SURFACE2D_SAMPLER:
CM_CHK_MOSSTATUS_GOTOFINISH(HalCm_Setup2DSurfaceSamplerState(
state, argParam, indexParam, bindingTable, 0, data));
break;
case CM_ARGUMENT_SURFACE2D:
CM_CHK_MOSSTATUS_GOTOFINISH(HalCm_Setup2DSurfaceState(
state, argParam, indexParam, bindingTable, 0, data));
break;
case CM_ARGUMENT_SURFACE3D:
CM_CHK_MOSSTATUS_GOTOFINISH(HalCm_Setup3DSurfaceState(
state, argParam, indexParam, bindingTable, 0, data));
break;
case CM_ARGUMENT_SURFACE_VME: // 3 surface indices
CM_CHK_MOSSTATUS_GOTOFINISH(HalCm_SetupVmeSurfaceState(
state, argParam, indexParam, bindingTable, 0, data));
vmeUsed = true;
break;
case CM_ARGUMENT_SURFACE_SAMPLER8X8_AVS: // sampler 8x8 surface
case CM_ARGUMENT_SURFACE_SAMPLER8X8_VA: // sampler 8x8 surface
CM_CHK_MOSSTATUS_GOTOFINISH(HalCm_SetupSampler8x8SurfaceState(
state, argParam, indexParam, bindingTable, 0, data));
break;
case CM_ARGUMENT_STATE_BUFFER:
CM_CHK_MOSSTATUS_GOTOFINISH( HalCm_SetupStateBufferSurfaceState(
state, argParam, indexParam, bindingTable, 0, data ) );
break;
case CM_ARGUMENT_SURFACE:
// Allow null surface
break;
case CM_ARGUMENT_SURFACE2D_SCOREBOARD:
CM_CHK_MOSSTATUS_GOTOFINISH(HalCm_Setup2DSurfaceState(
state, argParam, indexParam, bindingTable, 0, data));
break;
default:
eStatus = MOS_STATUS_INVALID_PARAMETER;
CM_ASSERTMESSAGE("Argument kind '%d' is not supported", argParam->kind);
goto finish;
}
}
if (perKernelGpGpuWalkerParames->gpgpuEnabled)
{
uint32_t offset = 0;
uint32_t localIdXOffset = kernelParam->argParams[localIdIndex].payloadOffset;
uint32_t localIdYOffset = localIdXOffset + 4;
uint32_t localIdZOffset = localIdXOffset + 8;
//totalCurbeSize aligned when parsing task
int32_t crossThreadSize = kernelParam->crossThreadConstDataLen;
//Cross thread constant data
MOS_SecureMemcpy(curbe + offset, crossThreadSize, data, crossThreadSize);
offset += crossThreadSize;
//Per-thread data
for (idZ = 0; idZ < perKernelGpGpuWalkerParames->threadDepth; idZ++)
{
for (idY = 0; idY < perKernelGpGpuWalkerParames->threadHeight; idY++)
{
for (idX = 0; idX < perKernelGpGpuWalkerParames->threadWidth; idX++)
{
*((uint32_t *)(data + localIdXOffset)) = idX;
*((uint32_t *)(data + localIdYOffset)) = idY;
*((uint32_t *)(data + localIdZOffset)) = idZ;
MOS_SecureMemcpy(curbe + offset, kernelParam->curbeSizePerThread, data + crossThreadSize, kernelParam->curbeSizePerThread);
offset += kernelParam->curbeSizePerThread;
}
}
}
// tell pfnLoadCurbeData the current curbe offset
if (state->dshEnabled)
{
PRENDERHAL_DYNAMIC_STATE dynamicState = stateHeap->pCurMediaState->pDynamicState;
dynamicState->Curbe.iCurrent -= MOS_ALIGN_CEIL(kernelParam->totalCurbeSize, state->renderHal->dwCurbeBlockAlign);
kernelParam->curbeOffset = dynamicState->Curbe.iCurrent;
}
else
{
stateHeap->pCurMediaState->iCurbeOffset -= MOS_ALIGN_CEIL(kernelParam->totalCurbeSize, state->renderHal->dwCurbeBlockAlign);
kernelParam->curbeOffset = stateHeap->pCurMediaState->iCurbeOffset;
}
// update curbe with data.
renderHal->pfnLoadCurbeData(renderHal,
stateHeap->pCurMediaState,
curbe,
kernelParam->totalCurbeSize);
}
else
{
CM_ASSERT(kernelParam->totalCurbeSize == kernelParam->curbeSizePerThread);
// tell pfnLoadCurbeData the current curbe offset
if (state->dshEnabled)
{
PRENDERHAL_DYNAMIC_STATE dynamicState = stateHeap->pCurMediaState->pDynamicState;
dynamicState->Curbe.iCurrent -= MOS_ALIGN_CEIL(kernelParam->totalCurbeSize, state->renderHal->dwCurbeBlockAlign);
kernelParam->curbeOffset = dynamicState->Curbe.iCurrent;
}
else
{
stateHeap->pCurMediaState->iCurbeOffset -= MOS_ALIGN_CEIL(kernelParam->totalCurbeSize, state->renderHal->dwCurbeBlockAlign);
kernelParam->curbeOffset = stateHeap->pCurMediaState->iCurbeOffset;
}
// update curbe with data.
renderHal->pfnLoadCurbeData(renderHal,
stateHeap->pCurMediaState,
data,
kernelParam->totalCurbeSize);
}
if (state->cmHalInterface->IsOverridePowerOptionPerGpuContext() == false) // false means override per Batch.
{
if ((vmeUsed == true) && state->cmHalInterface->IsRequestShutdownSubslicesForVmeUsage())
{
CM_CHK_MOSSTATUS_GOTOFINISH(state->pfnGetPlatformInfo(state, &platformInfo, true));
CM_POWER_OPTION cmPower;
cmPower.nSlice = 1;
cmPower.nSubSlice = platformInfo.numSubSlices / 2;
cmPower.nEU = (uint16_t)platformInfo.numEUsPerSubSlice;
state->pfnSetPowerOption(state, &cmPower);
}
}
}
#if MDF_CURBE_DATA_DUMP
if (state->dumpCurbeData)
{
HalCm_DumpCurbeData(state);
}
#endif
#if MDF_INTERFACE_DESCRIPTOR_DATA_DUMP
if (state->dumpIDData)
{
HalCm_DumpInterfaceDescriptorData(state);
}
#endif
finish:
return eStatus;
}
MOS_STATUS HalCm_SetConditionalEndInfo(
PCM_HAL_STATE state,
PCM_HAL_CONDITIONAL_BB_END_INFO conditionalEndInfo,
PMHW_MI_CONDITIONAL_BATCH_BUFFER_END_PARAMS conditionalBBEndParams,
uint32_t index
)
{
if (index >= CM_MAX_CONDITIONAL_END_CMDS)
{
return MOS_STATUS_INVALID_PARAMETER;
}
MOS_ZeroMemory(&conditionalBBEndParams[index], sizeof(MHW_MI_CONDITIONAL_BATCH_BUFFER_END_PARAMS));
conditionalBBEndParams[index].presSemaphoreBuffer = &(state->bufferTable[conditionalEndInfo[index].bufferTableIndex].osResource);
conditionalBBEndParams[index].dwValue = conditionalEndInfo[index].compareValue;
conditionalBBEndParams[index].bDisableCompareMask = conditionalEndInfo[index].disableCompareMask;
conditionalBBEndParams[index].dwOffset = conditionalEndInfo[index].offset;
return MOS_STATUS_SUCCESS;
}
//===============<Interface Functions>==========================================
//*-----------------------------------------------------------------------------
//| Purpose: Allocate Structures required for HW Rendering
//| Returns: Result of the operation
//*-----------------------------------------------------------------------------
MOS_STATUS HalCm_Allocate(
PCM_HAL_STATE state) // [in] Pointer to CM State
{
MOS_STATUS eStatus;
PCM_HAL_DEVICE_PARAM deviceParam;
PRENDERHAL_INTERFACE renderHal;
PRENDERHAL_STATE_HEAP_SETTINGS stateHeapSettings;
uint32_t i;
MOS_NULL_RENDERING_FLAGS nullHWAccelerationEnable;
RENDERHAL_SETTINGS renderHalSettings;
uint32_t maxTasks;
PMHW_BATCH_BUFFER batchBuffer = nullptr;
//------------------------------------
CM_ASSERT(state);
//------------------------------------
eStatus = MOS_STATUS_UNKNOWN;
deviceParam = &state->cmDeviceParam;
renderHal = state->renderHal;
stateHeapSettings = &renderHal->StateHeapSettings;
stateHeapSettings->iCurbeSize = CM_MAX_CURBE_SIZE_PER_TASK;
stateHeapSettings->iMediaStateHeaps = deviceParam->maxTasks + 1; // + 1 to handle sync issues with current RenderHal impl (we can remove this once we insert sync value in 2nd level BB)
stateHeapSettings->iMediaIDs = deviceParam->maxKernelsPerTask; // Number of Media IDs = Number of Kernels/Task
stateHeapSettings->iKernelCount = deviceParam->maxGshKernelEntries;
stateHeapSettings->iKernelBlockSize = deviceParam->maxKernelBinarySize; // The kernel occupied memory need be this block size aligned 256K for IVB/HSW
stateHeapSettings->iKernelHeapSize = deviceParam->maxGshKernelEntries * CM_32K; // CM_MAX_GSH_KERNEL_ENTRIES * 32*1024;
state->totalKernelSize = (int32_t*)MOS_AllocAndZeroMemory(sizeof(int32_t) * deviceParam->maxGshKernelEntries);
if(!state->totalKernelSize)
{
CM_ASSERTMESSAGE("Could not allocate enough memory for state->totalKernelSize\n");
eStatus = MOS_STATUS_NO_SPACE;
goto finish;
}
stateHeapSettings->iPerThreadScratchSize = deviceParam->maxPerThreadScratchSpaceSize;
stateHeapSettings->iSipSize = CM_MAX_SIP_SIZE;
stateHeapSettings->iBindingTables = deviceParam->maxKernelsPerTask; // Number of Binding tables = Number of Kernels/Task
stateHeapSettings->iSurfacesPerBT = CM_MAX_SURFACE_STATES_PER_BT; // Allocate Max Binding Table indices per binding table
stateHeapSettings->iSurfaceStates = CM_MAX_SURFACE_STATES; // Allocate Max Surfaces that can be indexed
stateHeapSettings->iSamplersAVS = deviceParam->maxAvsSamplers; // Allocate Max AVS samplers
// Initialize RenderHal Interface
CM_CHK_MOSSTATUS_GOTOFINISH(renderHal->pfnInitialize(renderHal, nullptr));
// Initialize Vebox Interface
CM_CHK_MOSSTATUS_GOTOFINISH(state->veboxInterface->CreateHeap());
// Initialize the table only in Static Mode (DSH doesn't use this table at all)
if (!state->dshEnabled)
{
// Init the data in kernel entries for Dynamic GSH
for (int32_t kernelID = 0; kernelID < stateHeapSettings->iKernelCount; ++kernelID)
{
if (kernelID > 0)
{
state->totalKernelSize[kernelID] = 0;
}
else
{
state->totalKernelSize[kernelID] = stateHeapSettings->iKernelHeapSize;
}
}
state->kernelNumInGsh = 1;
}
// Allocate BB (one for each media-state heap)
state->numBatchBuffers = stateHeapSettings->iMediaStateHeaps;
state->batchBuffers = (PMHW_BATCH_BUFFER)MOS_AllocAndZeroMemory(
state->numBatchBuffers *
sizeof(MHW_BATCH_BUFFER));
CM_CHK_NULL_GOTOFINISH_MOSERROR(state->batchBuffers);
batchBuffer = state->batchBuffers;
for (i = 0; i < (uint32_t)state->numBatchBuffers; i ++, batchBuffer ++)
{
batchBuffer->dwSyncTag = 0;
batchBuffer->bMatch = false;
batchBuffer->iPrivateType = RENDERHAL_BB_TYPE_CM;
batchBuffer->iPrivateSize = sizeof(CM_HAL_BB_ARGS);
batchBuffer->pPrivateData = (PCM_HAL_BB_ARGS)MOS_AllocAndZeroMemory(sizeof(CM_HAL_BB_ARGS));
CM_CHK_NULL_GOTOFINISH_MOSERROR(batchBuffer->pPrivateData);
((PCM_HAL_BB_ARGS)batchBuffer->pPrivateData)->refCount = 1;
}
// Allocate TimeStamp Buffer
CM_CHK_MOSSTATUS_GOTOFINISH(HalCm_AllocateTsResource(state));
// Allocate tracker resources
CM_CHK_MOSSTATUS_GOTOFINISH(HalCm_AllocateTrackerResource(state));
// Initialize dynamic general state heap
CM_HAL_HEAP_PARAM heapParams;
heapParams.behaviorGSH = HeapManager::Behavior::destructiveExtend;
heapParams.initialSizeGSH = 0x0080000;
heapParams.extendSizeGSH = 0x0080000;
heapParams.trackerResourceGSH = state->renderHal->trackerResource.data;
CM_CHK_MOSSTATUS_GOTOFINISH(HalCm_InitializeDynamicStateHeaps(state, &heapParams));
CM_CHK_MOSSTATUS_GOTOFINISH(HalCm_AllocateTables(state));
// Allocate Task Param to hold max tasks
state->taskParam = (PCM_HAL_TASK_PARAM)MOS_AllocAndZeroMemory(sizeof(CM_HAL_TASK_PARAM));
CM_CHK_NULL_GOTOFINISH_MOSERROR(state->taskParam);
state->currentTaskEntry = 0;
// Allocate Task TimeStamp to hold time stamps
state->taskTimeStamp = (PCM_HAL_TASK_TIMESTAMP)MOS_AllocAndZeroMemory(sizeof(CM_HAL_TASK_TIMESTAMP));
CM_CHK_NULL_GOTOFINISH_MOSERROR(state->taskTimeStamp);
// Setup Registration table entries
state->surfaceRegTable.count = state->cmDeviceParam.max2DSurfaceTableSize;
state->surfaceRegTable.entries = state->surf2DTable;
maxTasks = state->cmDeviceParam.maxTasks;
// Initialize the task status table
MOS_FillMemory(state->taskStatusTable, (size_t)maxTasks, CM_INVALID_INDEX);
// Init the null render flag
nullHWAccelerationEnable = state->osInterface->pfnGetNullHWRenderFlags(state->osInterface);
state->nullHwRenderCm = nullHWAccelerationEnable.Cm || nullHWAccelerationEnable.VPGobal;
//during initialization stage to allocate sip resource and Get sip binary.
if ((state->midThreadPreemptionDisabled == false)
|| (state->kernelDebugEnabled == true))
{
CM_CHK_MOSSTATUS_GOTOFINISH(state->cmHalInterface->AllocateSIPCSRResource());
state->pfnGetSipBinary(state);
}
//Init flag for conditional batch buffer
state->cbbEnabled = HalCm_IsCbbEnabled(state);
//Turn Turbo boost on
CM_CHK_MOSSTATUS_GOTOFINISH(state->pfnEnableTurboBoost(state));
state->tsFrequency = HalCm_GetTsFrequency(state->osInterface);
if (state->refactor)
{
state->advExecutor = CmExtensionCreator<CmExecutionAdv>::CreateClass();
}
else
{
state->advExecutor = CmExtensionCreator<CmExecutionAdv>::CreateBaseClass();
}
if (state->advExecutor == nullptr)
{
CM_ASSERTMESSAGE("Could not allocate enough memory for state->advExecutor\n");
eStatus = MOS_STATUS_NO_SPACE;
goto finish;
}
state->advExecutor->Initialize(state);
eStatus = MOS_STATUS_SUCCESS;
finish:
return eStatus;
}
uint16_t HalCm_GetKernelPerfTag(
PCM_HAL_STATE cmState,
PCM_HAL_KERNEL_PARAM *kernelParams,
uint32_t numKernels)
{
using namespace std;
CM_ASSERT(cmState);
CM_ASSERT(kernelParams);
int perfTagKernelNum = numKernels - 1;
if (numKernels > MAX_COMBINE_NUM_IN_PERFTAG)
{
perfTagKernelNum = MAX_COMBINE_NUM_IN_PERFTAG - 1;
}
// get a combined kernel name
uint32_t len = numKernels * CM_MAX_KERNEL_NAME_SIZE_IN_BYTE;
char *combinedName = MOS_NewArray(char, len);
if (combinedName == nullptr)
{ // Not need to abort the process as this is only for pnp profiling
CM_ASSERTMESSAGE("Error: Memory allocation error in getPertTag.");
return 0; // return the default perftag
}
CmSafeMemSet(combinedName, 0, len);
MOS_SecureStrcat(combinedName, len, kernelParams[0]->kernelName);
for (uint32_t i = 1; i < numKernels; i++)
{
MOS_SecureStrcat(combinedName, len, ";");
MOS_SecureStrcat(combinedName, len, kernelParams[i]->kernelName);
}
// get perftag index
int perfTagIndex = 0;
map<string, int>::iterator ite = cmState->perfTagIndexMap[perfTagKernelNum]->find(combinedName);
if (ite == cmState->perfTagIndexMap[perfTagKernelNum]->end())
{
if (cmState->currentPerfTagIndex[perfTagKernelNum] <= MAX_CUSTOMIZED_PERFTAG_INDEX)
{
cmState->perfTagIndexMap[perfTagKernelNum]->insert(pair<string, int>(combinedName, cmState->currentPerfTagIndex[perfTagKernelNum]));
perfTagIndex = cmState->currentPerfTagIndex[perfTagKernelNum] ++;
}
}
else
{
perfTagIndex = ite->second;
}
perfTagIndex = (perfTagIndex &0xFF) | (perfTagKernelNum << 8);
MosSafeDeleteArray(combinedName);
return (uint16_t)perfTagIndex;
}
//*-----------------------------------------------------------------------------
//| Purpose: Executes the CM Task
//| Returns: Result of the operation
//*-----------------------------------------------------------------------------
MOS_STATUS HalCm_ExecuteTask(
PCM_HAL_STATE state, // [in] Pointer to CM State
PCM_HAL_EXEC_TASK_PARAM execParam) // [in] Pointer to Task Param
{
MOS_STATUS eStatus;
PRENDERHAL_INTERFACE renderHal;
PRENDERHAL_MEDIA_STATE mediaState;
PMHW_BATCH_BUFFER batchBuffer;
PCM_HAL_BB_ARGS bbCmArgs;
PCM_HAL_KERNEL_PARAM kernelParam;
int32_t taskId;
int32_t remBindingTables;
int32_t bindingTable;
int32_t bti;
int32_t mediaID;
PRENDERHAL_KRN_ALLOCATION krnAllocations[CM_MAX_KERNELS_PER_TASK];
uint32_t vfeCurbeSize;
uint32_t maxInlineDataSize, maxIndirectDataSize;
uint32_t i;
void *cmdBuffer = nullptr;
PCM_HAL_TASK_PARAM taskParam = state->taskParam;
uint32_t btsizePower2;
PMOS_INTERFACE osInterface = nullptr;
//-----------------------------------
CM_ASSERT(state);
CM_ASSERT(execParam);
//-----------------------------------
eStatus = MOS_STATUS_SUCCESS;
renderHal = state->renderHal;
mediaState = nullptr;
batchBuffer = nullptr;
if (execParam->numKernels > state->cmDeviceParam.maxKernelsPerTask)
{
eStatus = MOS_STATUS_INVALID_PARAMETER;
CM_ASSERTMESSAGE("Number of Kernels per task exceeds maximum");
goto finish;
}
state->osInterface->pfnSetGpuContext(state->osInterface, (MOS_GPU_CONTEXT)execParam->queueOption.GPUContext);
// Reset states before execute
// (clear allocations, get GSH allocation index + any additional housekeeping)
state->osInterface->pfnResetOsStates(state->osInterface);
CM_CHK_MOSSTATUS_GOTOFINISH(renderHal->pfnReset(renderHal));
MOS_ZeroMemory(state->taskParam, sizeof(CM_HAL_TASK_PARAM));
MOS_FillMemory(
state->bti2DIndexTable,
state->cmDeviceParam.max2DSurfaceTableSize * sizeof( CM_HAL_MULTI_USE_BTI_ENTRY ),
CM_INVALID_INDEX );
MOS_FillMemory(
state->bti2DUPIndexTable,
state->cmDeviceParam.max2DSurfaceUPTableSize * sizeof( CM_HAL_MULTI_USE_BTI_ENTRY ),
CM_INVALID_INDEX );
MOS_FillMemory(
state->bti3DIndexTable,
state->cmDeviceParam.max3DSurfaceTableSize * sizeof( CM_HAL_MULTI_USE_BTI_ENTRY ),
CM_INVALID_INDEX );
MOS_FillMemory(
state->btiBufferIndexTable,
state->cmDeviceParam.maxBufferTableSize * sizeof( CM_HAL_MULTI_USE_BTI_ENTRY ),
CM_INVALID_INDEX );
MOS_FillMemory(
state->samplerIndexTable,
state->cmDeviceParam.maxSamplerTableSize,
CM_INVALID_INDEX);
MOS_FillMemory(
state->sampler8x8IndexTable,
state->cmDeviceParam.maxSampler8x8TableSize,
CM_INVALID_INDEX);
state->walkerParams.CmWalkerEnable = 0;
vfeCurbeSize = 0;
maxInlineDataSize = 0;
maxIndirectDataSize = 0;
// Get the Task Id
CM_CHK_MOSSTATUS_GOTOFINISH(HalCm_GetNewTaskId(state, &taskId));
// Parse the task
CM_CHK_MOSSTATUS_GOTOFINISH(HalCm_ParseTask(state, execParam));
// Reset the SSH configuration according to the property of the task
btsizePower2 = (uint32_t)renderHal->StateHeapSettings.iBTAlignment/renderHal->pRenderHalPltInterface->GetBTStateCmdSize();
while (btsizePower2 < taskParam->surfacePerBT)
{
btsizePower2 = btsizePower2 * 2;
}
taskParam->surfacePerBT = btsizePower2;
renderHal->pStateHeap->iBindingTableSize = MOS_ALIGN_CEIL(taskParam->surfacePerBT * // Reconfigure the binding table size
renderHal->pRenderHalPltInterface->GetBTStateCmdSize(), renderHal->StateHeapSettings.iBTAlignment);
renderHal->StateHeapSettings.iBindingTables = renderHal->StateHeapSettings.iBindingTables * // Reconfigure the binding table number
renderHal->StateHeapSettings.iSurfacesPerBT / taskParam->surfacePerBT;
renderHal->StateHeapSettings.iSurfacesPerBT = taskParam->surfacePerBT; // Reconfigure the surface per BT
if (execParam->numKernels > (uint32_t)renderHal->StateHeapSettings.iBindingTables)
{
eStatus = MOS_STATUS_INVALID_PARAMETER;
CM_ASSERTMESSAGE("Number of Kernels per task exceeds the number can be hold by binding table");
goto finish;
}
if (execParam->kernelDebugEnabled && Mos_ResourceIsNull(&state->sipResource.osResource))
{
HalCm_AllocateSipResource( state); // create sip resource if it does not exist
}
// Assign a MediaState from the MediaStateHeap
// !!!! THIS MUST BE BEFORE Getting the BATCH_BUFFER !!!
// since this method syncs the batch buffer and media state.
if (state->dshEnabled)
{
if ( execParam->userDefinedMediaState != nullptr )
{
// use exsiting media state as current state
mediaState = static_cast< PRENDERHAL_MEDIA_STATE >( execParam->userDefinedMediaState );
// update current state to dsh
renderHal->pStateHeap->pCurMediaState = mediaState;
// Refresh sync tag for all media states in submitted queue
state->criticalSectionDSH->Acquire();
renderHal->pfnRefreshSync( renderHal );
state->criticalSectionDSH->Release();
}
else
{
// Obtain media state configuration - Curbe, Samplers (3d/AVS/VA), 8x8 sampler table, Media IDs, Kernel Spill area
RENDERHAL_DYNAMIC_MEDIA_STATE_PARAMS params;
state->criticalSectionDSH->Acquire();
HalCm_DSH_GetDynamicStateConfiguration( state, ¶ms, execParam->numKernels, execParam->kernels, execParam->kernelCurbeOffset );
// Prepare Media States to accommodate all parameters - Curbe, Samplers (3d/AVS/VA), 8x8 sampler table, Media IDs
mediaState = renderHal->pfnAssignDynamicState( renderHal, ¶ms, RENDERHAL_COMPONENT_CM );
state->criticalSectionDSH->Release();
}
}
else
{
mediaState = renderHal->pfnAssignMediaState(renderHal, RENDERHAL_COMPONENT_CM);
}
CM_CHK_NULL_GOTOFINISH_MOSERROR(mediaState);
// Assign/Reset SSH instance
CM_CHK_MOSSTATUS_GOTOFINISH(renderHal->pfnAssignSshInstance(renderHal));
// Dynamic Batch Buffer allocation
if (!state->walkerParams.CmWalkerEnable)
{
// Get the Batch buffer
CM_CHK_MOSSTATUS_GOTOFINISH(HalCm_GetBatchBuffer(state, execParam->numKernels, execParam->kernels, &batchBuffer));
CM_CHK_NULL_GOTOFINISH_MOSERROR(batchBuffer);
bbCmArgs = (PCM_HAL_BB_ARGS)batchBuffer->pPrivateData;
// Lock the batch buffer
if ( (bbCmArgs->refCount == 1) ||
(state->taskParam->reuseBBUpdateMask == 1) )
{
CM_CHK_MOSSTATUS_GOTOFINISH(renderHal->pfnLockBB(renderHal, batchBuffer));
}
}
if (state->useNewSamplerHeap == false)
{
HalCm_AcquireSamplerStatistics(state);
}
// Load all kernels in the same state heap - expand ISH if necessary BEFORE programming media states.
// This is better than having to expand ISH in the middle of loading, when part of MediaIDs are
// already programmed - not a problem in the old implementation where it would simply remove old
// kernels out of the way.
if (state->dshEnabled)
{
CM_CHK_MOSSTATUS_GOTOFINISH(HalCm_DSH_LoadKernelArray(state, execParam->kernels, execParam->numKernels, krnAllocations));
}
for (i = 0; i < execParam->numKernels; i++)
{
CM_HAL_INDEX_PARAM indexParam;
MOS_ZeroMemory(&indexParam, sizeof(CM_HAL_INDEX_PARAM));
kernelParam = execParam->kernels[i];
CM_CHK_MOSSTATUS_GOTOFINISH(HalCm_SetupStatesForKernelInitial(state, mediaState, batchBuffer, taskId, kernelParam, &indexParam,
execParam->kernelCurbeOffset[i], bti, mediaID, krnAllocations[i]));
CM_CHK_MOSSTATUS_GOTOFINISH(HalCm_FinishStatesForKernel(state, mediaState, batchBuffer, taskId, kernelParam, i, &indexParam,
bti, mediaID, krnAllocations[i]));
vfeCurbeSize += MOS_ALIGN_CEIL(kernelParam->totalCurbeSize, state->renderHal->dwCurbeBlockAlign);
if (kernelParam->payloadSize > maxInlineDataSize)
{
maxInlineDataSize = kernelParam->payloadSize;
}
if (kernelParam->indirectDataParam.indirectDataSize > maxIndirectDataSize)
{
maxIndirectDataSize = kernelParam->indirectDataParam.indirectDataSize;
}
if (execParam->conditionalEndBitmap & (uint64_t)1 << i)
{
CM_CHK_MOSSTATUS_GOTOFINISH(HalCm_SetConditionalEndInfo(state, taskParam->conditionalEndInfo, taskParam->conditionalBBEndParams, i));
}
}
// Store the Max Payload Sizes in the Task params
state->taskParam->vfeCurbeSize = vfeCurbeSize;
if (maxIndirectDataSize)
{
state->taskParam->urbEntrySize = maxIndirectDataSize;
}
else
{
state->taskParam->urbEntrySize = maxInlineDataSize;
}
// We may have to send additional Binding table commands in command buffer.
// This is needed because the surface offset (from the base on SSH)
// calculation takes into account the max binding tables allocated in the
// SSH.
remBindingTables = renderHal->StateHeapSettings.iBindingTables - execParam->numKernels;
if (remBindingTables > 0)
{
for (i = 0; i < (uint32_t)remBindingTables; i++)
{
CM_CHK_MOSSTATUS_GOTOFINISH(renderHal->pfnAssignBindingTable(
renderHal,
&bindingTable));
}
}
// until now, we know binding table index for debug surface
// let's get system thread
osInterface = state->osInterface;
osInterface->pfnResetPerfBufferID(osInterface);
if (osInterface->pfnIsPerfTagSet(osInterface) == false)
{
osInterface->pfnIncPerfFrameID(osInterface);
uint16_t perfTag = HalCm_GetKernelPerfTag(state, execParam->kernels, execParam->numKernels);
osInterface->pfnSetPerfTag(osInterface, perfTag);
}
#if (_RELEASE_INTERNAL || _DEBUG)
#if defined(CM_DIRECT_GUC_SUPPORT)
// Update the task ID table
state->taskStatusTable[taskId] = (char)taskId;
//for GuC direct submission, need to send out dummy command buffer to make sure PDP table got binded
CM_CHK_MOSSTATUS_GOTOFINISH(state->cmHalInterface->SubmitDummyCommands(
batchBuffer, taskId, execParam->kernels, &cmdBuffer));
/* make sure Dummy submission is done */
CM_HAL_QUERY_TASK_PARAM queryParam;
queryParam.taskId = taskId;
queryParam.status = CM_TASK_IN_PROGRESS;
do {
state->pfnQueryTask(state, &queryParam);
} while (queryParam.status != CM_TASK_FINISHED);
#endif
#endif
// Submit HW commands and states
CM_CHK_MOSSTATUS_GOTOFINISH(state->cmHalInterface->SubmitCommands(
batchBuffer, taskId, execParam->kernels, &cmdBuffer));
// Set the Task ID
execParam->taskIdOut = taskId;
// Set OS data
if(cmdBuffer)
{
execParam->osData = cmdBuffer;
}
// Update the task ID table
state->taskStatusTable[taskId] = (char)taskId;
finish:
if (state->dshEnabled)
{
state->criticalSectionDSH->Acquire();
if (mediaState && eStatus != MOS_STATUS_SUCCESS)
{
// Failed, release media state and heap resources
renderHal->pfnReleaseDynamicState(renderHal, mediaState);
}
else
{
renderHal->pfnSubmitDynamicState(renderHal, mediaState);
}
state->criticalSectionDSH->Release();
}
if (batchBuffer) // for Media Walker, batchBuffer is empty
{
if (batchBuffer->bLocked)
{
// Only happens in Error cases
CM_CHK_NULL_RETURN_MOSERROR(batchBuffer->pPrivateData);
if (((PCM_HAL_BB_ARGS)batchBuffer->pPrivateData)->refCount == 1)
{
renderHal->pfnUnlockBB(renderHal, batchBuffer);
}
}
}
return eStatus;
}
//*-----------------------------------------------------------------------------
//| Purpose: Executes the CM Group Task
//| Returns: Result of the operation
//*-----------------------------------------------------------------------------
MOS_STATUS HalCm_ExecuteGroupTask(
PCM_HAL_STATE state, // [in] Pointer to CM State
PCM_HAL_EXEC_GROUP_TASK_PARAM execGroupParam) // [in] Pointer to Task Param
{
MOS_STATUS eStatus = MOS_STATUS_SUCCESS;
PRENDERHAL_INTERFACE renderHal = state->renderHal;
CM_HAL_INDEX_PARAM indexParam;
int32_t taskId;
uint32_t remBindingTables;
int32_t bindingTable;
int32_t bti;
int32_t mediaID;
PRENDERHAL_MEDIA_STATE mediaState = nullptr;
uint32_t i;
void *cmdBuffer = nullptr;
PCM_HAL_KERNEL_PARAM kernelParam = nullptr;
PCM_HAL_TASK_PARAM taskParam = state->taskParam;
uint32_t btsizePower2;
uint32_t vfeCurbeSize = 0;
PRENDERHAL_KRN_ALLOCATION krnAllocations[CM_MAX_KERNELS_PER_TASK];
PMOS_INTERFACE osInterface = nullptr;
//-----------------------------------
CM_ASSERT(state);
CM_ASSERT(execGroupParam);
//-----------------------------------
state->osInterface->pfnSetGpuContext(state->osInterface, (MOS_GPU_CONTEXT)execGroupParam->queueOption.GPUContext);
MOS_ZeroMemory(state->taskParam, sizeof(CM_HAL_TASK_PARAM));
MOS_ZeroMemory(&indexParam, sizeof(CM_HAL_INDEX_PARAM));
MOS_FillMemory(
state->bti2DIndexTable,
state->cmDeviceParam.max2DSurfaceTableSize * sizeof( CM_HAL_MULTI_USE_BTI_ENTRY ),
CM_INVALID_INDEX );
MOS_FillMemory(
state->bti2DUPIndexTable,
state->cmDeviceParam.max2DSurfaceUPTableSize * sizeof( CM_HAL_MULTI_USE_BTI_ENTRY ),
CM_INVALID_INDEX );
MOS_FillMemory(
state->bti3DIndexTable,
state->cmDeviceParam.max3DSurfaceTableSize * sizeof( CM_HAL_MULTI_USE_BTI_ENTRY ),
CM_INVALID_INDEX );
MOS_FillMemory(
state->btiBufferIndexTable,
state->cmDeviceParam.maxBufferTableSize * sizeof( CM_HAL_MULTI_USE_BTI_ENTRY ),
CM_INVALID_INDEX );
MOS_FillMemory(
state->samplerIndexTable,
state->cmDeviceParam.maxSamplerTableSize,
CM_INVALID_INDEX);
MOS_FillMemory(
state->sampler8x8IndexTable,
state->cmDeviceParam.maxSampler8x8TableSize,
CM_INVALID_INDEX);
// Reset states before execute
// (clear allocations, get GSH allocation index + any additional housekeeping)
state->osInterface->pfnResetOsStates(state->osInterface);
CM_CHK_MOSSTATUS_GOTOFINISH(renderHal->pfnReset(renderHal));
state->walkerParams.CmWalkerEnable = 0;
state->taskParam->blGpGpuWalkerEnabled = true;
// Get the Task Id
CM_CHK_MOSSTATUS_GOTOFINISH(HalCm_GetNewTaskId(state, &taskId));
// Parse the task
CM_CHK_MOSSTATUS_GOTOFINISH(HalCm_ParseGroupTask(state, execGroupParam));
// Reset the SSH configuration according to the property of the task
btsizePower2 = (uint32_t)renderHal->StateHeapSettings.iBTAlignment/renderHal->pRenderHalPltInterface->GetBTStateCmdSize();
while (btsizePower2 < taskParam->surfacePerBT)
{
btsizePower2 = btsizePower2 * 2;
}
taskParam->surfacePerBT = btsizePower2;
renderHal->pStateHeap->iBindingTableSize = MOS_ALIGN_CEIL(taskParam->surfacePerBT * // Reconfigure the binding table size
renderHal->pRenderHalPltInterface->GetBTStateCmdSize(),
renderHal->StateHeapSettings.iBTAlignment);
renderHal->StateHeapSettings.iBindingTables = renderHal->StateHeapSettings.iBindingTables * // Reconfigure the binding table number
renderHal->StateHeapSettings.iSurfacesPerBT / taskParam->surfacePerBT;
renderHal->StateHeapSettings.iSurfacesPerBT = taskParam->surfacePerBT; // Reconfigure the surface per BT
if (execGroupParam->numKernels > (uint32_t)renderHal->StateHeapSettings.iBindingTables)
{
eStatus = MOS_STATUS_INVALID_PARAMETER;
CM_ASSERTMESSAGE("Number of Kernels per task exceeds the number can be hold by binding table");
goto finish;
}
if (execGroupParam->kernelDebugEnabled && Mos_ResourceIsNull(&state->sipResource.osResource))
{
HalCm_AllocateSipResource( state); // create sip resource if it does not exist
}
// Assign a MediaState from the MediaStateHeap
// !!!! THIS MUST BE BEFORE Getting the BATCH_BUFFER !!!
// since this method syncs the batch buffer and media state.
if (state->dshEnabled)
{
if ( execGroupParam->userDefinedMediaState != nullptr )
{
// Preload all kernels
CM_CHK_MOSSTATUS_GOTOFINISH( HalCm_DSH_LoadKernelArray( state, execGroupParam->kernels, execGroupParam->numKernels, krnAllocations ) );
// use exsiting media state as current state
mediaState = static_cast< PRENDERHAL_MEDIA_STATE >( execGroupParam->userDefinedMediaState );
// update current state to dsh
renderHal->pStateHeap->pCurMediaState = mediaState;
state->criticalSectionDSH->Acquire();
// Refresh sync tag for all media states in submitted queue
renderHal->pfnRefreshSync( renderHal );
state->criticalSectionDSH->Release();
}
else
{
// Preload all kernels
CM_CHK_MOSSTATUS_GOTOFINISH(HalCm_DSH_LoadKernelArray(state, execGroupParam->kernels, execGroupParam->numKernels, krnAllocations));
// Obtain media state configuration - Curbe, Samplers (3d/AVS/VA), 8x8 sampler table, Media IDs, Kernel Spill area
RENDERHAL_DYNAMIC_MEDIA_STATE_PARAMS params;
state->criticalSectionDSH->Acquire();
HalCm_DSH_GetDynamicStateConfiguration(state, ¶ms, execGroupParam->numKernels, execGroupParam->kernels, execGroupParam->kernelCurbeOffset);
// Prepare Media States to accommodate all parameters
mediaState = renderHal->pfnAssignDynamicState(renderHal, ¶ms, RENDERHAL_COMPONENT_CM);
state->criticalSectionDSH->Release();
}
}
else
{
// Assign a MediaState from the MediaStateHeap
// !!!! THIS MUST BE BEFORE Getting the BATCH_BUFFER !!!
// since this method syncs the batch buffer and media state.
mediaState = renderHal->pfnAssignMediaState(renderHal, RENDERHAL_COMPONENT_CM);
}
CM_CHK_NULL_GOTOFINISH_MOSERROR(mediaState);
// Assign/Reset SSH instance
CM_CHK_MOSSTATUS_GOTOFINISH(renderHal->pfnAssignSshInstance(renderHal));
if (state->useNewSamplerHeap == false)
{
HalCm_AcquireSamplerStatistics(state);
}
for (i = 0; i < execGroupParam->numKernels; i++)
{
CM_HAL_INDEX_PARAM indexParam;
MOS_ZeroMemory(&indexParam, sizeof(CM_HAL_INDEX_PARAM));
kernelParam = execGroupParam->kernels[i];
CM_CHK_MOSSTATUS_GOTOFINISH(HalCm_SetupStatesForKernelInitial(state, mediaState, nullptr, taskId, kernelParam, &indexParam,
execGroupParam->kernelCurbeOffset[i], bti, mediaID, krnAllocations[i]));
CM_CHK_MOSSTATUS_GOTOFINISH(HalCm_FinishStatesForKernel(state, mediaState, nullptr, taskId, kernelParam, i, &indexParam,
bti, mediaID, krnAllocations[i]));
vfeCurbeSize += MOS_ALIGN_CEIL(kernelParam->totalCurbeSize, state->renderHal->dwCurbeBlockAlign);
if (execGroupParam->conditionalEndBitmap & (uint64_t)1 << i)
{
CM_CHK_MOSSTATUS_GOTOFINISH(HalCm_SetConditionalEndInfo(state, taskParam->conditionalEndInfo, taskParam->conditionalBBEndParams, i));
}
}
// Store the Max Payload Sizes in the Task params
state->taskParam->vfeCurbeSize = vfeCurbeSize;
state->taskParam->urbEntrySize = 0;
// We may have to send additional Binding table commands in command buffer.
// This is needed because the surface offset (from the base on SSH)
// calculation takes into account the max binding tables allocated in the
// SSH.
remBindingTables = renderHal->StateHeapSettings.iBindingTables - execGroupParam->numKernels;
if (remBindingTables > 0)
{
for (i = 0; i < remBindingTables; i++)
{
CM_CHK_MOSSTATUS_GOTOFINISH(renderHal->pfnAssignBindingTable(
renderHal,
&bindingTable));
}
}
// until now, we know binding table index for debug surface
// let's get system thread
if (execGroupParam->kernelDebugEnabled)
{
CM_CHK_MOSSTATUS_GOTOFINISH(state->pfnGetSipBinary(state));
}
osInterface = state->osInterface;
osInterface->pfnResetPerfBufferID(osInterface);
if (osInterface->pfnIsPerfTagSet(osInterface) == false)
{
osInterface->pfnIncPerfFrameID(osInterface);
int perfTag = HalCm_GetKernelPerfTag(state, execGroupParam->kernels, execGroupParam->numKernels);
osInterface->pfnSetPerfTag(osInterface, (uint16_t)perfTag);
}
// Submit HW commands and states
CM_CHK_MOSSTATUS_GOTOFINISH(state->cmHalInterface->SubmitCommands(
nullptr, taskId, execGroupParam->kernels, &cmdBuffer));
// Set the Task ID
execGroupParam->taskIdOut = taskId;
// Set OS data
if(cmdBuffer)
{
execGroupParam->osData = cmdBuffer;
}
// Update the task ID table
state->taskStatusTable[taskId] = (char)taskId;
finish:
if (state->dshEnabled)
{
state->criticalSectionDSH->Acquire();
if (mediaState && eStatus != MOS_STATUS_SUCCESS)
{
// Failed, release media state and heap resources
renderHal->pfnReleaseDynamicState(renderHal, mediaState);
}
else
{
renderHal->pfnSubmitDynamicState(renderHal, mediaState);
}
state->criticalSectionDSH->Release();
}
return eStatus;
}
MOS_STATUS HalCm_ExecuteHintsTask(
PCM_HAL_STATE state, // [in] Pointer to CM State
PCM_HAL_EXEC_HINTS_TASK_PARAM execHintsParam) // [in] Pointer to Task Param
{
MOS_STATUS eStatus;
PRENDERHAL_INTERFACE renderHal;
PRENDERHAL_MEDIA_STATE mediaState;
PMHW_BATCH_BUFFER batchBuffer;
PCM_HAL_BB_ARGS bbCmArgs;
PCM_HAL_KERNEL_PARAM kernelParam;
uint32_t i;
uint32_t numTasks;
uint64_t origKernelIds[CM_MAX_KERNELS_PER_TASK];
int32_t taskId;
int32_t remBindingTables;
int32_t bindingTable;
uint32_t vfeCurbeSize;
uint32_t maxInlineDataSize;
uint32_t maxIndirectDataSize;
int32_t *bindingTableEntries;
int32_t *mediaIds;
PRENDERHAL_KRN_ALLOCATION *krnAllocations;
PCM_HAL_INDEX_PARAM indexParams;
bool useMediaObjects;
void *cmdBuffer;
bool splitTask;
bool lastTask;
PMOS_INTERFACE osInterface = nullptr;
//------------------------------------
CM_ASSERT(state);
CM_ASSERT(execHintsParam);
//------------------------------------
eStatus = MOS_STATUS_SUCCESS;
renderHal = state->renderHal;
mediaState = nullptr;
batchBuffer = nullptr;
bindingTableEntries = nullptr;
mediaIds = nullptr;
krnAllocations = nullptr;
indexParams = nullptr;
useMediaObjects = false;
cmdBuffer = nullptr;
splitTask = false;
lastTask = false;
if (execHintsParam->numKernels > state->cmDeviceParam.maxKernelsPerTask)
{
eStatus = MOS_STATUS_INVALID_PARAMETER;
CM_ASSERTMESSAGE("Number of Kernels per task exceeds maximum");
goto finish;
}
state->osInterface->pfnSetGpuContext(state->osInterface, (MOS_GPU_CONTEXT)execHintsParam->queueOption.GPUContext);
bindingTableEntries = (int*)MOS_AllocAndZeroMemory(sizeof(int)*execHintsParam->numKernels);
mediaIds = (int*)MOS_AllocAndZeroMemory(sizeof(int)* execHintsParam->numKernels);
krnAllocations = (PRENDERHAL_KRN_ALLOCATION *)MOS_AllocAndZeroMemory(sizeof(void *)* execHintsParam->numKernels);
indexParams = (PCM_HAL_INDEX_PARAM)MOS_AllocAndZeroMemory(sizeof(CM_HAL_INDEX_PARAM)* execHintsParam->numKernels);
if (!bindingTableEntries || !mediaIds || !krnAllocations || !indexParams)
{
eStatus = MOS_STATUS_INVALID_PARAMETER;
CM_ASSERTMESSAGE("Memory allocation failed in ExecuteHints Task");
goto finish;
}
// check hints to see if need to split into multiple tasks
numTasks = ( execHintsParam->hints & CM_HINTS_MASK_NUM_TASKS ) >> CM_HINTS_NUM_BITS_TASK_POS;
if( numTasks > 1 )
{
splitTask = true;
}
MOS_FillMemory(bindingTableEntries, sizeof(int) * execHintsParam->numKernels, CM_INVALID_INDEX);
MOS_FillMemory(mediaIds, sizeof(int) * execHintsParam->numKernels, CM_INVALID_INDEX);
MOS_FillMemory(krnAllocations, sizeof(void *)* execHintsParam->numKernels, 0);
// Reset states before execute
// (clear allocations, get GSH allocation index + any additional housekeeping)
state->osInterface->pfnResetOsStates(state->osInterface);
CM_CHK_MOSSTATUS_GOTOFINISH(renderHal->pfnReset(renderHal));
MOS_ZeroMemory(state->taskParam, sizeof(CM_HAL_TASK_PARAM));
MOS_FillMemory(
state->bti2DIndexTable,
state->cmDeviceParam.max2DSurfaceTableSize * sizeof( CM_HAL_MULTI_USE_BTI_ENTRY ),
CM_INVALID_INDEX );
MOS_FillMemory(
state->bti2DUPIndexTable,
state->cmDeviceParam.max2DSurfaceUPTableSize * sizeof( CM_HAL_MULTI_USE_BTI_ENTRY ),
CM_INVALID_INDEX );
MOS_FillMemory(
state->bti3DIndexTable,
state->cmDeviceParam.max3DSurfaceTableSize * sizeof( CM_HAL_MULTI_USE_BTI_ENTRY ),
CM_INVALID_INDEX );
MOS_FillMemory(
state->btiBufferIndexTable,
state->cmDeviceParam.maxBufferTableSize * sizeof( CM_HAL_MULTI_USE_BTI_ENTRY ),
CM_INVALID_INDEX );
MOS_FillMemory(
state->samplerIndexTable,
state->cmDeviceParam.maxSamplerTableSize,
CM_INVALID_INDEX);
MOS_FillMemory(
state->sampler8x8IndexTable,
state->cmDeviceParam.maxSampler8x8TableSize,
CM_INVALID_INDEX);
state->walkerParams.CmWalkerEnable = 0;
vfeCurbeSize = 0;
maxInlineDataSize = 0;
maxIndirectDataSize = 0;
MOS_ZeroMemory(&origKernelIds, CM_MAX_KERNELS_PER_TASK * sizeof(uint64_t));
// Get the Task Id
CM_CHK_MOSSTATUS_GOTOFINISH(HalCm_GetNewTaskId(state, &taskId));
// Parse the task
CM_CHK_MOSSTATUS_GOTOFINISH(HalCm_ParseHintsTask(state, execHintsParam));
// Assign a MediaState from the MediaStateHeap
// !!!! THIS MUST BE BEFORE Getting the BATCH_BUFFER !!!
// since this method syncs the batch buffer and media state.
if (state->dshEnabled)
{
if ( execHintsParam->userDefinedMediaState != nullptr )
{
// use exsiting media state as current state
mediaState = static_cast< PRENDERHAL_MEDIA_STATE >( execHintsParam->userDefinedMediaState );
// update current state to dsh
renderHal->pStateHeap->pCurMediaState = mediaState;
// Refresh sync tag for all media states in submitted queue
state->criticalSectionDSH->Acquire();
renderHal->pfnRefreshSync( renderHal );
state->criticalSectionDSH->Release();
}
else
{
// Obtain media state configuration - Curbe, Samplers (3d/AVS/VA), 8x8 sampler table, Media IDs, Kernel Spill area
RENDERHAL_DYNAMIC_MEDIA_STATE_PARAMS params;
state->criticalSectionDSH->Acquire();
HalCm_DSH_GetDynamicStateConfiguration(state, ¶ms, execHintsParam->numKernels, execHintsParam->kernels, execHintsParam->kernelCurbeOffset);
// Prepare Media States to accommodate all parameters - Curbe, Samplers (3d/AVS/VA), 8x8 sampler table, Media IDs
mediaState = renderHal->pfnAssignDynamicState(renderHal, ¶ms, RENDERHAL_COMPONENT_CM);
state->criticalSectionDSH->Release();
}
}
else
{
mediaState = renderHal->pfnAssignMediaState(renderHal, RENDERHAL_COMPONENT_CM);
}
CM_CHK_NULL_GOTOFINISH_MOSERROR(mediaState);
if (state->useNewSamplerHeap == false)
{
HalCm_AcquireSamplerStatistics(state);
}
// Assign/Reset SSH instance
CM_CHK_MOSSTATUS_GOTOFINISH(renderHal->pfnAssignSshInstance(renderHal));
if (!state->walkerParams.CmWalkerEnable)
{
if( splitTask )
{
// save original kernel IDs for kernel binary re-use in GSH
for( i = 0; i < execHintsParam->numKernels; ++i )
{
origKernelIds[i] = execHintsParam->kernels[i]->kernelId;
}
// need to add tag to kernel IDs to distinguish batch buffer
CM_CHK_MOSSTATUS_GOTOFINISH(HalCm_AddKernelIDTag(execHintsParam->kernels, execHintsParam->numKernels, numTasks, execHintsParam->numTasksGenerated));
}
// Get the Batch buffer
CM_CHK_MOSSTATUS_GOTOFINISH(HalCm_GetBatchBuffer(state, execHintsParam->numKernels, execHintsParam->kernels, &batchBuffer));
if( splitTask )
{
// restore kernel IDs for kernel binary re-use in GSH
for( i = 0; i < execHintsParam->numKernels; ++i )
{
execHintsParam->kernels[i]->kernelId = origKernelIds[i];
}
}
// Lock the batch buffer
CM_CHK_NULL_GOTOFINISH_MOSERROR(batchBuffer->pPrivateData);
bbCmArgs = (PCM_HAL_BB_ARGS)batchBuffer->pPrivateData;
if ( (bbCmArgs->refCount == 1) ||
( state->taskParam->reuseBBUpdateMask == 1) )
{
CM_CHK_MOSSTATUS_GOTOFINISH(renderHal->pfnLockBB(renderHal, batchBuffer));
}
}
// Load all kernels in the same state heap - expand ISH if necessary BEFORE programming media states.
// This is better than having to expand ISH in the middle of loading, when part of MediaIDs are
// already programmed - not a problem in the old implementation where it would simply remove old
// kernels out of the way.
if (state->dshEnabled)
{
CM_CHK_MOSSTATUS_GOTOFINISH(HalCm_DSH_LoadKernelArray(state, execHintsParam->kernels, execHintsParam->numKernels, krnAllocations));
}
// 0: media walker
// 1: media object
if( (execHintsParam->hints & CM_HINTS_MASK_MEDIAOBJECT) == CM_HINTS_MASK_MEDIAOBJECT )
{
for (i = 0; i < execHintsParam->numKernels; ++i)
{
CM_CHK_MOSSTATUS_GOTOFINISH(HalCm_SetupStatesForKernelInitial(state, mediaState, batchBuffer, taskId, execHintsParam->kernels[i], &indexParams[i],
execHintsParam->kernelCurbeOffset[i], bindingTableEntries[i], mediaIds[i], krnAllocations[i]));
}
CM_CHK_NULL_GOTOFINISH_MOSERROR(batchBuffer);
CM_CHK_MOSSTATUS_GOTOFINISH(HalCm_FinishStatesForKernelMix(state, batchBuffer, taskId, execHintsParam->kernels,
indexParams, bindingTableEntries, mediaIds, krnAllocations, execHintsParam->numKernels, execHintsParam->hints, execHintsParam->isLastTask));
for( i = 0; i < execHintsParam->numKernels; ++i)
{
kernelParam = execHintsParam->kernels[i];
vfeCurbeSize += MOS_ALIGN_CEIL(kernelParam->totalCurbeSize, state->renderHal->dwCurbeBlockAlign);
if( kernelParam->payloadSize > maxInlineDataSize)
{
maxInlineDataSize = kernelParam->payloadSize;
}
if( kernelParam->indirectDataParam.indirectDataSize > maxIndirectDataSize )
{
maxIndirectDataSize = kernelParam->indirectDataParam.indirectDataSize;
}
}
// Store the Max Payload Sizes in the Task Param
state->taskParam->vfeCurbeSize = vfeCurbeSize;
if( maxIndirectDataSize)
{
state->taskParam->vfeCurbeSize = maxIndirectDataSize;
}
else
{
state->taskParam->urbEntrySize = maxInlineDataSize;
}
// We may have to send additional Binding table commands in command buffer.
// This is needed because the surface offset (from the base on SSH)
// calculation takes into account the max binding tables allocated in the
// SSH.
remBindingTables = state->cmDeviceParam.maxKernelsPerTask -
execHintsParam->numKernels;
if( remBindingTables > 0)
{
for( i = 0; i < (uint32_t)remBindingTables; ++i)
{
CM_CHK_MOSSTATUS_GOTOFINISH(renderHal->pfnAssignBindingTable(
renderHal,
&bindingTable));
}
}
osInterface = state->osInterface;
osInterface->pfnResetPerfBufferID(osInterface);
if (osInterface->pfnIsPerfTagSet(osInterface) == false)
{
osInterface->pfnIncPerfFrameID(osInterface);
int perfTag = HalCm_GetKernelPerfTag(state, execHintsParam->kernels, execHintsParam->numKernels);
osInterface->pfnSetPerfTag(osInterface, (uint16_t)perfTag);
}
// Submit HW commands and states
CM_CHK_MOSSTATUS_GOTOFINISH(state->cmHalInterface->SubmitCommands(
batchBuffer, taskId, execHintsParam->kernels, &cmdBuffer));
// Set the Task ID
execHintsParam->taskIdOut = taskId;
// Set OS data
if( cmdBuffer )
{
execHintsParam->osData = cmdBuffer;
}
// Update the task ID table
state->taskStatusTable[taskId] = (char)taskId;
}
else
{
// use media walker
// unimplemented for now
CM_ASSERTMESSAGE("Error: Media walker is not supported.");
eStatus = MOS_STATUS_UNKNOWN;
}
finish:
if (state->dshEnabled)
{
state->criticalSectionDSH->Acquire();
if (mediaState && eStatus != MOS_STATUS_SUCCESS)
{
// Failed, release media state and heap resources
renderHal->pfnReleaseDynamicState(renderHal, mediaState);
}
else
{
renderHal->pfnSubmitDynamicState(renderHal, mediaState);
}
state->criticalSectionDSH->Release();
}
if (batchBuffer) // for MediaWalker, batchBuffer is empty
{
if (batchBuffer->bLocked)
{
// Only happens in Error cases
CM_CHK_NULL_RETURN_MOSERROR(batchBuffer->pPrivateData);
if (((PCM_HAL_BB_ARGS)batchBuffer->pPrivateData)->refCount == 1)
{
renderHal->pfnUnlockBB(renderHal, batchBuffer);
}
}
}
// free memory
if( bindingTableEntries ) MOS_FreeMemory(bindingTableEntries);
if( mediaIds ) MOS_FreeMemory(mediaIds);
if( krnAllocations ) MOS_FreeMemory(krnAllocations);
if( indexParams ) MOS_FreeMemory( indexParams );
return eStatus;
}
//*-----------------------------------------------------------------------------
//| Purpose: Send Commands to HW
//| Returns: Get the HAL Max values
//*-----------------------------------------------------------------------------
MOS_STATUS HalCm_GetMaxValues(
PCM_HAL_STATE state, // [in] Pointer to CM State
PCM_HAL_MAX_VALUES maxValues) // [out] Pointer to Max values
{
PRENDERHAL_INTERFACE renderHal;
renderHal = state->renderHal;
maxValues->maxTasks = state->cmDeviceParam.maxTasks;
maxValues->maxKernelsPerTask = CM_MAX_KERNELS_PER_TASK;
maxValues->maxKernelBinarySize = state->cmDeviceParam.maxKernelBinarySize;
maxValues->maxSpillSizePerHwThread = state->cmDeviceParam.maxPerThreadScratchSpaceSize;
maxValues->maxSamplerTableSize = CM_MAX_SAMPLER_TABLE_SIZE;
maxValues->maxBufferTableSize = CM_MAX_BUFFER_SURFACE_TABLE_SIZE;
maxValues->max2DSurfaceTableSize = CM_MAX_2D_SURFACE_TABLE_SIZE;
maxValues->max3DSurfaceTableSize = CM_MAX_3D_SURFACE_TABLE_SIZE;
maxValues->maxArgsPerKernel = CM_MAX_ARGS_PER_KERNEL;
maxValues->maxUserThreadsPerTask = CM_MAX_USER_THREADS;
maxValues->maxUserThreadsPerTaskNoThreadArg = CM_MAX_USER_THREADS_NO_THREADARG;
maxValues->maxArgByteSizePerKernel = CM_MAX_ARG_BYTE_PER_KERNEL;
maxValues->maxSurfacesPerKernel = renderHal->pHwCaps->dwMaxBTIndex;
maxValues->maxSamplersPerKernel = renderHal->pHwCaps->dwMaxUnormSamplers;
maxValues->maxHwThreads = renderHal->pHwCaps->dwMaxThreads;
return MOS_STATUS_SUCCESS;
}
//*-----------------------------------------------------------------------------
//| Purpose: Get the HAL Max extended values
//| Returns: Get the HAL Max extended values
//*-----------------------------------------------------------------------------
MOS_STATUS HalCm_GetMaxValuesEx(
PCM_HAL_STATE state, // [in] Pointer to CM State
PCM_HAL_MAX_VALUES_EX maxValuesEx) // [out] Pointer to extended Max values
{
MOS_STATUS eStatus = MOS_STATUS_SUCCESS;
maxValuesEx->max2DUPSurfaceTableSize = CM_MAX_2D_SURFACE_UP_TABLE_SIZE;
maxValuesEx->maxSampler8x8TableSize = CM_MAX_SAMPLER_8X8_TABLE_SIZE;
maxValuesEx->maxCURBESizePerKernel = CM_MAX_CURBE_SIZE_PER_KERNEL;
maxValuesEx->maxCURBESizePerTask = CM_MAX_CURBE_SIZE_PER_TASK;
maxValuesEx->maxIndirectDataSizePerKernel = CM_MAX_INDIRECT_DATA_SIZE_PER_KERNEL;
//MaxThreadWidth x MaxThreadHeight x ColorCount
maxValuesEx->maxUserThreadsPerMediaWalker = \
state->cmHalInterface->GetMediaWalkerMaxThreadWidth()* \
state->cmHalInterface->GetMediaWalkerMaxThreadHeight() * \
CM_THREADSPACE_MAX_COLOR_COUNT;
CM_CHK_MOSSTATUS_GOTOFINISH(HalCm_GetMaxThreadCountPerThreadGroup( state, &maxValuesEx->maxUserThreadsPerThreadGroup ) );
finish:
return eStatus;
}
//*-----------------------------------------------------------------------------
//| Purpose: Register Sampler
//| Returns: Result of the operation.
//*-----------------------------------------------------------------------------
MOS_STATUS HalCm_RegisterSampler(
PCM_HAL_STATE state, // [in] Pointer to CM State
PCM_HAL_SAMPLER_PARAM param) // [in] Pointer to Sampler Param
{
MOS_STATUS eStatus;
PMHW_SAMPLER_STATE_PARAM entry;
uint32_t i;
eStatus = MOS_STATUS_SUCCESS;
entry = nullptr;
// Find a free slot
for (i = 0; i < state->cmDeviceParam.maxSamplerTableSize; i++)
{
if (!state->samplerTable[i].bInUse)
{
entry = &state->samplerTable[i];
param->handle = (uint32_t)i;
break;
}
}
if (!entry)
{
eStatus = MOS_STATUS_INVALID_PARAMETER;
CM_ASSERTMESSAGE("Sampler table is full");
goto finish;
}
entry->SamplerType = MHW_SAMPLER_TYPE_3D;
if (state->useNewSamplerHeap == true)
{
entry->ElementType = MHW_Sampler1Element;
}
else
{
entry->ElementType = MHW_Sampler4Elements;
}
CM_CHK_MOSSTATUS_GOTOFINISH(HalCm_GetGfxMapFilter(param->minFilter, &entry->Unorm.MinFilter));
CM_CHK_MOSSTATUS_GOTOFINISH(HalCm_GetGfxMapFilter(param->magFilter, &entry->Unorm.MagFilter));
CM_CHK_MOSSTATUS_GOTOFINISH(HalCm_GetGfxTextAddress(param->addressU, &entry->Unorm.AddressU));
CM_CHK_MOSSTATUS_GOTOFINISH(HalCm_GetGfxTextAddress(param->addressV, &entry->Unorm.AddressV));
CM_CHK_MOSSTATUS_GOTOFINISH(HalCm_GetGfxTextAddress(param->addressW, &entry->Unorm.AddressW));
entry->Unorm.SurfaceFormat = (MHW_SAMPLER_SURFACE_PIXEL_TYPE)param->surfaceFormat;
switch (entry->Unorm.SurfaceFormat)
{
case MHW_SAMPLER_SURFACE_PIXEL_UINT:
entry->Unorm.BorderColorRedU = param->borderColorRedU;
entry->Unorm.BorderColorGreenU = param->borderColorGreenU;
entry->Unorm.BorderColorBlueU = param->borderColorBlueU;
entry->Unorm.BorderColorAlphaU = param->borderColorAlphaU;
break;
case MHW_SAMPLER_SURFACE_PIXEL_SINT:
entry->Unorm.BorderColorRedS = param->borderColorRedS;
entry->Unorm.BorderColorGreenS = param->borderColorGreenS;
entry->Unorm.BorderColorBlueS = param->borderColorBlueS;
entry->Unorm.BorderColorAlphaS = param->borderColorAlphaS;
break;
default:
entry->Unorm.BorderColorRedF = param->borderColorRedF;
entry->Unorm.BorderColorGreenF = param->borderColorGreenF;
entry->Unorm.BorderColorBlueF = param->borderColorBlueF;
entry->Unorm.BorderColorAlphaF = param->borderColorAlphaF;
}
entry->Unorm.bBorderColorIsValid = true;
entry->bInUse = true;
finish:
return eStatus;
}
//*-----------------------------------------------------------------------------
//| Purpose: UnRegister Sampler
//| Returns: Result of the operation.
//*-----------------------------------------------------------------------------
MOS_STATUS HalCm_UnRegisterSampler(
PCM_HAL_STATE state, // [in] Pointer to CM State
uint32_t handle) // [in] Pointer to Sampler Param
{
MOS_STATUS eStatus;
PMHW_SAMPLER_STATE_PARAM entry;
eStatus = MOS_STATUS_SUCCESS;
if (handle >= state->cmDeviceParam.maxSamplerTableSize)
{
eStatus = MOS_STATUS_INVALID_HANDLE;
CM_ASSERTMESSAGE("Invalid handle '%d'", handle);
goto finish;
}
entry = &state->samplerTable[handle];
// need to clear the state entirely instead of just setting bInUse to false
MOS_ZeroMemory(entry, sizeof(MHW_SAMPLER_STATE_PARAM));
finish:
return eStatus;
}
//*-----------------------------------------------------------------------------
//| Purpose: Register Sampler8x8
//| Returns: Result of the operation.
//*-----------------------------------------------------------------------------
MOS_STATUS HalCm_RegisterSampler8x8(
PCM_HAL_STATE state,
PCM_HAL_SAMPLER_8X8_PARAM param)
{
return state->cmHalInterface->RegisterSampler8x8(param);
}
//*-----------------------------------------------------------------------------
//| Purpose: UnRegister Sampler
//| Returns: Result of the operation.
//*-----------------------------------------------------------------------------
MOS_STATUS HalCm_UnRegisterSampler8x8(
PCM_HAL_STATE state, // [in] Pointer to CM State
uint32_t handle) // [in] Pointer to Sampler8x8 Param
{
MOS_STATUS eStatus;
uint32_t index8x8;
PMHW_SAMPLER_STATE_PARAM entry;
PCM_HAL_SAMPLER_8X8_ENTRY sampler8x8Entry;
eStatus = MOS_STATUS_SUCCESS;
if (handle >= state->cmDeviceParam.maxSamplerTableSize) {
eStatus = MOS_STATUS_INVALID_HANDLE;
CM_ASSERTMESSAGE("Invalid handle '%d'", handle);
goto finish;
}
entry = &state->samplerTable[handle];
entry->bInUse = false;
if ( entry->SamplerType == MHW_SAMPLER_TYPE_AVS )
{
index8x8 = entry->Avs.stateID;
if ( index8x8 >= state->cmDeviceParam.maxSampler8x8TableSize )
{
eStatus = MOS_STATUS_INVALID_HANDLE;
CM_ASSERTMESSAGE( "Invalid 8x8 handle '%d'", handle );
goto finish;
}
sampler8x8Entry = &state->sampler8x8Table[ index8x8 ];
sampler8x8Entry->inUse = false;
}
// need to clear the state entirely instead of just setting bInUse to false
MOS_ZeroMemory(entry, sizeof(MHW_SAMPLER_STATE_PARAM));
finish:
return eStatus;
}
//*-----------------------------------------------------------------------------
//| Purpose: Frees the buffer and removes from the table
//| Returns: Result of the operation.
//*-----------------------------------------------------------------------------
MOS_STATUS HalCm_FreeBuffer(
PCM_HAL_STATE state, // [in] Pointer to CM State
uint32_t handle) // [in] Pointer to Buffer Param
{
MOS_STATUS eStatus;
PCM_HAL_BUFFER_ENTRY entry;
PMOS_INTERFACE osInterface;
eStatus = MOS_STATUS_SUCCESS;
osInterface = state->osInterface;
// Get the Buffer Entry
CM_CHK_MOSSTATUS_GOTOFINISH(HalCm_GetBufferEntry(state, handle, &entry));
if (state->advExecutor)
{
state->advExecutor->DeleteBufferStateMgr(entry->surfStateMgr);
}
if (entry->isAllocatedbyCmrtUmd)
{
osInterface->pfnFreeResourceWithFlag(osInterface, &entry->osResource, SURFACE_FLAG_ASSUME_NOT_IN_USE);
}
else
{
HalCm_OsResource_Unreference(&entry->osResource);
}
osInterface->pfnResetResourceAllocationIndex(osInterface, &entry->osResource);
entry->size = 0;
entry->address = nullptr;
finish:
return eStatus;
}
//*-----------------------------------------------------------------------------
//| Purpose: Set surface read flag used in on demand sync
//| Returns: Result of the operation.
//*-----------------------------------------------------------------------------
MOS_STATUS HalCm_SetSurfaceReadFlag(
PCM_HAL_STATE state, // [in] Pointer to CM State
uint32_t handle, // [in] index of surface 2d
bool readSync,
MOS_GPU_CONTEXT gpuContext)
{
MOS_STATUS eStatus = MOS_STATUS_SUCCESS;
PCM_HAL_SURFACE2D_ENTRY entry;
// Get the Buffer Entry
CM_CHK_MOSSTATUS_GOTOFINISH(HalCm_GetSurface2DEntry(state, handle, &entry));
if (HalCm_IsValidGpuContext(gpuContext))
{
entry->readSyncs[gpuContext] = readSync;
state->advExecutor->Set2DRenderTarget(entry->surfStateMgr, !readSync);
}
else
{
return MOS_STATUS_UNKNOWN;
}
finish:
return eStatus;
}
//*-----------------------------------------------------------------------------
//| Purpose: Read the data from buffer and return
//| Returns: Result of the operation.
//*-----------------------------------------------------------------------------
MOS_STATUS HalCm_LockBuffer(
PCM_HAL_STATE state, // [in] Pointer to CM State
PCM_HAL_BUFFER_PARAM param) // [in] Pointer to Buffer Param
{
MOS_STATUS eStatus;
PCM_HAL_BUFFER_ENTRY entry;
PMOS_INTERFACE osInterface;
MOS_LOCK_PARAMS lockFlags;
eStatus = MOS_STATUS_SUCCESS;
osInterface = state->osInterface;
CM_CHK_MOSSTATUS_GOTOFINISH(HalCm_GetBufferEntry(state, param->handle, &entry));
if ((param->lockFlag != CM_HAL_LOCKFLAG_READONLY) && (param->lockFlag != CM_HAL_LOCKFLAG_WRITEONLY) )
{
eStatus = MOS_STATUS_INVALID_HANDLE;
CM_ASSERTMESSAGE("Invalid lock flag!");
eStatus = MOS_STATUS_UNKNOWN;
goto finish;
}
// Lock the resource
MOS_ZeroMemory(&lockFlags, sizeof(MOS_LOCK_PARAMS));
if (param->lockFlag == CM_HAL_LOCKFLAG_READONLY)
{
lockFlags.ReadOnly = true;
}
else
{
lockFlags.WriteOnly = true;
}
lockFlags.ForceCached = true;
param->data = osInterface->pfnLockResource(
osInterface,
&entry->osResource,
&lockFlags);
CM_CHK_NULL_GOTOFINISH_MOSERROR(param->data);
finish:
return eStatus;
}
//*-----------------------------------------------------------------------------
//| Purpose: Writes the data to buffer
//| Returns: Result of the operation.
//*-----------------------------------------------------------------------------
MOS_STATUS HalCm_UnlockBuffer(
PCM_HAL_STATE state, // [in] Pointer to CM State
PCM_HAL_BUFFER_PARAM param) // [in] Pointer to Buffer Param
{
MOS_STATUS eStatus;
PCM_HAL_BUFFER_ENTRY entry;
PMOS_INTERFACE osInterface;
eStatus = MOS_STATUS_SUCCESS;
osInterface = state->osInterface;
CM_CHK_MOSSTATUS_GOTOFINISH(HalCm_GetBufferEntry(state, param->handle, &entry));
CM_CHK_HRESULT_GOTOFINISH_MOSERROR(osInterface->pfnUnlockResource(osInterface, &entry->osResource));
finish:
return eStatus;
}
//*-----------------------------------------------------------------------------
//| Purpose: Frees the buffer and removes from the table
//| Returns: Result of the operation.
//*-----------------------------------------------------------------------------
MOS_STATUS HalCm_FreeSurface2DUP(
PCM_HAL_STATE state, // [in] Pointer to CM State
uint32_t handle) // [in] Pointer to Buffer Param
{
MOS_STATUS eStatus;
PCM_HAL_SURFACE2D_UP_ENTRY entry;
PMOS_INTERFACE osInterface;
eStatus = MOS_STATUS_SUCCESS;
osInterface = state->osInterface;
// Get the Buffer Entry
CM_CHK_MOSSTATUS_GOTOFINISH(HalCm_GetResourceUPEntry(state, handle, &entry));
if (state->advExecutor)
{
state->advExecutor->Delete2DStateMgr(entry->surfStateMgr);
}
osInterface->pfnFreeResourceWithFlag(osInterface, &entry->osResource, SURFACE_FLAG_ASSUME_NOT_IN_USE);
osInterface->pfnResetResourceAllocationIndex(osInterface, &entry->osResource);
entry->width = 0;
finish:
return eStatus;
}
//*-----------------------------------------------------------------------------
//| Purpose: Get 2D surface pitch and physical size
//| Returns: Result of the operation.
//*-----------------------------------------------------------------------------
MOS_STATUS HalCm_GetSurface2DTileYPitch(
PCM_HAL_STATE state, // [in] Pointer to CM State
PCM_HAL_SURFACE2D_PARAM param) // [in] Pointer to Buffer Param
{
MOS_STATUS eStatus;
MOS_SURFACE surface;
PRENDERHAL_INTERFACE renderHal;
uint32_t index;
RENDERHAL_GET_SURFACE_INFO info;
//-----------------------------------------------
CM_ASSERT(state);
//-----------------------------------------------
eStatus = MOS_STATUS_UNKNOWN;
renderHal = state->renderHal;
index = param->handle;
// Get Details of 2D surface and fill the surface
MOS_ZeroMemory(&surface, sizeof(surface));
surface.OsResource = state->umdSurf2DTable[index].osResource;
surface.dwWidth = state->umdSurf2DTable[index].width;
surface.dwHeight = state->umdSurf2DTable[index].height;
surface.Format = state->umdSurf2DTable[index].format;
surface.dwDepth = 1;
MOS_ZeroMemory(&info, sizeof(RENDERHAL_GET_SURFACE_INFO));
CM_CHK_MOSSTATUS_GOTOFINISH(RenderHal_GetSurfaceInfo(
state->osInterface,
&info,
&surface));
param->pitch = surface.dwPitch;
finish:
return eStatus;
}
//*-----------------------------------------------------------------------------
//| Purpose: Sets width and height values for 2D surface state
//| Returns: Result of the operation.
//*-----------------------------------------------------------------------------
MOS_STATUS HalCm_Set2DSurfaceStateParam(
PCM_HAL_STATE state,
PCM_HAL_SURFACE2D_SURFACE_STATE_PARAM param,
uint32_t aliasIndex,
uint32_t handle)
{
MOS_STATUS eStatus;
uint32_t width;
uint32_t height;
CM_CHK_NULL_GOTOFINISH_MOSERROR(state);
CM_CHK_NULL_GOTOFINISH_MOSERROR(param);
eStatus = MOS_STATUS_SUCCESS;
if (aliasIndex < state->surfaceArraySize)
{
state->umdSurf2DTable[handle].surfStateSet = true;
}
state->umdSurf2DTable[handle].surfaceStateParam[aliasIndex / state->surfaceArraySize] = *param;
finish:
return eStatus;
}
//*-----------------------------------------------------------------------------
//| Purpose: Sets width and height values for 2D surface state
//| Returns: Result of the operation.
//*-----------------------------------------------------------------------------
MOS_STATUS HalCm_SetBufferSurfaceStateParameters(
PCM_HAL_STATE state,
PCM_HAL_BUFFER_SURFACE_STATE_PARAM param)
{
MOS_STATUS eStatus;
uint32_t size;
uint32_t offset;
uint32_t index;
uint32_t aliasIndex;
CM_CHK_NULL_GOTOFINISH_MOSERROR(state);
CM_CHK_NULL_GOTOFINISH_MOSERROR(param);
eStatus = MOS_STATUS_SUCCESS;
index = param->handle;
aliasIndex = param->aliasIndex;
if (aliasIndex < state->surfaceArraySize)
state->bufferTable[index].surfStateSet = true;
state->bufferTable[index].surfaceStateEntry[aliasIndex / state->surfaceArraySize].surfaceStateSize = param->size;
state->bufferTable[index].surfaceStateEntry[aliasIndex / state->surfaceArraySize].surfaceStateOffset = param->offset;
state->bufferTable[index].surfaceStateEntry[aliasIndex / state->surfaceArraySize].surfaceStateMOCS = param->mocs;
finish:
return eStatus;
}
//*-----------------------------------------------------------------------------
//| Purpose: Sets mocs value for surface
//| Returns: Result of the operation.
//*-----------------------------------------------------------------------------
MOS_STATUS HalCm_SetSurfaceMOCS(
PCM_HAL_STATE state,
uint32_t handle,
uint16_t mocs,
uint32_t argKind)
{
MOS_STATUS eStatus = MOS_STATUS_SUCCESS;
switch (argKind)
{
case CM_ARGUMENT_SURFACEBUFFER:
state->bufferTable[handle].memObjCtl = mocs;
state->advExecutor->SetBufferMemoryObjectControl(state->bufferTable[handle].surfStateMgr, mocs);
break;
case CM_ARGUMENT_SURFACE2D:
case CM_ARGUMENT_SURFACE2D_SAMPLER:
case CM_ARGUMENT_SURFACE_SAMPLER8X8_AVS:
case CM_ARGUMENT_SURFACE_SAMPLER8X8_VA:
state->umdSurf2DTable[handle].memObjCtl = mocs;
state->advExecutor->Set2DMemoryObjectControl(state->umdSurf2DTable[handle].surfStateMgr, mocs);
break;
case CM_ARGUMENT_SURFACE2D_UP:
case CM_ARGUMENT_SURFACE2DUP_SAMPLER:
state->surf2DUPTable[handle].memObjCtl = mocs;
state->advExecutor->Set2DMemoryObjectControl(state->surf2DUPTable[handle].surfStateMgr, mocs);
break;
case CM_ARGUMENT_SURFACE3D:
state->surf3DTable[handle].memObjCtl = mocs;
break;
default:
eStatus = MOS_STATUS_INVALID_PARAMETER;
CM_ASSERTMESSAGE("Invalid argument type in MOCS settings");
goto finish;
}
finish:
return eStatus;
}
//*-----------------------------------------------------------------------------
//| Purpose: Allocate surface 2D
//| Returns: Result of the operation.
//*-----------------------------------------------------------------------------
MOS_STATUS HalCm_AllocateSurface2D(
PCM_HAL_STATE state, // [in] Pointer to CM State
PCM_HAL_SURFACE2D_PARAM param) // [in] Pointer to surface 2D Param
{
MOS_STATUS eStatus;
PMOS_INTERFACE osInterface;
PCM_HAL_SURFACE2D_ENTRY entry = nullptr;
MOS_ALLOC_GFXRES_PARAMS allocParams;
uint32_t i;
//-----------------------------------------------
CM_ASSERT(param->width > 0);
//-----------------------------------------------
eStatus = MOS_STATUS_SUCCESS;
osInterface = state->osInterface;
// Find a free slot
for (i = 0; i < state->cmDeviceParam.max2DSurfaceTableSize; i++)
{
if(Mos_ResourceIsNull(&state->umdSurf2DTable[i].osResource))
{
entry = &state->umdSurf2DTable[i];
param->handle = (uint32_t)i;
break;
}
}
if (!entry)
{
eStatus = MOS_STATUS_INVALID_PARAMETER;
CM_ASSERTMESSAGE("Surface2D table is full");
goto finish;
}
if(param->isAllocatedbyCmrtUmd)
{
MOS_ZeroMemory(&allocParams, sizeof(MOS_ALLOC_GFXRES_PARAMS));
allocParams.Type = MOS_GFXRES_2D;
allocParams.dwWidth = param->width;
allocParams.dwHeight = param->height;
allocParams.pSystemMemory = param->data;
allocParams.Format = param->format;
allocParams.TileType = MOS_TILE_Y;
allocParams.pBufName = "CmSurface2D";
CM_CHK_HRESULT_GOTOFINISH_MOSERROR(osInterface->pfnAllocateResource(
osInterface,
&allocParams,
&entry->osResource));
entry->width = param->width;
entry->height = param->height;
entry->format = param->format;
entry->isAllocatedbyCmrtUmd = param->isAllocatedbyCmrtUmd;
}
else
{
entry->width = param->width;
entry->height = param->height;
entry->format = param->format;
entry->isAllocatedbyCmrtUmd = false;
entry->osResource = *param->mosResource;
HalCm_OsResource_Reference(&entry->osResource);
}
if (state->advExecutor)
{
entry->surfStateMgr = state->advExecutor->Create2DStateMgr(&entry->osResource);
}
for (int i = 0; i < CM_HAL_GPU_CONTEXT_COUNT; i++)
{
entry->readSyncs[i] = false;
}
finish:
return eStatus;
}
//*-----------------------------------------------------------------------------
//| Purpose: Allocate surface 2D
//| Returns: Result of the operation.
//*-----------------------------------------------------------------------------
MOS_STATUS HalCm_UpdateSurface2D(
PCM_HAL_STATE state, // [in] Pointer to CM State
PCM_HAL_SURFACE2D_PARAM param) // [in] Pointer to surface 2D Param
{
MOS_STATUS hr;
PMOS_INTERFACE osInterface;
PCM_HAL_SURFACE2D_ENTRY entry = nullptr;
MOS_ALLOC_GFXRES_PARAMS allocParams;
uint32_t i = param->handle;
//-----------------------------------------------
CM_ASSERT(param->width > 0);
//-----------------------------------------------
hr = MOS_STATUS_SUCCESS;
osInterface = state->osInterface;
entry = &state->umdSurf2DTable[i];
HalCm_OsResource_Unreference(&entry->osResource);
entry->width = param->width;
entry->height = param->height;
entry->format = param->format;
entry->isAllocatedbyCmrtUmd = false;
entry->osResource = *param->mosResource;
HalCm_OsResource_Reference(&entry->osResource);
if (state->advExecutor)
{
state->advExecutor->Delete2DStateMgr(entry->surfStateMgr);
entry->surfStateMgr = state->advExecutor->Create2DStateMgr(&entry->osResource);
}
for (int i = 0; i < CM_HAL_GPU_CONTEXT_COUNT; i++)
{
entry->readSyncs[i] = false;
}
return hr;
}
//*-----------------------------------------------------------------------------
//| Purpose: Allocate Linear Buffer or BufferUP
//| Returns: Result of the operation.
//*-----------------------------------------------------------------------------
MOS_STATUS HalCm_UpdateBuffer(
PCM_HAL_STATE state, // [in] Pointer to CM State
PCM_HAL_BUFFER_PARAM param) // [in] Pointer to Buffer Param
{
MOS_STATUS hr;
PMOS_INTERFACE osInterface;
PCM_HAL_BUFFER_ENTRY entry = nullptr;
MOS_ALLOC_GFXRES_PARAMS allocParams;
uint32_t i = param->handle;
PMOS_RESOURCE osResource;
//-----------------------------------------------
CM_ASSERT(param->size > 0);
//-----------------------------------------------
hr = MOS_STATUS_SUCCESS;
osInterface = state->renderHal->pOsInterface;
entry = &state->bufferTable[i];
HalCm_OsResource_Unreference(&entry->osResource);
entry->osResource = *param->mosResource;
HalCm_OsResource_Reference(&entry->osResource);
entry->size = param->size;
entry->isAllocatedbyCmrtUmd = false;
entry->surfaceStateEntry[0].surfaceStateSize = entry->size;
entry->surfaceStateEntry[0].surfaceStateOffset = 0;
entry->surfaceStateEntry[0].surfaceStateMOCS = 0;
if (state->advExecutor)
{
state->advExecutor->DeleteBufferStateMgr(entry->surfStateMgr);
entry->surfStateMgr = state->advExecutor->CreateBufferStateMgr(&entry->osResource);
state->advExecutor->SetBufferOrigSize(entry->surfStateMgr, entry->size);
}
return hr;
}
//*-----------------------------------------------------------------------------
//| Purpose: Frees the surface 2D and removes from the table
//| Returns: Result of the operation.
//*-----------------------------------------------------------------------------
MOS_STATUS HalCm_FreeSurface2D(
PCM_HAL_STATE state, // [in] Pointer to CM State
uint32_t handle) // [in] Pointer to Buffer Param
{
MOS_STATUS eStatus;
PCM_HAL_SURFACE2D_ENTRY entry;
PMOS_INTERFACE osInterface;
eStatus = MOS_STATUS_SUCCESS;
osInterface = state->osInterface;
// Get the Buffer Entry
CM_CHK_MOSSTATUS_GOTOFINISH(HalCm_GetSurface2DEntry(state, handle, &entry));
if (state->advExecutor)
{
state->advExecutor->Delete2DStateMgr(entry->surfStateMgr);
}
if(entry->isAllocatedbyCmrtUmd)
{
osInterface->pfnFreeResourceWithFlag(osInterface, &entry->osResource, SURFACE_FLAG_ASSUME_NOT_IN_USE);
}
else
{
HalCm_OsResource_Unreference(&entry->osResource);
}
MOS_ZeroMemory(&entry->osResource, sizeof(entry->osResource));
entry->width = 0;
entry->height = 0;
entry->frameType = CM_FRAME;
for (int i = 0; i < CM_HAL_GPU_CONTEXT_COUNT; i++)
{
entry->readSyncs[i] = false;
}
finish:
return eStatus;
}
//*-----------------------------------------------------------------------------
//| Purpose: Allocate 3D resource
//| Returns: Result of the operation.
//*-----------------------------------------------------------------------------
MOS_STATUS HalCm_AllocateSurface3D(CM_HAL_STATE *state, // [in] Pointer to CM State
CM_HAL_3DRESOURCE_PARAM *param) // [in] Pointer to Buffer Param)
{
MOS_STATUS eStatus = MOS_STATUS_SUCCESS;
//-----------------------------------------------
CM_ASSERT(state);
CM_ASSERT(param->depth > 1);
CM_ASSERT(param->width > 0);
CM_ASSERT(param->height > 0);
//-----------------------------------------------
// Finds a free slot.
CM_HAL_3DRESOURCE_ENTRY *entry = nullptr;
for (uint32_t i = 0; i < state->cmDeviceParam.max3DSurfaceTableSize; i++)
{
if (Mos_ResourceIsNull(&state->surf3DTable[i].osResource))
{
entry = &state->surf3DTable[i];
param->handle = (uint32_t)i;
break;
}
}
if (!entry)
{
eStatus = MOS_STATUS_INVALID_PARAMETER;
CM_ASSERTMESSAGE("3D surface table is full");
return eStatus;
}
Mos_ResetResource(&entry->osResource); // Resets the Resource
MOS_ALLOC_GFXRES_PARAMS alloc_params;
MOS_ZeroMemory(&alloc_params, sizeof(alloc_params));
alloc_params.Type = MOS_GFXRES_VOLUME;
alloc_params.TileType = MOS_TILE_Y;
alloc_params.dwWidth = param->width;
alloc_params.dwHeight = param->height;
alloc_params.dwDepth = param->depth;
alloc_params.pSystemMemory = param->data;
alloc_params.Format = param->format;
alloc_params.pBufName = "CmSurface3D";
MOS_INTERFACE *osInterface = state->renderHal->pOsInterface;
CM_CHK_HRESULT_GOTOFINISH_MOSERROR(osInterface->pfnAllocateResource(
osInterface,
&alloc_params,
&entry->osResource));
entry->width = param->width;
entry->height = param->height;
entry->depth = param->depth;
entry->format = param->format;
finish:
return eStatus;
}
//*-----------------------------------------------------------------------------
//| Purpose: Frees the resource and removes from the table
//| Returns: Result of the operation.
//*-----------------------------------------------------------------------------
MOS_STATUS HalCm_Free3DResource(
PCM_HAL_STATE state, // [in] Pointer to CM State
uint32_t handle) // [in] Pointer to Buffer Param
{
MOS_STATUS eStatus;
PCM_HAL_3DRESOURCE_ENTRY entry;
PMOS_INTERFACE osInterface;
eStatus = MOS_STATUS_SUCCESS;
osInterface = state->osInterface;
// Get the Buffer Entry
CM_CHK_MOSSTATUS_GOTOFINISH(HalCm_Get3DResourceEntry(state, handle, &entry));
osInterface->pfnFreeResourceWithFlag(osInterface, &entry->osResource, SURFACE_FLAG_ASSUME_NOT_IN_USE);
osInterface->pfnResetResourceAllocationIndex(osInterface, &entry->osResource);
finish:
return eStatus;
}
//*-----------------------------------------------------------------------------
//| Purpose: Lock the resource and return
//| Returns: Result of the operation.
//*-----------------------------------------------------------------------------
MOS_STATUS HalCm_Lock3DResource(
PCM_HAL_STATE state, // [in] Pointer to CM State
PCM_HAL_3DRESOURCE_PARAM param) // [in] Pointer to 3D Param
{
MOS_STATUS eStatus = MOS_STATUS_SUCCESS;
PCM_HAL_3DRESOURCE_ENTRY entry;
MOS_LOCK_PARAMS lockFlags;
RENDERHAL_GET_SURFACE_INFO info;
PMOS_INTERFACE osInterface = nullptr;
MOS_SURFACE surface;
// Get the 3D Resource Entry
CM_CHK_MOSSTATUS_GOTOFINISH(HalCm_Get3DResourceEntry(state, param->handle, &entry));
if ((param->lockFlag != CM_HAL_LOCKFLAG_READONLY) && (param->lockFlag != CM_HAL_LOCKFLAG_WRITEONLY) )
{
CM_ASSERTMESSAGE("Invalid lock flag!");
eStatus = MOS_STATUS_UNKNOWN;
goto finish;
}
// Get resource information
MOS_ZeroMemory(&surface, sizeof(surface));
surface.OsResource = entry->osResource;
surface.Format = Format_Invalid;
osInterface = state->osInterface;
MOS_ZeroMemory(&info, sizeof(RENDERHAL_GET_SURFACE_INFO));
CM_CHK_MOSSTATUS_GOTOFINISH(RenderHal_GetSurfaceInfo(
osInterface,
&info,
&surface));
param->pitch = surface.dwPitch;
param->qpitch = surface.dwQPitch;
param->qpitchEnabled = state->cmHalInterface->IsSurf3DQpitchSupportedbyHw();
// Lock the resource
MOS_ZeroMemory(&lockFlags, sizeof(MOS_LOCK_PARAMS));
if (param->lockFlag == CM_HAL_LOCKFLAG_READONLY)
{
lockFlags.ReadOnly = true;
}
else
{
lockFlags.WriteOnly = true;
}
lockFlags.ForceCached = true;
param->data = osInterface->pfnLockResource(
osInterface,
&entry->osResource,
&lockFlags);
CM_CHK_NULL_GOTOFINISH_MOSERROR(param->data);
finish:
return eStatus;
}
//*-----------------------------------------------------------------------------
//| Purpose: Unlock the resource and return
//| Returns: Result of the operation.
//*-----------------------------------------------------------------------------
MOS_STATUS HalCm_Unlock3DResource(
PCM_HAL_STATE state, // [in] Pointer to CM State
PCM_HAL_3DRESOURCE_PARAM param) // [in] Pointer to 3D Param
{
MOS_STATUS eStatus;
PCM_HAL_3DRESOURCE_ENTRY entry;
PMOS_INTERFACE osInterface;
eStatus = MOS_STATUS_SUCCESS;
osInterface = state->osInterface;
// Get the 3D Resource Entry
CM_CHK_MOSSTATUS_GOTOFINISH(HalCm_Get3DResourceEntry(state, param->handle, &entry));
// Lock the resource
CM_CHK_HRESULT_GOTOFINISH_MOSERROR(osInterface->pfnUnlockResource(osInterface, &entry->osResource));
finish:
return eStatus;
}
MOS_STATUS HalCm_SetCompressionMode(
PCM_HAL_STATE state,
CM_HAL_SURFACE2D_COMPRESSIOM_PARAM mmcParam)
{
MOS_STATUS eStatus = MOS_STATUS_SUCCESS;
PMOS_INTERFACE osInterface = state->osInterface;
PCM_HAL_SURFACE2D_ENTRY entry;
// Get the 2D Resource Entry
CM_CHK_MOSSTATUS_GOTOFINISH(HalCm_GetSurface2DEntry(state, mmcParam.handle, &entry));
//set compression bit passed down
CM_CHK_MOSSTATUS_GOTOFINISH(osInterface->pfnSetMemoryCompressionMode(osInterface, &(entry->osResource), (MOS_MEMCOMP_STATE)mmcParam.mmcMode));
finish:
return eStatus;
}
MOS_STATUS HalCm_SetL3Cache(
const L3ConfigRegisterValues *l3Values,
PCmHalL3Settings cmHalL3Cache )
{
MOS_STATUS eStatus = MOS_STATUS_SUCCESS;
// in legacy platforms, we map:
// ConfigRegister0->SqcReg1
// ConfigRegister1->CntlReg2
// ConfigRegister2->CntlReg3
// ConfigRegister3->CntlReg
CM_CHK_NULL_GOTOFINISH_MOSERROR( cmHalL3Cache );
CM_CHK_NULL_GOTOFINISH_MOSERROR(l3Values);
cmHalL3Cache->overrideSettings =
(l3Values->config_register0 || l3Values->config_register1 ||
l3Values->config_register2 || l3Values->config_register3 );
cmHalL3Cache->cntlRegOverride = (l3Values->config_register3 != 0);
cmHalL3Cache->cntlReg2Override = (l3Values->config_register1 != 0);
cmHalL3Cache->cntlReg3Override = (l3Values->config_register2 != 0);
cmHalL3Cache->sqcReg1Override = (l3Values->config_register0 != 0);
cmHalL3Cache->cntlReg = l3Values->config_register3;
cmHalL3Cache->cntlReg2 = l3Values->config_register1;
cmHalL3Cache->cntlReg3 = l3Values->config_register2;
cmHalL3Cache->sqcReg1 = l3Values->config_register0;
finish:
return MOS_STATUS_SUCCESS;
}
//*-----------------------------------------------------------------------------
//| Purpose: Set Cap values
//| Returns: Result of the operation.
//*-----------------------------------------------------------------------------
MOS_STATUS HalCm_SetCaps(
PCM_HAL_STATE state,
PCM_HAL_MAX_SET_CAPS_PARAM setCapsParam)
{
MOS_STATUS eStatus = MOS_STATUS_SUCCESS;
CM_CHK_NULL_GOTOFINISH_MOSERROR(state);
CM_CHK_NULL_GOTOFINISH_MOSERROR(setCapsParam);
CM_CHK_NULL_GOTOFINISH_MOSERROR(state->renderHal);
CM_CHK_NULL_GOTOFINISH_MOSERROR(state->renderHal->pHwCaps)
switch (setCapsParam->type)
{
case CM_SET_MAX_HW_THREADS:
if( setCapsParam->maxValue <= 0 ||
setCapsParam->maxValue > state->renderHal->pHwCaps->dwMaxThreads )
{
eStatus = MOS_STATUS_UNKNOWN;
goto finish;
}
else
{
state->maxHWThreadValues.apiValue = setCapsParam->maxValue;
}
break;
case CM_SET_HW_L3_CONFIG:
eStatus = state->cmHalInterface->SetL3CacheConfig( &setCapsParam->l3CacheValues,
&state->l3Settings );
break;
default:
eStatus = MOS_STATUS_UNKNOWN;
goto finish;
}
finish:
return eStatus;
}
//*-----------------------------------------------------------------------------
//| Purpose: Task sets the power option which will be used by this task
//| Returns: Result of the operation.
//*-----------------------------------------------------------------------------
MOS_STATUS HalCm_SetPowerOption(
PCM_HAL_STATE state,
PCM_POWER_OPTION powerOption )
{
if (state->cmHalInterface->IsOverridePowerOptionPerGpuContext())
{
CM_NORMALMESSAGE("WARNING: Deprecated function due to per context SSEU overriding is enabled.\n");
return MOS_STATUS_SUCCESS;
}
MOS_SecureMemcpy( &state->powerOption, sizeof( state->powerOption ), powerOption, sizeof( state->powerOption ) );
return MOS_STATUS_SUCCESS;
}
//*-----------------------------------------------------------------------------
// Purpose: Get the time in ns from QueryPerformanceCounter
// Returns: Result of the operation
//*-----------------------------------------------------------------------------
MOS_STATUS HalCm_GetGlobalTime(LARGE_INTEGER *globalTime)
{
if(globalTime == nullptr)
{
return MOS_STATUS_NULL_POINTER;
}
if (MOS_QueryPerformanceCounter((uint64_t*)&(globalTime->QuadPart)) == false)
{
return MOS_STATUS_UNKNOWN;
}
return MOS_STATUS_SUCCESS;
}
//*-----------------------------------------------------------------------------
// Purpose: Convert time from nanosecond to QPC time
// Returns: Result of the operation
//*-----------------------------------------------------------------------------
MOS_STATUS HalCm_ConvertToQPCTime(uint64_t nanoseconds, LARGE_INTEGER *qpcTime)
{
LARGE_INTEGER perfFreq;
if(qpcTime == nullptr)
{
return MOS_STATUS_NULL_POINTER;
}
if (MOS_QueryPerformanceFrequency((uint64_t*)&perfFreq.QuadPart) == false)
{
return MOS_STATUS_UNKNOWN;
}
qpcTime->QuadPart = (uint64_t)(nanoseconds * perfFreq.QuadPart / 1000000000.0);
return MOS_STATUS_SUCCESS;
}
//------------------------------------------------------------------------------
//| Purpose: Halcm updates power state to hw state
//| Returns:
//------------------------------------------------------------------------------
MOS_STATUS HalCm_UpdatePowerOption(
PCM_HAL_STATE state,
PCM_POWER_OPTION powerOption )
{
MOS_STATUS eStatus = MOS_STATUS_SUCCESS;
if (state->cmHalInterface->IsOverridePowerOptionPerGpuContext())
{
CM_NORMALMESSAGE("WARNING: Deprecated function due to per context SSEU overriding is enabled.\n");
return MOS_STATUS_SUCCESS;
}
PRENDERHAL_INTERFACE renderHal = state->renderHal;
RENDERHAL_POWEROPTION renderPowerOption;
renderPowerOption.nSlice = (uint8_t)powerOption->nSlice;
renderPowerOption.nSubSlice = (uint8_t)powerOption->nSubSlice;
renderPowerOption.nEU = (uint8_t)powerOption->nEU;
// option set in CM create device to use slice shutdown for life of CM device ( override previous value if necessary )
if ( state->requestSingleSlice == true )
{
renderPowerOption.nSlice = 1;
}
renderHal->pfnSetPowerOptionMode( renderHal, &renderPowerOption );
return eStatus;
}
MOS_STATUS HalCm_InitPerfTagIndexMap(PCM_HAL_STATE cmState)
{
using namespace std;
MOS_STATUS eStatus = MOS_STATUS_SUCCESS;
CM_ASSERT(cmState);
for (int i = 0; i < MAX_COMBINE_NUM_IN_PERFTAG; i++)
{
cmState->currentPerfTagIndex[i] = 1;
#if MOS_MESSAGES_ENABLED
cmState->perfTagIndexMap[i] = MOS_NewUtil<map<string, int> >(__FUNCTION__, __FILE__, __LINE__);
#else
cmState->perfTagIndexMap[i] = MOS_NewUtil<map<string, int> >();
#endif
CM_CHK_NULL_GOTOFINISH_MOSERROR(cmState->perfTagIndexMap[i]);
}
cmState->perfTagIndexMap[0]->insert(pair<string, int>("surfaceCopy_read_NV12_32x32", GPUCOPY_READ_PERFTAG_INDEX));
cmState->perfTagIndexMap[0]->insert(pair<string, int>("surfaceCopy_read_NV12_aligned_32x32", GPUCOPY_READ_PERFTAG_INDEX));
cmState->perfTagIndexMap[0]->insert(pair<string, int>("surfaceCopy_read_32x32", GPUCOPY_READ_PERFTAG_INDEX));
cmState->perfTagIndexMap[0]->insert(pair<string, int>("surfaceCopy_read_aligned_32x32", GPUCOPY_READ_PERFTAG_INDEX));
cmState->perfTagIndexMap[0]->insert(pair<string, int>("surfaceCopy_write_NV12_32x32", GPUCOPY_WRITE_PERFTAG_INDEX));
cmState->perfTagIndexMap[0]->insert(pair<string, int>("surfaceCopy_write_32x32", GPUCOPY_WRITE_PERFTAG_INDEX));
cmState->perfTagIndexMap[0]->insert(pair<string, int>("SurfaceCopy_2DTo2D_NV12_32x32", GPUCOPY_G2G_PERFTAG_INDEX));
cmState->perfTagIndexMap[0]->insert(pair<string, int>("SurfaceCopy_2DTo2D_32x32", GPUCOPY_G2G_PERFTAG_INDEX));
cmState->perfTagIndexMap[0]->insert(pair<string, int>("SurfaceCopy_BufferToBuffer_4k", GPUCOPY_C2C_PERFTAG_INDEX));
cmState->perfTagIndexMap[0]->insert(pair<string, int>("SurfaceCopy_BufferToBuffer_4k", GPUCOPY_C2C_PERFTAG_INDEX));
cmState->perfTagIndexMap[0]->insert(pair<string, int>("surfaceCopy_set_NV12", GPUINIT_PERFTAG_INDEX));
cmState->perfTagIndexMap[0]->insert(pair<string, int>("surfaceCopy_set", GPUINIT_PERFTAG_INDEX));
finish:
return eStatus;
}
MOS_STATUS HalCm_InsertToStateBufferList(
PCM_HAL_STATE state,
void *kernelPtr,
uint32_t stateBufferIndex,
CM_STATE_BUFFER_TYPE stateBufferType,
uint32_t stateBufferSize,
uint64_t stateBufferVaPtr,
PRENDERHAL_MEDIA_STATE mediaStatePtr )
{
MOS_STATUS result = MOS_STATUS_SUCCESS;
CM_HAL_STATE_BUFFER_ENTRY entry;
entry.kernelPtr = kernelPtr;
entry.stateBufferIndex = stateBufferIndex;
entry.stateBufferType = stateBufferType;
entry.stateBufferSize = stateBufferSize;
entry.stateBufferVaPtr = stateBufferVaPtr;
entry.mediaStatePtr = mediaStatePtr;
( *state->state_buffer_list_ptr )[ kernelPtr ] = entry;
return result;
}
MOS_STATUS HalCm_DeleteFromStateBufferList(
PCM_HAL_STATE state,
void *kernelPtr )
{
MOS_STATUS result = MOS_STATUS_SUCCESS;
state->state_buffer_list_ptr->erase( kernelPtr );
return result;
}
PRENDERHAL_MEDIA_STATE HalCm_GetMediaStatePtrForKernel(
PCM_HAL_STATE state,
void *kernelPtr )
{
if ( state->state_buffer_list_ptr->find( kernelPtr ) != state->state_buffer_list_ptr->end() )
{
return ( *state->state_buffer_list_ptr )[ kernelPtr ].mediaStatePtr;
}
else
{
return nullptr;
}
}
uint64_t HalCm_GetStateBufferVAPtrForSurfaceIndex(
PCM_HAL_STATE state,
uint32_t surfIndex )
{
for ( auto listItem = state->state_buffer_list_ptr->begin(); listItem != state->state_buffer_list_ptr->end(); listItem++ )
{
if ( listItem->second.stateBufferIndex == surfIndex )
{
return listItem->second.stateBufferVaPtr;
}
}
return 0;
}
PRENDERHAL_MEDIA_STATE HalCm_GetMediaStatePtrForSurfaceIndex(
PCM_HAL_STATE state,
uint32_t surfIndex )
{
for ( auto listItem = state->state_buffer_list_ptr->begin(); listItem != state->state_buffer_list_ptr->end(); listItem++ )
{
if ( listItem->second.stateBufferIndex == surfIndex )
{
return listItem->second.mediaStatePtr;
}
}
return nullptr;
}
uint64_t HalCm_GetStateBufferVAPtrForMediaStatePtr(
PCM_HAL_STATE state,
PRENDERHAL_MEDIA_STATE mediaStatePtr )
{
for ( auto listItem = state->state_buffer_list_ptr->begin(); listItem != state->state_buffer_list_ptr->end(); listItem++ )
{
if ( listItem->second.mediaStatePtr == mediaStatePtr )
{
return listItem->second.stateBufferVaPtr;
}
}
return 0;
}
uint32_t HalCm_GetStateBufferSizeForKernel(
PCM_HAL_STATE state,
void *kernelPtr )
{
if ( state->state_buffer_list_ptr->find( kernelPtr ) != state->state_buffer_list_ptr->end() )
{
return ( *state->state_buffer_list_ptr )[ kernelPtr ].stateBufferSize;
}
else
{
return 0;
}
}
CM_STATE_BUFFER_TYPE HalCm_GetStateBufferTypeForKernel(
PCM_HAL_STATE state,
void *kernelPtr )
{
if ( state->state_buffer_list_ptr->find( kernelPtr ) != state->state_buffer_list_ptr->end() )
{
return ( *state->state_buffer_list_ptr )[ kernelPtr ].stateBufferType;
}
else
{
return CM_STATE_BUFFER_NONE;
}
}
MOS_STATUS HalCm_CreateGPUContext(
PCM_HAL_STATE state,
MOS_GPU_CONTEXT gpuContext,
MOS_GPU_NODE gpuNode,
PMOS_GPUCTX_CREATOPTIONS pMosGpuContextCreateOption)
{
MOS_STATUS eStatus = MOS_STATUS_SUCCESS;
// Create Compute Context on Compute Node
CM_CHK_HRESULT_GOTOFINISH_MOSERROR(state->osInterface->pfnCreateGpuContext(
state->osInterface,
gpuContext,
gpuNode,
pMosGpuContextCreateOption));
// Register Compute Context with the Batch Buffer completion event
CM_CHK_HRESULT_GOTOFINISH_MOSERROR(state->osInterface->pfnRegisterBBCompleteNotifyEvent(
state->osInterface,
gpuContext));
finish:
return eStatus;
}
//*-----------------------------------------------------------------------------
//| Purpose: Creates instance of HAL CM State
//| Returns: Result of the operation
//| Note: Caller must call pfnAllocate to allocate all HalCm/Mhw states and objects.
//| Caller MUST call HalCm_Destroy to destroy the instance
//*-----------------------------------------------------------------------------
MOS_STATUS HalCm_Create(
PMOS_CONTEXT osDriverContext, // [in] OS Driver Context
PCM_HAL_CREATE_PARAM param, // [in] Create Param
PCM_HAL_STATE *cmState) // [out] double pointer to CM State
{
MOS_STATUS eStatus;
PCM_HAL_STATE state = nullptr;
uint32_t numCmdBuffers = 0;
MhwInterfaces *mhwInterfaces = nullptr;
MhwInterfaces::CreateParams params;
//-----------------------------------------
CM_ASSERT(osDriverContext);
CM_ASSERT(param);
CM_ASSERT(cmState);
//-----------------------------------------
eStatus = MOS_STATUS_SUCCESS;
// Allocate State structure
state = (PCM_HAL_STATE)MOS_AllocAndZeroMemory(sizeof(CM_HAL_STATE));
CM_CHK_NULL_GOTOFINISH_MOSERROR(state);
// Allocate/Initialize OS Interface
state->osInterface = (PMOS_INTERFACE)
MOS_AllocAndZeroMemory(sizeof(MOS_INTERFACE));
CM_CHK_NULL_GOTOFINISH_MOSERROR(state->osInterface);
state->osInterface->bDeallocateOnExit = true;
CM_CHK_HRESULT_GOTOFINISH_MOSERROR(Mos_InitInterface(state->osInterface, osDriverContext, COMPONENT_CM));
#if (_RELEASE_INTERNAL || _DEBUG)
#if defined(CM_DIRECT_GUC_SUPPORT)
state->osInterface->m_pWorkQueueMngr = new CMRTWorkQueueMngr();
#endif
#endif
state->osInterface->pfnGetPlatform(state->osInterface, &state->platform);
state->skuTable = state->osInterface->pfnGetSkuTable(state->osInterface);
state->waTable = state->osInterface->pfnGetWaTable (state->osInterface);
{
MOS_GPUCTX_CREATOPTIONS createOption;
// Create VEBOX Context
createOption.CmdBufferNumScale = MOS_GPU_CONTEXT_CREATE_DEFAULT;
CM_CHK_MOSSTATUS_GOTOFINISH(HalCm_CreateGPUContext(
state,
MOS_GPU_CONTEXT_VEBOX,
MOS_GPU_NODE_VE,
&createOption));
}
// Allocate/Initialize CM Rendering Interface
state->renderHal = (PRENDERHAL_INTERFACE)
MOS_AllocAndZeroMemory(sizeof(RENDERHAL_INTERFACE));
CM_CHK_NULL_GOTOFINISH_MOSERROR(state->renderHal);
state->dshEnabled = param->dynamicStateHeap;
state->renderHal->bDynamicStateHeap = state->dshEnabled;
if (state->dshEnabled)
{
CM_CHK_MOSSTATUS_GOTOFINISH(RenderHal_InitInterface_Dynamic(state->renderHal, &state->cpInterface, state->osInterface));
}
else
{
CM_CHK_MOSSTATUS_GOTOFINISH(RenderHal_InitInterface(state->renderHal, &state->cpInterface, state->osInterface));
}
// Allocate/Initialize VEBOX Interface
CmSafeMemSet(¶ms, 0, sizeof(params));
params.Flags.m_vebox = 1;
mhwInterfaces = MhwInterfaces::CreateFactory(params, state->osInterface);
if (mhwInterfaces)
{
CM_CHK_NULL_GOTOFINISH_MOSERROR(mhwInterfaces->m_veboxInterface);
state->veboxInterface = mhwInterfaces->m_veboxInterface;
// MhwInterfaces always create CP and MI interfaces, so we have to delete those we don't need.
MOS_Delete(mhwInterfaces->m_miInterface);
Delete_MhwCpInterface(mhwInterfaces->m_cpInterface);
mhwInterfaces->m_cpInterface = nullptr;
MOS_Delete(mhwInterfaces);
}
else
{
CM_ASSERTMESSAGE("Allocate MhwInterfaces failed");
return MOS_STATUS_NO_SPACE;
}
// set IsMDFLoad to distinguish MDF context from other Media Contexts
state->renderHal->IsMDFLoad = true;
// disable YV12SinglePass as CMRT & compiler don't support it
state->renderHal->bEnableYV12SinglePass = false;
state->cmDeviceParam.maxKernelBinarySize = CM_KERNEL_BINARY_BLOCK_SIZE;
// set if the new sampler heap management is used or not
// currently new sampler heap management depends on DSH
if (state->dshEnabled)
{
state->useNewSamplerHeap = true;
}
else
{
state->useNewSamplerHeap = false;
}
//Get Max Scratch Space Size
if( param->disableScratchSpace)
{
state->cmDeviceParam.maxPerThreadScratchSpaceSize = 0;
}
else
{
//Gen7_5 + : (MaxScratchSpaceSize + 1) *16k
if(param->scratchSpaceSize == CM_DEVICE_CONFIG_SCRATCH_SPACE_SIZE_DEFAULT)
{ //By default, 128K for HSW
state->cmDeviceParam.maxPerThreadScratchSpaceSize = 8 * CM_DEVICE_CONFIG_SCRATCH_SPACE_SIZE_16K_STEP;
}
else
{
state->cmDeviceParam.maxPerThreadScratchSpaceSize = (param->scratchSpaceSize)*
CM_DEVICE_CONFIG_SCRATCH_SPACE_SIZE_16K_STEP;
}
}
// Initialize kernel parameters
state->kernelParamsRenderHal.pMhwKernelParam = &state->kernelParamsMhw;
// Enable SLM in L3 Cache
state->l3Settings.enableSlm = true;
// Slice shutdown
state->requestSingleSlice = param->requestSliceShutdown;
//mid thread preemption on/off and SIP debug control
state->midThreadPreemptionDisabled = param->disabledMidThreadPreemption;
state->kernelDebugEnabled = param->enabledKernelDebug;
// init mapping for the state buffer
#if MOS_MESSAGES_ENABLED
state->state_buffer_list_ptr = MOS_NewUtil<std::map< void *, CM_HAL_STATE_BUFFER_ENTRY> >(__FUNCTION__, __FILE__, __LINE__);
#else
state->state_buffer_list_ptr = MOS_NewUtil<std::map< void *, CM_HAL_STATE_BUFFER_ENTRY> >();
#endif
CM_CHK_NULL_GOTOFINISH_MOSERROR( state->state_buffer_list_ptr );
MOS_ZeroMemory(&state->hintIndexes.kernelIndexes, sizeof(uint32_t) * CM_MAX_TASKS_EU_SATURATION);
MOS_ZeroMemory(&state->hintIndexes.dispatchIndexes, sizeof(uint32_t) * CM_MAX_TASKS_EU_SATURATION);
// get the global media profiler
state->perfProfiler = MediaPerfProfiler::Instance();
CM_CHK_NULL_GOTOFINISH_MOSERROR(state->perfProfiler);
CM_CHK_MOSSTATUS_GOTOFINISH(state->perfProfiler->Initialize((void*)state, state->osInterface));
state->criticalSectionDSH = MOS_New(CMRT_UMD::CSync);
CM_CHK_NULL_GOTOFINISH_MOSERROR(state->criticalSectionDSH);
state->cmDeviceParam.maxKernelsPerTask = CM_MAX_KERNELS_PER_TASK;
state->cmDeviceParam.maxSamplerTableSize = CM_MAX_SAMPLER_TABLE_SIZE;
state->cmDeviceParam.maxSampler8x8TableSize = state->renderHal->pHwSizes->dwSizeSampler8x8Table;
state->cmDeviceParam.maxBufferTableSize = CM_MAX_BUFFER_SURFACE_TABLE_SIZE;
state->cmDeviceParam.max2DSurfaceUPTableSize = CM_MAX_2D_SURFACE_UP_TABLE_SIZE;
state->cmDeviceParam.max2DSurfaceTableSize = CM_MAX_2D_SURFACE_TABLE_SIZE;
state->cmDeviceParam.max3DSurfaceTableSize = CM_MAX_3D_SURFACE_TABLE_SIZE;
state->cmDeviceParam.maxTasks = param->maxTaskNumber;
state->cmDeviceParam.maxAvsSamplers = CM_MAX_AVS_SAMPLER_SIZE;
state->cmDeviceParam.maxGshKernelEntries = param->kernelBinarySizeinGSH / (CM_32K);
if (state->dshEnabled)
{
// Initialize Kernel Cache Hit/Miss counters
state->dshKernelCacheMiss = 0;
state->dshKernelCacheHit = 0;
}
// Setup Function pointers
state->pfnCmAllocate = HalCm_Allocate;
state->pfnGetMaxValues = HalCm_GetMaxValues;
state->pfnGetMaxValuesEx = HalCm_GetMaxValuesEx;
state->pfnExecuteTask = HalCm_ExecuteTask;
state->pfnExecuteGroupTask = HalCm_ExecuteGroupTask;
state->pfnExecuteHintsTask = HalCm_ExecuteHintsTask;
state->pfnRegisterSampler = HalCm_RegisterSampler;
state->pfnUnRegisterSampler = HalCm_UnRegisterSampler;
state->pfnRegisterSampler8x8 = HalCm_RegisterSampler8x8;
state->pfnUnRegisterSampler8x8 = HalCm_UnRegisterSampler8x8;
state->pfnFreeBuffer = HalCm_FreeBuffer;
state->pfnLockBuffer = HalCm_LockBuffer;
state->pfnUnlockBuffer = HalCm_UnlockBuffer;
state->pfnFreeSurface2DUP = HalCm_FreeSurface2DUP;
state->pfnGetSurface2DTileYPitch = HalCm_GetSurface2DTileYPitch;
state->pfnSet2DSurfaceStateParam = HalCm_Set2DSurfaceStateParam;
state->pfnSetBufferSurfaceStatePara = HalCm_SetBufferSurfaceStateParameters;
state->pfnSetSurfaceMOCS = HalCm_SetSurfaceMOCS;
/************************************************************/
state->pfnAllocateSurface2D = HalCm_AllocateSurface2D;
state->pfnAllocate3DResource = HalCm_AllocateSurface3D;
state->pfnFreeSurface2D = HalCm_FreeSurface2D;
state->pfnLock2DResource = HalCm_Lock2DResource;
state->pfnUnlock2DResource = HalCm_Unlock2DResource;
state->pfnSetCompressionMode = HalCm_SetCompressionMode;
/************************************************************/
state->pfnFree3DResource = HalCm_Free3DResource;
state->pfnLock3DResource = HalCm_Lock3DResource;
state->pfnUnlock3DResource = HalCm_Unlock3DResource;
state->pfnSetCaps = HalCm_SetCaps;
state->pfnSetPowerOption = HalCm_SetPowerOption;
state->pfnUpdatePowerOption = HalCm_UpdatePowerOption;
state->pfnSendMediaWalkerState = HalCm_SendMediaWalkerState;
state->pfnSendGpGpuWalkerState = HalCm_SendGpGpuWalkerState;
state->pfnSetSurfaceReadFlag = HalCm_SetSurfaceReadFlag;
state->pfnSetVtuneProfilingFlag = HalCm_SetVtuneProfilingFlag;
state->pfnExecuteVeboxTask = HalCm_ExecuteVeboxTask;
state->pfnGetSipBinary = HalCm_GetSipBinary;
state->pfnGetTaskSyncLocation = HalCm_GetTaskSyncLocation;
state->pfnGetGlobalTime = HalCm_GetGlobalTime;
state->pfnConvertToQPCTime = HalCm_ConvertToQPCTime;
state->pfnInsertToStateBufferList = HalCm_InsertToStateBufferList;
state->pfnDeleteFromStateBufferList = HalCm_DeleteFromStateBufferList;
state->pfnGetMediaStatePtrForKernel = HalCm_GetMediaStatePtrForKernel;
state->pfnGetStateBufferVAPtrForSurfaceIndex = HalCm_GetStateBufferVAPtrForSurfaceIndex;
state->pfnGetMediaStatePtrForSurfaceIndex = HalCm_GetMediaStatePtrForSurfaceIndex;
state->pfnGetStateBufferVAPtrForMediaStatePtr = HalCm_GetStateBufferVAPtrForMediaStatePtr;
state->pfnGetStateBufferSizeForKernel = HalCm_GetStateBufferSizeForKernel;
state->pfnGetStateBufferTypeForKernel = HalCm_GetStateBufferTypeForKernel;
state->pfnCreateGPUContext = HalCm_CreateGPUContext;
state->pfnDSHUnregisterKernel = HalCm_DSH_UnregisterKernel;
state->pfnUpdateBuffer = HalCm_UpdateBuffer;
state->pfnUpdateSurface2D = HalCm_UpdateSurface2D;
//==========<Initialize 5 OS-dependent DDI functions: pfnAllocate3DResource, pfnAllocateSurface2DUP====
// pfnAllocateBuffer,pfnRegisterKMDNotifyEventHandle, pfnGetSurface2DPitchAndSize >====
HalCm_OsInitInterface(state);
HalCm_InitPerfTagIndexMap(state);
state->maxHWThreadValues.userFeatureValue = 0;
state->maxHWThreadValues.apiValue = 0;
HalCm_GetUserFeatureSettings(state);
#if MDF_COMMAND_BUFFER_DUMP
HalCm_InitDumpCommandBuffer(state);
state->pfnInitDumpCommandBuffer = HalCm_InitDumpCommandBuffer;
state->pfnDumpCommadBuffer = HalCm_DumpCommadBuffer;
#endif //MDF_COMMAND_BUFFER_DUMP
#if MDF_CURBE_DATA_DUMP
HalCm_InitDumpCurbeData(state);
#endif
#if MDF_SURFACE_CONTENT_DUMP
HalCm_InitSurfaceDump(state);
#endif
#if MDF_SURFACE_STATE_DUMP
HalCm_InitDumpSurfaceState(state);
state->pfnInitDumpSurfaceState = HalCm_InitDumpSurfaceState;
state->pfnDumpSurfaceState = HalCm_DumpSurfaceState;
#endif
#if MDF_INTERFACE_DESCRIPTOR_DATA_DUMP
HalCm_InitDumpInterfaceDescriporData(state);
#endif
state->cmHalInterface = CMHalDevice::CreateFactory(state);
CM_CHK_NULL_GOTOFINISH_MOSERROR(state->cmHalInterface);
if (param->refactor)
{
state->refactor = true;
}
else
{
state->refactor = false;
}
state->requestCustomGpuContext = param->requestCustomGpuContext;
#if (_DEBUG || _RELEASE_INTERNAL)
{
FILE *fp1 = nullptr;
MOS_SecureFileOpen(&fp1, "refactor.key", "r");
if (fp1 != nullptr)
{
state->refactor = true;
fclose(fp1);
}
FILE *fp2 = nullptr;
MOS_SecureFileOpen(&fp2, "origin.key", "r");
if (fp2 != nullptr)
{
state->refactor = false;
fclose(fp2);
}
}
if (state->refactor)
{
CM_NORMALMESSAGE("Use refactor path!\n");
}
else
{
CM_NORMALMESSAGE("Use origin path!\n");
}
#endif
finish:
if (eStatus != MOS_STATUS_SUCCESS)
{
HalCm_Destroy(state);
*cmState = nullptr;
}
else
{
*cmState = state;
}
return eStatus;
}
//*-----------------------------------------------------------------------------
//| Purpose: Destroys instance of HAL CM State
//| Returns: N/A
//*-----------------------------------------------------------------------------
void HalCm_Destroy(
PCM_HAL_STATE state) // [in] Pointer to CM State
{
MOS_STATUS eStatus;
int32_t i;
if (state)
{
//Delete CmHal Interface
MosSafeDelete(state->cmHalInterface);
Delete_MhwCpInterface(state->cpInterface);
state->cpInterface = nullptr;
MosSafeDelete(state->state_buffer_list_ptr);
MosSafeDelete(state->criticalSectionDSH);
// Delete the unified media profiler
if (state->perfProfiler)
{
MediaPerfProfiler::Destroy(state->perfProfiler, (void*)state, state->osInterface);
state->perfProfiler = nullptr;
}
// Delete Batch Buffers
if (state->batchBuffers)
{
for (i=0; i < state->numBatchBuffers; i++)
{
if (!Mos_ResourceIsNull(&state->batchBuffers[i].OsResource))
{
eStatus = (MOS_STATUS)state->renderHal->pfnFreeBB(
state->renderHal,
&state->batchBuffers[i]);
CM_ASSERT(eStatus == MOS_STATUS_SUCCESS);
}
MOS_FreeMemory(state->batchBuffers[i].pPrivateData);
}
MOS_FreeMemory(state->batchBuffers);
state->batchBuffers = nullptr;
}
// Delete TimeStamp Buffer
HalCm_FreeTsResource(state);
if ((state->midThreadPreemptionDisabled == false) || (state->kernelDebugEnabled == true)) {
// Delete CSR surface
HalCm_FreeCsrResource(state);
// Delete sip surface
HalCm_FreeSipResource(state);
}
// Delete tracker resource
HalCm_FreeTrackerResources(state);
// Delete advance executor
MOS_Delete(state->advExecutor);
// Delete heap manager
if (state->renderHal)
{
MOS_Delete(state->renderHal->dgsheapManager);
}
if (state->hLibModule)
{
MOS_FreeLibrary(state->hLibModule);
state->hLibModule = nullptr;
}
// Delete RenderHal Interface
if (state->renderHal)
{
if (state->renderHal->pfnDestroy)
{
state->renderHal->pfnDestroy(state->renderHal);
}
MOS_FreeMemory(state->renderHal);
state->renderHal = nullptr;
}
// Delete VEBOX Interface
if (state->veboxInterface
&& state->veboxInterface->m_veboxHeap)
{
state->veboxInterface->DestroyHeap( );
MOS_Delete(state->veboxInterface);
state->veboxInterface = nullptr;
}
// Delete OS Interface
if (state->osInterface)
{
if (state->osInterface->pfnDestroy)
{
state->osInterface->pfnDestroy(state->osInterface, true);
}
if (state->osInterface->bDeallocateOnExit)
{
MOS_FreeMemory(state->osInterface);
state->osInterface = nullptr;
}
}
// Delete the TaskParam
MOS_FreeMemory(state->taskParam);
// Delete the TaskTimeStamp
MOS_FreeMemory(state->taskTimeStamp);
// Delete Tables
MOS_FreeMemory(state->tableMemories);
// Delete the pTotalKernelSize table for GSH
MOS_FreeMemory(state->totalKernelSize);
// Delete the perfTag Map
for (int i = 0; i < MAX_COMBINE_NUM_IN_PERFTAG; i++)
{
MosSafeDelete(state->perfTagIndexMap[i]);
}
// Delete the state
MOS_FreeMemory(state);
}
}
void HalCm_GetUserFeatureSettings(
PCM_HAL_STATE cmState
)
{
#if (_DEBUG || _RELEASE_INTERNAL)
PMOS_INTERFACE osInterface;
PMOS_USER_FEATURE_INTERFACE userFeatureInterface;
MOS_USER_FEATURE userFeature;
MOS_USER_FEATURE_VALUE userFeatureValue;
MOS_ZeroMemory(&userFeatureValue, sizeof(userFeatureValue));
osInterface = cmState->osInterface;
userFeatureInterface = &osInterface->UserFeatureInterface;
userFeature = *userFeatureInterface->pUserFeatureInit;
userFeature.Type = MOS_USER_FEATURE_TYPE_USER;
userFeature.pPath = (char *)__MEDIA_USER_FEATURE_SUBKEY_INTERNAL;
userFeature.pValues = &userFeatureValue;
userFeature.uiNumValues = 1;
if (userFeatureInterface->pfnReadValue(
userFeatureInterface,
&userFeature,
(char *)VPHAL_CM_MAX_THREADS,
MOS_USER_FEATURE_VALUE_TYPE_UINT32) == MOS_STATUS_SUCCESS)
{
uint32_t data = userFeature.pValues[0].u32Data;
if ((data > 0) && (data <= cmState->renderHal->pHwCaps->dwMaxThreads))
{
cmState->maxHWThreadValues.userFeatureValue = data;
}
}
#else
UNUSED(cmState);
#endif // _DEBUG || _RELEASE_INTERNAL
}
//*-----------------------------------------------------------------------------
//| Purpose: Gathers information about the surface - used by GT-Pin
//| Returns: MOS_STATUS_SUCCESS if surface type recognized, S_FAIL otherwise
//*-----------------------------------------------------------------------------
MOS_STATUS HalCm_GetSurfaceDetails(
PCM_HAL_STATE cmState,
PCM_HAL_INDEX_PARAM indexParam,
uint32_t btIndex,
MOS_SURFACE& surface,
int16_t globalSurface,
PRENDERHAL_SURFACE_STATE_ENTRY surfaceEntry,
uint32_t tempPlaneIndex,
RENDERHAL_SURFACE_STATE_PARAMS surfaceParam,
CM_HAL_KERNEL_ARG_KIND argKind
)
{
MOS_STATUS eStatus = MOS_STATUS_UNKNOWN;
PCM_SURFACE_DETAILS surfaceInfos = nullptr;
PCM_SURFACE_DETAILS pgSurfaceInfos = nullptr;
PCM_HAL_TASK_PARAM taskParam = cmState->taskParam;
uint32_t curKernelIndex = taskParam->curKernelIndex;
PMOS_PLANE_OFFSET planeOffset = 0;
uint32_t maxEntryNum = 0;
MOS_OS_FORMAT tempOsFormat ;
CM_SURFACE_BTI_INFO surfBTIInfo;
cmState->cmHalInterface->GetHwSurfaceBTIInfo(&surfBTIInfo);
UNUSED(indexParam);
if(curKernelIndex+1>taskParam->surfEntryInfoArrays.kernelNum)
{
eStatus = MOS_STATUS_INVALID_PARAMETER;
CM_ASSERTMESSAGE(
"Mismatched kernel index: curKernelIndex '%d' vs krnNum '%d'",
curKernelIndex,taskParam->surfEntryInfoArrays.kernelNum);
goto finish;
}
surfaceInfos = taskParam->surfEntryInfoArrays.surfEntryInfosArray[curKernelIndex].surfEntryInfos;
pgSurfaceInfos = taskParam->surfEntryInfoArrays.surfEntryInfosArray[curKernelIndex].globalSurfInfos;
tempOsFormat = cmState->osInterface->pfnFmt_MosToOs(surface.Format);
switch (argKind)
{
case CM_ARGUMENT_SURFACEBUFFER:
if((btIndex >= surfBTIInfo.reservedSurfaceStart) &&
(btIndex < surfBTIInfo.reservedSurfaceStart + CM_MAX_GLOBAL_SURFACE_NUMBER))
{
btIndex = btIndex - surfBTIInfo.reservedSurfaceStart;
maxEntryNum = taskParam->surfEntryInfoArrays.surfEntryInfosArray->globalSurfNum;
if ( btIndex >= maxEntryNum )
{
eStatus = MOS_STATUS_INVALID_PARAMETER;
CM_ASSERTMESSAGE(
"Array for surface details is full: Max number of entries '%d' and trying to add index '%d'",
maxEntryNum, btIndex);
goto finish;
}
MOS_ZeroMemory(&pgSurfaceInfos[btIndex], sizeof(CM_SURFACE_DETAILS));
pgSurfaceInfos[btIndex].width = surface.dwWidth;
pgSurfaceInfos[btIndex].format = DDI_FORMAT_UNKNOWN;
}
else
{
btIndex = btIndex - surfBTIInfo.reservedSurfaceStart - CM_MAX_GLOBAL_SURFACE_NUMBER;
maxEntryNum = taskParam->surfEntryInfoArrays.surfEntryInfosArray->maxEntryNum;
if ( btIndex >= maxEntryNum )
{
eStatus = MOS_STATUS_INVALID_PARAMETER;
CM_ASSERTMESSAGE(
"Array for surface details is full: Max number of entries '%d' and trying to add index '%d'",
maxEntryNum, btIndex);
goto finish;
}
MOS_ZeroMemory(&surfaceInfos[btIndex], sizeof(CM_SURFACE_DETAILS));
surfaceInfos[btIndex].width = surface.dwWidth;
surfaceInfos[btIndex].format = DDI_FORMAT_UNKNOWN;
}
if (globalSurface < 0)
{
++taskParam->surfEntryInfoArrays.surfEntryInfosArray[curKernelIndex].usedIndex;
}
eStatus = MOS_STATUS_SUCCESS;
break;
case CM_ARGUMENT_SURFACE2D_UP:
case CM_ARGUMENT_SURFACE2D:
// VME surface and sampler8x8 called with CM_ARGUMENT_SURFACE2D
btIndex = btIndex - surfBTIInfo.reservedSurfaceStart - CM_MAX_GLOBAL_SURFACE_NUMBER;
maxEntryNum = taskParam->surfEntryInfoArrays.surfEntryInfosArray->maxEntryNum;
if ( btIndex >= maxEntryNum )
{
eStatus = MOS_STATUS_INVALID_PARAMETER;
CM_ASSERTMESSAGE(
"Array for surface details is full: Max number of entries '%d' and trying to add index '%d'",
maxEntryNum, btIndex);
goto finish;
}
surfaceInfos[btIndex].width = surfaceEntry->dwWidth;
surfaceInfos[btIndex].height = surfaceEntry->dwHeight;
surfaceInfos[btIndex].depth = 0;
surfaceInfos[btIndex].format = (DdiSurfaceFormat)tempOsFormat;
surfaceInfos[btIndex].planeIndex = tempPlaneIndex;
surfaceInfos[btIndex].pitch = surfaceEntry->dwPitch;
surfaceInfos[btIndex].slicePitch = 0;
surfaceInfos[btIndex].surfaceBaseAddress = 0;
surfaceInfos[btIndex].tileWalk = surfaceEntry->bTileWalk;
surfaceInfos[btIndex].tiledSurface = surfaceEntry->bTiledSurface;
if (surfaceEntry->YUVPlane == MHW_U_PLANE ||
surfaceEntry->YUVPlane == MHW_V_PLANE)
{
planeOffset = (surfaceEntry->YUVPlane == MHW_U_PLANE)
? &surface.UPlaneOffset
: &surface.VPlaneOffset;
surfaceInfos[btIndex].yOffset = planeOffset->iYOffset >> 1;
if ( argKind == CM_ARGUMENT_SURFACE2D_UP )
{
surfaceInfos[btIndex].xOffset = (planeOffset->iXOffset/(uint32_t)sizeof(uint32_t)) >> 2;
}
else
{
uint32_t pixelsPerSampleUV = 0;
//Get Pixels Per Sample if we use dataport read
if(surfaceParam.bWidthInDword_UV)
{
RenderHal_GetPixelsPerSample(surface.Format, &pixelsPerSampleUV);
}
else
{
// If the kernel uses sampler - do not change width (it affects coordinates)
pixelsPerSampleUV = 1;
}
if(pixelsPerSampleUV == 1)
{
surfaceInfos[btIndex].xOffset = planeOffset->iXOffset >> 2;
}
else
{
surfaceInfos[btIndex].xOffset = (planeOffset->iXOffset/(uint32_t)sizeof(uint32_t)) >> 2;
}
}
}
else
{
surfaceInfos[btIndex].xOffset = (surface.YPlaneOffset.iXOffset/(uint32_t)sizeof(uint32_t)) >> 2;
surfaceInfos[btIndex].yOffset = surface.YPlaneOffset.iYOffset >> 1;
}
++taskParam->surfEntryInfoArrays.surfEntryInfosArray[curKernelIndex].usedIndex;
++tempPlaneIndex;
eStatus = MOS_STATUS_SUCCESS;
break;
case CM_ARGUMENT_SURFACE3D:
btIndex = btIndex - surfBTIInfo.normalSurfaceStart - CM_MAX_GLOBAL_SURFACE_NUMBER;
maxEntryNum = taskParam->surfEntryInfoArrays.surfEntryInfosArray->maxEntryNum;
if ( btIndex >= maxEntryNum )
{
eStatus = MOS_STATUS_INVALID_PARAMETER;
CM_ASSERTMESSAGE(
"Array for surface details is full: Max number of entries '%d' and trying to add index '%d'",
maxEntryNum, btIndex);
goto finish;
}
surfaceInfos[btIndex].width = surfaceEntry->dwWidth;
surfaceInfos[btIndex].height = surfaceEntry->dwHeight;
surfaceInfos[btIndex].depth = surface.dwDepth;
surfaceInfos[btIndex].format = (DdiSurfaceFormat)tempOsFormat;
surfaceInfos[btIndex].pitch = surfaceEntry->dwPitch;
surfaceInfos[btIndex].planeIndex = tempPlaneIndex;
surfaceInfos[btIndex].slicePitch = surface.dwSlicePitch;
surfaceInfos[btIndex].surfaceBaseAddress = 0;
surfaceInfos[btIndex].tileWalk = surfaceEntry->bTileWalk;
surfaceInfos[btIndex].tiledSurface = surfaceEntry->bTiledSurface;
if (surfaceEntry->YUVPlane == MHW_U_PLANE ||
surfaceEntry->YUVPlane == MHW_V_PLANE)
{
planeOffset = (surfaceEntry->YUVPlane == MHW_U_PLANE)
? &surface.UPlaneOffset
: &surface.VPlaneOffset;
surfaceInfos[btIndex].yOffset = planeOffset->iYOffset >> 1;
surfaceInfos[btIndex].xOffset = (planeOffset->iXOffset/(uint32_t)sizeof(uint32_t)) >> 2;
}
else
{
surfaceInfos[btIndex].xOffset = (surface.YPlaneOffset.iXOffset/(uint32_t)sizeof(uint32_t)) >> 2;
surfaceInfos[btIndex].yOffset = surface.YPlaneOffset.iYOffset >> 1;
}
++tempPlaneIndex;
++taskParam->surfEntryInfoArrays.surfEntryInfosArray[curKernelIndex].usedIndex;
eStatus = MOS_STATUS_SUCCESS;
break;
default:
break;
}
finish:
return eStatus;
}
uint32_t HalCm_GetFreeBindingIndex(
PCM_HAL_STATE state,
PCM_HAL_INDEX_PARAM indexParam,
uint32_t total)
{
CM_SURFACE_BTI_INFO surfBTIInfo;
state->cmHalInterface->GetHwSurfaceBTIInfo(&surfBTIInfo);
uint32_t btIndex = surfBTIInfo.normalSurfaceStart;
uint32_t unAllocated = total;
while (btIndex < 256 && unAllocated > 0)
{
uint32_t arrayIndex = btIndex >> 5;
uint32_t bitMask = (uint32_t)0x1 << (btIndex % 32);
if (indexParam->btArray[arrayIndex] & bitMask)
{
// oops, occupied
if (unAllocated != total)
{
// clear previous allocation
uint32_t allocated = total - unAllocated;
uint32_t tmpIndex = btIndex - 1;
while (allocated > 0)
{
uint32_t arrayIndex = tmpIndex >> 5;
uint32_t bitMask = 1 << (tmpIndex % 32);
indexParam->btArray[arrayIndex] &= ~bitMask;
allocated--;
tmpIndex--;
}
// reset
unAllocated = total;
}
}
else
{
indexParam->btArray[arrayIndex] |= bitMask;
unAllocated--;
}
btIndex++;
}
if (unAllocated == 0)
{
// found slot
return btIndex - total;
}
// no slot
return 0;
}
void HalCm_PreSetBindingIndex(
PCM_HAL_INDEX_PARAM indexParam,
uint32_t start,
uint32_t end)
{
uint32_t btIndex;
for ( btIndex = start; btIndex <= end ; btIndex++)
{
uint32_t arrayIndex = btIndex >> 5;
uint32_t bitMask = 1 << (btIndex % 32);
indexParam->btArray[arrayIndex] |= bitMask;
}
}
//*-----------------------------------------------------------------------------
//| Purpose: Setup surface State with BTIndex
//| Returns: Result of the operation
//*-----------------------------------------------------------------------------
MOS_STATUS HalCm_Setup2DSurfaceStateWithBTIndex(
PCM_HAL_STATE state,
int32_t bindingTable,
uint32_t surfIndex,
uint32_t btIndex,
bool pixelPitch)
{
PRENDERHAL_INTERFACE renderHal = state->renderHal;
MOS_STATUS eStatus;
RENDERHAL_SURFACE surface;
RENDERHAL_SURFACE_STATE_PARAMS surfaceParam;
PRENDERHAL_SURFACE_STATE_ENTRY surfaceEntries[MHW_MAX_SURFACE_PLANES];
int32_t nSurfaceEntries, i;
uint16_t memObjCtl;
uint32_t offsetSrc;
PRENDERHAL_STATE_HEAP stateHeap;
eStatus = MOS_STATUS_UNKNOWN;
nSurfaceEntries = 0;
if (surfIndex == CM_NULL_SURFACE)
{
return MOS_STATUS_SUCCESS;
}
memObjCtl = CM_DEFAULT_CACHE_TYPE;
// check the surfIndex
if (surfIndex >= state->cmDeviceParam.max2DSurfaceTableSize ||
Mos_ResourceIsNull(&state->umdSurf2DTable[surfIndex].osResource) )
{
CM_ASSERTMESSAGE(
"Invalid 2D surface array index '%d'", surfIndex);
return MOS_STATUS_UNKNOWN;
}
// Check to see if surface is already assigned
uint32_t nBTInTable = ( unsigned char )CM_INVALID_INDEX;
if ( pixelPitch )
{
nBTInTable = state->bti2DIndexTable[ surfIndex ].BTI.samplerSurfIndex;
}
else
{
nBTInTable = state->bti2DIndexTable[ surfIndex ].BTI.regularSurfIndex;
}
if ( btIndex == nBTInTable )
{
nSurfaceEntries = state->bti2DIndexTable[ surfIndex ].nPlaneNumber;
stateHeap = renderHal->pStateHeap;
// Get Offset to Current Binding Table
uint32_t offsetDst = ( stateHeap->iCurSshBufferIndex * stateHeap->dwSshIntanceSize ) + // Points to the Base of Current SSH Buffer Instance
( stateHeap->iBindingTableOffset ) + // Moves the pointer to Base of Array of Binding Tables
( bindingTable * stateHeap->iBindingTableSize ) + // Moves the pointer to a Particular Binding Table
( btIndex * sizeof( uint32_t ) ); // Move the pointer to correct entry
uint32_t *bindingTableEntry = ( uint32_t *)( stateHeap->pSshBuffer + offsetDst );
if ( pixelPitch )
{
MOS_SecureMemcpy( bindingTableEntry, sizeof( uint32_t ) * nSurfaceEntries, state->bti2DIndexTable[ surfIndex ].BTITableEntry.samplerBtiEntryPosition, sizeof( uint32_t ) * nSurfaceEntries );
}
else
{
MOS_SecureMemcpy( bindingTableEntry, sizeof( uint32_t ) * nSurfaceEntries, state->bti2DIndexTable[ surfIndex ].BTITableEntry.regularBtiEntryPosition, sizeof( uint32_t ) * nSurfaceEntries );
}
return MOS_STATUS_SUCCESS;
}
// Get Details of 2D surface and fill the surface
CM_CHK_MOSSTATUS_GOTOFINISH(HalCm_GetSurfaceAndRegister(state, &surface, CM_ARGUMENT_SURFACE2D, surfIndex, pixelPitch));
// Setup 2D surface
MOS_ZeroMemory(&surfaceParam, sizeof(surfaceParam));
surfaceParam.Type = renderHal->SurfaceTypeDefault;
surfaceParam.Boundary = RENDERHAL_SS_BOUNDARY_ORIGINAL;
if (!pixelPitch) {
surfaceParam.bWidthInDword_UV = true;
surfaceParam.bWidthInDword_Y = true;
}
surfaceParam.bRenderTarget = isRenderTarget(state, surfIndex);
//Cache configurations
state->cmHalInterface->HwSetSurfaceMemoryObjectControl(memObjCtl, &surfaceParam);
CM_CHK_MOSSTATUS_GOTOFINISH(renderHal->pfnSetupSurfaceState(
renderHal,
&surface,
&surfaceParam,
&nSurfaceEntries,
surfaceEntries,
nullptr));
for (i = 0; i < nSurfaceEntries; i++)
{
// Bind the surface State
CM_CHK_MOSSTATUS_GOTOFINISH(renderHal->pfnBindSurfaceState(
renderHal,
bindingTable,
btIndex + i,
surfaceEntries[i]));
}
state->bti2DIndexTable[ surfIndex ].nPlaneNumber = nSurfaceEntries;
// Get Offset to Current Binding Table
stateHeap = renderHal->pStateHeap;
offsetSrc = ( stateHeap->iCurSshBufferIndex * stateHeap->dwSshIntanceSize ) + // Points to the Base of Current SSH Buffer Instance
( stateHeap->iBindingTableOffset ) + // Moves the pointer to Base of Array of Binding Tables
( bindingTable * stateHeap->iBindingTableSize ) + // Moves the pointer to a Particular Binding Table
( btIndex * sizeof( uint32_t ) ); // Move the pointer to correct entry
if ( pixelPitch )
{
state->bti2DIndexTable[ surfIndex ].BTI.samplerSurfIndex = btIndex;
state->bti2DIndexTable[ surfIndex ].BTITableEntry.samplerBtiEntryPosition = stateHeap->pSshBuffer + offsetSrc;
}
else
{
state->bti2DIndexTable[ surfIndex ].BTI.regularSurfIndex = btIndex;
state->bti2DIndexTable[ surfIndex ].BTITableEntry.regularBtiEntryPosition = stateHeap->pSshBuffer + offsetSrc;
}
eStatus = MOS_STATUS_SUCCESS;
finish:
return eStatus;
}
//*-----------------------------------------------------------------------------
//| Purpose: Setup Buffer surface State with BTIndex
//| Returns: Result of the operation
//*-----------------------------------------------------------------------------
MOS_STATUS HalCm_SetupBufferSurfaceStateWithBTIndex(
PCM_HAL_STATE state,
int32_t bindingTable,
uint32_t surfIndex,
uint32_t btIndex,
bool pixelPitch)
{
PRENDERHAL_INTERFACE renderHal = state->renderHal;
MOS_STATUS eStatus;
RENDERHAL_SURFACE surface;
RENDERHAL_SURFACE_STATE_PARAMS surfaceParam;
PRENDERHAL_SURFACE_STATE_ENTRY surfaceEntry;
uint16_t memObjCtl;
uint32_t offsetSrc;
PRENDERHAL_STATE_HEAP stateHeap;
UNUSED(pixelPitch);
eStatus = MOS_STATUS_UNKNOWN;
if (surfIndex == CM_NULL_SURFACE)
{
return MOS_STATUS_SUCCESS;
}
memObjCtl = CM_DEFAULT_CACHE_TYPE;
// Check to see if surface is already assigned
if ( btIndex == ( uint32_t )state->btiBufferIndexTable[ surfIndex ].BTI.regularSurfIndex )
{
uint32_t nSurfaceEntries = state->btiBufferIndexTable[ surfIndex ].nPlaneNumber;
stateHeap = renderHal->pStateHeap;
// Get Offset to Current Binding Table
uint32_t offsetDst = ( stateHeap->iCurSshBufferIndex * stateHeap->dwSshIntanceSize ) + // Points to the Base of Current SSH Buffer Instance
( stateHeap->iBindingTableOffset ) + // Moves the pointer to Base of Array of Binding Tables
( bindingTable * stateHeap->iBindingTableSize ) + // Moves the pointer to a Particular Binding Table
( btIndex * sizeof( uint32_t ) ); // Move the pointer to correct entry
uint32_t *bindingTableEntry = ( uint32_t *)( stateHeap->pSshBuffer + offsetDst );
MOS_SecureMemcpy( bindingTableEntry, sizeof( uint32_t ) * nSurfaceEntries, state->btiBufferIndexTable[ surfIndex ].BTITableEntry.regularBtiEntryPosition, sizeof( uint32_t ) * nSurfaceEntries );
return MOS_STATUS_SUCCESS;
}
// Get Details of Buffer surface and fill the surface
CM_CHK_MOSSTATUS_GOTOFINISH(HalCm_GetSurfaceAndRegister(state, &surface, CM_ARGUMENT_SURFACEBUFFER, surfIndex, 0));
// set up buffer surface
MOS_ZeroMemory(&surfaceParam, sizeof(surfaceParam));
// Set bRenderTarget by default
surfaceParam.bRenderTarget = true;
// Setup Buffer surface
CM_CHK_MOSSTATUS_GOTOFINISH(renderHal->pfnSetupBufferSurfaceState(
renderHal,
&surface,
&surfaceParam,
&surfaceEntry));
//Cache configurations
state->cmHalInterface->HwSetSurfaceMemoryObjectControl(memObjCtl, &surfaceParam);
// Bind the surface State
CM_CHK_MOSSTATUS_GOTOFINISH(renderHal->pfnBindSurfaceState(
renderHal,
bindingTable,
btIndex,
surfaceEntry));
state->btiBufferIndexTable[ surfIndex ].BTI.regularSurfIndex = btIndex;
state->btiBufferIndexTable[ surfIndex ].nPlaneNumber = 1;
stateHeap = renderHal->pStateHeap;
offsetSrc = ( stateHeap->iCurSshBufferIndex * stateHeap->dwSshIntanceSize ) + // Points to the Base of Current SSH Buffer Instance
( stateHeap->iBindingTableOffset ) + // Moves the pointer to Base of Array of Binding Tables
( bindingTable * stateHeap->iBindingTableSize ) + // Moves the pointer to a Particular Binding Table
( btIndex * sizeof( uint32_t ) ); // Move the pointer to correct entry
state->btiBufferIndexTable[ surfIndex ].BTITableEntry.regularBtiEntryPosition = stateHeap->pSshBuffer + offsetSrc;
eStatus = MOS_STATUS_SUCCESS;
finish:
return eStatus;
}
MOS_STATUS HalCm_Setup2DSurfaceUPStateWithBTIndex(
PCM_HAL_STATE state,
int32_t bindingTable,
uint32_t surfIndex,
uint32_t btIndex,
bool pixelPitch)
{
MOS_STATUS eStatus;
RENDERHAL_SURFACE surface;
RENDERHAL_SURFACE_STATE_PARAMS surfaceParam;
PRENDERHAL_INTERFACE renderHal;
PRENDERHAL_SURFACE_STATE_ENTRY surfaceEntries[MHW_MAX_SURFACE_PLANES];
int32_t nSurfaceEntries, i;
uint16_t memObjCtl;
uint32_t offsetSrc;
PRENDERHAL_STATE_HEAP stateHeap;
eStatus = MOS_STATUS_UNKNOWN;
renderHal = state->renderHal;
if (surfIndex == CM_NULL_SURFACE)
{
return MOS_STATUS_SUCCESS;
}
memObjCtl = CM_DEFAULT_CACHE_TYPE;
// Check to see if surface is already assigned
uint32_t nBTInTable = ( unsigned char )CM_INVALID_INDEX;
if ( pixelPitch )
{
nBTInTable = state->bti2DUPIndexTable[ surfIndex ].BTI.samplerSurfIndex;
}
else
{
nBTInTable = state->bti2DUPIndexTable[ surfIndex ].BTI.regularSurfIndex;
}
if ( btIndex == nBTInTable )
{
uint32_t nSurfaceEntries = state->bti2DUPIndexTable[ surfIndex ].nPlaneNumber;
stateHeap = renderHal->pStateHeap;
// Get Offset to Current Binding Table
uint32_t offsetDst = ( stateHeap->iCurSshBufferIndex * stateHeap->dwSshIntanceSize ) + // Points to the Base of Current SSH Buffer Instance
( stateHeap->iBindingTableOffset ) + // Moves the pointer to Base of Array of Binding Tables
( bindingTable * stateHeap->iBindingTableSize ) + // Moves the pointer to a Particular Binding Table
( btIndex * sizeof( uint32_t ) ); // Move the pointer to correct entry
uint32_t *bindingTableEntry = ( uint32_t *)( stateHeap->pSshBuffer + offsetDst );
if ( pixelPitch )
{
MOS_SecureMemcpy( bindingTableEntry, sizeof( uint32_t ) * nSurfaceEntries, state->bti2DUPIndexTable[ surfIndex ].BTITableEntry.samplerBtiEntryPosition, sizeof( uint32_t ) * nSurfaceEntries );
}
else
{
MOS_SecureMemcpy( bindingTableEntry, sizeof( uint32_t ) * nSurfaceEntries, state->bti2DUPIndexTable[ surfIndex ].BTITableEntry.regularBtiEntryPosition, sizeof( uint32_t ) * nSurfaceEntries );
}
return MOS_STATUS_SUCCESS;
}
// Get Details of 2DUP surface and fill the surface
CM_CHK_MOSSTATUS_GOTOFINISH( HalCm_GetSurfaceAndRegister( state, &surface, CM_ARGUMENT_SURFACE2D_UP, surfIndex, pixelPitch ) );
// Setup 2D surface
MOS_ZeroMemory( &surfaceParam, sizeof( surfaceParam ) );
surfaceParam.Type = renderHal->SurfaceTypeDefault;
surfaceParam.Boundary = RENDERHAL_SS_BOUNDARY_ORIGINAL;
if ( !pixelPitch )
{
surfaceParam.bWidthInDword_UV = true;
surfaceParam.bWidthInDword_Y = true;
}
surfaceParam.bRenderTarget = true;
//Cache configurations
state->cmHalInterface->HwSetSurfaceMemoryObjectControl(memObjCtl, &surfaceParam);
CM_CHK_MOSSTATUS_GOTOFINISH(renderHal->pfnSetupSurfaceState(
renderHal,
&surface,
&surfaceParam,
&nSurfaceEntries,
surfaceEntries,
nullptr));
for (i = 0; i < nSurfaceEntries; i++)
{
// Bind the surface State
CM_CHK_MOSSTATUS_GOTOFINISH(renderHal->pfnBindSurfaceState(
renderHal,
bindingTable,
btIndex + i,
surfaceEntries[i]));
}
state->bti2DUPIndexTable[ surfIndex ].nPlaneNumber = nSurfaceEntries;
stateHeap = renderHal->pStateHeap;
offsetSrc = ( stateHeap->iCurSshBufferIndex * stateHeap->dwSshIntanceSize ) + // Points to the Base of Current SSH Buffer Instance
( stateHeap->iBindingTableOffset ) + // Moves the pointer to Base of Array of Binding Tables
( bindingTable * stateHeap->iBindingTableSize ) + // Moves the pointer to a Particular Binding Table
( btIndex * sizeof( uint32_t ) ); // Move the pointer to correct entry
if ( pixelPitch )
{
state->bti2DUPIndexTable[ surfIndex ].BTI.samplerSurfIndex = btIndex;
state->bti2DUPIndexTable[ surfIndex ].BTITableEntry.samplerBtiEntryPosition = stateHeap->pSshBuffer + offsetSrc;
}
else
{
state->bti2DUPIndexTable[ surfIndex ].BTI.regularSurfIndex = btIndex;
state->bti2DUPIndexTable[ surfIndex ].BTITableEntry.regularBtiEntryPosition = stateHeap->pSshBuffer + offsetSrc;
}
eStatus = MOS_STATUS_SUCCESS;
finish:
return eStatus;
}
MOS_STATUS HalCm_SetupSampler8x8SurfaceStateWithBTIndex(
PCM_HAL_STATE state,
int32_t bindingTable,
uint32_t surfIndex,
uint32_t btIndex,
bool pixelPitch,
CM_HAL_KERNEL_ARG_KIND kind,
uint32_t addressControl )
{
MOS_STATUS eStatus;
RENDERHAL_SURFACE surface;
RENDERHAL_SURFACE_STATE_PARAMS surfaceParam;
PRENDERHAL_INTERFACE renderHal;
PRENDERHAL_SURFACE_STATE_ENTRY surfaceEntries[ MHW_MAX_SURFACE_PLANES ];
int32_t nSurfaceEntries;
uint16_t memObjCtl;
int32_t i;
uint32_t offsetSrc;
PRENDERHAL_STATE_HEAP stateHeap;
UNUSED(pixelPitch);
eStatus = MOS_STATUS_UNKNOWN;
renderHal = state->renderHal;
if ( surfIndex == CM_NULL_SURFACE )
{
eStatus = MOS_STATUS_SUCCESS;
goto finish;
}
memObjCtl = CM_DEFAULT_CACHE_TYPE;
// check to see if index is valid
if ( surfIndex >= state->cmDeviceParam.max2DSurfaceTableSize ||
Mos_ResourceIsNull( &state->umdSurf2DTable[ surfIndex ].osResource ) )
{
eStatus = MOS_STATUS_INVALID_PARAMETER;
CM_ASSERTMESSAGE(
"Invalid 2D surface array index '%d'", surfIndex );
goto finish;
}
// Get Details of Sampler8x8 surface and fill the surface
CM_CHK_MOSSTATUS_GOTOFINISH( HalCm_GetSurfaceAndRegister( state, &surface, kind, surfIndex, 0 ) );
// Setup surface
MOS_ZeroMemory( &surfaceParam, sizeof( surfaceParam ) );
surfaceParam.Type = renderHal->SurfaceTypeAdvanced;
surfaceParam.bRenderTarget = true;
surfaceParam.bWidthInDword_Y = false;
surfaceParam.bWidthInDword_UV = false;
surfaceParam.Boundary = RENDERHAL_SS_BOUNDARY_ORIGINAL;
surfaceParam.bVASurface = ( kind == CM_ARGUMENT_SURFACE_SAMPLER8X8_VA ) ? 1 : 0;
surfaceParam.AddressControl = addressControl;
state->cmHalInterface->HwSetSurfaceMemoryObjectControl(memObjCtl, &surfaceParam );
renderHal->bEnableP010SinglePass = state->cmHalInterface->IsP010SinglePassSupported();
nSurfaceEntries = 0;
CM_CHK_MOSSTATUS_GOTOFINISH( renderHal->pfnSetupSurfaceState(
renderHal,
&surface,
&surfaceParam,
&nSurfaceEntries,
surfaceEntries,
nullptr ) );
CM_ASSERT( nSurfaceEntries == 1 );
for ( i = 0; i < nSurfaceEntries; i++ )
{
// Bind the surface State
CM_CHK_MOSSTATUS_GOTOFINISH( renderHal->pfnBindSurfaceState(
renderHal,
bindingTable,
btIndex + i,
surfaceEntries[ i ] ) );
}
stateHeap = renderHal->pStateHeap;
offsetSrc = ( stateHeap->iCurSshBufferIndex * stateHeap->dwSshIntanceSize ) + // Points to the Base of Current SSH Buffer Instance
( stateHeap->iBindingTableOffset ) + // Moves the pointer to Base of Array of Binding Tables
( bindingTable * stateHeap->iBindingTableSize ) + // Moves the pointer to a Particular Binding Table
( btIndex * sizeof( uint32_t ) ); // Move the pointer to correct entry
state->bti2DIndexTable[ surfIndex ].nPlaneNumber = nSurfaceEntries;
state->bti2DIndexTable[ surfIndex ].BTITableEntry.sampler8x8BtiEntryPosition = stateHeap->pSshBuffer + offsetSrc;
state->bti2DIndexTable[ surfIndex ].BTI.sampler8x8SurfIndex = btIndex;
eStatus = MOS_STATUS_SUCCESS;
finish:
renderHal->bEnableP010SinglePass = false;
return eStatus;
}
//*-----------------------------------------------------------------------------
//| Purpose: Setup 3D surface State with BTIndex
//| Returns: Result of the operation
//*-----------------------------------------------------------------------------
MOS_STATUS HalCm_Setup3DSurfaceStateWithBTIndex(
PCM_HAL_STATE state,
int32_t bindingTable,
uint32_t surfIndex,
uint32_t btIndex)
{
PRENDERHAL_INTERFACE renderHal = state->renderHal;
MOS_STATUS eStatus;
RENDERHAL_SURFACE surface;
RENDERHAL_SURFACE_STATE_PARAMS surfaceParam;
PRENDERHAL_SURFACE_STATE_ENTRY surfaceEntries[MHW_MAX_SURFACE_PLANES];
int32_t nSurfaceEntries, i;
uint16_t memObjCtl;
uint32_t offsetSrc;
PRENDERHAL_STATE_HEAP stateHeap;
eStatus = MOS_STATUS_UNKNOWN;
nSurfaceEntries = 0;
if (surfIndex == CM_NULL_SURFACE)
{
return MOS_STATUS_SUCCESS;
}
memObjCtl = CM_DEFAULT_CACHE_TYPE;
// check the surfIndex
if (surfIndex >= state->cmDeviceParam.max3DSurfaceTableSize ||
Mos_ResourceIsNull(&state->surf3DTable[surfIndex].osResource))
{
eStatus = MOS_STATUS_INVALID_PARAMETER;
CM_ASSERTMESSAGE(
"Invalid 3D surface array index '%d'", surfIndex);
return MOS_STATUS_UNKNOWN;
}
// Check to see if surface is already assigned
uint32_t nBTInTable = (unsigned char)CM_INVALID_INDEX;
nBTInTable = state->bti3DIndexTable[surfIndex].BTI.regularSurfIndex;
if (btIndex == nBTInTable)
{
nSurfaceEntries = state->bti3DIndexTable[surfIndex].nPlaneNumber;
stateHeap = renderHal->pStateHeap;
// Get Offset to Current Binding Table
uint32_t offsetDst = (stateHeap->iCurSshBufferIndex * stateHeap->dwSshIntanceSize) + // Points to the Base of Current SSH Buffer Instance
(stateHeap->iBindingTableOffset) + // Moves the pointer to Base of Array of Binding Tables
(bindingTable * stateHeap->iBindingTableSize) + // Moves the pointer to a Particular Binding Table
(btIndex * sizeof(uint32_t)); // Move the pointer to correct entry
uint32_t *bindingTableEntry = (uint32_t*)(stateHeap->pSshBuffer + offsetDst);
MOS_SecureMemcpy(bindingTableEntry, sizeof(uint32_t)* nSurfaceEntries, state->bti3DIndexTable[surfIndex].BTITableEntry.regularBtiEntryPosition, sizeof(uint32_t)* nSurfaceEntries);
return MOS_STATUS_SUCCESS;
}
// Get Details of 3D surface and fill the surface
CM_CHK_MOSSTATUS_GOTOFINISH(HalCm_GetSurfaceAndRegister(state, &surface, CM_ARGUMENT_SURFACE3D, surfIndex, false));
// Setup 3D surface
MOS_ZeroMemory(&surfaceParam, sizeof(surfaceParam));
surfaceParam.Type = renderHal->SurfaceTypeDefault;
surfaceParam.Boundary = RENDERHAL_SS_BOUNDARY_ORIGINAL;
//Cache configurations
state->cmHalInterface->HwSetSurfaceMemoryObjectControl(memObjCtl, &surfaceParam);
//Set bRenderTarget by default
surfaceParam.bRenderTarget = true;
CM_CHK_MOSSTATUS_GOTOFINISH(renderHal->pfnSetupSurfaceState(
renderHal,
&surface,
&surfaceParam,
&nSurfaceEntries,
surfaceEntries,
nullptr));
for (i = 0; i < nSurfaceEntries; i++)
{
// Bind the surface State
CM_CHK_MOSSTATUS_GOTOFINISH(renderHal->pfnBindSurfaceState(
renderHal,
bindingTable,
btIndex + i,
surfaceEntries[i]));
}
state->bti3DIndexTable[surfIndex].BTI.regularSurfIndex = btIndex;
state->bti3DIndexTable[surfIndex].nPlaneNumber = nSurfaceEntries;
// Get Offset to Current Binding Table
stateHeap = renderHal->pStateHeap;
offsetSrc = (stateHeap->iCurSshBufferIndex * stateHeap->dwSshIntanceSize) + // Points to the Base of Current SSH Buffer Instance
(stateHeap->iBindingTableOffset) + // Moves the pointer to Base of Array of Binding Tables
(bindingTable * stateHeap->iBindingTableSize) + // Moves the pointer to a Particular Binding Table
(btIndex * sizeof(uint32_t)); // Move the pointer to correct entry
state->bti3DIndexTable[surfIndex].BTI.regularSurfIndex = btIndex;
state->bti3DIndexTable[surfIndex].BTITableEntry.regularBtiEntryPosition = stateHeap->pSshBuffer + offsetSrc;
eStatus = MOS_STATUS_SUCCESS;
finish:
return eStatus;
}
//|-----------------------------------------------------------------------------
//| Purpose : Tag-based Synchronization on Resource
//| Input : state - Hal CM State
//| surface surface
//| isWrite - Write or Read
//| Returns : Result of the operation
//|-----------------------------------------------------------------------------
MOS_STATUS HalCm_SyncOnResource(
PCM_HAL_STATE state,
PMOS_SURFACE surface,
bool isWrite)
{
MOS_STATUS eStatus;
PMOS_INTERFACE osInterface;
eStatus = MOS_STATUS_SUCCESS;
osInterface = state->osInterface;
if (surface == nullptr || Mos_ResourceIsNull(&surface->OsResource))
{
CM_ASSERTMESSAGE("Input resource is not valid.");
eStatus = MOS_STATUS_UNKNOWN;
return eStatus;
}
osInterface->pfnSyncOnResource(
osInterface,
&(surface->OsResource),
state->osInterface->CurrentGpuContextOrdinal, //state->GpuContext,
isWrite);
// Sync Render Target with Overlay Context
if (surface->bOverlay)
{
osInterface->pfnSyncOnOverlayResource(
osInterface,
&(surface->OsResource),
state->osInterface->CurrentGpuContextOrdinal);
}
return eStatus;
}
//!
//! \brief Send Media Walker State
//! \details Send MEDIA_OBJECT_WALKER command
//! \param PCM_HAL_STATE state
//! [in] Pointer to CM_HAL_STATE Structure
//! \param PRENDERHAL_INTERFACE renderHal
//! [in] Pointer to Hardware Interface Structure
//! \param PMOS_COMMAND_BUFFER cmdBuffer
//! [in] Pointer to Command Buffer
//! \return MOS_STATUS
//!
MOS_STATUS HalCm_SendMediaWalkerState(
PCM_HAL_STATE state,
PCM_HAL_KERNEL_PARAM kernelParam,
PMOS_COMMAND_BUFFER cmdBuffer)
{
PRENDERHAL_INTERFACE renderHal;
MHW_WALKER_PARAMS mediaWalkerParams;
MOS_STATUS eStatus;
eStatus = MOS_STATUS_SUCCESS;
renderHal = state->renderHal;
MOS_SecureMemcpy(&mediaWalkerParams, sizeof(MHW_WALKER_PARAMS), &kernelParam->walkerParams, sizeof(CM_HAL_WALKER_PARAMS));
if (kernelParam->kernelThreadSpaceParam.threadSpaceWidth)
{
//per-kernel thread space is set, need use its own dependency mask
mediaWalkerParams.UseScoreboard = renderHal->VfeScoreboard.ScoreboardEnable;
mediaWalkerParams.ScoreboardMask = kernelParam->kernelThreadSpaceParam.globalDependencyMask;
}
else
{
//No per-kernel thread space setting, need use per-task depedency mask
mediaWalkerParams.UseScoreboard = renderHal->VfeScoreboard.ScoreboardEnable;
mediaWalkerParams.ScoreboardMask = renderHal->VfeScoreboard.ScoreboardMask;
}
eStatus = renderHal->pMhwRenderInterface->AddMediaObjectWalkerCmd(
cmdBuffer, &mediaWalkerParams);
return eStatus;
}
//!
//! \brief Send GpGpu Walker State
//! \details Send GPGPU_WALKER state
//! \param PCM_HAL_STATE state
//! [in] Pointer to CM_HAL_STATE Structure
//! \param PRENDERHAL_INTERFACE renderHal
//! [in] Pointer to Hardware Interface Structure
//! \param PMOS_COMMAND_BUFFER cmdBuffer
//! [in] Pointer to Command Buffer
//! \return MOS_STATUS
//!
MOS_STATUS HalCm_SendGpGpuWalkerState(
PCM_HAL_STATE state,
PCM_HAL_KERNEL_PARAM kernelParam,
PMOS_COMMAND_BUFFER cmdBuffer)
{
MhwRenderInterface *mhwRender;
MHW_GPGPU_WALKER_PARAMS gpGpuWalkerParams;
MOS_STATUS eStatus;
eStatus = MOS_STATUS_SUCCESS;
mhwRender = state->renderHal->pMhwRenderInterface;
gpGpuWalkerParams.InterfaceDescriptorOffset = kernelParam->gpgpuWalkerParams.interfaceDescriptorOffset;
gpGpuWalkerParams.GpGpuEnable = kernelParam->gpgpuWalkerParams.gpgpuEnabled;
gpGpuWalkerParams.GroupWidth = kernelParam->gpgpuWalkerParams.groupWidth;
gpGpuWalkerParams.GroupHeight = kernelParam->gpgpuWalkerParams.groupHeight;
gpGpuWalkerParams.GroupDepth = kernelParam->gpgpuWalkerParams.groupDepth;
gpGpuWalkerParams.ThreadWidth = kernelParam->gpgpuWalkerParams.threadWidth;
gpGpuWalkerParams.ThreadHeight = kernelParam->gpgpuWalkerParams.threadHeight;
gpGpuWalkerParams.ThreadDepth = kernelParam->gpgpuWalkerParams.threadDepth;
gpGpuWalkerParams.SLMSize = kernelParam->slmSize;
eStatus = mhwRender->AddGpGpuWalkerStateCmd(cmdBuffer, &gpGpuWalkerParams);
return eStatus;
}
//!
//! \brief surface Format Convert
//! \details Convert RENDERHAL_SURFACE to MHW_VEBOX_SURFACE
//! \param PRENDERHAL_SURFACE renderHalSurface
//! [in] Pointer to RENDERHAL_SURFACE Structure
//! \param PMHW_VEBOX_SURFACE_PARAMS mhwVeboxSurface
//! [in] Pointer to PMHW_VEBOX_SURFACE_PARAMS
//! \return MOS_STATUS
//!
MOS_STATUS HalCm_Convert_RENDERHAL_SURFACE_To_MHW_VEBOX_SURFACE(
PRENDERHAL_SURFACE renderHalSurface,
PMHW_VEBOX_SURFACE_PARAMS mhwVeboxSurface)
{
PMOS_SURFACE surface;
MOS_STATUS eStatus = MOS_STATUS_SUCCESS;
CM_CHK_NULL_GOTOFINISH_MOSERROR(renderHalSurface);
CM_CHK_NULL_GOTOFINISH_MOSERROR(mhwVeboxSurface);
surface = &renderHalSurface->OsSurface;
mhwVeboxSurface->Format = surface->Format;
mhwVeboxSurface->dwWidth = surface->dwWidth;
mhwVeboxSurface->dwHeight = surface->dwHeight;
mhwVeboxSurface->dwPitch = surface->dwPitch;
if (surface->dwPitch > 0)
{
mhwVeboxSurface->dwUYoffset = ((surface->UPlaneOffset.iSurfaceOffset - surface->YPlaneOffset.iSurfaceOffset) / surface->dwPitch)
+ surface->UPlaneOffset.iYOffset;
}
mhwVeboxSurface->TileType = surface->TileType;
mhwVeboxSurface->rcMaxSrc = renderHalSurface->rcMaxSrc;
mhwVeboxSurface->pOsResource = &surface->OsResource;
finish:
return eStatus;
}
//!
//! \brief Set Vtune Profiling Flag
//! \details Trun Vtune Profiling Flag On or off
//! \param PCM_HAL_STATE state
//! [in] Pointer to CM_HAL_STATE Structure
//! \return MOS_STATUS_SUCCESS
//!
MOS_STATUS HalCm_SetVtuneProfilingFlag(
PCM_HAL_STATE state,
bool vtuneOn)
{
state->vtuneProfilerOn = vtuneOn;
return MOS_STATUS_SUCCESS;
}
//*-----------------------------------------------------------------------------
//| Purpose: Get the offset for the Task Sync Location given the task ID
//| Returns: Sync Location
//*-----------------------------------------------------------------------------
int32_t HalCm_GetTaskSyncLocation(
PCM_HAL_STATE state,
int32_t taskId) // [in] Task ID
{
return (taskId * state->cmHalInterface->GetTimeStampResourceSize());
}
void HalCm_GetLegacyRenderHalL3Setting( CmHalL3Settings *l3SettingsPtr, RENDERHAL_L3_CACHE_SETTINGS *l3SettingsLegacyPtr )
{
*l3SettingsLegacyPtr = {};
l3SettingsLegacyPtr->bOverride = l3SettingsPtr->overrideSettings;
l3SettingsLegacyPtr->bEnableSLM = l3SettingsPtr->enableSlm;
l3SettingsLegacyPtr->bL3CachingEnabled = l3SettingsPtr->l3CachingEnabled;
l3SettingsLegacyPtr->bCntlRegOverride = l3SettingsPtr->cntlRegOverride;
l3SettingsLegacyPtr->bCntlReg2Override = l3SettingsPtr->cntlReg2Override;
l3SettingsLegacyPtr->bCntlReg3Override = l3SettingsPtr->cntlReg3Override;
l3SettingsLegacyPtr->bSqcReg1Override = l3SettingsPtr->sqcReg1Override;
l3SettingsLegacyPtr->bSqcReg4Override = l3SettingsPtr->sqcReg4Override;
l3SettingsLegacyPtr->bLra1RegOverride = l3SettingsPtr->lra1RegOverride;
l3SettingsLegacyPtr->dwCntlReg = l3SettingsPtr->cntlReg;
l3SettingsLegacyPtr->dwCntlReg2 = l3SettingsPtr->cntlReg2;
l3SettingsLegacyPtr->dwCntlReg3 = l3SettingsPtr->cntlReg3;
l3SettingsLegacyPtr->dwSqcReg1 = l3SettingsPtr->sqcReg1;
l3SettingsLegacyPtr->dwSqcReg4 = l3SettingsPtr->sqcReg4;
l3SettingsLegacyPtr->dwLra1Reg = l3SettingsPtr->lra1Reg;
return;
}
uint64_t HalCm_ConvertTicksToNanoSeconds(
PCM_HAL_STATE state,
uint64_t ticks)
{
if (state->tsFrequency == 0)
{
// if KMD doesn't report an valid value, fall back to default configs
return state->cmHalInterface->ConverTicksToNanoSecondsDefault(ticks);
}
return (ticks * 1000000000) / (state->tsFrequency);
}
//!
//! \brief Check GPU context
//! \details Check if the GPU context is valid for CM layer
//! \param MOS_GPU_CONTEXT gpuContext
//! [in] GPU Context ordinal
//! \return true/false
//!
bool HalCm_IsValidGpuContext(
MOS_GPU_CONTEXT gpuContext)
{
if( gpuContext == MOS_GPU_CONTEXT_RENDER3
|| gpuContext == MOS_GPU_CONTEXT_RENDER4
|| gpuContext == MOS_GPU_CONTEXT_CM_COMPUTE
|| gpuContext == MOS_GPU_CONTEXT_VEBOX)
{
return true;
}
else
{
CM_ASSERTMESSAGE("Invalid GPU context for CM.");
return false;
}
}
|
/**
* Prompt user to enable GPS and Location Services
*
* @param mGoogleApiClient
* @param activity
*/
public static void locationChecker(GoogleApiClient mGoogleApiClient, final Activity activity) {
LocationRequest locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(30 * 1000);
locationRequest.setFastestInterval(5 * 1000);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(locationRequest);
builder.setAlwaysShow(true);
PendingResult<LocationSettingsResult> result =
LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient, builder.build());
result.setResultCallback(getResultCallback(activity));
} |
/** Returns the object with the settings used for calls to scheduleExperiment. */
public OperationCallSettings<ScheduleExperimentRequest, Empty, ScheduleExperimentMetadata>
scheduleExperimentOperationSettings() {
return ((ExperimentServiceStubSettings) getStubSettings())
.scheduleExperimentOperationSettings();
} |
# Copyright 2021 Huawei Technologies Co., Ltd
#
# 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 numpy as np
import pytest
import mindspore
import mindspore.context as context
import mindspore.nn as nn
from mindspore import Tensor
from mindspore.ops.operations import _grad_ops as G
from mindspore.ops.functional import vmap
context.set_context(mode=context.GRAPH_MODE, device_target="CPU")
class LayerNormGradNet(nn.Cell):
def __init__(self, begin_norm_axis, begin_params_axis):
super(LayerNormGradNet, self).__init__()
self.norm = G.LayerNormGrad(begin_norm_axis, begin_params_axis)
def construct(self, dy, x, var, mean, gamma):
return self.norm(dy, x, var, mean, gamma)
def layer_norm_grad_np(x, dy, gamma, epsilon, begin_norm_axis, begin_params_axis):
begin_norm_axis = begin_norm_axis if begin_norm_axis >= 0 else begin_norm_axis + len(x.shape)
begin_params_axis = begin_params_axis if begin_params_axis >= 0 else begin_params_axis + len(x.shape)
norm_axis = [i for i in range(begin_norm_axis, len(x.shape))]
param_axis = [i for i in range(0, begin_params_axis)]
num = 1
for i in range(begin_norm_axis, len(x.shape)):
num *= x.shape[i]
mean = np.mean(x, axis=tuple(norm_axis), keepdims=True)
var = np.var(x, axis=tuple(norm_axis), keepdims=True)
gamma = gamma.reshape((*((1,) * begin_params_axis), *x.shape[begin_params_axis:]))
dg = np.sum(dy * np.power(var + epsilon, -0.5) * (x - mean), axis=tuple(param_axis), keepdims=True)
db = np.sum(dy, axis=tuple(param_axis), keepdims=True)
sum1 = np.sum((-0.5) * dy * gamma * (x - mean) * np.power(var + epsilon, -1.5), axis=tuple(norm_axis),
keepdims=True)
sum2 = np.sum(dy * gamma, axis=tuple(norm_axis), keepdims=True)
sum3 = np.sum(-2.0 * (x - mean), axis=tuple(norm_axis), keepdims=True)
dx1 = dy * gamma * np.power(var + epsilon, -0.5)
dx2 = sum1 * 2.0 / num * (x - mean)
dx3 = ((-1.0) * np.power(var + epsilon, -0.5) * sum2 + (1.0 / num) * sum1 * sum3) * (1.0 / num)
dx = dx1 + dx2 + dx3
ret = (dx, dg, db, mean, var)
return ret
@pytest.mark.level0
@pytest.mark.platform_x86_cpu
@pytest.mark.env_onecard
def test_layernormgrad0():
begin_norm_axis = 1
begin_params_axis = 1
x_np = np.random.randn(4096, 3072).astype(np.float32)
dy_np = np.random.randn(4096, 3072).astype(np.float32)
gamma_np = np.random.randn(*x_np.shape[begin_params_axis:]).astype(np.float32)
epsilon = 10e-12
dx_np, dg_np, db_np, mean_np, var_np = layer_norm_grad_np(x_np, dy_np, gamma_np, epsilon, begin_norm_axis,
begin_params_axis)
dy_ms = Tensor(dy_np)
x_ms = Tensor(x_np)
var_ms = Tensor(var_np)
mean_ms = Tensor(mean_np)
gamma_ms = Tensor(gamma_np)
net = LayerNormGradNet(begin_norm_axis, begin_params_axis)
dx_ms, dg_ms, db_ms = net(x_ms, dy_ms, var_ms, mean_ms, gamma_ms)
assert np.allclose(dx_ms.asnumpy(), dx_np, rtol=1e-4, atol=1e-4)
assert np.allclose(dg_ms.asnumpy(), dg_np, rtol=1e-4, atol=1e-3)
assert np.allclose(db_ms.asnumpy(), db_np, rtol=1e-4, atol=1e-3)
@pytest.mark.level0
@pytest.mark.platform_x86_cpu
@pytest.mark.env_onecard
def test_layernormgrad1():
begin_norm_axis = 1
begin_params_axis = 1
x_np = np.random.randn(640, 768).astype(np.float32)
dy_np = np.random.randn(640, 768).astype(np.float32)
gamma_np = np.random.randn(*x_np.shape[begin_params_axis:]).astype(np.float32)
epsilon = 10e-12
dx_np, dg_np, db_np, mean_np, var_np = layer_norm_grad_np(x_np, dy_np, gamma_np, epsilon, begin_norm_axis,
begin_params_axis)
dy_ms = Tensor(dy_np)
x_ms = Tensor(x_np)
var_ms = Tensor(var_np)
mean_ms = Tensor(mean_np)
gamma_ms = Tensor(gamma_np)
net = LayerNormGradNet(begin_norm_axis, begin_params_axis)
dx_ms, dg_ms, db_ms = net(x_ms, dy_ms, var_ms, mean_ms, gamma_ms)
assert np.allclose(dx_ms.asnumpy(), dx_np, rtol=1e-4, atol=1e-4)
assert np.allclose(dg_ms.asnumpy(), dg_np, rtol=1e-4, atol=1e-3)
assert np.allclose(db_ms.asnumpy(), db_np, rtol=1e-4, atol=1e-3)
@pytest.mark.level0
@pytest.mark.platform_x86_cpu
@pytest.mark.env_onecard
def test_layernormgrad2():
begin_norm_axis = -1
begin_params_axis = -1
x_np = np.random.randn(32, 128, 768).astype(np.float32)
dy_np = np.random.randn(32, 128, 768).astype(np.float32)
gamma_np = np.random.randn(*x_np.shape[begin_params_axis:]).astype(np.float32)
epsilon = 10e-12
dx_np, dg_np, db_np, mean_np, var_np = layer_norm_grad_np(x_np, dy_np, gamma_np, epsilon, begin_norm_axis,
begin_params_axis)
dy_ms = Tensor(dy_np)
x_ms = Tensor(x_np)
var_ms = Tensor(var_np)
mean_ms = Tensor(mean_np)
gamma_ms = Tensor(gamma_np)
net = LayerNormGradNet(begin_norm_axis, begin_params_axis)
dx_ms, dg_ms, db_ms = net(x_ms, dy_ms, var_ms, mean_ms, gamma_ms)
assert np.allclose(dx_ms.asnumpy(), dx_np, rtol=1e-4, atol=1e-4)
assert np.allclose(dg_ms.asnumpy(), dg_np, rtol=1e-4, atol=1e-3)
assert np.allclose(db_ms.asnumpy(), db_np, rtol=1e-4, atol=1e-3)
@pytest.mark.level0
@pytest.mark.platform_x86_cpu
@pytest.mark.env_onecard
def test_layernormgrad3():
begin_norm_axis = -1
begin_params_axis = -1
x_np = np.random.randn(32, 64).astype(np.float32)
dy_np = np.random.randn(32, 64).astype(np.float32)
gamma_np = np.random.randn(*x_np.shape[begin_params_axis:]).astype(np.float32)
epsilon = 10e-12
dx_np, dg_np, db_np, mean_np, var_np = layer_norm_grad_np(x_np, dy_np, gamma_np, epsilon, begin_norm_axis,
begin_params_axis)
dy_ms = Tensor(dy_np)
x_ms = Tensor(x_np)
var_ms = Tensor(var_np)
mean_ms = Tensor(mean_np)
gamma_ms = Tensor(gamma_np)
net = LayerNormGradNet(begin_norm_axis, begin_params_axis)
dx_ms, dg_ms, db_ms = net(x_ms, dy_ms, var_ms, mean_ms, gamma_ms)
assert np.allclose(dx_ms.asnumpy(), dx_np, rtol=1e-4, atol=1e-4)
assert np.allclose(dg_ms.asnumpy(), dg_np, rtol=1e-4, atol=1e-3)
assert np.allclose(db_ms.asnumpy(), db_np, rtol=1e-4, atol=1e-3)
@pytest.mark.level0
@pytest.mark.platform_x86_cpu
@pytest.mark.env_onecard
def test_layernormgrad4():
begin_norm_axis = -1
begin_params_axis = -1
x_np = np.random.randn(32, 64).astype(np.float32)
dy_np = np.random.randn(32, 64).astype(np.float32)
gamma_np = np.random.randn(*x_np.shape[begin_params_axis:]).astype(np.float32)
epsilon = 10e-12
dx_np, dg_np, db_np, mean_np, var_np = layer_norm_grad_np(x_np, dy_np, gamma_np, epsilon, begin_norm_axis,
begin_params_axis)
dy_ms = Tensor(dy_np)
x_ms = Tensor(x_np)
var_ms = Tensor(var_np)
mean_ms = Tensor(mean_np)
gamma_ms = Tensor(gamma_np)
net = LayerNormGradNet(begin_norm_axis, begin_params_axis)
dx_ms, dg_ms, db_ms = net(x_ms, dy_ms, var_ms, mean_ms, gamma_ms)
assert np.allclose(dx_ms.asnumpy(), dx_np, rtol=1e-4, atol=1e-4)
assert np.allclose(dg_ms.asnumpy(), dg_np, rtol=1e-4, atol=1e-3)
assert np.allclose(db_ms.asnumpy(), db_np, rtol=1e-4, atol=1e-3)
@pytest.mark.level0
@pytest.mark.platform_x86_cpu
@pytest.mark.env_onecard
def test_layernormgrad5():
begin_norm_axis = 2
begin_params_axis = 1
x_np = np.random.randn(128, 2, 16, 32).astype(np.float32)
dy_np = np.random.randn(128, 2, 16, 32).astype(np.float32)
gamma_np = np.random.randn(*x_np.shape[begin_params_axis:]).astype(np.float32)
epsilon = 10e-12
dx_np, dg_np, db_np, mean_np, var_np = layer_norm_grad_np(x_np, dy_np, gamma_np, epsilon, begin_norm_axis,
begin_params_axis)
dy_ms = Tensor(dy_np)
x_ms = Tensor(x_np)
var_ms = Tensor(var_np)
mean_ms = Tensor(mean_np)
gamma_ms = Tensor(gamma_np)
net = LayerNormGradNet(begin_norm_axis, begin_params_axis)
dx_ms, dg_ms, db_ms = net(x_ms, dy_ms, var_ms, mean_ms, gamma_ms)
assert np.allclose(dx_ms.asnumpy(), dx_np, rtol=1e-4, atol=1e-4)
assert np.allclose(db_ms.asnumpy(), db_np, rtol=1e-4, atol=1e-3)
assert np.allclose(dg_ms.asnumpy(), dg_np, rtol=1e-4, atol=1e-3)
@pytest.mark.level0
@pytest.mark.platform_x86_cpu
@pytest.mark.env_onecard
def test_layernormgrad_vmap():
"""
Feature: layernormgrad vmap
Description: test the layernorm vmap with in_axes=(0, 0, 0, 0, 0).
Expectation: match to np benchmark.
"""
begin_norm_axis = -1
begin_params_axis = -1
np.random.seed(20)
x_np = np.random.rand(2, 3, 4).astype(np.float32)
gamma_np = np.random.rand(2, 4).astype(np.float32)
dy_np = np.random.rand(2, 3, 4).astype(np.float32)
epsilon = 10e-12
dx_np, dg_np, db_np, mean_np, var_np = [], [], [], [], []
for i in range(2):
dx_npt, dg_npt, db_npt, mean_npt, var_npt = layer_norm_grad_np(x_np[i], dy_np[i], gamma_np[i], epsilon,
begin_norm_axis, begin_params_axis)
dx_np.append(dx_npt)
dg_np.append(dg_npt)
db_np.append(db_npt)
mean_np.append(mean_npt)
var_np.append(var_npt)
dx_np = np.stack(dx_np)
dg_np = np.concatenate(dg_np)
db_np = np.concatenate(db_np)
mean_np = np.stack(mean_np)
var_np = np.stack(var_np)
dy_ms = Tensor(dy_np)
x_ms = Tensor(x_np)
var_ms = Tensor(var_np)
mean_ms = Tensor(mean_np)
gamma_ms = Tensor(gamma_np)
net = vmap(LayerNormGradNet(begin_norm_axis, begin_params_axis), in_axes=(0, 0, 0, 0, 0))
dx_ms, dg_ms, db_ms = net(x_ms, dy_ms, var_ms, mean_ms, gamma_ms)
assert np.allclose(dx_ms.asnumpy(), dx_np, rtol=1e-4, atol=1e-4)
assert np.allclose(db_ms.asnumpy(), db_np, rtol=1e-4, atol=1e-3)
assert np.allclose(dg_ms.asnumpy(), dg_np, rtol=1e-4, atol=1e-3)
@pytest.mark.level0
@pytest.mark.platform_x86_cpu
@pytest.mark.env_onecard
def test_layernormgrad_vmap_gamma_inaxes_none():
"""
Feature: layernormgrad vmap
Description: test the layernormgrad vmap with in_axes=(0, 0, 0, 0, None).
Expectation: match to np benchmark.
"""
begin_norm_axis = -1
begin_params_axis = -1
np.random.seed(20)
x_np = np.random.rand(2, 3, 4).astype(np.float32)
gamma_np = np.random.rand(4).astype(np.float32)
dy_np = np.random.rand(2, 3, 4).astype(np.float32)
epsilon = 10e-12
dx_np, dg_np, db_np, mean_np, var_np = [], [], [], [], []
for i in range(2):
dx_npt, dg_npt, db_npt, mean_npt, var_npt = layer_norm_grad_np(x_np[i], dy_np[i], gamma_np, epsilon,
begin_norm_axis, begin_params_axis)
dx_np.append(dx_npt)
dg_np.append(dg_npt)
db_np.append(db_npt)
mean_np.append(mean_npt)
var_np.append(var_npt)
dx_np = np.stack(dx_np)
dg_np = np.concatenate(dg_np)
db_np = np.concatenate(db_np)
mean_np = np.stack(mean_np)
var_np = np.stack(var_np)
dy_ms = Tensor(dy_np)
x_ms = Tensor(x_np)
var_ms = Tensor(var_np)
mean_ms = Tensor(mean_np)
gamma_ms = Tensor(gamma_np)
net = vmap(LayerNormGradNet(begin_norm_axis, begin_params_axis), in_axes=(0, 0, 0, 0, None))
dx_ms, dg_ms, db_ms = net(x_ms, dy_ms, var_ms, mean_ms, gamma_ms)
assert np.allclose(dx_ms.asnumpy(), dx_np, rtol=1e-4, atol=1e-4)
assert np.allclose(db_ms.asnumpy(), db_np, rtol=1e-4, atol=1e-3)
assert np.allclose(dg_ms.asnumpy(), dg_np, rtol=1e-4, atol=1e-3)
def test_layernormgrad_vmap_begin_params_axis_zero():
"""
Feature: layernormgrad vmap
Description: test the layernormgrad vmap with begin_params_axis is zero.
Expectation: match to np benchmark.
"""
begin_norm_axis = 0
begin_params_axis = 0
np.random.seed(20)
x_np = np.random.rand(2, 3, 4).astype(np.float32)
gamma_np = np.random.rand(2, 3, 4).astype(np.float32)
mean_np = np.random.rand(2, 1, 1).astype(np.float32)
var_np = np.random.rand(2, 1, 1).astype(np.float32)
dy_np = np.random.rand(2, 3, 4).astype(np.float32)
dy_ms = Tensor(dy_np)
x_ms = Tensor(x_np)
var_ms = Tensor(var_np)
mean_ms = Tensor(mean_np)
gamma_ms = Tensor(gamma_np)
net = vmap(LayerNormGradNet(begin_norm_axis, begin_params_axis), in_axes=(0, 0, 0, 0, 0))
dx_ms, dg_ms, db_ms = net(x_ms, dy_ms, var_ms, mean_ms, gamma_ms)
dx_np = np.array([[[0.29349965, 0.09497279, 0.21129131, 0.20282865],
[-0.11929998, -0.01752168, -0.09565887, -0.02527836],
[-0.24030682, -0.45376804, 0.19080639, -0.04156461]],
[[-0.05764255, -0.1135768, -0.2989949, -0.06860729],
[0.30945677, -0.3742769, 0.03696045, 0.30060476],
[-0.12331586, 0.2866478, -0.2975512, 0.40029585]]])
dg_np = np.array([[[-0.21599445, 0.06744852, 0.06027506, -0.00690226],
[-0.6125504, -0.10115692, -0.2220997, -0.18417971],
[-0.09819805, -0.0273493, -0.4573944, -0.07762876]],
[[0.76242846, 0.49870878, 0.36768562, -0.05466934],
[-0.03460428, 0.07832275, 0.08179377, 0.1454187],
[0.9776515, 1.0904244, 0.21857749, 0.02462499]]])
db_np = np.array([[[0.7786879, 0.8039706, 0.7860714, 0.592287],
[0.6644892, 0.6465673, 0.42563647, 0.51356834],
[0.50125784, 0.03708381, 0.7081161, 0.6204306]],
[[0.77780855, 0.45940948, 0.37980556, 0.2918922],
[0.55722886, 0.0841636, 0.6312817, 0.9445705],
[0.89123756, 0.8785826, 0.34475163, 0.7031005]]])
assert np.allclose(dx_ms.asnumpy(), dx_np, rtol=1e-4, atol=1e-4)
assert np.allclose(db_ms.asnumpy(), db_np, rtol=1e-4, atol=1e-3)
assert np.allclose(dg_ms.asnumpy(), dg_np, rtol=1e-4, atol=1e-3)
@pytest.mark.level0
@pytest.mark.platform_x86_cpu
@pytest.mark.env_onecard
def test_layernormgrad_dynamic_shape():
"""
Feature: Test LayerNormGrad dynamic shape.
Description: The input x shape is dynamic.
Expectation: match to np benchmark.
"""
begin_norm_axis = 2
begin_params_axis = 1
x_np = np.random.randn(128, 2, 16, 32).astype(np.float32)
dy_np = np.random.randn(128, 2, 16, 32).astype(np.float32)
gamma_np = np.random.randn(*x_np.shape[begin_params_axis:]).astype(np.float32)
epsilon = 10e-12
dx_np, dg_np, db_np, mean_np, var_np = layer_norm_grad_np(x_np, dy_np, gamma_np, epsilon, begin_norm_axis,
begin_params_axis)
dy_ms = Tensor(dy_np)
x_ms = Tensor(x_np)
var_ms = Tensor(var_np)
mean_ms = Tensor(mean_np)
gamma_ms = Tensor(gamma_np)
net = LayerNormGradNet(begin_norm_axis, begin_params_axis)
x_dynamic = Tensor(shape=[None, 2, 16, 32], dtype=mindspore.float32)
net.set_inputs(x_dynamic, dy_ms, var_ms, mean_ms, gamma_ms)
dx_ms, dg_ms, db_ms = net(x_ms, dy_ms, var_ms, mean_ms, gamma_ms)
assert np.allclose(dx_ms.asnumpy(), dx_np, rtol=1e-6, atol=1e-6)
assert np.allclose(db_ms.asnumpy(), db_np, rtol=1e-6, atol=1e-3)
assert np.allclose(dg_ms.asnumpy(), dg_np, rtol=1e-6, atol=1e-3)
@pytest.mark.level0
@pytest.mark.platform_x86_cpu
@pytest.mark.env_onecard
def test_layernormgrad_double():
"""
Feature: Test LayerNormGrad double support.
Description: The input x type is double.
Expectation: match to np benchmark.
"""
begin_norm_axis = 1
begin_params_axis = 1
x_np = np.random.randn(4096, 3072).astype(np.float64)
dy_np = np.random.randn(4096, 3072).astype(np.float64)
gamma_np = np.random.randn(*x_np.shape[begin_params_axis:]).astype(np.float64)
epsilon = 10e-12
dx_np, dg_np, db_np, mean_np, var_np = layer_norm_grad_np(x_np, dy_np, gamma_np, epsilon, begin_norm_axis,
begin_params_axis)
dy_ms = Tensor(dy_np)
x_ms = Tensor(x_np)
var_ms = Tensor(var_np.astype(np.float32))
mean_ms = Tensor(mean_np.astype(np.float32))
gamma_ms = Tensor(gamma_np)
net = LayerNormGradNet(begin_norm_axis, begin_params_axis)
dx_ms, dg_ms, db_ms = net(x_ms, dy_ms, var_ms, mean_ms, gamma_ms)
assert np.allclose(dx_ms.asnumpy(), dx_np, rtol=1e-4, atol=1e-4)
assert np.allclose(dg_ms.asnumpy(), dg_np, rtol=1e-4, atol=1e-3)
assert np.allclose(db_ms.asnumpy(), db_np, rtol=1e-4, atol=1e-3)
|
/**
* Add productStock to user cart.
*/
@PutMapping
@ResponseStatus(HttpStatus.NO_CONTENT)
public void addProductToCart(
@RequestParam final String cartId,
@RequestParam final String productStockId,
@RequestParam(value = "count", required = false, defaultValue = "1") final int count) {
log.info("start addProductStock: {} to cart: {} with count: {}", productStockId, cartId, count);
cartService.addProduct(cartId, productStockId, count);
} |
<reponame>Shamann/G2Plot
import { M, randomFloat } from 'miz';
import { sankey } from '../../../../../src/plots/sankey/sankey';
import { cutoffCircle } from '../../../../../src/plots/sankey/circle';
import { transformDataToNodeLinkData } from '../../../../../src/utils/data';
const C = [
'A',
'B',
'C',
'D',
'E',
'F',
'G',
'H',
'I',
'J',
'K',
'L',
'M',
'N',
'O',
'P',
'K',
'R',
'S',
'T',
'U',
'V',
'W',
'Z',
'Y',
'Z',
];
describe('sankey', () => {
it('monkey for deep', () => {
for (let i = 0; i < 100; i++) {
const layout = sankey()
.nodeWidth(0.008)
// @ts-ignore
.nodePadding(0.02)
.nodeAlign((_, maxDepth) => randomFloat(0, maxDepth, 0))
.extent([
[0, 0],
[1, 1],
]);
const data = M.arrayOf(
M.shape({
source: M.oneOf(C),
target: M.oneOf(C),
value: M.number(1, 10),
}),
10,
50
).mock();
const sankeyLayoutInputData = transformDataToNodeLinkData(
cutoffCircle(data, 'source', 'target'),
'source',
'target',
'value'
);
// 不报错即可
expect(() => {
layout(sankeyLayoutInputData);
}).not.toThrow();
}
});
});
|
/*
* 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.geode.internal.jta;
import static org.apache.geode.cache.RegionShortcut.PARTITION;
import static org.apache.geode.cache.client.ClientRegionShortcut.LOCAL;
import static org.apache.geode.test.dunit.VM.getHostName;
import static org.apache.geode.test.dunit.VM.getVM;
import static org.junit.Assert.assertEquals;
import java.io.Serializable;
import java.util.concurrent.TimeUnit;
import javax.transaction.Status;
import org.awaitility.Awaitility;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.apache.geode.cache.PartitionAttributesFactory;
import org.apache.geode.cache.Region;
import org.apache.geode.cache.RegionFactory;
import org.apache.geode.cache.RegionShortcut;
import org.apache.geode.cache.TransactionId;
import org.apache.geode.cache.client.ClientRegionFactory;
import org.apache.geode.cache.client.PoolFactory;
import org.apache.geode.cache.client.PoolManager;
import org.apache.geode.cache.client.internal.InternalClientCache;
import org.apache.geode.cache.client.internal.PoolImpl;
import org.apache.geode.cache.server.CacheServer;
import org.apache.geode.distributed.internal.ServerLocation;
import org.apache.geode.internal.cache.InternalCache;
import org.apache.geode.internal.cache.PeerTXStateStub;
import org.apache.geode.internal.cache.TXManagerImpl;
import org.apache.geode.internal.cache.TXStateProxyImpl;
import org.apache.geode.internal.cache.tier.sockets.CacheServerTestUtil;
import org.apache.geode.internal.cache.tx.ClientTXStateStub;
import org.apache.geode.internal.logging.LogService;
import org.apache.geode.test.dunit.VM;
import org.apache.geode.test.dunit.rules.CacheRule;
import org.apache.geode.test.dunit.rules.ClientCacheRule;
import org.apache.geode.test.dunit.rules.DistributedRule;
import org.apache.geode.test.junit.rules.serializable.SerializableTestName;
@SuppressWarnings("serial")
public class ClientServerJTAFailoverDistributedTest implements Serializable {
private final int key = 1;
private final String value = "value1";
private final String newValue = "value2";
private String hostName;
private String uniqueName;
private String regionName;
private String replicateRegionName;
private VM server1;
private VM server2;
private VM server3;
private VM client1;
private int port1;
private int port2;
private boolean hasReplicateRegion = false;
@Rule
public DistributedRule distributedRule = new DistributedRule();
@Rule
public CacheRule cacheRule = new CacheRule();
@Rule
public ClientCacheRule clientCacheRule = new ClientCacheRule();
@Rule
public SerializableTestName testName = new SerializableTestName();
@Before
public void setUp() {
server1 = getVM(0);
server2 = getVM(1);
server3 = getVM(2);
client1 = getVM(3);
hostName = getHostName();
uniqueName = getClass().getSimpleName() + "_" + testName.getMethodName();
regionName = uniqueName + "_region";
replicateRegionName = uniqueName + "_replicate_region";
}
@Test
public void jtaCanFailoverAfterDoneBeforeCompletion() {
server3.invoke(() -> createServerRegion(1, false));
server3.invoke(() -> doPut(key, value));
port1 = server1.invoke(() -> createServerRegion(1, true));
port2 = server2.invoke(() -> createServerRegion(1, true));
client1.invoke(() -> createClientRegion(port1, port2));
Object[] beforeCompletionResults = client1.invoke(() -> doBeforeCompletion());
int port = (Integer) beforeCompletionResults[1];
if (port == port1) {
server1.invoke(() -> cacheRule.getCache().close());
} else {
assert port == port2;
server2.invoke(() -> cacheRule.getCache().close());
}
client1.invoke(() -> doAfterCompletion((TransactionId) beforeCompletionResults[0], true));
}
private int createServerRegion(int totalNumBuckets, boolean isAccessor) throws Exception {
PartitionAttributesFactory<?, ?> partitionAttributesFactory = new PartitionAttributesFactory();
partitionAttributesFactory.setTotalNumBuckets(totalNumBuckets);
if (isAccessor) {
partitionAttributesFactory.setLocalMaxMemory(0);
}
RegionFactory regionFactory = cacheRule.getOrCreateCache().createRegionFactory(PARTITION);
regionFactory.setPartitionAttributes(partitionAttributesFactory.create());
regionFactory.create(regionName);
if (hasReplicateRegion) {
cacheRule.getOrCreateCache().createRegionFactory(RegionShortcut.REPLICATE)
.create(replicateRegionName);
}
CacheServer server = cacheRule.getCache().addCacheServer();
server.setPort(0);
server.start();
return server.getPort();
}
private void createClientRegion(int... ports) {
clientCacheRule.createClientCache();
CacheServerTestUtil.disableShufflingOfEndpoints();
PoolImpl pool;
try {
pool = getPool(ports);
} finally {
CacheServerTestUtil.enableShufflingOfEndpoints();
}
ClientRegionFactory<?, ?> clientRegionFactory =
clientCacheRule.getClientCache().createClientRegionFactory(LOCAL);
clientRegionFactory.setPoolName(pool.getName());
clientRegionFactory.create(regionName);
if (hasReplicateRegion) {
clientRegionFactory.create(replicateRegionName);
}
if (ports.length > 1) {
pool.acquireConnection(new ServerLocation(hostName, port1));
}
}
private PoolImpl getPool(int... ports) {
PoolFactory factory = PoolManager.createFactory();
for (int port : ports) {
factory.addServer(hostName, port);
}
return (PoolImpl) factory.setReadTimeout(2000).setSocketBufferSize(1000)
.setMinConnections(4).create(uniqueName);
}
private void doPut(int key, String value) {
cacheRule.getCache().getRegion(regionName).put(key, value);
}
private Object[] doBeforeCompletion() {
Object[] results = new Object[2];
InternalClientCache cache = clientCacheRule.getClientCache();
Region region = cache.getRegion(regionName);
Region replicateRegion = hasReplicateRegion ? cache.getRegion(replicateRegionName) : null;
TXManagerImpl txManager = (TXManagerImpl) cache.getCacheTransactionManager();
txManager.begin();
region.put(key, newValue);
if (hasReplicateRegion) {
replicateRegion.put(key, newValue);
}
TXStateProxyImpl txStateProxy = (TXStateProxyImpl) txManager.getTXState();
ClientTXStateStub clientTXStateStub = (ClientTXStateStub) txStateProxy.getRealDeal(null, null);
clientTXStateStub.beforeCompletion();
TransactionId transactionId = txManager.suspend();
int port = clientTXStateStub.getServerAffinityLocation().getPort();
results[0] = transactionId;
results[1] = port;
return results;
}
private void doAfterCompletion(TransactionId transactionId, boolean isCommit) {
InternalClientCache cache = clientCacheRule.getClientCache();
Region region = cache.getRegion(regionName);
Region replicateRegion = cache.getRegion(replicateRegionName);
TXManagerImpl txManager = (TXManagerImpl) cache.getCacheTransactionManager();
txManager.resume(transactionId);
TXStateProxyImpl txStateProxy = (TXStateProxyImpl) txManager.getTXState();
ClientTXStateStub clientTXStateStub = (ClientTXStateStub) txStateProxy.getRealDeal(null, null);
try {
clientTXStateStub
.afterCompletion(isCommit ? Status.STATUS_COMMITTED : Status.STATUS_ROLLEDBACK);
} catch (Exception exception) {
LogService.getLogger().info("exception stack ", exception);
throw exception;
}
if (isCommit) {
assertEquals(newValue, region.get(key));
if (hasReplicateRegion) {
assertEquals(newValue, replicateRegion.get(key));
}
} else {
assertEquals(value, region.get(key));
}
}
@Test
public void jtaCanFailoverToJTAHostAfterDoneBeforeCompletion() {
port2 = server2.invoke(() -> createServerRegion(1, false));
server2.invoke(() -> doPut(key, value));
port1 = server1.invoke(() -> createServerRegion(1, true));
client1.invoke(() -> createClientRegion(port1, port2));
Object[] beforeCompletionResults = client1.invoke(() -> doBeforeCompletion());
server1.invoke(() -> cacheRule.getCache().close());
client1.invoke(() -> doAfterCompletion((TransactionId) beforeCompletionResults[0], true));
}
@Test
public void jtaCanFailoverWithRollbackAfterDoneBeforeCompletion() {
server3.invoke(() -> createServerRegion(1, false));
server3.invoke(() -> doPut(key, value));
port1 = server1.invoke(() -> createServerRegion(1, true));
port2 = server2.invoke(() -> createServerRegion(1, true));
client1.invoke(() -> createClientRegion(port1, port2));
Object[] beforeCompletionResults = client1.invoke(() -> doBeforeCompletion());
int port = (Integer) beforeCompletionResults[1];
if (port == port1) {
server1.invoke(() -> cacheRule.getCache().close());
} else {
assert port == port2;
server2.invoke(() -> cacheRule.getCache().close());
}
client1.invoke(() -> doAfterCompletion((TransactionId) beforeCompletionResults[0], false));
createClientRegion(port == port1 ? port2 : port1);
doPutTransaction(true);
}
private void doPutTransaction(boolean isClient) {
Region region;
TXManagerImpl txManager;
if (isClient) {
InternalClientCache cache = clientCacheRule.getClientCache();
region = cache.getRegion(regionName);
txManager = (TXManagerImpl) cache.getCacheTransactionManager();
} else {
InternalCache cache = cacheRule.getCache();
region = cache.getRegion(regionName);
txManager = (TXManagerImpl) cache.getCacheTransactionManager();
Awaitility.await().atMost(30, TimeUnit.SECONDS).pollInterval(10, TimeUnit.MILLISECONDS)
.until(() -> txManager.isHostedTXStatesEmpty());
}
txManager.begin();
region.put(key, newValue);
txManager.commit();
assertEquals(newValue, region.get(key));
}
@Test
public void locksHeldInBeforeCompletionCanBeReleaseIfOriginatorDeparted() {
server1.invoke(() -> createServerRegion(1, false));
server1.invoke(() -> doPut(key, value));
server2.invoke(() -> createServerRegion(1, true));
server2.invoke(() -> doBeforeCompletionOnPeer());
server2.invoke(() -> cacheRule.getCache().close());
server1.invoke(() -> doPutTransaction(false));
}
private void doBeforeCompletionOnPeer() {
InternalCache cache = cacheRule.getCache();
Region region = cache.getRegion(regionName);
TXManagerImpl txManager = (TXManagerImpl) cache.getCacheTransactionManager();
txManager.begin();
region.put(key, newValue);
TXStateProxyImpl txStateProxy = (TXStateProxyImpl) txManager.getTXState();
PeerTXStateStub txStateStub = (PeerTXStateStub) txStateProxy.getRealDeal(null, null);
txStateStub.beforeCompletion();
}
@Test
public void jtaCanFailoverToJTAHostForMixedRegionsAfterDoneBeforeCompletion() {
hasReplicateRegion = true;
port2 = server2.invoke(() -> createServerRegion(1, false));
server2.invoke(() -> doPut(key, value));
port1 = server1.invoke(() -> createServerRegion(1, true));
client1.invoke(() -> createClientRegion(port1, port2));
Object[] beforeCompletionResults = client1.invoke(() -> doBeforeCompletion());
server1.invoke(() -> cacheRule.getCache().close());
client1.invoke(() -> doAfterCompletion((TransactionId) beforeCompletionResults[0], true));
}
}
|
package encryption
import (
"context"
"fmt"
"strconv"
"github.com/go-logr/logr"
"github.com/google/uuid"
"github.com/pkg/errors"
"github.com/storageos/api-manager/controllers/pvc-mutator/encryption/keys"
"github.com/storageos/api-manager/internal/pkg/provisioner"
"github.com/storageos/api-manager/internal/pkg/storageos"
corev1 "k8s.io/api/core/v1"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
)
const (
// SecretNameAnnotationKey is the name of the pvc annotation to store the
// encryption secret name in.
SecretNameAnnotationKey = "storageos.com/encryption-secret-name"
// SecretNamespaceAnnotationKey is the name of the pvc annotation to store
// the encryption secret namespace in.
SecretNamespaceAnnotationKey = "storageos.com/encryption-secret-namespace"
// VolumeSecretNamePrefix will be used to prefix all volume key secrets.
VolumeSecretNamePrefix = "storageos-volume-key"
// VolumeSecretPVCNameLabel is used to set the reference to the PVC name on
// the volume key secret. The namespace is not needed as it will be the
// same as the secret.
VolumeSecretPVCNameLabel = "storageos.com/pvc"
// NamespaceSecretName is the name of the secret containing the user key in
// each namespace with encrypted volumes.
NamespaceSecretName = "storageos-namespace-key"
)
var (
// ErrCrossNamespace is returned if a encryption key secret is requested
// that is not it the PVC namespace.
ErrCrossNamespace = errors.New("encryption key secret namespace must match pvc namespace")
)
// +kubebuilder:rbac:groups="",resources=secrets,verbs=get;list;watch;create;update;patch;delete
// KeyManager is the encrption key manager, responsible for creating and
// retrieving secrets that contain the keys required for volume encryption.
type KeyManager interface {
Ensure(ctx context.Context, userKeyRef client.ObjectKey, volKeyRef client.ObjectKey, nsSecretLabels map[string]string, volSecretLabels map[string]string) error
}
// EncryptionKeySetter is responsible for generating and setting pvc encryption
// keys on a pvc.
type EncryptionKeySetter struct {
// enabledLabel is the pvc label used to indicate that the volume
// must have encryption enabled. It must be set to "true" to enable.
enabledLabel string
// secretNameAnnotationKey is the pvc annotation that stores the name of the
// secret containing the encryption key.
secretNameAnnotationKey string
// secretNamespaceAnnotationKey is the pvc annotation that stores the
// namespace of the secret containing the encryption key.
secretNamespaceAnnotationKey string
// labels that should be applied to any kubernetes resources created by the
// key manager.
labels map[string]string
client.Client
keys KeyManager
log logr.Logger
}
// NewKeySetter returns a new PVC encryption key mutating admission
// controller that generates volume encryption keys and sets references to their
// location as PVC annotations.
func NewKeySetter(k8s client.Client, labels map[string]string) *EncryptionKeySetter {
return &EncryptionKeySetter{
enabledLabel: storageos.ReservedLabelEncryption,
secretNameAnnotationKey: SecretNameAnnotationKey,
secretNamespaceAnnotationKey: SecretNamespaceAnnotationKey,
Client: k8s,
keys: keys.New(k8s),
labels: labels,
log: ctrl.Log.WithName("keygen"),
}
}
// MutatePVC mutates a given pvc with annotations containing its encryption key,
// if the pvc has encryption enabled.
//
// Errors returned here may block creation of the PVC, depending on the
// FailurePolicy set in the webhook configuration.
func (s *EncryptionKeySetter) MutatePVC(ctx context.Context, pvc *corev1.PersistentVolumeClaim, namespace string) error {
log := s.log.WithValues("pvc", client.ObjectKeyFromObject(pvc).String())
log.V(4).Info("received pvc for mutation")
// Retrieve StorageClass of the PVC.
storageClass, err := provisioner.StorageClassForPVC(s.Client, pvc)
if err != nil {
return errors.Wrap(err, "failed to retrieve storageclass of pvc")
}
// Skip mutation if the PVC is not provisioned by StorageOS.
provisioned := provisioner.IsProvisionedStorageClass(storageClass, provisioner.DriverName)
if !provisioned {
log.V(4).Info("pvc will not be provisioned by StorageOS, skipping")
return nil
}
// Skip mutation if the PVC does not have encryption enabled.
// The encryption label should be added to StorageOS PVCs
// or inherited from StorageOS StorageClass.
// Invalid value of encryption must block PVC creation.
enabled, err := s.isEnabled(pvc.GetLabels(), storageClass.Parameters)
if err != nil {
return errors.Wrap(err, fmt.Sprintf("failed to parse boolean value for %q pvc label or storageclass parameter", s.enabledLabel))
}
if !enabled {
log.V(4).Info("pvc does not have encryption enabled, skipping")
return nil
}
// Do not allow secrets from another namespace to be referenced. We assume
// that if the user can create PVCs in the namespace then they should be
// able to read volume secrets from that namespace. We can't assume the
// same for other namespaces.
if requested, ok := pvc.Annotations[s.secretNamespaceAnnotationKey]; ok && requested != namespace {
return ErrCrossNamespace
}
// Ensure the keys exist, creating them if not.
nsKeyRef := s.NamespaceSecretKeyRef(namespace)
volKeyRef := s.VolumeSecretKeyRef(pvc, namespace)
// Add the PVC reference to the volume key secret labels. This is
// convenience only and should not be relied on. The volume key should
// really relate to the PV, not the PVC but the PV hasn't been provisioned
// yet.
volSecretLabels := s.VolumeSecretLabels(pvc.GetName())
// Ensure that the encryption keys exist where expected, creating them if
// needed.
if err := s.keys.Ensure(ctx, nsKeyRef, volKeyRef, s.labels, volSecretLabels); err != nil {
return errors.Wrap(err, "failed to ensure encryption key present for pvc")
}
// Set annotations on the PVC pointing to the volume key secret. The
// namespace key secret does not need to be passed to the control plane.
if pvc.Annotations == nil {
pvc.Annotations = make(map[string]string)
}
pvc.Annotations[s.secretNameAnnotationKey] = volKeyRef.Name
pvc.Annotations[s.secretNamespaceAnnotationKey] = volKeyRef.Namespace
log.Info("set volume encryption key annotations")
return nil
}
// VolumeSecretLabels returns the labels that should be set on the volume key
// secret.
func (s *EncryptionKeySetter) VolumeSecretLabels(pvcName string) map[string]string {
labels := make(map[string]string)
for k, v := range s.labels {
labels[k] = v
}
// pvcName should never be empty, but no point setting if it is.
if pvcName != "" {
labels[VolumeSecretPVCNameLabel] = pvcName
}
return labels
}
// NamespaceSecretKeyRef returns the reference of the secret that should be used to
// store the user encryption key for a namespace.
//
// This key is used to create volume keys.
func (s *EncryptionKeySetter) NamespaceSecretKeyRef(pvcNamespace string) client.ObjectKey {
return client.ObjectKey{
Name: NamespaceSecretName,
Namespace: pvcNamespace,
}
}
// VolumeSecretKeyRef returns the reference of the secret that should be used to
// store the encryption keys for a volume provisioned by the PVC.
func (s *EncryptionKeySetter) VolumeSecretKeyRef(pvc *corev1.PersistentVolumeClaim, pvcNamespace string) client.ObjectKey {
annotations := pvc.GetAnnotations()
name, ok := annotations[s.secretNameAnnotationKey]
if !ok || name == "" {
name = GenerateVolumeSecretName()
}
namespace, ok := annotations[s.secretNamespaceAnnotationKey]
if !ok || namespace == "" {
namespace = pvcNamespace
}
return client.ObjectKey{
Name: name,
Namespace: namespace,
}
}
// GenerateVolumeSecretName returns the name of the secret to use for the volume
// key.
//
// The secret relates to the StorageOS volume (or Kubernetes PV), not the PVC
// which may be deleted and then the PV reused. Since the volume hasn't been
// provisioned yet we don't have a reference for it, so generate a unique
// identifier to use instead.
func GenerateVolumeSecretName() string {
return fmt.Sprintf("%s-%s", VolumeSecretNamePrefix, uuid.New().String())
}
// isEnabled iterates on the given maps and looks for encryption key. First occurrence wins.
func (s *EncryptionKeySetter) isEnabled(hayStacks ...map[string]string) (bool, error) {
for _, hayStack := range hayStacks {
val, exists := hayStack[s.enabledLabel]
if exists {
return strconv.ParseBool(val)
}
}
return false, nil
}
|
Baby
My postpartum experience in six words or less:
Oh My God, What Just HAPPENED?
(If the challenge had allowed for a couple more words I probably would have included some profanity.)
You might feel the same way too. Awestruck and thunderstruck and monstertruck. Completely amazed at what your body just accomplished…but now your body is…things are not quite…look at that BABY…
Oh my God. What just HAPPENED?
(Or you might not. You might be one of those women who bask in a gentle glowy glow afterwards, with your perfect makeup and hair and oh look! The basketball you’ve been carrying under your shirt is gone and HI AB MUSCLES! And then your milk comes in five minutes later and your baby poops gold ingots and you know what? This column is probably not for you. Move along.)
For the rest of you, now, a few things you should probably be ready for immediately post-birth:
You will still look very pregnant.
I know, I know. No-brainer, right? This isn’t like giving birth in a sitcom. But both times I admit to being a little (okay, very) taken aback by my empty, squashy abdomen. What was once so round and ripe and lovely now resembled a large batch of smushy bread dough. It deflated a bit each day, but there were definitely days when I stood in front of the mirror and regarded myself with frustration because ARGH. GO AWAY BELLY.
It will. Eventually. Patience.
Your uterus will continue to contract, painfully at times.
Uterine contractions are the key to getting your stomach to deflate, but man. They are not super pleasant. I was particularly shocked by the force of my discomfort this time, probably because I didn’t go through the rigors of labor, but instead walked into the hospital feeling all fine and dandy. (I had a scheduled c-section back in October.) Then I was doped to the gills and hacked up and wheeled back to my room and suddenly…what the hell? Why do I feel like I’m in labor NOW?
At their worst, postpartum uterine contractions can feel like labor pains. Other times, they’re more like vicious menstrual cramps. They’re uncomfortable for sure, but ESSENTIAL. Breastfeeding is the best way to stimulate your uterus – it tells your body that indeed, the baby is out and pregnancy is over. My son nursed and nursed and NURSED during our hospital stay and the nurses were always “congratulating” my on my “good work” with my rapidly contracting uterus. I usually just glared at them, since they determined my progress by mashing on my super-sensitive abdomen and OW. GO AWAY.
If you aren’t breastfeeding, you can stimulate uterine contractions just by holding your baby. Skin-to-skin contact is best, so don’t be afraid to undo the hospital swaddle and get him all good and baby-naked and let him curl up on your chest. Smell his head, feel his breath, stroke his skin – these little acts of affection can actually trigger powerful hormonal reactions that will get your uterus in shape.
You will bleed.
So as if menstrual cramps weren’t enough, you’ve also got the privilege of having the LONGEST PERIOD OF YOUR LIFE. Lochia. It’s blood, mucus, placental tissue. It lasts a freaking long time. Four to six weeks, usually. (Although it’s normal for it to stop and start during that time frame as well, or to even stop completely and then come back with a vengeance right around six weeks.)
The first three to five days after you give birth, the blood will be bright red and constant and totally something out of Carrie. The first trip to the bathroom will be gory, to say the least (particularly if you’ve been confined to bed for any reason, like after a c-section). (I swear the first time I got up to pee it was a freaking HORROR MOVIE, and BONUS, post-section a nurse accompanies you the first time and it’s awkward and gross and I kept making weird inappropriate jokes while trying not to get woozy at the sight of all. that. blood. and keep most of it off the floor and in the toilet.)
At some point the blood will start looking pink or brown, and eventually it will be more like white-ish or yellow-ish mucus. The hospital will provide a wide variety of pads, in different sizes and shapes and you’ll want to steal pretty much every pad you can get your grubby mitts on.
(Lochia shouldn’t smell, by the way, or at least shouldn’t smell any different than your run-of-the-mill period. If you do notice an order or any green-looking gunk, call your doctor right away to get checked out for infection.)
You may be in a lot of pain.
C-sections, episiotomies, tears, rough deliveries and other complications can lead to pretty significant pain afterwards. Don’t feel the need to be a hero here – you’ve got enough going on, including the responsibility of a WHOLE NEW HUMAN BEING. Take care of yourself and speak up. Percocet and Ibuprofen are effective and breastfeeding-compatible.
For all my fellow c-sectioners out there: do NOT mess around with missing or even delaying your pain medication. My first birth was an emergency c-section after hours of labor and pushing and you know what? I FELT GREAT. The hospital staff administered my medication like clockwork and the first time I really felt significant pain was when I got home and – you guessed it – got distracted and missed a dose. You don’t even realize it until you go to get out of bed or reach for the milk or do some other small movement and suddenly you realize that OH, I HAVE BEEN NEARLY CUT IN HALF.
This time I had the scheduled c-section, which I had been assured by tons of people was actually easier and less traumatic than the emergency procedure. The problem was that the hospital had switched medication policies and it was now completely up to the patient to request pain medication. Every. Single. Dose. Of pain medication required me to monitor the clock and call the nurse and justify my pain level using the 1 to 10 scale. The bigger problem was that NO ONE TOLD ME THIS, so I sat in my room for hours after the surgery wondering when the Percocet would arrive. (Look, you might also be super mentally sharp afterwards either, you know?) My husband finally caught on before I did and called the nurse, but by this point I was literally sobbing from the pain and it took a few doses before I felt like it was really back under control. LET THIS BE A LESSON TO YE ALL. Stay on TOP of that medication. If you’re allowed to take Ibuprofen every six hours, set your watch, set your partner’s watch, set an alarm on your phone, buy a stopwatch, whatever.
Your milk may take a few days to come in.
I gave birth on Wednesday afternoon and my milk came in on Sunday morning, just BARELY in time for us to avoid the dreaded 10% weight loss marker. (Your baby WILL lose some weight, that’s unavoidable. The goal is to keep it within a reasonable percentage amount.) With my first baby, my milk took a full seven days to come in, and we simply had to supplement in the meantime, as Noah lost more than 10% of his birth weight and was getting lethargic and a little sickly looking.
This time, I was so petrified of that happening again I packed Mother’s Milk tea and fenugreek supplements in my hospital bag (both are herbal remedies that increase and stimulate milk production). Once I got the all-clear for a regular diet, I started taking them. I do believe they made a difference, as I had a very abundant milk supply right from the get-go. If you have no reason to believe you’ll have supply problems, there’s no reason to be this aggressive: your baby will get colostrum in the early days and your milk will follow at some point. A hospital may offer you formula regardless, and you can decide for yourself if you think it’s necessary. (I turned it down but ended up giving Ezra an ounce or two the night we got home, more because I just needed a break from his round-the-clock tongue-tied nursing.)
Your emotions are yours and yours alone.
There’s no “right” way to feel about your birth experience or your body or your baby. You might burst into tears every time you look at her because the force of your love has just up and pummeled you senseless. You might look at her and not be so sure about this motherhood thing after all. You might be preoccupied with how you look and your own discomfort. You might have a hard time coming to terms with how the birth happened or the fact that you are no longer pregnant. You might be too exhausted to give a crap about any of it.
For now, cut yourself a LOT of slack. Yes, giving birth is the most natural thing in the world and been done for millennia blah blah blah, but this time it’s YOU who gave birth and YOU are your own damn unique person. Your hormones are going haywire, but will settle down after a few days. (I found day five to be the most emotionally draining, like every pregnancy hormone I’d built up over nine months just crashed through the floor and left my body.) A little sadness or a crying jag or two immediately postpartum does not mean you’ll have postpartum depression or never bond with your baby or be a terrible mother woe woe weep omg. Likewise, feeling absolutely ecstatic and wonderful at first doesn’t mean you might experience a little crash later on, or even a major one. Stay aware of your emotions (we’ll cover PPD in more detail another day) but in the early days it’s important to just…let yourself feel how you feel, look how you look and take it one day (or one Ibuprofen dose) at a time. |
A critical blow-up exponent in a chemotaxis system with nonlinear signal production
This paper is concerned with radially symmetric solutions of the Keller–Segel system with nonlinear signal production, as given by in the ball for and R > 0, where f is a suitably regular function generalizing the prototype determined by the choice , , with . The main results assert that if in this setting the number κ satisfies then for any prescribed mass level m > 0, there exist initial data u0 with , for which the solution of the corresponding Neumann initial-boundary value problem blows up in finite time. The condition in () is essentially optimal and is indicated by a complementary result according to which in the case , for widely arbitrary initial data, a global bounded classical solution can always be found. |
/**
* @author Carlo Sciolla
* @since 0.1
*/
public class OrgFileType extends LanguageFileType {
public final static OrgFileType INSTANCE = new OrgFileType();
public final static String ORG_DEFAULT_EXTENSION = "org";
protected OrgFileType() {
super(OrgLanguage.INSTANCE);
}
@NotNull
@Override
public String getName() {
return "OrgMode";
}
@NotNull
@Override
public String getDescription() {
return OrgBundle.message("org.file.type.description");
}
@NotNull
@Override
public String getDefaultExtension() {
return OrgFileType.ORG_DEFAULT_EXTENSION;
}
@Override
public Icon getIcon() {
return OrgIcons.ORG_ICON;
}
} |
/* Dump out the mn10300 specific architecture information. */
static void
mn10300_dump_tdep (struct gdbarch *gdbarch, struct ui_file *file)
{
struct gdbarch_tdep *tdep = gdbarch_tdep (gdbarch);
fprintf_unfiltered (file, "mn10300_dump_tdep: am33_mode = %d\n",
tdep->am33_mode);
} |
/**
* Write font of a diagram component
*/
Element writeFont(IFontAttribute fontObject, Element styleElement) {
Element fontElement = new Element(ELEMENT_FONT, ARCHIMATE3_NAMESPACE);
try {
FontData fontData = null;
String fontString = fontObject.getFont();
if(fontString != null) {
fontData = new FontData(fontString);
}
else {
fontData = FontFactory.getDefaultUserViewFontData();
}
fontElement.setAttribute(ATTRIBUTE_FONTNAME, fontData.getName());
fontElement.setAttribute(ATTRIBUTE_FONTSIZE, Integer.toString(fontData.getHeight()));
int style = fontData.getStyle();
String styleString = "";
if((style & SWT.BOLD) == SWT.BOLD) {
styleString += "bold";
}
if((style & SWT.ITALIC) == SWT.ITALIC) {
if(StringUtils.isSet(styleString)) {
styleString += " ";
}
styleString += "italic";
}
if(hasSomeText(styleString)) {
fontElement.setAttribute(ATTRIBUTE_FONTSTYLE, styleString);
}
}
catch(Exception ex) {
ex.printStackTrace();
}
String fontColorString = fontObject.getFontColor();
RGB rgb = ColorFactory.convertStringToRGB(fontColorString);
Element fontColorElement = new Element(ELEMENT_FONTCOLOR, ARCHIMATE3_NAMESPACE);
fontElement.addContent(fontColorElement);
writeRGBAttributes(rgb, -1, fontColorElement);
if(hasElementContent(fontElement)) {
styleElement.addContent(fontElement);
}
return fontElement;
} |
import * as http from 'http';
// import { Subscription } from 'rxjs/Subscription';
// import { Observable } from 'rxjs/Observable';
// import { merge } from 'rxjs/operator/merge';
// import { FromEventObservable } from 'rxjs/observable/FromEventObservable';
// import { Subject } from 'rxjs/Subject';
import { ServerConfig, HttpServerConfig } from '../ConfigRX';
import { Request, RequestI } from './Request';
// import { Helpers } from './HelpeR';
import { Header, Headers, RawHeaders } from './headers/Headers';
// private charsetRegExp = /;\s*charset\s*=/;
export interface Response {
id: string;
raw: http.ServerResponse;
date: Date;
status: {
code: number;
message: string;
};
headers: {
raw: RawHeaders,
written: RawHeaders
};
body?: string | Buffer;
}
export function Response(req) {
(<any>http).ServerResponse.bind(this, req);
}
util.inherits(Response, http.ServerResponse)
/**
public parse(req: RequestI, serverRes: http.ServerResponse): ResponseI {
let res = <ResponseI>{};
res.id = req.id;
res.raw = serverRes;
return res;
}
public writeHead(statusCode: number, reasonPhrase?: string, headers?: any): void {
}
public write(chunk: Buffer | string, encoding?: string, fd?: string): void {
}
public end(chunk?: Buffer | string, encoding?: string): void {
}
public json(obj: Object) {
var body = Helpers.JSONify(obj);
// content-type
if (!this.headers.getHeader('Content-Type')) {
this.headers.setHeader('Content-Type', 'application/json');
}
return this.write(body);
};
public sendStatus(code: number) {
let body = statuses[code]
this.statusCode = code;
ContentType.set('txt');
this.send(code);
}
public writeBody(body: Buffer | string): void {
let chunk = body;
let type: string;
let encoding: string;
let length: number;
let app = this.app;
switch (typeof chunk) {
case 'boolean':
case 'number':
case 'object':
if (chunk === null) {
chunk = '';
} else if (Buffer.isBuffer(chunk)) {
if (!this.getHeader('Content-Type')) {
type = 'bin';
}
} else {
// return this.json(chunk);
}
break;
default:
case 'string':
if (!this.getHeader('Content-Type')) {
type = 'html';
}
break;
}
// write strings in utf-8
if (typeof chunk === 'string') {
encoding = 'utf8';
type = this.getHeader('Content-Type');
// reflect this in content-type
if (typeof type === 'string') {
this.setHeaders({'Content-Type': setCharset(type, 'utf-8')});
}
}
// populate Content-Length
if (chunk !== undefined) {
if (!Buffer.isBuffer(chunk)) {
// convert chunk to Buffer; saves later double conversions
chunk = new Buffer(chunk, encoding);
encoding = undefined;
}
length = chunk.length;
this.setHeaders({'Content-Length': length});
}
// populate ETag
let etag;
let generateETag = length !== undefined && app.get('etag fn');
if (typeof generateETag === 'function' && !this.getHeader('ETag')) {
if ((etag = generateETag(chunk, encoding))) {
this.setHeaders({'ETag': etag});
}
}
// freshness
if (this.fresh) this.statusCode = 304;
// strip irrelevant headers
if (204 === this.statusCode || 304 === this.statusCode) {
this.removeHeader('Content-Type');
this.removeHeader('Content-Length');
this.removeHeader('Content-MD5');
this.removeHeader('Transfer-Encoding');
chunk = '';
}
if (req.method === 'HEAD') {
// skip body for HEAD
this.end();
} else {
// respond
this.end(chunk, encoding);
}
}
}
/**
* Respond to the Acceptable formats using an `obj`
* of mime-type callbacks.
*
* This method uses `req.accepted`, an array of
* acceptable types ordered by their quality values.
* When "Accept" is not present the _first_ callback
* is invoked, otherwise the first match is used. When
* no match is performed the server responds with
* 406 "Not Acceptable".
*
* Content-Type is set for you, however if you choose
* you may alter this within the callback using `res.type()`
* or `res.set('Content-Type', ...)`.
*
* res.format({
* 'text/plain': function(){
* res.send('hey');
* },
*
* 'text/html': function(){
* res.send('<p>hey</p>');
* },
*
* 'appliation/json': function(){
* res.send({ message: 'hey' });
* }
* });
*
* In addition to canonicalized MIME types you may
* also use extnames mapped to these types:
*
* res.format({
* text: function(){
* res.send('hey');
* },
*
* html: function(){
* res.send('<p>hey</p>');
* },
*
* json: function(){
* res.send({ message: 'hey' });
* }
* });
*
* By default Express passes an `Error`
* with a `.status` of 406 to `next(err)`
* if a match is not made. If you provide
* a `.default` callback it will be invoked
* instead.
*
* @param {Object} obj
* @return {ServerResponse} for chaining
* @public
*/
res.format = function(obj){
var req = this.req;
var next = req.next;
var fn = obj.default;
if (fn) delete obj.default;
var keys = Object.keys(obj);
var key = keys.length > 0
? req.accepts(keys)
: false;
this.vary("Accept");
if (key) {
this.set('Content-Type', normalizeType(key).value);
obj[key](req, this, next);
} else if (fn) {
fn();
} else {
var err = new Error('Not Acceptable');
err.status = err.statusCode = 406;
err.types = normalizeTypes(keys).map(function(o){ return o.value });
next(err);
}
return this;
};
Response.prototype._findFormatter = function _findFormatter(callback) {
var formatter;
var type = this.contentType || this.getHeader('Content-Type');
if (!type) {
if (this.req.accepts(this.acceptable)) {
type = this.req.accepts(this.acceptable);
}
if (!type) {
return callback(new errors.NotAcceptableError({
message: 'could not find suitable formatter'
}));
}
} else if (type.indexOf(';') !== '-1') {
type = type.split(';')[0];
}
if (!(formatter = this.formatters[type])) {
if (type.indexOf('/') === -1) {
type = mime.lookup(type);
}
if (this.acceptable.indexOf(type) === -1) {
type = 'application/octet-stream';
}
formatter = this.formatters[type] || this.formatters['*/*'];
// this is a catastrophic case - should always fall back on
// octet-stream but if for some reason that's gone, return a 500.
if (!formatter) {
return callback(new errors.InternalServerError({
message: 'could not find formatter for application/octet-stream'
}));
}
}
if (this._charSet) {
type = type + '; charset=' + this._charSet;
}
this.setHeader('Content-Type', type);
return callback(null, formatter, type);
};
/**
* Redirect to the given `url` with optional response `status`
* defaulting to 302.
*
* The resulting `url` is determined by `res.location()`, so
* it will play nicely with mounted apps, relative paths,
* `"back"` etc.
*
* Examples:
*
* res.redirect('/foo/bar');
* res.redirect('http://example.com');
* res.redirect(301, 'http://example.com');
* res.redirect('../login'); // /blog/post/1 -> /blog/login
*
* @public
*/
public redirect(url) {
var address = url;
var body;
var status = 302;
// Set location header
address = this.location(address).getHeader('Location');
// Support text/{plain,html} by default
this.format({
text: function(){
body = statuses[status] + '. Redirecting to ' + address
},
html: function(){
var u = escapeHtml(address);
body = '<p>' + statuses[status] + '. Redirecting to <a href="' + u + '">' + u + '</a></p>'
},
default: function(){
body = '';
}
});
// Respond
this.statusCode = status;
this.setHeader('Content-Length', Buffer.byteLength(body));
if (this.req.method === 'HEAD') {
this.end();
} else {
this.end(body);
}
};
/**
* Transfer the file at the given `path`.
*
* Automatically sets the _Content-Type_ response header field.
* The callback `callback(err)` is invoked when the transfer is complete
* or when an error occurs. Be sure to check `res.sentHeader`
* if you wish to attempt responding, as the header and some data
* may have already been transferred.
*
* Options:
*
* - `maxAge` defaulting to 0 (can be string converted by `ms`)
* - `root` root directory for relative filenames
* - `headers` object of headers to serve with file
* - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them
*
* Other options are passed along to `send`.
*
* Examples:
*
* The following example illustrates how `res.sendFile()` may
* be used as an alternative for the `static()` middleware for
* dynamic situations. The code backing `res.sendFile()` is actually
* the same code, so HTTP cache support etc is identical.
*
* app.get('/user/:uid/photos/:file', function(req, res){
* var uid = req.params.uid
* , file = req.params.file;
*
* req.user.mayViewFilesFrom(uid, function(yes){
* if (yes) {
* res.sendFile('/uploads/' + uid + '/' + file);
* } else {
* res.send(403, 'Sorry! you cant see that.');
* }
* });
* });
*
* @public
*/
res.sendFile = function sendFile(path, options, callback) {
var done = callback;
var next = req.next;
var opts = options || {};
if (!path) {
throw new TypeError('path argument is required to res.sendFile');
}
// support function as second arg
if (typeof options === 'function') {
done = options;
opts = {};
}
if (!opts.root && !isAbsolute(path)) {
throw new TypeError('path must be absolute or specify root to res.sendFile');
}
// create file stream
var pathname = encodeURI(path);
var file = send(req, pathname, opts);
// transfer
sendfile(res, file, opts, function (err) {
if (done) return done(err);
if (err && err.code === 'EISDIR') return next();
// next() all but write errors
if (err && err.code !== 'ECONNABORTED' && err.syscall !== 'write') {
next(err);
}
});
};
// pipe the send file stream
function sendfile(res, file, options, callback) {
var done = false;
var streaming;
// request aborted
function onaborted() {
if (done) return;
done = true;
var err = new Error('Request aborted');
err.code = 'ECONNABORTED';
callback(err);
}
// directory
function ondirectory() {
if (done) return;
done = true;
var err = new Error('EISDIR, read');
err.code = 'EISDIR';
callback(err);
}
// errors
function onerror(err) {
if (done) return;
done = true;
callback(err);
}
// ended
function onend() {
if (done) return;
done = true;
callback();
}
// file
function onfile() {
streaming = false;
}
// finished
function onfinish(err) {
if (err && err.code === 'ECONNRESET') return onaborted();
if (err) return onerror(err);
if (done) return;
setImmediate(function () {
if (streaming !== false && !done) {
onaborted();
return;
}
if (done) return;
done = true;
callback();
});
}
// streaming
function onstream() {
streaming = true;
}
file.on('directory', ondirectory);
file.on('end', onend);
file.on('error', onerror);
file.on('file', onfile);
file.on('stream', onstream);
onFinished(res, onfinish);
if (options.headers) {
// set headers on successful transfer
file.on('headers', function headers(res) {
var obj = options.headers;
var keys = Object.keys(obj);
for (var i = 0; i < keys.length; i++) {
var k = keys[i];
res.setHeader(k, obj[k]);
}
});
}
// pipe
file.pipe(res);
}
/**
* Transfer the file at the given `path` as an attachment.
*
* Optionally providing an alternate attachment `filename`,
* and optional callback `callback(err)`. The callback is invoked
* when the data transfer is complete, or when an error has
* ocurred. Be sure to check `res.headersSent` if you plan to respond.
*
* This method uses `res.sendfile()`.
*
* @public
*/
res.download = function download(path, filename, callback) {
var done = callback;
var name = filename;
// support function as second arg
if (typeof filename === 'function') {
done = filename;
name = null;
}
// set Content-Disposition when file is sent
var headers = {
'Content-Disposition': contentDisposition(name || path)
};
// Resolve the full path for sendFile
var fullPath = resolve(path);
return this.sendFile(fullPath, { headers: headers }, done);
}; |
import React from 'react';
import { TileLayer as LeafletTileLayer } from 'react-leaflet';
import { LEAFLET } from '../constants';
export const TileLayer = () => (
<LeafletTileLayer
attribution={'© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'}
url={LEAFLET.TILE_SERVER_URL}
/>
);
|
/**
* Wraps calling the OnMaintenance() method that derived classes use to provide
* common exception handling.
*
*/
private void actionOnMaintenance() {
try {
onMaintenance();
} catch (Exception ex) {
}
} |
def EntityIdToArray(entity_type, entity_id):
onto_keys = OntologyClassKeys(entity_type)
dict_ids = SplitMoniker(entity_id)
try:
def decode_cgi_arg(a_key):
a_val_raw = dict_ids[a_key]
try:
val_decod = a_key.ValueDecode(a_val_raw)
return val_decod
except AttributeError:
return urllib_unquote(a_val_raw)
return [decode_cgi_arg(a_key) for a_key in onto_keys]
except KeyError:
logging.error("missing key: type=%s id=%s onto=%s", entity_type, entity_id, str(onto_keys))
raise |
Get this — there was a 3-week-old girl who was born pregnant with two fetuses.
According to ABC News, the baby girl, born in Hong Kong, had a condition called “fetus in fetu,” where an undeveloped fetus grows inside the womb of another baby (its twin). This happened back in 2010, but was recently unveiled in a study from the Hong Kong Medical Journal, which said this condition affects 1 in 500,000 births.
Doctors first noticed this after they saw what they thought to be a pair of tumors in the young baby’s abdomen, according to First to Know. But the tumors turned out to be twin fetuses, each with ribs, limbs and a spine, First to Know reported.
“It was almost impossible to detect during the prenatal checkup, as the embryo inside the baby was too small,” said Dr. Yu Kai-man, a specialists at Queen Elizabeth Hospital in Hong Kong, where the tests were done. “Since it is impossible for the little girl to have conceived the pregnancy on her own, the fertilization of the twin fetuses, of course, belongs to her parents, which has gone to the wrong place.”
The girl, according to the study, was released eight days after the doctors removed the fetuses.
According to UPI, Yu, the doctor who helped write the study, said the condition is classified by the World Health Organization as a form of cancer, even though the cause remains unknown.
Better ultrasound tests in the early stages of pregnancy will help discover the cause of the condition, Yu said.
Twitter: @herbscribner |
import { config } from '../../config';
import * as Utils from '../common/utils';
export default class NewEmployee {
name: string;
department: string;
location: string;
inTime: string;
outTime: string;
inTimeForCSV: string;
photo: string;
type: string;
id: number;
blobId: string;
camId: number;
alertId: number;
constructor(res) {
const dynamicKey = res.data.awi_facial_recognition.awi_app_data.awi_blobs.awi_blob_ids[0];
const intime = res.data.timestamp;
const outtime = res.data.timestamp;
this.department = res.data.awi_facial_recognition.awi_app_data.awi_blobs[dynamicKey].classification.awi_blob_db[0].awi_subclass;
this.inTime = intime;
this.inTimeForCSV = Utils.getFormattedTime(intime);
this.outTime = Utils.getFormattedTime(outtime);
this.location = res.data.awi_facial_recognition.location;
this.type = 'auto';
this.name = res.data.awi_facial_recognition.awi_app_data.awi_blobs[dynamicKey].classification.awi_blob_db[0].awi_label;
this.id = res.data.awi_facial_recognition.awi_app_data.awi_blobs[dynamicKey].classification.awi_blob_db[0].awi_id;
this.blobId = dynamicKey;
this.alertId = res.data.awi_facial_recognition.id;
this.camId = res.data.awi_facial_recognition.awi_camid;
const img = res.data.awi_facial_recognition.awi_app_data.awi_blobs[dynamicKey].img_base64;
this.photo = this.getUpdatedImageUrl(img);
}
getUpdatedImageUrl(imgUrl) {
const host = imgUrl.split('/')[2].split(':')[0];
const port = imgUrl.split('/')[2].split(':')[1];
let url = imgUrl.replace(host, config.SERVER_ADDRESS);
url = url.replace(port, config.PORT);
return url;
}
}
|
{-# LANGUAGE TupleSections #-}
-----------------------------------------------------------------------------
-- |
-- Module : XMonad.Hooks.DynamicIcons
-- Copyright : (c) <NAME> <<EMAIL>>
-- License : BSD3-style (see LICENSE)
--
-- Maintainer : <NAME> <<EMAIL>>
-- Stability : unstable
-- Portability : unportable
--
-- Dynamically change workspace text based on the contents of the workspace
-----------------------------------------------------------------------------
module XMonad.Hooks.DynamicIcons (
-- * Usage
-- $usage
-- * Creating Dynamic Icons
dynamicLogIconsWithPP, dynamicLogIconsConvert,
-- * Data Types
appIcon, IconSet,
IconConfig(..), Icon(..),
) where
import XMonad
import qualified XMonad.StackSet as S
import qualified Data.Map as M
import XMonad.Hooks.DynamicLog
import Data.Maybe (catMaybes)
-- $usage
-- Dynamically changes a 'Workspace's 'WorkspaceId' based on the 'Window's inside the Workspace.
-- 'IconSet's describe which icons are shown depending on which windows fit a 'Query'.
--
-- To create an 'IconSet' make a 'Query' that returns a ['Icon'].
--
-- 'appIcon' can be used to simplify this process
-- For example,
--
-- > icons :: IconSet
-- > icons = composeAll
-- > [ className =? "discord" --> appIcon "\xfb6e"
-- > , className =? "Discord" --> appIcon "\xf268"
-- > , className =? "Firefox" --> appIcon "\63288"
-- > , className =? "Spotify" <||> className =? "spotify" --> appIcon "阮"
-- > ]
--
-- then you can add the hook to your config
--
-- > xmonad $ def
-- > { logHook = dynamicLogIconsWithPP icons xmobarPP <> myManageHook
-- > }
--
-- Here is an example of this
--
-- <<https://imgur.com/download/eauPNPz/Dynamic%20Icons%20in%20XMonad>>
--
-- NOTE: You can use any string you want here. The example shown here, uses NerdFont Icons to represent open applications
-- | Custom datatype for custom icons based on the state of the 'Workspace'
-- For example,
--
-- > Icon "<bold>discord</bold>" "<bold>discord</bold>" "discord" ""
--
-- Then you can add it to your IconSet.
--
-- > icons :: IconSet
-- > icons = mconcat
-- > [ className =? "discord" --> pure [Icon "<bold>discord</bold>" "<bold>discord</bold>" "discord" ""]
-- > ]
data Icon = Icon
{ iconCurrent :: !String -- ^ If the 'Workspace' is the current workspace
, iconVisible :: !String -- ^ If the 'Workspace' is visible (Xinerama only)
, iconHidden :: !String -- ^ If the 'Workspace' isnt visible but still has windows
, iconHiddenNoWindows :: !String -- ^ If the 'Workspace' isnt visible and has no windows
}
-- | The set of Icons to use
type IconSet = Query [Icon]
baseIconSet :: String -> Icon
baseIconSet x =
Icon { iconCurrent = x
, iconVisible = x
, iconHidden = x
, iconHiddenNoWindows = x
}
-- | Create an 'IconSet' from a 'String'
appIcon :: String -> IconSet
appIcon x = pure [baseIconSet x]
-- | Adjusts the 'PP' and then runs 'dynamicLogWithPP'
dynamicLogIconsWithPP :: IconSet -- ^ The 'IconSet' to use
-> PP -- ^ The 'PP' to alter
-> X () -- ^ The resulting 'X' action
dynamicLogIconsWithPP iconset pp = dynamicLogWithPP =<< dynamicLogIconsConvert (def{ iconConfigIcons = iconset, iconConfigPP = pp })
-- | Datatype for expanded 'Icon' configurations
data IconConfig = IconConfig
{ iconConfigIcons :: IconSet -- ^ The 'IconSet' to use
, iconConfigStack :: [String] -> String -- ^ The function to manage stacking of 'Icon's
, iconConfigPP :: PP -- ^ The 'PP' to alter
}
instance Default IconConfig where
def = IconConfig
{ iconConfigIcons = mempty
, iconConfigStack = wrap "[" "]" . unwords
, iconConfigPP = def
}
-- | This is the same as 'dynamicLogIconsWithPP' but it takes a 'IconConfig'.
-- This allows you to manually customise the 'Icon's the stacking function and also your `PP`
dynamicLogIconsConvert :: IconConfig -> X PP
dynamicLogIconsConvert iconConfig = do
ws <- gets (S.workspaces . windowset)
icons <- M.fromList . catMaybes <$> mapM (getIcons (iconConfigIcons iconConfig)) ws
pure $ (iconConfigPP iconConfig)
{ ppCurrent = ppSection ppCurrent iconCurrent icons
, ppVisible = ppSection ppVisible iconVisible icons
, ppHidden = ppSection ppHidden iconHidden icons
, ppHiddenNoWindows = ppSection ppHiddenNoWindows iconHiddenNoWindows icons
}
where
ppSection pF f icons = pF (iconConfigPP iconConfig) . concatIcons f . iconLookup icons
iconLookup icons x = M.findWithDefault [baseIconSet x] x icons
concatIcons f y
| length y > 1 = iconConfigStack iconConfig $ map f y
| otherwise = concatMap f y
getIcons :: IconSet -> WindowSpace -> X (Maybe (WorkspaceId, [Icon]))
getIcons is w = do
validIcons <- sequence $ foldMap (runQuery is) . S.integrate <$> S.stack w
pure $ (S.tag w,) <$> (validIcons >>= \x -> if null x then Nothing else Just x)
|
// Do not test for null message, it cannot legally be null.
private static class EmptyActionDef implements ActionDef {
private static final long serialVersionUID = 1L;
StringWriter sw;
String name;
protected EmptyActionDef(StringWriter sw, String name) {
this.sw = sw;
this.name = name;
}
@Override
public void validateDefinition() throws QuickFixException {
}
@Override
public void appendDependencies(Set<DefDescriptor<?>> dependencies) {
}
@Override
public void validateReferences() throws QuickFixException {
}
@Override
public void markValid() {
}
@Override
public boolean isValid() {
return true;
}
@Override
public Location getLocation() {
return null;
}
@Override
public DefinitionAccess getAccess() {
return null;
}
@Override
public <D extends Definition> D getSubDefinition(SubDefDescriptor<D, ?> descriptor) {
return null;
}
@Override
public void retrieveLabels() throws QuickFixException {
}
@Override
public String getAPIVersion() {
return null;
}
@Override
public String getDescription() {
return null;
}
@Override
public String getOwnHash() {
return null;
}
@Override
public void appendSupers(Set<DefDescriptor<?>> supers) throws QuickFixException {
}
@Override
public void serialize(Json json) throws IOException {
}
@Override
public DefDescriptor<ActionDef> getDescriptor() {
return null;
}
@Override
public ActionType getActionType() {
return null;
}
@Override
public String getName() {
return this.name;
}
@Override
public DefDescriptor<TypeDef> getReturnType() {
return null;
}
@Override
public List<ValueDef> getParameters() {
return null;
}
@Override
public List<String> getLoggableParams() {
return Lists.newArrayList();
}
} |
<filename>src/nordic32/plugins/protection/actions.go<gh_stars>0
package protection
import (
"hps"
nm "hps/networkmachine"
sm "hps/statemachine"
"nordic32/model"
q "nordic32/query"
"strconv"
)
func actions(network *model.Network, m *model.Link) {
query := createDisconnectionQuery(network, m)
m.PropertyOverloaded().Changed(func(p *hps.Property, oldValue interface{}) {
value, _ := p.GetBool()
if value && query() {
m.Disconnect()
}
})
}
func createDisconnectionQuery(network *model.Network, m *model.Link) func() bool {
from, ok := network.Substation(m.From())
if !ok {
panic("Substation " + m.From() + " could not be found.")
}
fromBay, ok := from.LineBay(m.Name())
if !ok {
panic("Error while processing machine " + m.Name() + ": " +
"Could not find corresponding line bay for machine " + from.Name())
}
to, ok := network.Substation(m.To())
if !ok {
panic("Substation " + m.To() + " could not be found.")
}
toBay, ok := to.LineBay(m.Name())
if !ok {
panic("Error while processing machine " + m.Name() + ": " +
"Could not find corresponding line bay for machine " + to.Name())
}
fromQuery := createWorkingBayQuery(fromBay)
toQuery := createWorkingBayQuery(toBay)
return func() bool {
return fromQuery() || toQuery()
}
}
func createWorkingBayQuery(m *model.LineBay) func() bool {
breaker, _ := m.Breaker()
primaryRelay, _ := m.PrimaryRelay()
backupRelay, _ := m.BackupRelay()
battery, _ := m.Battery()
wiring, _ := m.Wiring()
return func() bool {
return breakerIsOk(breaker) && (ok(primaryRelay) || ok(backupRelay)) && ok(battery) && ok(wiring)
}
}
func ok(m hps.IMachine) bool {
return m.(*sm.Machine).State().Name() == "ok"
}
func breakerIsOk(m hps.IMachine) bool {
if simpleBreaker, ok := m.(sm.IStateMachine); ok {
return simpleBreaker.State().Name() == "ok"
}
// multi-channel compromisable breaker
// TODO move this code to the diversity study plugin
if twoChannelBreaker, ok := m.(*nm.Machine); ok {
machines := twoChannelBreaker.Machines()
i := 1
isOk := true
for {
component, ok := q.FindMachineByName(machines, "Component"+strconv.Itoa(i))
if !ok {
break
}
state := component.(*sm.Machine).State().Name()
isOk = isOk && (state == "ok" || state == "compromised-ok")
i++
}
return isOk
}
return true
}
|
def client_appointments():
if request.method == 'POST':
cid = request.form.get('search11')
if Client.query.get(int(cid)):
client = Client.query.get(int(cid))
answer = str([str(x.day.date) + ' @ ' + str(
x.time) for x in client.appointments])
return render_template('results6.html', answer=answer)
return render_template('base6.html') |
THE Y + LONG-BASELINE CONFIGURATION TO ACHIEVE HIGH RESOLUTION WITH ALMA
The ALMA array configuration design has been split into a compact array, an extended array, and a “zoom” spiral array which aims to connect them. The currently accepted extended array is a 14 km ring around Chascón. Based on Fourier plane coverage, resolution, operations, engineering, and environmental arguments, we present an alternative to the extended configuration: a Y-shaped set of zooming configurations, which naturaly grows out of the spiral zoom configurations. This set of preliminary configurations indicates a savings of about 20 km in roads and cables, and 35 fewer pads compared to the current ring design. It has smoothly varying resolution, which permits the observer to tailor the resolution to his requirements. Reconfiguration is much smoother with the Y configuration than the 14 km diameter ring. The most extended Y configuration obtains the same resolution as the 14 km ring array. However, in order to achieve these advantages, together with the highest possible resolution for the ALMA interferometer, we need to explore the possibility of extending the Science Preserve by at least two kilometres to the west of its current western boundary. 1.A Brief History of “Y” and “O” Configurations This section is a bit pedantic, but it is instructive in that it shows us how we got to the current design with a 14 km ring array around Chascón, and how we have a 4.5 km triangle around the Conway spiral configuration. There is nothing particularly fundamental about these decisions. On the other hand, using a Y configuration for the longest baselines is a viable alternative, which is in keeping with much of the design philosophy behind the Conway spiral configurations. Many historical and even modern radio telescopes have the linear E-W configuration. The main advantage of the E-W configuration is simplicity. The most unfortunate aspects of an E-W array are the inability to perform snapshot observations and the inability to image low declination sources in two dimensions. Adding a N-S spur to the E-W track can fix both of these problems, and a Y can be thought of as a further modification. The experience at the VLA indicates that the ability to image far southern sources and to make snapshot observations has been greatly beneficial. However, there are problems with the VLA's configurations. Any Y arrangement of antennas will have more short baselines than long baselines, and the exponential distribution on antennas along each arm further exacerbates this situation. In addition, the regularity of the placement of the antennas at the VLA results in very large sidelobes in the snapshot point spread function (PSF). These two problems led Cornwell (1986) and Keto (1992) to write algorithms which sought to spread out the Fourier plane samples more. Cornwell's circular configuration and Keto's Reuleaux triangle configuration resulted in uniform (u,v) distributions with a maximum number of long baselines, and the ring became the leading configuration design for the MMA during the period 1986-1996. In the mid 1990's, some concern developed over the uniform (u,v) coverage which the ring arrays produced. Specifically, the uniform coverage resulted in very large near-in sidelobes in the PSF, and it was thought that a Gaussian coverage might be better, since we often aim to achieve a Gaussian PSF restoring beam (Holdaway, 1996a). Defenders of the uniform coverage held on for many years. The main argument for the ring arrays seemed to be that it afforded the highest resolution for any given maximum baseline length. Supporters of the filled-type configurations, which produced a more Gaussian coverage, responded by saying that if you need higher resolution, go to a more extended configuration. Of course, that argument breaks down for the most extended configuration, and it was conceded that a ring array had a place for the most extended configuration. |
def download():
url = "http://webspace.apiit.edu.my/"\
"intake-timetable/download_timetable/" + \
file_name
u = urllib2.urlopen(url)
f = open(file_name, 'wb')
meta = u.info()
file_size = int(meta.getheaders("Content-Length")[0])
print "Downloading data: %s bytes" % (file_size)
file_size_dl = 0
block_sz = 8 # bytes
while True:
buffer = u.read(block_sz)
if not buffer:
break
file_size_dl += len(buffer)
f.write(buffer)
status = r"%10d [%3.2f%%]" % (
file_size_dl, file_size_dl * 100. / file_size)
status = status + chr(8) * (len(status) + 1)
print status,
f.close()
print "\nDone!\n" |
The fourth Tehran Auction has broken the all-time record of Iran’s art auctions thanks to the sale of a painting by Sohrab Sepehri for over $965,000 (€865,000), which brought the total revenue of the sales to over $7.25 million (€6.5 million).
The second most expensive sale of the event was another painting by the late Iranian poet and painter, which was sold for about $600,000. A total of 126 works by various artists, including Masoud Arabshahi, Mohammad Ehsaii, Jalil Rasouli, Behjat Sadr, and Parviz Kalantari went under the hammer.
The event, dubbed Modern and Contemporary Iranian Art Auction, was hosted by Iranian actor Reza Kianian at Tehran’s Grand Azadi Hotel.
Related articles:
The other Iran | 2014 Tehran Art Auction grosses over $4 million,
The Guardian | Tehran auction shifts millions of pounds worth of art in spite of sanctions
4th Tehran Auction (2015) – Showroom 4th Tehran Auction (2015) – Showroom 4th Tehran Auction (2015) – Photo by H. Khahi for ISNA 4th Tehran Auction (2015) – Photo by H. Khahi for ISNA 4th Tehran Auction (2015) – Photo by S. Padash for Fars News Agency 4th Tehran Auction (2015) – Photo by S. Padash for Fars News Agency Massoud Arabshahi – Untitled Aydin Aghdashloo – Enigma XXV Abolghasem Saiedi – Untitled Bahman Mohassess – Untitled Behjat Sadr – Untitled Ali Akbar Sadeghi – Love Garden Jalil Rasouli – Divine Bird Hossein Zenderoudi – Untitled Parviz Kalantari – Untitled Koorosh Shishegaran – Portrait Mohammad Ghaffari (Kamal-al-Molk) – Untitled Nikzad Nodjoumi – The Last Touch Manouchehr Yektai – Untitled Parviz Tanavoli – Monument I for Word Heech Reza Derakhshani – The Red Cypress Seyed Mohammad Ehsai – Affection Sohrab Sepehri – Untitled Sohrab Sepehri – Untitled
Sources: Press TV | Iran | Culture, IRNA | Photos, ISNA | Photos, Fars News Agency | Photos, Tehran Auction | 2015 Lot |
import asyncio
import json
from typing import Awaitable
from unittest import TestCase
from unittest.mock import AsyncMock, patch
from hummingbot.connector.exchange.altmarkets.altmarkets_constants import Constants
from hummingbot.connector.exchange.altmarkets.altmarkets_websocket import AltmarketsWebsocket
from hummingbot.connector.test_support.network_mocking_assistant import NetworkMockingAssistant
from hummingbot.core.api_throttler.async_throttler import AsyncThrottler
class AltmarketsWebsocketTests(TestCase):
def setUp(self) -> None:
super().setUp()
self.mocking_assistant = NetworkMockingAssistant()
def async_run_with_timeout(self, coroutine: Awaitable, timeout: int = 1):
ret = asyncio.get_event_loop().run_until_complete(asyncio.wait_for(coroutine, timeout))
return ret
@patch("websockets.connect", new_callable=AsyncMock)
@patch("hummingbot.connector.exchange.altmarkets.altmarkets_websocket.AltmarketsWebsocket.generate_request_id")
def test_send_subscription_message(self, request_id_mock, ws_connect_mock):
request_id_mock.return_value = 1234567899
ws_connect_mock.return_value = self.mocking_assistant.create_websocket_mock()
throttler = AsyncThrottler(Constants.RATE_LIMITS)
websocket = AltmarketsWebsocket(throttler=throttler)
message = [Constants.WS_SUB["TRADES"].format(trading_pair="btcusdt")]
self.async_run_with_timeout(websocket.connect())
self.async_run_with_timeout(websocket.subscribe(message))
self.async_run_with_timeout(websocket.unsubscribe(message))
sent_requests = self.mocking_assistant.text_messages_sent_through_websocket(ws_connect_mock.return_value)
expected_subscribe_message = {"event": "subscribe", "id": 1234567899, "streams": ['btcusdt.trades']}
self.assertTrue(any(
(expected_subscribe_message == json.loads(sent_request) for sent_request in sent_requests)))
expected_unsubscribe_message = {"event": "unsubscribe", "id": 1234567899, "streams": ['btcusdt.trades']}
self.assertTrue(any(
(expected_unsubscribe_message == json.loads(sent_request) for sent_request in sent_requests)))
|
<gh_stars>10-100
/* eslint-disable @typescript-eslint/ban-types */
import { ActionContext, Store } from 'vuex'
import { Ref } from '@vue/composition-api'
export type ModuleKey = 'state' | 'mutations' | 'actions' | 'getters'
export type VuexStore<R> = Store<R> & {
_modulesNamespaceMap: Dictionary<{
_rawModule: {
state?: Dictionary<any>
actions?: Dictionary<any>
mutations?: Dictionary<any>
getters?: Dictionary<any>
}
}>
}
export type Computed<T> = Readonly<Ref<Readonly<T>>>
export type Dictionary<T = any> = { [k: string]: T }
export type StateMap<T = any> = T extends object
? {
[K in keyof T]: T[K] extends Function
? Readonly<Ref<T[K]>>
: Computed<T[K]>
}
: Dictionary<Computed<any>>
export type GetterMap<T = any> = T extends object
? {
[K in keyof T]: T[K] extends (...args: any) => infer R
? R extends Function
? Readonly<Ref<R>>
: Readonly<Ref<T[K]>>
: Computed<T[K]>
}
: Dictionary<Computed<any>>
export type ActionMap<T = any> = T extends object
? {
[K in keyof T]: T[K] extends (
ctx: ActionContext<any, any>,
...payload: infer P
) => infer R
? (...payload: P) => R
: T[K]
}
: Dictionary<(payload: any) => Promise<any> | any>
export type MutationMap<T = any> = T extends object
? {
[K in keyof T]: T[K] extends (state: any, ...payload: infer P) => infer R
? (...payload: P) => R
: T[K]
}
: Dictionary<(payload: any) => void>
|
Single-Cell Gene Regulatory Network Analysis Reveals Potential Mechanisms of Action of Antimalarials Against SARS-CoV-2
The efficiency of antimalarials, chloroquine (CQ) and hydroxychloroquine (HCQ), in the prevention and treatment of coronavirus disease 2019 (COVID-19) is under intense debate. The mechanisms of action of antimalarials against severe acute respiratory syndrome coronavirus 2 (SARS-CoV-2) have not been fully elucidated. Here, we applied a network-based comparative analysis, implemented in our machine learning workflow—scTenifoldNet, to scRNA-seq data from COVID-19 patients with different levels of severity. We found that genes of the Malaria pathway expressed in macrophages are significantly differentially regulated between patients with moderate and severe symptoms. Our findings help reveal the mechanisms of action of CQ and HCQ during SARS-CoV-2 infection, providing new evidence to support the use of these antimalarial drugs in the treatment of COVID-19, especially for patients who are mildly affected or in the early stage of the infection. |
Update: Susannah lands a new gig
It was likely pressure from the Chicago Blackhawks organization itself and not CSN that led to Susannah Collins being dismissed from Comcast SportsNet Chicago.
Obviously, this is a severe over-reaction by the team in response to her simple “flub” Tuesday.
As you obviously know, Susannah Collins made pretty much every homepage you can think of between Tuesday night and Wednesday afternoon: AOL, Yahoo!, Yardbarker (twice actually, the second time was for her interview of Danica Patrick during Shoot-the-Puck) and every online news agency: E! News, Huffington Post, NESN, well, whatever you get the idea.
Collins inadvertently said that the Blackhawks had a “tremendous amount of sex during the regular season.” She meant to say “success.” She made a mistake, she corrected herself right away. And she moved on. She took it, and all the publicity that came later, like a champ.
Her Twitter stream that night conveyed that she’s a professional, and that she has a sense of humor about herself. (Obviously, she's been silent there since May 1)
The Blackhawks probably started watching Collins very closely and scrutinizing her work after she tweeted the following on March 10th following a 4 goal first period by Edmonton...
You know it's a bad game when the 1st intermission interview is scrapped. #Yikes — Susannah Collins (@susannahcollins) March 10, 2013
As my "Deep Throat" source pointed out, this tweet probably put her on the Hawks management radar. Yes, the Hawks would have issue with this. Despite the fact that it's pretty light, and barely critical. That's how they roll, no negativity is allowed.
Ok, back to my harangue.
CSN released a statement, but it’s boring and doesn’t say anything; exactly like all statements regarding this sort of thing always do! I won’t even bother copying and pasting the statement, because it’s just banal corporatespeak and platitudes.
That’s fine.
CSN doesn’t want to comment further, and they probably don’t want people like me writing about this. They likely don’t want any extra attention on this. Well, too bad.
Because I hope half the city reads this. And if they don't read me, that's fine. But I hope half the city reads somebody who publishes a message similar to what I have to say.
The Network claims Susannah Collins wasn’t canned because of all the attention she got over her “sex” sentence.
OMG! SHE SAID SEX ON THE AIR!!!! SOMEBODY COVER MY PURITAN EARS!!!!!
Good, I really hope that wasn’t grounds for dismissal. Because that would be really stupid.
Here’s what they claim as their reason. quoting the Tribune:
the mistake put a spotlight on Collins, and that quickly refocused attention on a series of raunchy YouTube videos uploaded between 2009 and 2010. As co-host of Sports Nutz, Collins pushed the boundaries of sports journalism; and good taste; with sexually explicit reports and potentially offensive racial stereotypes.
I had an exclusive with Susannah Collins exactly one month ago.
In that exclusive she said:
Well, a friend of a friend was starting a new web series called Sports Nutz which basically entailed me and another girl giving snarky sports commentary. I was making no money at all, but was happier than I had been in ages, so I kept with it. In our second season, we did an episode called “Douchebag Nation” (no joke) about belligerent college basketball fans. Deadspin picked up the video, it went viral, and the Executive Producer of Inside the NFL just happened to see it. He called me in for an interview with Showtime Sports/CBS Sports and I landed the gig.
So Comcast knew about these videos all along?
BUT NOW it’s an issue? All of a sudden?
These videos were not only kosher with Showtime and CBS Sports, they actually helped her GET DISCOVERED!
But now they’re too racy for Comcast? Or should I say for the Blackhawks? Because we all know about the Blackhawks and the CSN ownership structure, and how that arrangement can instigate all sorts of conflicts of interest.
To quote William Costigan Jr. (Dicaprio's character) in The Departed: "maybe you should ask some questions? Some real questions?"
I don’t think Comcast is as much to blame here.I think it's the Blackhawks.
Ever since John McDonough took over the Hawks, he’s been all about message control and brand management. Josh Mora was fired (excuse me, did not have his contract renewed) because he reported something that the Blackhawks didn’t like him reporting. Mora reported that the Blackhawks knew Marian Hossa was injured BEFORE they signed him. He also reported the firing of Dale Tallon. John McDondough and his little lickspittle Jay Blunk just would not have any of that. Even though Mora was only doing his job.
Look at it this way. There's been a fair amount of turnover at the position of CSN Blackhawks beat reporter within just a couple years. Josh Mora. Sarah Kustok. Susannah Collins. Now whoever replaces Susannah Collins. That's four in four years. This is getting to sound like Chicago Bears QBs in the 1990s or 2000s.
Why so much turnover? Are the Blackhawks that obsessed with controlling the message that they must have someone in there who’s in total compliance at all times?
I mean these are questions, right?
Today’s news cycle moves like this:
Somebody does something on television. There’s a million people sitting at home with nothing to do. However, they’ve got a blog, a flipshare, and a DVR. So they post what just happened within 20-30 minutes. Within 4-5 hours it gets picked up by somebody with influence. Within 12-14 hours, it’s EVERYWHERE. Within 24 hours, the interest dwindles. Within 36 hours NO ONE CARES anymore.
Or as Jay Cutler would say: "DON'T CARE!!!!!!!"
"They've moved on to the next flow" as Eminem said in Lose Yourself.
So to fire Susannah Collins over simply misspeaking, is just not right.
And to fire her over something that happened years ago, something that they were well aware of for a long time already? I have to call that out. That's total b.s!
The finger prints of John McDonough, and/or Jay Blunk, the Waylon Smithers to McDonough's Monty Burns are all over this decision.
Paul M. Banks is the owner of The Sports Bank.net. He’s also an author who also contributes regularly to MSN, Fox Sports , Chicago Now, Walter Football.com and Yardbarker
Banks has appeared on Comcast SportsNet and the History Channel, as well as Clear Channel, ESPN and CBS radio all over the world. President Barack Obama follows him on Twitter (@PaulMBanks)
Type your email address in the box and click the "create subscription" button. My list is completely spam free, and you can opt out at any time. |
#include "SceneManager/SceneManagerChooseHero.h"
#include "SceneGraph/DrawableNode.h"
#include "Party/CharacterClass.h"
#include "Controller/Localization.h"
#include "Controller/GameController.h"
#include "Party/ItemFactory.h"
#include "SceneManager/SceneManagerVillage.h"
SceneManagerChooseHero::SceneManagerChooseHero()
{
GameController* controller = GameController::getInstance();
//ctor
m_finished = false;
m_selected = 0;
m_textNode = new TextNode("");
m_gui->addChild(m_textNode);
TextNode* selectHero = new TextNode(Localization::GetInstance()->GetLocalization("menu.chooseHero"));
m_gui->addChild(selectHero);
selectHero->moveNode(40.0f, 0.0f);
PersistentProgress* progress = controller->GetPersistentProgress();
int xPos = 50;
int yPos = selectHero->getBoundingBox().height + 50.0f;
for(int i = 0; i < (int)CharacterClass::CharacterClassEnum::COUNT; i++)
{
CharacterClass::CharacterClassEnum classEnum = (CharacterClass::CharacterClassEnum)i;
bool available = progress->IsClassUnlocked(classEnum);
m_classAvailable[classEnum] = available;
CharacterClass* charClass = CharacterClass::GetCharacterClass(classEnum);
sf::Sprite* classSprite = new sf::Sprite();
if(available)
{
classSprite->setTexture(*TextureList::getTexture(charClass->GetClassSprite()));
}
else
{
classSprite->setTexture(*TextureList::getTexture(TextureList::TextureFiles::LockedCharacter));
}
DrawableNode* sprite = new DrawableNode(classSprite);
sprite->setBoundingBox(classSprite->getLocalBounds());
m_classNodes.push_back(sprite);
sprite->moveNode(xPos, yPos);
xPos += (int)classSprite->getLocalBounds().width + 30;
m_gui->addChild(sprite);
}
sf::Sprite* targetSprite = new sf::Sprite(*TextureList::getTexture(TextureList::TextureFiles::TargetCursor));
m_cursor = new DrawableNode(targetSprite);
m_cursor->setBoundingBox(targetSprite->getLocalBounds());
m_gui->addChild(m_cursor);
sf::Sprite* backgroundSprite = new sf::Sprite(*TextureList::getTexture(TextureList::TextureFiles::DescriptionBox));
Node* background = new DrawableNode(backgroundSprite);
int x = GameController::getInstance()->GetWindowWidth() - backgroundSprite->getLocalBounds().width;
x /= 2;
int y = GameController::getInstance()->GetWindowHeight() - backgroundSprite->getLocalBounds().height;
background->moveNode(x,y);
m_gui->addChild(background);
m_description = new TextNode();
m_description->SetColor(sf::Color::Black);
background->addChild(m_description);
m_description->moveNode(5, 5);
m_description->SetFontSize(15);
m_description->SetMaxLength(630);
ShowForCharacterClass();
}
SceneManagerChooseHero::~SceneManagerChooseHero()
{
//dtor
}
void SceneManagerChooseHero::ShowForCharacterClass()
{
CharacterClass* charClass = CharacterClass::GetCharacterClass((CharacterClass::CharacterClassEnum)m_selected);
if(m_classAvailable[(CharacterClass::CharacterClassEnum)m_selected])
{
m_textNode->SetText(Localization::GetInstance()->GetLocalization(charClass->GetName()));
}
else
{
m_textNode->SetText(Localization::GetInstance()->GetLocalization("character_class.locked"));
}
m_description->SetText(Localization::GetInstance()->GetLocalization(charClass->GetName() + ".desc"));
sf::FloatRect selectedNode = m_classNodes[m_selected]->getGlobalBoundingBox();
int xMid = selectedNode.left + selectedNode.width/2;
sf::FloatRect cursorBounds = m_cursor->getBoundingBox();
m_cursor->setPosition(xMid - cursorBounds.width / 2, selectedNode.top - cursorBounds.height);
sf::FloatRect textBounds = m_textNode->getBoundingBox();
m_textNode->setPosition(xMid - textBounds.width / 2, selectedNode.top + 40);
}
void SceneManagerChooseHero::Tick()
{
GameController* controller = GameController::getInstance();
if(controller->IsKeyPressed(Configuration::Accept) && m_classAvailable[(CharacterClass::CharacterClassEnum)m_selected])
{
StartDungeon();
}
else if(controller->IsKeyPressed(Configuration::MoveRight))
{
ChooseNext();
}
else if(controller->IsKeyPressed(Configuration::MoveLeft))
{
ChoosePrev();
}
else if(controller->IsKeyPressed(Configuration::Cancel))
{
m_finished = true;
}
}
void SceneManagerChooseHero::StartDungeon()
{
GameController* controller = GameController::getInstance();
Party* party = controller->getParty();
PartyMember* p;
p = CharacterClass::GetCharacterClass((CharacterClass::CharacterClassEnum)m_selected)->GetNewPartyMember();
p->SetTeamId(0);
party->AddPartyMember(p);
m_finished = true;
PersistentProgress* progress = controller->GetPersistentProgress();
party->AddMoney(progress->GetStartMoney());
//create new party with x member
int partyInitialSize = progress->GetStartMember();
for(int i = 1; i < partyInitialSize; i++)
{
party->AddRandomMember();
}
std::vector<std::shared_ptr<PartyMember> > * partyMember = party->GetActivePartyMembers();
ItemFactory* itemFactory = ItemFactory::GetInstance();
for(int i = 0; i < 3; i++)
{
Equipment* equipment = (Equipment*)itemFactory->GetRandomEquipment(Equipment::EquipmentPosition::MainHand, ItemFactory::StartingItem);
std::shared_ptr<Item> item = party->AddItem(equipment);
if(partyMember->size() > i)
{
std::shared_ptr<PartyMember> member = partyMember->at(i);
member->SetEquipment(Equipment::EquipmentPosition::MainHand, std::static_pointer_cast<Equipment>(item));
member->Heal(member->GetAttribute(BattleEnums::Attribute::MaxHp));
}
}
controller->LoadSceneManagerBefore(std::shared_ptr<SceneManager>(new SceneManagerVillage(30,20,time(NULL),new MapFillVillage())), this);
}
void SceneManagerChooseHero::ChooseNext()
{
m_selected++;
if(m_selected >= (int)CharacterClass::CharacterClassEnum::COUNT)
m_selected = 0;
ShowForCharacterClass();
}
void SceneManagerChooseHero::ChoosePrev()
{
m_selected--;
if(m_selected < 0)
m_selected = (int)CharacterClass::CharacterClassEnum::COUNT - 1;
ShowForCharacterClass();
}
bool SceneManagerChooseHero::IsFinished()
{
return m_finished;
}
bool SceneManagerChooseHero::IsTransparent()
{
return false;
}
bool SceneManagerChooseHero::PausesSceneManagerBelow()
{
return true;
}
|
import React, { useState } from "react"
import { useLocalStorage } from "./../utils/useLocalStorage"
interface IProps {
ingredients: string[]
}
function distinct(arr) {
return [...new Set(arr)]
}
export const IngredientList = ({ ingredients }: IProps) => {
const ListKey = `Ingredients/${typeof window !== "undefined" &&
window.location}`
const [selectedIds, setSelectedIds] = useLocalStorage(ListKey, [])
const isSelected = (index: number) => selectedIds.indexOf(index) !== -1
const handlePress = (index: number) => {
setSelectedIds(prevSelectedIds => {
if (isSelected(index)) {
return prevSelectedIds.filter(id => id !== index)
} else {
return distinct([...prevSelectedIds, index])
}
})
}
return (
<ul>
{ingredients.map((ingredient, index) => (
<li
className="mb-3 cursor-pointer"
key={`${ingredient}-${index}`}
style={
isSelected(index)
? {
textDecoration: "line-through",
}
: {}
}
onClick={() => handlePress(index)}
>
{ingredient}
</li>
))}
</ul>
)
}
export default IngredientList
|
<reponame>Wynand91/logs_analysis
# !/usr/bin/env python3
import psycopg2
class GetLog:
def __init__(self):
self.conn = psycopg2.connect('dbname=news')
self.cursor = self.conn.cursor()
self.to_be_printed = []
# create views
# total views per article
self.cursor.execute(
"CREATE OR REPLACE VIEW total_article_views AS "
"SELECT path, COUNT(*) AS total_views "
"FROM log "
"GROUP BY path "
"ORDER BY total_views DESC "
"OFFSET 1;"
)
# total views per article with author of article
self.cursor.execute(
"CREATE OR REPLACE VIEW total_views_with_author AS "
"SELECT articles.author, articles.title,"
"total_article_views.total_views "
"FROM articles JOIN total_article_views "
"ON total_article_views.path "
"LIKE concat('%', articles.slug) "
"ORDER BY total_views DESC; "
)
# total responses per day
self.cursor.execute(
"CREATE OR REPLACE VIEW responses_in_day AS "
"SELECT date_trunc('day', log.time) AS day, "
" count(status) AS responses "
"FROM log "
"GROUP BY day;"
)
# total 404 error responses per day
self.cursor.execute(
"CREATE OR REPLACE VIEW errors_in_day AS "
"SELECT date_trunc('day', log.time) AS date, "
" count(status) as errors "
"FROM log "
"WHERE status LIKE concat('404','%') "
"GROUP BY date;"
)
# Joined responses_in_day and errors_in_day
self.cursor.execute(
"CREATE OR REPLACE VIEW responses_and_errors AS "
"SELECT * FROM responses_in_day "
"JOIN errors_in_day "
"ON responses_in_day.day = errors_in_day.date;"
)
# What are the most popular three articles of all time?
def most_popular_articles(self):
self.cursor.execute(
"SELECT title, total_views "
"FROM total_views_with_author "
"LIMIT 3;"
)
result = self.cursor.fetchall()
for article in result:
self.to_be_printed.append(
article[0] + ' - ' + str(article[1]) + ' views \n'
)
self.to_be_printed.append("-" * 50 + "\n")
# Who are the most popular article authors of all time?
def most_popular_authors(self):
self.cursor.execute(
"SELECT name, SUM(total_views) AS sum_of_views "
"FROM authors JOIN total_views_with_author "
"ON authors.id = total_views_with_author.author "
"GROUP BY name "
"ORDER BY sum_of_views DESC; "
)
result = self.cursor.fetchall()
for author in result:
self.to_be_printed.append(
author[0] + ' - ' + str(author[1]) + ' views \n'
)
self.to_be_printed.append("-"*50 + "\n")
# On which days were more than 1% of responses 404 responses?
def error_log(self):
self.cursor.execute(
"SELECT * FROM ("
" SELECT TO_CHAR(day, 'Mon DD, YYYY'), ROUND(errors * 100.0 / responses, 2) "
" AS percent "
" FROM responses_and_errors"
" ) as percentages "
"WHERE percent > 1.00;"
)
result = self.cursor.fetchall()
for res in result:
self.to_be_printed.append(
res[0] + ' - ' + str(res[1]) + '% errors'
)
self.to_be_printed.append("\n")
# Method writes content of to_be_printed list to file
def write_file(self):
with open('log_result.txt', 'w') as f:
for item in self.to_be_printed:
f.write(item)
def __del__(self):
self.conn.close()
if __name__ == '__main__':
instance = GetLog()
instance.most_popular_articles()
instance.most_popular_authors()
instance.error_log()
instance.write_file()
|
def load_model_from_file(model: torch.nn.Module, model_file_path: Path) -> None:
if model_file_path.is_file():
try:
model.load_state_dict(torch.load(model_file_path))
except Exception as e:
logging.warning("Couldn't load model. Attempting to map CUDA tensors to CPU to solve error.")
else:
logging.warning("Could not find model: {}".format(model_file_path))
raise FileExistsError(f"Cannot load model file {model_file_path} into {model}...") |
// Called by Oboe audio callback implementation. It is called after AAP processing, and
// fill the audio outputs into an intermediate buffer, interleaving the results,
// then copied into the ring buffer.
void AAPMidiProcessor::fillAudioOutput() {
for (auto &data : instance_data_list) {
if (data->instance_id == instrument_instance_id) {
int numPorts = data->audio_out_ports.size();
for (int p = 0; p < numPorts; p++) {
int portIndex = data->audio_out_ports[p];
auto src = (float*) data->plugin_buffer->buffers[portIndex];
for (int i = 0; i < aap_frame_size; i++)
interleave_buffer[i * numPorts + p] = src[i];
}
}
}
zix_ring_write(aap_input_ring_buffer, interleave_buffer, channel_count * aap_frame_size * sizeof(float));
} |
Dispatch Family, We are just over seven weeks away from the Dispatch 2011 Tour kickoff! Brad, Chad, and Pete are practicing all the tunes - old and new - and they can't wait to get on stage and see all of you this summer. They have also been in and out of the studio working on some new material, and we are thrilled to share with you the first look at Dispatch In The Studio where they reveal some parts of the new songs plus their patented exercise program, Squat A Friend. Take a look here and click to watch: In other news...
DISPATCH TO PLAY LATE NIGHT WITH JIMMY FALLON! On April 27th Dispatch will be performing on Late Night with Jimmy Fallon. They will debut their FIRST NEW SONG IN OVER 10 YEARS live on national TV! Be sure to catch the band's return to late night as they unveil brand new material in anticipation of their upcoming release. (more on the release soon... ) AND - How would you like to join the band not just in studio but ON STAGE DURING THE PERFORMANCE? Click here and you will be directed to the “Band Bench” Sweepstakes entry form. Enter for a chance to win seats on the band benches at Fallon and an opportunity to surround the stage during Dispatch’s performance. Please make sure you include the band code "DIS" in your entry form.
TOUR UPDATE A select number of premium tickets have been released to all the shows on the tour. We have released some of the band's ticket holds (= great seats!) so if you missed out during the on-sale, here's your chance. Click here for tickets. Many of the shows this tour have sold out, and the premium seats noted above will go very quickly, however there are still some seats left in the following cities: June 05 @ Red Rocks in Morrison, CO
June 07 @ UIC Pavilion in Chicago, IL
June 11 @ The Greek Theatre in Berkeley, CA
June 12 @ The Greek Theatre in Los Angeles, CA
June 18 @ Red Bull Arena in Harrison, NJ
June 26 @ TD Garden in Boston, MA Get your tickets now as these shows, too, will likely sell out.
NEW WEBSITE Last but not least, head on over to the all new DISPATCHMUSIC.COM for the brand new website!
More soon,
Team Dispatch |
<filename>resimpy/pcr/Amplify.py
__version__ = "v1.0"
__copyright__ = "Copyright 2022"
__license__ = "MIT"
__lab__ = "<NAME> lab"
from resimpy.util.random.Ordering import ordering as ranord
from resimpy.util.random.Sampling import sampling as ranspl
from resimpy.util.random.Number import number as rannum
from resimpy.pcr.Error import error as pcrerr
class amplify(object):
def __init__(self, pcr_params):
self.pcr_params = pcr_params
def np(self, ):
for ipcr in range(self.pcr_params['pcr_num']):
print('===>at PCR {}'.format(ipcr + 1))
self.pcr_params['ipcr'] = ipcr
self.pcr_params = self.flow(params=self.pcr_params)
# print(std_flow_params.keys())
return self.pcr_params
@pcrerr(method='default')
@ranspl(method='uniform')
@rannum(type='binomial')
@ranord(method='uniform')
def flow(self, params):
return params |
/**
* Send the message using multicast and use convergence to gather the
* results. Note that this routine must be synchronized because
* only one multicast can be active at a time; othewise, the client
* may get back an unexpected result. However, there can be many unicast
* requests active along with a multicast request, hence the separate
* thread for multicast.
*
* The subtlety of the timing routine is that it will only resend the
* message when one of the multicast convergence timeout intervals
* elapses. Further, for efficiency, it will give up after a complete
* interval has gone by without receiving any results. This may mean
* that the intervals have to be extended in larger networks. In the
* common case, multicast convergence will complete under 3 seconds
* as all results will arrive during the first interval (1 second long)
* and none will arrive during the second interval.
*
* @param addr The multicast/broadcast address to send the request to.
* @param ds The datagram socket to send on.
* @param msg The message to send.
* @param vResult A vector in which to put the returns.
* @param msTimeouts Array of timeout values for multicast convergence.
* @param maxResults Maximum replies desired.
* @param continueAfterFound If true, continue after something is
* found. Try three times if nothing was
* found. If false, exit at the first
* timeout. DA discovery should set this
* to true so as many DAs as possible are
* found, otherwise, it should be false.
* @exception ServiceLocationException
* If results cannot be obtained in the timeout interval
* specified in the 'config.' or
* if networking resources cannot be obtained or used
* effectively.
*/
static public void
transactConvergeMsg(InetAddress addr,
DatagramSocket ds,
SrvLocMsg msg,
Vector vResult,
int[] msTimeouts,
int maxResults,
boolean continueAfterFound)
throws ServiceLocationException {
if (config == null) {
config = SLPConfig.getSLPConfig();
}
int numReplies = 0;
int tries = 0;
SrvLocMsg rply = null;
ByteArrayOutputStream baos = null;
int multiMax = config.getMulticastMaximumWait();
long lStartTime = System.currentTimeMillis();
int mtu = config.getMTU();
try {
send(ds, msg, addr);
tries++;
long lTimeSent = System.currentTimeMillis();
while (numReplies < maxResults) {
byte [] incoming = new byte[mtu];
DatagramPacket dprecv =
new DatagramPacket(incoming, incoming.length);
int iTimeout =
getTimeout(lStartTime, lTimeSent, multiMax, msTimeouts);
if (iTimeout < 0) {
break;
}
ds.setSoTimeout(iTimeout);
try {
ds.receive(dprecv);
} catch (InterruptedIOException ex) {
if ((!continueAfterFound && numReplies > 0) ||
(int)(System.currentTimeMillis() - lStartTime) > multiMax ||
tries >= 3) {
break;
}
send(ds, msg, addr);
tries++;
lTimeSent = System.currentTimeMillis();
continue;
}
DataInputStream dis =
new DataInputStream(
new ByteArrayInputStream(dprecv.getData()));
InetAddress raddr = dprecv.getAddress();
rply = internalize(dis, raddr);
if (!filterRply(msg, rply, raddr)) {
continue;
}
if (!addPreviousResponder(msg, raddr)) {
continue;
}
SrvLocHeader rhdr = rply.getHeader();
if (rhdr.overflow) {
rply = transactTCPMsg(raddr, msg, false);
if (rply == null) {
continue;
}
rhdr = rply.getHeader();
}
if (vResult.size() < maxResults) {
vResult.addElement(rply);
}
numReplies += rhdr.iNumReplies;
if (!continueAfterFound) {
break;
}
}
} catch (ServiceLocationException ex) {
if (ex.getErrorCode() ==
ServiceLocationException.PREVIOUS_RESPONDER_OVERFLOW) {
return;
}
throw ex;
} catch (IOException ex) {
throw
new ServiceLocationException(
ServiceLocationException.NETWORK_ERROR,
"ioexception_conv",
new Object[] {ex, ex.getMessage()});
}
} |
On the spin-observables in pseudoscalar meson photoproduction
Spin-observables in pseudoscalar meson photoproduction is discussed. This work is complementary to the earlier works on this topic. Here, the reaction amplitude is expressed in Pauli-spin basis which allows to calculate all the observables straightforwardly. We make use of the fact that the underlying reflection symmetry about the reaction plane can be most conveniently and easily exploited in this basis to help finding the non-vanishing and independent observables in this reaction. The important issue of complete experiments is reviewed. By expressing the reaction amplitude in Pauli-spin basis, many sets of eight observables - distinct from those found in earlier works from the amplitude in transversity basis - capable of determining the reaction amplitude up to an overall phase are found. It is also shown that some of the combinations of the spin observables are suited for studying certain aspects of the reaction dynamics. In particular, it is shown that, even at energies close to threshold, where the number of partial-waves are restricted, the unpolarized cross section and single-polarization observables alone are not sufficient to constrain the reaction amplitude completely. For this, some double-polarization observables are required. This work should be useful, especially, for newcomers in the field of baryon spectroscopy, where the photoproduction reactions are a major tool for probing the baryon spectra.
Introduction
Model-independent aspects of pseudoscalar meson photoproduction reactions have been discussed by a number of authors in the past . For example, Fasano, Tabakin and Saghai have given a detailed account on the general structure of the single-and double-spin observables in this reaction, with emphasis on the low energy behavior of these observables.
Chiang and Tabakin , on the other hand, have shown that, for a given total energy of the system and meson production angle, one requires a minimum of eight carefully chosen independent observables -the so-called complete experiments -to determine the full reaction amplitude up to an arbitrary overall phase. This problem has been revisited quite recently in Ref. , where it is shown that the completeness condition of a set of four observables to resolve the phase ambiguity of the photoproduction amplitude in transversity representation holds only when the magnitudes of the relative phases are different from each other. In situations where the equality of the magnitudes occurs, it has been shown that additional one or two or even three chosen observables are required to resolve the phase ambiguity, depending on the particular set of four observables considered. This increases the minimum number of observables required for a complete experiment. A way of gauging when the equal magnitudes situation occurs has been also provided in Ref. .
In Ref. , also the Fierz transformations of the gamma matrices have been used to develop useful linear and nonlinear relationships between the spin observables. These relations not only help finding the complete sets of experiments, but also yield important constraints among the 16 non-redundant observables for this reaction. Also, Moravcsik has discussed the quadratic constraints among bilinear products of reaction amplitudes in terms of the experimental observables for a reaction with arbitrary spins. Artru, Richard and Soffer have derived various positivity constraints among the spin observables which is very useful in determining the allowed domain of physical observables, in addition to testing the consistency of various available measurements and also the validity of some dynamical assumptions in theoretical models.
Sandorf et al. have given a thorough consideration of the spin observables in pseudoscalar photoproduction reaction, especially, involving the issues of practical purposes. Among other things, they have concluded that, while a mathematical solution to the problem of determining an amplitude free of ambiguities may require eight observables , experiments with realistically achievable uncertainties will require a significantly larger number of observables. Further detailed studies along this line have been carried out by the Gent group , where a statistically more sound analysis is performed to constrain the photoproduction amplitude . Recently, with the advances in experimental techniques, many spin-observables in photoproduction reactions became possible to be measured and this has attracted much renewed interest in constraints on partial-wave analysis in the context of complete experiments (for some of the related earlier works, see, e.g., Refs. ). Of particular interest in this connection is the issue of whether the baryon resonances can be extracted model independently or with minimal model requirements. Efforts along this line is currently in progress .
In this work, we consider those same issues mentioned above; as such, it is complementary to the earlier works on this topic . In contrast to those studies, we consider the photoproduction amplitude in Pauli-spin basis which allows us to calculate the spin-observables in general in a straightforward and quite pedestrian way. We will make used of the underlying reflection symmetry about the reaction plane -which can be conveniently and easily exploited in this basis -to help find the non-vanishing and independent observables in this reaction. Also, the Paulispin amplitude is simply related to that of the usual Chew-Goldberger-Low-Nambu (CGLN) form due to this symmetry. The important and non-trivial issue of the complete experiments is reviewed. In particular, by using Pauli-spin representation of the reaction amplitude instead of transversity representation, we identify other sets of observables, not reported in , for complete experiments. In addition, certain combinations of the observables are shown to be useful in isolating (low) partial-wave states to learn about the reaction dynamics. In particular, we show that even at energies close to threshold, where the number of partial-waves are restricted, the unpolarized cross section and single-polarization observables alone are not sufficient to constrain the reaction dynamics model independently. For this, double-polarization observables are required.
This note is organized as follows. In Sec. 2, we give the general form of the pseudoscalar meson photoproduction amplitude. It is a variant of the well-known CGLN form of the amplitude and has a simple relation to the amplitude in Pauli-spin basis. In Sec. 3 the definitions of various spin asymmetries are given. In Sec. 4, the basic formulas for the spin observables in general are derived in terms of the Paulispin amplitudes. Using these basic formulas, the spin observables for linearly and circularly polarized photons are derived in Secs. 5 and 6, respectively. Section 7 gives a dictionary for different notations used in the literature for double-spin observables and Sec. 8 summarizes the non-redundant observables. In Sec. 9, the issue of the complete experiments is reviewed. In Sec. 10 the observables are expressed in terms of the amplitudesà la CGLN given in Sec. 2. Observables in the rotated frame are given in Sec. 11. A brief partial-wave analysis is given in Sec. 12. Finally, Sec. 13 contains the summary. Details of the analysis on complete experiments using the Paulispin representation of the reaction amplitude are given in Appendices A and B. In Appendix C, the beam-target asymmetry E is shown to be a measure of the helicity asymmetry.
Note that gauge freedom always allows one to make the choice ǫ µ = ǫ ′ µ − λk µ for any λ. For example, for λ = ( ǫ ′ ·k)/| k|, ǫ ·k = 0 but ǫ 0 = 0, i.e., the virtual photon has no longitudinal component and the amplitudeM corresponds to a virtual photon with transverse and scalar components. Alternatively, one could make the choice λ = ǫ ′ 0 /k 0 for the gauge parameter, leading to ǫ 0 = 0, i. e., the photon polarization has no scalar component. In this case the electroproduction amplitude can be expressed as (2) corresponding to a virtual photon with transverse and longitudinal components. Obviously, the coefficients f i in Eqs. (1) and (2) are not independent from each other.
In fact, f 7 and f 8 in Eq. (1) are related to f i (i = 1, 3 − 6) in Eq. (2) by the gauge invariance conditions k 0 For further convenience, following Ref. , we re-write Eq. (1) aŝ where, apart from an irrelevant overall constant phase, It is also immediate to relate the coefficients F i to the coefficients f i in Eq. (2). For photoproduction, the terms proportional to F 7 and F 8 in Eq. (4) do not contribute due to the transversality of the real photon,k · ǫ = 0, so that, ǫ 0 = 0. Recall that k µ ǫ µ = 0 always. Hence, Eq. (4) reduces tô Note from the above equation that only the coefficient F 1 contains the final S partial-wave state. Also, the coefficient F 4 contains no partial waves lower than the D-wave in the final state.
For isovector meson electroproductions, such as the pion electroproduction, the full reaction amplitude,M, contains also the isospin structure. Its general form can be obtained by forming a scalar out of the available operators in isospin space for this reaction, viz.,M whereπ j (j = 0, ±1) stands for the produced pion state in isospin space. τ = (τ −1 , τ 0 , τ +1 ) denotes the usual Pauli matrix in isospin space. Each coefficientM X (X = A, B, C) in the above equation is an independent amplitudeM in spin space given by Eq. (6).
It is well-known that the coefficients f i in Eqs. (1,2), or F i in Eq. (4), can be expanded in partial waves which allows for partial-wave analyses. In photoninduced reactions, it is customary to use the multipole decomposition instead of partialwave decomposition. In electroproduction, which of the two decomposions to use is just a matter of convenience. In photoproduction, however, the multipole decomposion is preferred over the partial-wave decomposition, since in the former decomposition, the multipoles S l± (see below) vanish identically due to the transversality of the real photon, while in the latter decomposition, only a certain combinations of the partial-wave matrix elements are probed. Explicitly, the multipole decomposition of the photoproduction amplitude in Eq. (6) is given by with P ′ l ≡ P ′ l (x) and P ′′ l ≡ P ′′ l (x) denoting, respectively, the derivative and the doublederivative of the Legendre Polynomial of first kind, P l ≡ P l (x), with respect to x. N ≡ 4πW/m N , where m N denotes the nucleon mass.
The above equation may be inverted to yield with N + l ≡ i/ and N − l ≡ i/ . The longitudinal multipole amplitude (L l± ), associated with the alternative form of the electroproduction amplitude given by Eq. (2), is related to the scalar multipole amplitude (S l± ) by
General cross section
The general spin-dependent cross section can be expressed in terms of the cross sections with specified spin polarization states of the particles in the initial and final states in a given reaction process. These cross sections are referred to as the spin observables. For pseudoscalar meson photoproduction off the nucleon, described by the amplitude given by Eq. (6), the associated general cross section can be written as The superscript γ on the Pauli spin matrix, σ γ , indicates that this operator acts on the real photon helicity space. P a stands for the polarization vector which specifies the direction and the degree of (spin) polarization of the ensemble of particles a, as a = photon(γ), target nucleon(N) or recoil nucleon(N ′ ). It is given by wheren i stands for the unit vector specifying the direction of the polarization. Details on the polarization vector for a real photon, P γ (called Stokes vector), may be found in Ref. . Equation (11) can be re-written as In the above equations, the superscript p i stands for the linear(l) or circular(c) polarization of the photon as we shall specify in Secs. 5 and 6.
Basic observables in photoproduction
Observables in reaction processes may be written in terms of the corresponding amplitudes expressed in different representations (or basis). Which representation to use depends on the particular physics aspect(s) one is interested in to investigate. In ‡ Here, we refer to B pi , T i , R j , etc. as the spin-asymmetries. Strictly speaking, they are called the analyzing powers . Asymmetries are the quantities photoproduction reactions, the most commonly used representations are in terms of the coefficients F ià la CGLN, as given by Eq. (6), and the helicity representation . Also, the transversity representation is especially convenient in connection to the problem of complete experiments . Of course, the multipole expansion is used for partialwave analyses. In this work, we express the photoproduction amplitude in the Pauli-spin representation. As we shall see in the following, this allows us to calculate the spinobservables, in general, in a straightforward and quite pedestrian way. We will make used of the underlying reflection symmetry about the reaction plane -which can be most conveniently and easily exploited in this representation -to help find the non-vanishing and independent observables in this reaction. Also, the Pauli-spin amplitude is simply related to that of the usual CGLN form due to this symmetry as given in the next section.
We first define a set of three mutually orthogonal unit vectors {x,ŷ,ẑ} in terms of the available momenta in the problem to be used as the reference frame. Namely, We now note that, for a given photon polarization ǫ λ , the photoproduction amplitude given by Eq. (6) can be expressed in a compact notation aŝ with σ 0 = 1 and σ i (i = 1, 2, 3) denoting the usual Pauli-spin matrices. Throughout this note we use (1,2,3) or (x, y, z) indistinguishably. The coefficients M λ m are given explicitly in terms of F i in Secs. 5 and 6 for a linearly and a circularly polarized photon, respectively.
Using the photoproduction amplitude in the form given by Eq. (16), any observable corresponding to the photon polarization ǫ λ can be calculated straightforwardly. Then, following , the cross section with the polarization of the photon ǫ λ incident on an unpolarized target is given by For a given photon polarization ǫ λ , and target-nucleon spin in the i-direction (i = x, y, z), the corresponding spin observable, T λ i , can be expressed as where the subscripts (i, j, k) run cyclically, i.e., (1,2,3), (2,3,1), (3,1,2). Throughout this note, we use (1,2,3) or (x, y, z) indistinguishably. Similarly, the spin observable, R λ i , of the outgoing nucleon in the i-direction induced by a photon beam with polarization ǫ λ is given by where the subscripts (i, j, k) run cyclically. Another spin observable is the spin transfer coefficient induced by a polarized photon beam, K λ ij , which is given by where ǫ ijk denotes the Levi-Civita antisymmetric tensor and (i, j, k) may take any of the values (1, 2, 3). The diagonal terms reduce to Equations (17,18,19,20) exhaust all the possible basic observables in photoproduction with a polarized photon beam. Any other observables may be constructed by appropriate linear combinations of them. In the following two sections, the spin asymmetries defined in Sec. 3 will be calculated based on these basic observables.
Observables with linear photon polarization
In what follows, ǫ ⊥ ≡ŷ and ǫ ≡ cos θx − sin θẑ denote the photon polarization perpendicular and parallel to the reaction plane (xz-plane), respectively. Here, cos θ ≡ k ·q. Recall that the reaction plane is defined as the plane containing the vectors k (in the +z-direction) and q and thatŷ is perpendicular to the reaction plane (cf. Eq. (15)). Then, in this case, Eq. (16) becomeŝ The particular form of the polarized photon amplitudes above, in which only the two of the four coefficients F i enter the amplitudeM ⊥ and the absence of F 2 inM , is a direct consequence of the reflection symmetry in the reaction plane and leads to many interesting features of the resulting observables. The coefficients M λ m in Eq. (16) can be read off of Eq. (22) As mentioned above, due to the reflection symmetry encoded in Eq. (22), not all the observables are independent from each other. For example, from Eqs. (18,19), using Eq. (23), we have Also, from Eqs. (20,21) In terms of the amplitudes M m , the completely unpolarized cross section becomes § Note that to obtain the proper unpolarized cross section, dσ/dΩ given above should be multiplied by the incident flux and the final-state phase-space density factor, namely, in the center-of-mass frame of the system. Here, m N denotes the nucleon mass.
Recall that the operator σ γ x acts on the real photon helicity space. In the context of the above equation, σ γ x =P ⊥ −P , where the projection operatorP λ specifies the state of the photon polarization; namely,P λ ǫ ≡ ǫ λ . Note thatP λ ′P λ = δ λ ′ λ and λP λ = 1. The projection operatorP λ defined here is associated with the Stokes vector, P γ , introduced in Sec. 3 which specifies the direction and degree of polarization of the photon. For example,P ⊥ (P ) corresponds to P γ x = +1 (P γ x = −1), while the projection operator for circular polarizations (cf. Eq. (45)),P ± corresponds to P γ z = ±1.
The target asymmetry is given by and T x = T z = 0.
Similarly, we have for the recoil asymmetry and R x = R z = 0.
The target-recoil asymmetry using an unpolarized photon beam is given by where (i, j, k) may take any of the values (1, 2, 3) as in Eq. (20). The diagonal terms reduce to with and the non-vanishing off-diagonal ones It is interesting to note that, using Eq. (23) in Eqs. (18,19), one obtains which shows that the recoil-nucleon asymmetry, P , can be determined by measuring the beam-target asymmetry, T l y , involving the polarization of the photon and nucleon in the initial state. This may be relevant experimentally for photoproduction reactions where the recoil particle is not self-analyzing. Furthermore, from Eqs. (28,33), As pointed out in Ref. , these results are all consequences of the reflection symmetry in the reaction plane.
The linear photon polarization, ǫ ⊥ and ǫ , discussed above can be generalized to any direction in the plane containing these vectors by rotating them about the axis along the meson momentum q by an angle φ: For the linear polarizations defined above, Eq. (16) becomeŝ with We, then, have from Eqs. (17,18), The polarization observable R λ i are given by the expressions for T λ i above with the sign of For the triple-polarization observables we have, from Eq. (20), For i = j, K λ ji is given by K λ ij given above with the sign of Im changed.
From Eqs. (40), the beam asymmetry is given by Also, from Eq. (40), the double-polarization asymmetries (beam-target (T l i ) and beam-recoil (R l i )) are Finally, from Eq. (41), the (triple-polarization) beam-target-recoil (K l ′ ij ) asymmetries are In the above equations, T c i and R c i denote the double-polarization asymmetries with circularly polarized photons as given by Eq. (53) in the next section. As one can see, apart from K l ′ yy , which is related to the unpolarized cross section, the triple-polarization asymmetries given above are directly related to the double-polarization asymmetries.
Observables with circular photon polarization
The circular polarization of the photon is defined by The corresponding amplitudesM ± are related to those with the linear photon polarization given in Eq. (22) bŷ wherẽ with M m given by Eq. (23). The cross section for a circularly polarized photon and an unpolarized nucleon target is then given by which immediately leads to the (circular) beam asymmetry (p z ≡ c) From Eqs. (18,19), the double-polarization observables It is straightforward to show that, for the diagonal spin observables K ± ii , one obtains and that the off-diagonal ones become From Eq. (50), the double-polarization asymmetries, beam-target (T c i ) and beam- and and From Eqs. (44,54), we see that the triple-polarization asymmetries are simply redundant.
Different notations
In the literature, one uses different notations for the double-polarization observables than used in this note. Here is a dictionary: Also, some authors use different conventions for defining the double-polarization asymmetries. See, e.g., Ref. for a list of different definitions used by some of the groups. The conventions in this work are consistent with those of Refs. , except for the sign of E in the latter reference. Also, our E, G, and L x differ in sign from those in Ref. . Two of the double-polarization asymmetries, T l ′ y and R l ′ y , are related to the single-polarization asymmetries, R y (≡ P ) and T y (≡ T ), respectively. A third double-polarization asymmetry, K yy (target-recoil asymmetry), is related to the beam asymmetry, B l (≡ Σ). All the triple-polarization asymmetries are related to the doublepolarization asymmetries. There are, then, 16 non-redundant observables in total. Appropriate combinations of them yield (using the commonly adopted notations as given in the previous section) dσ dΩ
Complete experiments
The relations in the upper two rows in Eq. (56) determine the magnitude of the amplitudes M m , while the relations in the lower rows determine the phase difference between the corresponding two amplitudes, i.e., M 0 and M 2 , and, M 1 and M 3 , etc. Note that it requires both Re M i M * j and Im M i M * j for fixing the phase difference between the amplitudes M i and M j completely.
From the results in Eq. (56), one might naively conclude that one needs at least 12 independent observables to determine the photoproduction amplitude completely, apart from an arbitrary overall phase. For example, as mentioned above, the observables Σ, T x , L z , together with the unpolarized cross section dσ/dΩ (first two rows in Eq. (56)) determine the magnitudes of the amplitudes M m , while T , P , T z and L x (the next two rows in Eq. (56)) determine the relative phase of M 0 and M 2 , and of M 1 and M 3 , respectively. We, then, need two more constraints provided by, say, F , C x , H, and O x (left column of the next two rows in Eq. (56)) to determine the relative phase between M 0 and M 1 . This ends up with the total of 12 independent observables to determine the photoproduction amplitude. However, as discussed in the following, careful considerations reveal that one actually needs less observables to determine the photoproduction amplitude.
An early account on the issue of complete experiments has been given by Baker, Donnachie and Storrow in their classical work . The problem is not trivial. In fact, early studies on this issue have resulted in contradictory findings. The situation has been cleared by the authors of Ref. who have derived the necessary and sufficient conditions for determining the full photoproduction amplitude up to discrete ambiguities. They also provided the rules for choosing further measurements to resolve these ambiguities. According to these authors, for a given kinematics (total energy of the system and meson production angle), one requires nine observables to determine the full reaction amplitude up to an arbitrary overall phase. Keaton and Workman , however, have realized that the issue is not quite that simple and that there are cases obeying the rules given in Ref. that still leave unsolved ambiguities. Then, as mentioned in the Introduction, in a detailed analysis, Chiang and Tabakin have shown that the minimum number of required observables to determine the pseudoscalar meson photoproduction amplitude is eight. The issue of complete experiments has been revisited quite recently in Ref. which corroborates the original findings of Ref. . However, it is found that the argument of eight observables required for a complete experiment hols only when the magnitudes of the relative phases α ij , as defined in Ref. , differ from each other.
To address the problem of complete experiments, it is convenient to express the complex amplitudes M i 's in the form As mentioned before, the magnitudes B i 's are determined from the four observables through the relations in the first two rows in Eq. (56). Then, a set of carefully chosen four observables from the remaining spin-observables in Eq. (56) serves to determine the relative phases {φ 01 , φ 12 , φ 23 } (φ ij ≡ φ i −φ j ) or any combinations of three relative phases φ ij 's that allow to determine the phases φ i (i = 0, · · · , 3) of the reaction amplitude up to an overall phase. In Refs. , the above described procedure of determining the reaction amplitude, directly in terms of the magnitudes and phases, have been carried out for amplitudes expressed in transversity basis instead of Pauli-spin basis as used in the present work. Transversity basis is related to Pauli-spin basis by a simple rotation of the quantization axis. In the latter case, the quantization axis is along the incident photon momentum, while in the former case, it is along the axis perpendicular to the reaction plane . In transversity basis, the magnitudes of the amplitudes M i 's are determined by the unpolarized cross section dσ/dΩ, and single-spin observables Σ, T and P , leaving the double-spin observables to determine the phases of the amplitude . This is a nice feature of the transversity amplitudes from the experimental point of view for reactions where the baryon in the final state is self-analyzing, such as the Λ and Σ hyperons, so that the recoil-asymmetry P can be measured without measuring the spin of the recoil baryon explicitly. Otherwise, the measurement of the recoil asymmetry is much more involved than measuring the other single-spin observables. Also, measuring the phases of the transversity amplitudes is trickier than measuring their magnitudes in general. As can be seen from Eq. (56), in Pauli-spin basis, the double-spin observables T x and L z enter in the determination of the magnitudes of the Pauli-spin amplitudes. We also mention that none of the single-spin observables enter in the determination of the magnitudes of the helicity amplitudes . An immediate consequence of these differences, is that one can find more possible sets of minimum number of observables, distinct from those determined in Refs. , that can determine the photoproduction amplitude up to an overall phase.
The sets of minimum number (four) of spin observables that resolve the phase ambiguity of the Pauli-spin amplitudes up to an overall phase can be determined in complete analogy to what has been done in Ref. for transversity amplitudes. For details, see Appendix A. The results are given in Tables. 1, 2, 3, and 4. Note that, there, the kinematic restrictions on the relative phase angles for those sets of four observables -that resolve the phase ambiguity otherwise -are indicated. The restrictions of the type (β ik ± α kl ) = ±π/2 at the level of pairs of observables as discussed in Appendix B are not indicated. For details, see Appendix B. The restrictions are less severe for determining the relative phases of the reaction amplitude in Pauli-spin representation than in transversity representation as discussed also in Appendix B.
Those sets of four spin observables not involving the single-spin observables T and P yield distinct sets of eight observables to determine the photoproduction amplitude compared to those sets of eight observables containing the sets of four double-spin observables given in Refs. that do not involve T x and L z .
Anyway, these results reveal that it is experimentally extremely demanding to determine the photoproduction amplitude uniquely for it requires to measure both the single-and double-spin observables for each kinematics. Moreover, as has been pointed out in Ref. , experimental data have finite accuracies which limits our ability to determine the reaction amplitude in a complete experiment. Due to these difficulties, in practice, it requires to measure more observables than those of a complete experiment to determine the amplitude. In this regard, measurements of more observables among those 16 non-redundant ones are not just desirable for consistency check purposes, but they are a necessity. Note that for isovector meson photoproduction, we see from Eq. (7) that one requires to measure, in principle, at least three charged channels (e.g., γp → π 0 p, γp → π + n, and γn → π − p) to determine the corresponding reaction amplitude. Measurements of the fourth channel (γn → π 0 n) may be useful, especially, if comparable level of accuracies of the data achieved in the charged channels can be attained. The issue of the complete experiments in connection to the actual experimental data has been further addressed by the Gent group in detailed analyses, including a statistically more sound analysis to constrain the photoproduction amplitude . It should also be mentioned that there have been initiatives toward finding constraints on partial-wave analysis in the context of complete experiments motivated by the recent advances in experimental techniques that allow for possibilities of many spin-observables in photoproduction reactions to be measured. Of particular interest in this connection is the issue of whether the baryon resonances can be extracted model independently or with minimal model assumptions. Efforts in this direction are currently in progress . Here, we remark that quantum mechanics does not allow to determine the overall phase of the reaction amplitude from experiment. For this, some physics input is required. This fact must have a strong impact on partial-wave analysis for extracting the baryon resonances in the context of complete experiments for, if the overall phase of the amplitude is unknown, the corresponding partial-wave amplitude is an ill defined quantity, unless the unknown overall phase is a constant, independent on the meson production angle.
Before leaving this section, it should be mentioned that the Fierz transformation may be used to obtain various relationships among the 16 non-redundat observables .
They are very helpful for testing the consistency of these observables extracted either experimentally or calculated based on theoretical models. An exhaustive number of these Fierz relations are given in Refs. . Thus, we refrain from giving them here. The conventions for the spin observables in Ref. are consistent with those used in this work, except for the sign difference of E.
Observables in terms of the amplitudes F i
Of course, if one wishes, any of the observables discussed in Secs.5 and 6, can be expressed directly in terms of the coefficients F i appearing in the most general form of the photoproduction amplitude given by Eq. (6). For example, inserting Eq. (23) into Eq. (26), the unpolarized cross section becomes dσ dΩ From Eqs. (23,28,29,30), the single-polarization asymmetries become The beam-target asymmetries, are given by (from Eqs. (23,43,53)) In Appendix C, the beam-target asymmetry E is shown to correspond to the helicity asymmetry.
The beam-recoil asymmetries are given by (from Eqs. (23,53)) and, from Eqs. (23,43), The target-recoil asymmetries are, from Eqs. (33,34), Some of the appropriate combinations of the spin observables may be useful for learning about certain aspects of the reaction dynamics. For example, may tell us about the D-wave interferences at low energies, because the amplitude F 4 contains no partial-waves lower than the D-wave in the final state.
Another example is the case of the combinations dσ dΩ which filter out the S-wave contributions since the S-wave is contained only in the amplitude F 1 .
Other combinations such as dσ dΩ can determine the amplitudes F i (here, i = 1, 2). Note that the combinations T + P and/or L x + T z can be useful to shed light on the S-wave interference at low energies as the S-waves are contained only in F 1 , as mentioned above. Also, note that the quantities that are proportional to the imaginary part of the product of the amplitudes should be more sensitive to the final state interaction compared to those that depend only on the real part.
Observables in the rotate frame
In the literature, some of the spin observables involving recoil-nucleon spin polarization are specified in the rotated coordinate system with the quantization axis along the direction of the meson momentum q. Here we give the spin observables in this rotated frame. The rotated reference frame, {x ′ ,ŷ ′ ,ẑ ′ }, is obtained from {x,ŷ,ẑ} (cf. Eq. (15)) by rotating the latter by an angle θ (cos θ ≡k ·q) counterclockwise about theŷ-axis. Explicitly,x ′ = cos θx − sin θẑ , z ′ = sin θx + cos θẑ , Note that, in terms of this rotated primed reference frame, the linear photon polarization ǫ and ǫ ⊥ defined in the unprimed frame can be expressed as Also, the photon and meson momenta, k and q, respectively, are given bŷ Inserting Eqs. (68,69) into Eq. (6), we can express the photoproduction amplitudê M for a given photon polarization in the primed reference frame aŝ where We are now in position to express all the observables in the rotated primed frame, {x ′ ,ŷ ′ ,ẑ ′ }. To this end, we simply make the substitution M i → M i ′ in the observables in the unprimed frame, {x,ŷ,ẑ}, considered in the previous sections. In particular, from Eq. (53), we have where φ ′ plays the same role in the rotated frame as the angle φ introduced in Eq. (37). Similarly, since we have In terms of the amplitudes F i in Eq. (6), we have, from Eqs. (71,72), and, from Eqs. (63,74), (76)
Photoproduction near threshold
We now consider the partial waves with the orbital angular momentum l ≤ 2 in the final state. Then, from Eq. (8), Writing Eq. (77) in a short hand notation Here, we note that, if the expansion were made in j = l ± 1 2 ≤ 3 2 instead of in l ≤ 2, then, no E 2+ and M 2+ multipoles would enter in any of the expression in this section.
where α l ,α l , β l , δ l and ρ l can be read off of Eq. (77), we have for the cross section and single-spin asymmetries, according to Eqs. (58,59), dσ dΩ = |α 0 +α 2 + α 1 cos θ + α 2 cos 2 θ| 2 + 1 2 |β 1 + β 2 cos θ| 2 + |δ 1 + δ 2 cos θ| 2 + |ρ 2 | 2 +2Re α 0 +α 2 + (α 1 + δ 1 ) cos θ + (α 2 + δ 2 ) cos 2 θ ρ * 2 sin 2 θ , If we consider only the S-and P -waves in the final state, the above results reduce to dσ dΩ = |α 0 + α 1 cos θ| 2 + 1 2 Another possible scenario is to keep only the S-wave and its interference with the P -and D-waves, as has been done in Ref. , which is motivated by the fact that, near threshold η photoproduction is dominated by the S-wave final state. We then have dσ dΩ It is interesting to note that Eqs. (80, 81) reveal that the two scenarios considered above lead exactly to the same angular dependences for the corresponding observables considered here. However, the dynamics is very different from each other. For example, while the beam asymmetry, Σ, is due to the difference of the squared magnitudes of the P -wave multipoles in the former scenario (cf. Eq. (80)), it is entirely due to the interference between the S-and D-waves in the later scenario (cf. Eq. (81)). The cos θ sin θ terms in both the target (T ) and recoil (P ) asymmetries arise from the interference among the P -wave multipoles in the former scenario, while in the later scenario, they arise from the interference of the S-and D-wave multipoles. In other words, the assumption of the S-wave dominance alone, in conjunction with the observables considered above, does not constrain the presence or absence of the D-wave contribution. To do this, we require double-polarization observables. For example, the combination of the double-spin asymmetries given by Eq. (64), will tell us about the presence or absence of the D-wave for, F 4 contains no lower partial waves.
The analysis of this section reveals that even at low energies, where the number of partial-waves are restricted, the unpolarized cross section and single-polarization observables alone are -strictly speaking -not sufficient to constrain the reaction dynamics model independently. For this, double-polarization observables are required.
Summary
In this note we have discussed the model-independent aspects of the reaction amplitude in pseudoscalar meson photoproduction. In contrast to the earlier works, the photoproduction amplitude has been expressed in Pauli-spin basis which allows to calculate the spin-observables straightforwardly and in a quite pedestrian way. In doing so, we made use of the fact that the underlying reflection symmetry about the reaction plane can be most conveniently and easily exploited in this basis to help finding the non-vanishing and non-redundant observables in this reaction.
The problem of complete experiments has been reviewed. In particular, by expressing the photoproduction amplitude in Pauli-spin basis, we have identified additional sets of eight observables that can determine the photoproduction amplitude up to an arbitrary phase compared to those found in Refs. using transversity basis for expressing the reaction amplitude. In addition, we found that the kinematic restrictions required for the sets of four observables to resolve the phase ambiguity of the reaction amplitude is less severe for the case of Pauli-spin amplitudes than for transversity amplitudes in general. On the other hand, as has been pointed out in Ref. (see, also, Refs. ), in view of the experimental data having finite accuracieswhich limits our ability to determine the reaction amplitude in a complete experimentin practice, it requires to measure more observables than those of a complete experiment to determine the photoproduction amplitude. In this regard, measurements of more observables among those 16 non-redundant ones are not just desirable for consistency check purposes, but they are a necessity.
Also, certain combinations of the observables have been shown to be useful in isolating some (low) partial-wave states to learn about the reaction dynamics. There, we have shown, in particular, that even at energies close to threshold, where the number of partial-waves are restricted, the unpolarized cross section and singlepolarization observables alone are not sufficient to constrain the reaction dynamics model independently in the strict sense. For this, double-polarization observables are required.
The present work should be useful, especially, for newcomers in the filed of baryon spectroscopy, where the photoproduction reaction processes are a major tool for probing the baryon spectra.
Acknowledgement
We thank Igor Strakovsky for the encouragement to prepare this note and for valuable suggestions.
Appendix A.
In this appendix we give the details how to identify all the possible sets of the minimum number of observables that determine the magnitudes and relative phases of the amplitudes M i (i = 0 − 3) expressed in Pauli-spin basis, apart from an arbitrary overall phase. To this end, we rewrite all the 16 non-redundant observables given in Sec. 8 and group them as follows: 1) Two from a given group and two from another group: 2 + 2 case.
2) Two from a given group and one from each of the remaining two groups: 2 + 1 + 1 case.
3) Three from a given group and one from another group: 3 + 1 case. 4) all four observables from one group: 4 case.
Then, in complete analogy with the derivation in Ref for the transversity amplitudes, we determine all the sets of observables that resolve the phase ambiguity of the Pauli-spin amplitudes. The results are displayed in Tables. 1, 2 which implies that the relative phases φ ij and φ kl are subject to a 2-fold ambiguity each: where β ij and α kl are uniquely defined with 0 ≤ β ij ≤ π and −π/2 ≤ α kl ≤ +π/2. They result in 4-fold ambiguities we have the 2-fold ambiguity where the angle ζ ≡ ζ m 1ν,2ν ′ is uniquely defined through In the following we simply use ζ and N to avoid the heavy notation, but it should be kept in mind that they depend on the given pair of observables. For the pair of observables considered above, ν = ν ′ = ±. Here, β ij and α kl are uniquely defined by with 0 ≤ β ij ≤ π and −π/2 ≤ α kl ≤ +π/2. Analogously, for the pair of observables of the form The determination of the phases of the photoproduction amplitude rests on whether or not the relative phase ambiguity discussed above can be resolved through one of the relations below : 14) The sets of four spin observables that resolve the phase ambiguity of the Pauli-spin amplitudes up to an arbitrary overall phase are displayed in Tables. 1, 2 and 3 for the 2 + 2 cases mentioned in item(1) earlier in this appendix.
Here, the symmetries of the corresponding phases are the same to those for the we have The above results lead to the same form of the solutions as given Eq. (A.25).
Here, the symmetries of the corresponding phases are the same to those for the The sets of four spin observables that resolve the phase ambiguity of the Pauli-spin amplitudes up to an arbitrary overall phase are displayed in Table. 4 for the case of 2(a) + 1(b) + 1(c). The other sets can be obtained by appropriate permutations of a, b and c.
It should be mentioned that, as has been pointed out in Ref. , there are some kinematic restrictions on the sets of carefully chosen four observables to be able to resolve the phase ambiguity of the Pauli-spin amplitudes -as indicated in Tables. 1,2,3 and 4. These restrictions wouldn't be much of a concern if their violations were rare events. Unfortunately, we have no reason a priori to expect the violations to be rare. In the following Appendix B, we provide a way to gauge when such restrictions are violated.
Appendix B.
There are two different levels of kinematic restrictions in the relative phase angles; one is at the level of a chosen pair of observables and the other is at the level of a set of two pairs of observables. First, we discuss the restrictions at the level of a pair of observables and, then, at the level of a set of two pairs of observables.
Let's start with the pair of observables of the form (O m n+ , O m n− ). From Eq. (A.8), we see that the 4-fold ambiguities become degenerated when (β ij ± α kl ) = ±π/2 or α kl = π/2. These translate to the conditions where the indices on which N depends are restored.
For the observables of the form (O m 1ν , O m ′ 1ν ′ ) (m = m ′ and ν, ν ′ = ±), the degeneracy in the 4-fold ambiguity -according to Eq. (A.21) -occurs when (β λλ ′ ik (η) ± α λλ ′ jl (η)) = ±π/2. With the help of Eq. (A.17), this translates to For all the other pairs of observables of the form (O m nν , O m ′ n ′ ν ′ ) (m = m ′ and ν, ν ′ = ±), the occurrence of the degeneracy in the 4-fold ambiguity can be verified using The above relations provide a means of gauging whether the restriction condition has been violated or not. Of course -as mentioned above in connection to the degeneracy of the phase ambiguity at the level of a pair of observables -here, the phase ambiguity cannot be resolved also when (β 02 − α 13 ) = −π/2 or (β 03 + α 12 ) = π/2. These two later We now turn our attention to some of the features of the Pauli-spin amplitudes and transversity amplitudes in resolving the phase ambiguity of the photoproduction amplitude. We note that in Pauli-spin representation, all the observables are of the form given by Eq. (A.5) involving cos φ ij and sin φ kl , while in transversity representation, the observables are of the forms O m 1± = B ij sin φ ij ± B kl sin φ kl or O m 2± = B ij cos φ ij ± B kl cos φ kl , (B.10) involving either sin φ ij and sin φ kl or cos φ ij and cos φ kl . In helicity representation, the observables are also of the form given by Eq. (B.10) above . The above mentioned difference in expressing the observables in different representations leads to different kinematic constraints for the possible solutions to resolve the phase ambiguities of the corresponding amplitudes. 4) which, as has been pointed out, cannot resolve the phase ambiguity of the Pauli-spin amplitudes when β 02 = α 13 and β 03 = −α 12 , simultaneously. Note that, due to the distinct domains of the angles β ij 's and α kl 's, the first equality can happen only when β 02 and α 13 are both on the first quadrant, while the second equality happens only if β 03 is in the first quadrant |
/**
For conditions of distribution and use, see copyright notice in LICENSE
@file OgreMaterialUtils.cpp
@brief Utilitity functions for dealing with OGRE material scripts. */
#include "StableHeaders.h"
#include "DebugOperatorNew.h"
#include "OgreMaterialUtils.h"
#include "OgreRenderingModule.h"
#include "AssetAPI.h"
#include "FileUtils.h"
#include <Ogre.h>
#include "MemoryLeakCheck.h"
namespace OgreRenderer
{
std::string AddDoubleQuotesIfNecessary(const std::string &str)
{
std::string ret = str;
if (ret.find(' ') != std::string::npos)
{
ret.insert(0, "\"");
ret.append("\"");
}
return ret;
}
void DesanitateAssetIds(std::string &script, const QStringList &keywords)
{
QStringList lines = QString(script.c_str()).split("\n");
for(int i = 0; i < lines.size(); ++i)
{
QString id;
int idx = -1, offset = -1;
foreach(const QString &keyword, keywords)
if (lines[i].contains(keyword))
{
idx = lines[i].indexOf(keyword);
offset = keyword.length();
id = keyword;
break;
}
if (idx != -1 && offset != -1)
{
QString desanitatedRef = AssetAPI::DesanitateAssetRef(lines[i].mid(idx + offset).trimmed());
lines[i] = lines[i].left(idx);
lines[i].append(id + desanitatedRef);
}
}
script = lines.join("\n").toStdString();
}
Ogre::MaterialPtr CloneMaterial(const std::string& sourceMaterialName, const std::string &newName)
{
Ogre::MaterialManager &mm = Ogre::MaterialManager::getSingleton();
Ogre::MaterialPtr material = mm.getByName(AssetAPI::SanitateAssetRef(sourceMaterialName));
if (!material.get())
{
::LogWarning("Failed to clone material \"" + sourceMaterialName + "\". It was not found.");
return Ogre::MaterialPtr();
}
material = material->clone(AssetAPI::SanitateAssetRef(newName));
if (!material.get())
{
::LogWarning("Failed to clone material \"" + sourceMaterialName + "\" to name \"" + AssetAPI::SanitateAssetRef(newName) + "\"");
return Ogre::MaterialPtr();
}
return material;
}
Ogre::MaterialPtr GetOrCreateLitTexturedMaterial(const std::string& materialName)
{
std::string baseMaterialName = "LitTextured";
Ogre::MaterialManager &mm = Ogre::MaterialManager::getSingleton();
Ogre::MaterialPtr material = mm.getByName(AssetAPI::SanitateAssetRef(materialName));
if (!material.get())
{
Ogre::MaterialPtr baseMaterial = mm.getByName(AssetAPI::SanitateAssetRef(baseMaterialName));
if (baseMaterial.isNull())
return Ogre::MaterialPtr();
material = baseMaterial->clone(AssetAPI::SanitateAssetRef(materialName));
}
assert(material.get());
return material;
}
Ogre::MaterialPtr GetOrCreateUnlitTexturedMaterial(const std::string& materialName)
{
std::string baseMaterialName = "UnlitTextured";
Ogre::MaterialManager &mm = Ogre::MaterialManager::getSingleton();
Ogre::MaterialPtr material = mm.getByName(AssetAPI::SanitateAssetRef(materialName));
if (!material.get())
{
Ogre::MaterialPtr baseMaterial = mm.getByName(AssetAPI::SanitateAssetRef(baseMaterialName));
if (baseMaterial.isNull())
return Ogre::MaterialPtr();
material = baseMaterial->clone(AssetAPI::SanitateAssetRef(materialName));
}
assert(material.get());
return material;
}
void SetTextureUnitOnMaterial(Ogre::MaterialPtr material, const std::string& texture_name, uint index)
{
if (material.isNull())
return;
std::string sanitatedtexname = AssetAPI::SanitateAssetRef(texture_name);
Ogre::TextureManager &tm = Ogre::TextureManager::getSingleton();
Ogre::TexturePtr tex = tm.getByName(sanitatedtexname);
Ogre::Material::TechniqueIterator iter = material->getTechniqueIterator();
while(iter.hasMoreElements())
{
Ogre::Technique *tech = iter.getNext();
assert(tech);
Ogre::Technique::PassIterator passIter = tech->getPassIterator();
while(passIter.hasMoreElements())
{
Ogre::Pass *pass = passIter.getNext();
Ogre::Pass::TextureUnitStateIterator texIter = pass->getTextureUnitStateIterator();
uint cmp_index = 0;
while(texIter.hasMoreElements())
{
Ogre::TextureUnitState *texUnit = texIter.getNext();
if (index == cmp_index)
{
if (tex.get())
texUnit->setTextureName(sanitatedtexname);
else
texUnit->setTextureName("TextureMissing.png");
return; // We found and replaced the index we wanted to - can early-out return without looping the rest of the indices for nothing.
}
cmp_index++;
}
}
}
}
void ReplaceTextureOnMaterial(Ogre::MaterialPtr material, const std::string& original_name, const std::string& texture_name)
{
if (material.isNull())
return;
std::string sanitatedorgname = AssetAPI::SanitateAssetRef(original_name);
std::string sanitatedtexname = AssetAPI::SanitateAssetRef(texture_name);
Ogre::TextureManager &tm = Ogre::TextureManager::getSingleton();
Ogre::TexturePtr tex = tm.getByName(sanitatedtexname);
Ogre::Material::TechniqueIterator iter = material->getTechniqueIterator();
while(iter.hasMoreElements())
{
Ogre::Technique *tech = iter.getNext();
assert(tech);
Ogre::Technique::PassIterator passIter = tech->getPassIterator();
while(passIter.hasMoreElements())
{
Ogre::Pass *pass = passIter.getNext();
Ogre::Pass::TextureUnitStateIterator texIter = pass->getTextureUnitStateIterator();
while(texIter.hasMoreElements())
{
Ogre::TextureUnitState *texUnit = texIter.getNext();
if (texUnit->getTextureName() == sanitatedorgname)
{
if (tex.get())
texUnit->setTextureName(sanitatedtexname);
else
texUnit->setTextureName("TextureMissing.png");
}
}
}
}
}
void GetTextureNamesFromMaterial(Ogre::MaterialPtr material, StringVector& textures)
{
textures.clear();
if (material.isNull())
return;
// Use a set internally to avoid duplicates
std::set<std::string> textures_set;
Ogre::Material::TechniqueIterator iter = material->getTechniqueIterator();
while(iter.hasMoreElements())
{
Ogre::Technique *tech = iter.getNext();
assert(tech);
Ogre::Technique::PassIterator passIter = tech->getPassIterator();
while(passIter.hasMoreElements())
{
Ogre::Pass *pass = passIter.getNext();
Ogre::Pass::TextureUnitStateIterator texIter = pass->getTextureUnitStateIterator();
while(texIter.hasMoreElements())
{
Ogre::TextureUnitState *texUnit = texIter.getNext();
const std::string& texname = texUnit->getTextureName();
if (!texname.empty())
textures_set.insert(texname);
}
}
}
std::set<std::string>::iterator i = textures_set.begin();
while(i != textures_set.end())
{
textures.push_back(*i);
++i;
}
}
bool ProcessBraces(const std::string& line, int& braceLevel)
{
if (line == "{")
{
++braceLevel;
return true;
}
else if (line == "}")
{
--braceLevel;
return true;
}
else return false;
}
QSet<QString> ProcessMaterialFileForTextures(const QString& matfilename, const QSet<QString>& used_materials)
{
QSet<QString> used_textures;
bool known_material = false;
// Read the material file
QFile matfile(matfilename);
if (!matfile.open(QFile::ReadOnly))
{
LogError("Could not open material file " + matfilename);
return used_textures;
}
else
{
QByteArray bytes = matfile.readAll();
matfile.close();
if (bytes.size())
{
int num_materials = 0;
int brace_level = 0;
bool skip_until_next = false;
int skip_brace_level = 0;
#include "DisableMemoryLeakCheck.h"
Ogre::DataStreamPtr data = Ogre::DataStreamPtr(new Ogre::MemoryDataStream(bytes.data(), bytes.size()));
#include "EnableMemoryLeakCheck.h"
while(!data->eof())
{
std::string line = data->getLine();
// Skip empty lines & comments
if ((line.length()) && (line.substr(0, 2) != "//"))
{
// Process opening/closing braces
if (!OgreRenderer::ProcessBraces(line, brace_level))
{
// If not a brace and on level 0, it should be a new material
if ((brace_level == 0) && (line.substr(0, 8) == "material") && (line.length() > 8))
{
std::string matname = line.substr(9);
ReplaceCharInplace(matname, '/', '_');
line = "material " + matname;
if (used_materials.find(matname.c_str()) == used_materials.end())
{
known_material = false;
}
else
{
known_material = true;
++num_materials;
}
}
else
{
// Check for textures
if (known_material)
if ((line.substr(0, 8) == "texture ") && (line.length() > 8))
used_textures.insert(line.substr(8).c_str());
}
}
else
{
if (brace_level <= skip_brace_level)
skip_until_next = false;
}
}
}
}
}
return used_textures;
}
QSet<QString> ProcessMaterialForTextures(const QString &material)
{
QSet<QString> textures;
QStringList lines = material.split("\n");
for(int i = 0; i < lines.size(); ++i)
{
int idx = lines[i].indexOf("texture ");
if (idx != -1)
textures.insert(lines[i].mid(idx + 8).trimmed());
}
return textures;
}
QString LoadSingleMaterialFromFile(const QString &filename, const QString &materialName)
{
QString material;
bool right_material = false;
// Read the material file
QFile matfile(filename);
if (!matfile.open(QFile::ReadOnly))
{
LogError("Could not open material file " + filename);
return material;
}
else
{
QByteArray bytes = matfile.readAll();
matfile.close();
if (bytes.size() == 0)
{
LogError("Empty material file: " + filename);
return material;
}
int brace_level = 0;
bool skip_until_next = false;
int skip_brace_level = 0;
#include "DisableMemoryLeakCheck.h"
Ogre::DataStreamPtr data = Ogre::DataStreamPtr(new Ogre::MemoryDataStream(bytes.data(), bytes.size()));
#include "EnableMemoryLeakCheck.h"
while(!data->eof())
{
std::string line = data->getLine();
// Skip empty lines & comments
if ((line.length()) && (line.substr(0, 2) != "//"))
{
// Process opening/closing braces
if (!OgreRenderer::ProcessBraces(line, brace_level))
{
// If not a brace and on level 0, it should be a new material
if ((brace_level == 0) && (line.substr(0, 8) == "material") && (line.length() > 8))
{
std::string matname = line.substr(9);
ReplaceCharInplace(matname, '/', '_');
line = "material " + matname;
if (matname.c_str() == materialName)
right_material = true;
else
right_material = false;
}
// Write line to the modified copy
if (!skip_until_next && right_material)
{
// Add indentation.
for(int i =0; i < brace_level; ++i)
material.append(" ");
material.append(line.c_str());
material.append("\n");
}
}
else
{
// Write line to the modified copy
if (!skip_until_next && right_material)
{
// Add indentation.
int i = 0;
if (line.find("{") != std::string::npos)
++i;
for(; i < brace_level; ++i)
material.append(" ");
material.append(line.c_str());
material.append("\n");
}
if (brace_level <= skip_brace_level)
{
skip_until_next = false;
///\todo return material; here?
}
}
}
}
}
return material;
}
std::set<MaterialInfo> LoadAllMaterialsFromFile(const QString &filename)
{
std::set<MaterialInfo> materials;
// Read the material file
QFile matfile(filename);
if (!matfile.open(QFile::ReadOnly))
{
LogError("Could not open material file " + filename);
return materials;
}
else
{
QByteArray bytes = matfile.readAll();
matfile.close();
if (bytes.size() == 0)
{
LogError("Empty material file: " + filename);
return materials;
}
int brace_level = 0;
int skip_brace_level = 0;
MaterialInfo material;
material.source = filename;
#include "DisableMemoryLeakCheck.h"
Ogre::DataStreamPtr data = Ogre::DataStreamPtr(new Ogre::MemoryDataStream(bytes.data(), bytes.size()));
#include "EnableMemoryLeakCheck.h"
while(!data->eof())
{
std::string line = data->getLine();
// Skip empty lines & comments
if ((line.length()) && (line.substr(0, 2) != "//"))
{
// Process opening/closing braces
if (!OgreRenderer::ProcessBraces(line, brace_level))
{
// If not a brace and on level 0, it should be a new material
if ((brace_level == 0) && (line.substr(0, 8) == "material") && (line.length() > 8))
{
QString matname = line.substr(9).c_str();
matname.replace('/', '_');
material.name = matname.trimmed();
material.data.clear();
}
// Add indentation.
for(int i =0; i < brace_level; ++i)
material.data.append(" ");
material.data.append(line.c_str());
material.data.append("\n");
}
else
{
// Add indentation.
int i = 0;
if (line.find("{") != std::string::npos)
++i;
for(; i < brace_level; ++i)
material.data.append(" ");
material.data.append(line.c_str());
material.data.append("\n");
if (brace_level <= skip_brace_level)
materials.insert(material);
}
}
}
}
return materials;
}
QStringList FindMaterialFiles(const QString &dir)
{
QStringList files;
foreach(const QString &file, DirectorySearch(dir, true, QDir::Files | QDir::NoDotAndDotDot | QDir::NoSymLinks))
if (file.endsWith(".material", Qt::CaseInsensitive))
files.append(file);
return files;
}
ShaderParameterMap GatherShaderParameters(const Ogre::MaterialPtr &material, bool includeTextureUnits)
{
ShaderParameterMap ret;
if (material.isNull())
return ret;
// Material
Ogre::Material::TechniqueIterator tIter = material->getTechniqueIterator();
while(tIter.hasMoreElements())
{
// Technique
Ogre::Technique *tech = tIter.getNext();
Ogre::Technique::PassIterator pIter = tech->getPassIterator();
while(pIter.hasMoreElements())
{
// Pass
Ogre::Pass *pass = pIter.getNext();
// Vertex program
if (pass->hasVertexProgram())
{
const Ogre::GpuProgramPtr &verProg = pass->getVertexProgram();
if (!verProg.isNull())
{
Ogre::GpuProgramParametersSharedPtr verPtr = pass->getVertexProgramParameters();
if (verPtr->hasNamedParameters())
{
// Named parameters (constants)
Ogre::GpuConstantDefinitionIterator mapIter = verPtr->getConstantDefinitionIterator();
while(mapIter.hasMoreElements())
{
QString paramName = mapIter.peekNextKey().c_str();
const Ogre::GpuConstantDefinition ¶mDef = mapIter.getNext();
// Filter names that end with '[0]'
int found = paramName.indexOf("[0]");
if (found != -1)
continue;
// Ignore auto parameters
bool isAutoParam = false;
Ogre::GpuProgramParameters::AutoConstantIterator autoConstIter = verPtr->getAutoConstantIterator();
while(autoConstIter.hasMoreElements())
{
Ogre::GpuProgramParameters::AutoConstantEntry autoConstEnt = autoConstIter.getNext();
if (autoConstEnt.physicalIndex == paramDef.physicalIndex)
{
isAutoParam = true;
break;
}
}
if (isAutoParam)
continue;
// if (!paramDef.isFloat())
// continue;
size_t count = paramDef.elementSize * paramDef.arraySize;
QVector<float> paramValue;
QVector<float>::iterator iter;
paramValue.resize((int)count);
verPtr->_readRawConstants(paramDef.physicalIndex, count, &*paramValue.begin());
QTextStream vector_string;
QString string;
vector_string.setString(&string, QIODevice::WriteOnly);
for(iter = paramValue.begin(); iter != paramValue.end(); ++iter)
vector_string << *iter << " ";
QMap<QString, QVariant> typeValuePair;
//typeValuePair[GpuConstantTypeToString(paramDef.constType)] = *vector_string.string();
typeValuePair[QString::number(paramDef.constType)] = *vector_string.string();
// Add to "VP" to the end of the parameter name in order to identify VP parameters.
ret[paramName.append(" VP").toLatin1()] = QVariant(typeValuePair);
}
}
}
}
// Fragment program
if (pass->hasFragmentProgram())
{
const Ogre::GpuProgramPtr fragProg = pass->getFragmentProgram();
if (!fragProg.isNull())
{
Ogre::GpuProgramParametersSharedPtr fragPtr = pass->getFragmentProgramParameters();
if (!fragPtr.isNull())
{
if (fragPtr->hasNamedParameters())
{
// Named parameters (constants)
Ogre::GpuConstantDefinitionIterator mapIter = fragPtr->getConstantDefinitionIterator();
while(mapIter.hasMoreElements())
{
QString paramName = mapIter.peekNextKey().c_str();
const Ogre::GpuConstantDefinition ¶mDef = mapIter.getNext();
// Filter names that end with '[0]'
int found = paramName.indexOf("[0]");
if (found != -1)
continue;
// Ignore auto parameters
bool isAutoParam = false;
Ogre::GpuProgramParameters::AutoConstantIterator autoConstIter = fragPtr->getAutoConstantIterator();
while(autoConstIter.hasMoreElements())
{
Ogre::GpuProgramParameters::AutoConstantEntry autoConstEnt = autoConstIter.getNext();
if (autoConstEnt.physicalIndex == paramDef.physicalIndex)
{
isAutoParam = true;
break;
}
}
if (isAutoParam)
continue;
// if (!paramDef.isFloat())
// continue;
size_t count = paramDef.elementSize * paramDef.arraySize;
QVector<float> paramValue;
QVector<float>::iterator iter;
paramValue.resize((int)count);
fragPtr->_readRawConstants(paramDef.physicalIndex, count, &*paramValue.begin());
QTextStream vector_string;
QString string;
vector_string.setString(&string, QIODevice::WriteOnly);
for(iter = paramValue.begin(); iter != paramValue.end(); ++iter)
vector_string << *iter << " ";
QMap<QString, QVariant> typeValuePair;
//typeValuePair[GpuConstantTypeToString(paramDef.constType)] = *vector_string.string();
typeValuePair[QString::number(paramDef.constType)] = *vector_string.string();
// Add to " FP" to the end of the parameter name in order to identify FP parameters
ret[paramName.append(" FP").toLatin1()] = QVariant(typeValuePair);
}
}
}
}
}
if (includeTextureUnits)
{
Ogre::Pass::TextureUnitStateIterator texIter = pass->getTextureUnitStateIterator();
while(texIter.hasMoreElements())
{
// Texture units
const Ogre::TextureUnitState *tu = texIter.getNext();
// Don't insert tu's with empty texture names (i.e. shadowMap)
if(tu->getTextureName().size() > 0)
{
QString tuName(tu->getName().c_str());
QMap<QString, QVariant> typeValuePair;
typeValuePair[TextureTypeToString(tu->getTextureType())] = tu->getTextureName().c_str();
// add to " TU" to the end of the parameter name in order to identify texture units.
ret[tuName.append(" TU").toLatin1()] = typeValuePair;
}
}
}
}
}
return ret;
}
QString GpuConstantTypeToString(Ogre::GpuConstantType type)
{
using namespace Ogre;
///@note We use GCT_UNKNOWN for texture units' texture names.
switch(type)
{
case GCT_FLOAT1:
return "float";
case GCT_FLOAT2:
return "float2";
case GCT_FLOAT3:
return "float3";
case GCT_FLOAT4:
return "float4";
case GCT_SAMPLER1D:
return "Sampler1D";
case GCT_SAMPLER2D:
return "Sampler2D";
case GCT_SAMPLER3D:
return "Sampler3D";
case GCT_SAMPLERCUBE:
return "SamplerCube";
case GCT_SAMPLER1DSHADOW:
return "Sampler1DShadow";
case GCT_SAMPLER2DSHADOW:
return "Sampler2DShadow";
case GCT_MATRIX_2X2:
return "float2x2";
case GCT_MATRIX_2X3:
return "float2x3";
case GCT_MATRIX_2X4:
return "float2x4";
case GCT_MATRIX_3X2:
return "float3x2";
case GCT_MATRIX_3X3:
return "float3x3";
case GCT_MATRIX_3X4:
return "float3x4";
case GCT_MATRIX_4X2:
return "float4x2";
case GCT_MATRIX_4X3:
return "float4x3";
case GCT_MATRIX_4X4:
return "float4x4";
case GCT_INT1:
return "int";
case GCT_INT2:
return "int2";
case GCT_INT3:
return "int3";
case GCT_INT4:
return "int4";
case GCT_UNKNOWN:
default:
return "Unknown";
};
}
QString TextureTypeToString(Ogre::TextureType type)
{
using namespace Ogre;
switch(type)
{
case TEX_TYPE_1D:
return "Tex1D";
case TEX_TYPE_2D:
return "Tex2D";
case TEX_TYPE_3D:
return "Tex3D";
case TEX_TYPE_CUBE_MAP:
return "TexCubeMap";
default:
return "Unknown";
};
}
}
|
// ruleProcessPoints runs points through a rules conditions and and updates condition
// and rule active status. Returns true if point was processed and active is true.
// Currently, this function only processes the first point that matches -- this should
// handle all current uses.
func ruleProcessPoints(nc *natsgo.Conn, r *data.Rule, nodeID string, points data.Points) (bool, bool, error) {
pointsProcessed := false
for _, p := range points {
for i, c := range r.Conditions {
var active bool
switch c.ConditionType {
case data.PointValuePointValue:
if c.NodeID != "" && c.NodeID != nodeID {
continue
}
if c.PointKey != "" && c.PointKey != p.Key {
continue
}
if c.PointType != "" && c.PointType != p.Type {
continue
}
switch c.PointValueType {
case data.PointValueNumber:
pointsProcessed = true
switch c.Operator {
case data.PointValueGreaterThan:
active = p.Value > c.PointValue
case data.PointValueLessThan:
active = p.Value < c.PointValue
case data.PointValueEqual:
active = p.Value == c.PointValue
case data.PointValueNotEqual:
active = p.Value != c.PointValue
}
case data.PointValueText:
pointsProcessed = true
switch c.Operator {
case data.PointValueEqual:
case data.PointValueNotEqual:
case data.PointValueContains:
}
case data.PointValueOnOff:
pointsProcessed = true
condValue := c.PointValue != 0
pointValue := p.Value != 0
active = condValue == pointValue
}
case data.PointValueSchedule:
if p.Type != data.PointTypeTrigger {
continue
}
pointsProcessed = true
sched := newSchedule(c.StartTime, c.EndTime, c.Weekdays)
var err error
active, err = sched.activeForTime(p.Time)
if err != nil {
log.Println("Error parsing schedule time: ", err)
continue
}
}
if active != c.Active {
p := data.Point{
Type: data.PointTypeActive,
Time: time.Now(),
Value: data.BoolToFloat(active),
}
err := nats.SendNodePoint(nc, c.ID, p, false)
if err != nil {
log.Println("Rule error sending point: ", err)
}
r.Conditions[i].Active = active
}
}
}
if pointsProcessed {
allActive := true
for _, c := range r.Conditions {
if !c.Active {
allActive = false
break
}
}
changed := false
if allActive != r.Active {
p := data.Point{
Type: data.PointTypeActive,
Time: time.Now(),
Value: data.BoolToFloat(allActive),
}
err := nats.SendNodePoint(nc, r.ID, p, false)
if err != nil {
log.Println("Rule error sending point: ", err)
}
changed = true
}
return allActive, changed, nil
}
return false, false, nil
} |
package com.openvehicletracking.protocols.xtakip.hxprotocol;
import com.openvehicletracking.protocols.BaseCommandMessage;
import com.openvehicletracking.protocols.xtakip.XTakipProtocol;
/**
* Created by oksuz on 20/05/2017.
*
*/
public final class HXProtocolMessage extends BaseCommandMessage {
@Override
public String getProtocolName() {
return XTakipProtocol.NAME;
}
@Override
public int getType() {
return 'H' + 'X';
}
}
|
<gh_stars>0
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10 ** 7)
A, B = map(int, input().split())
S = input().strip()
import string
for v in S[:A]:
if v not in string.digits:
print('No')
sys.exit(0)
if S[A] != '-':
print('No')
sys.exit(0)
for v in S[A+1:]:
if v not in string.digits:
print('No')
sys.exit(0)
print('Yes')
|
// GENERATED WITH generate-modules-sdk
// Warning: Do not edit by hand, all changes will be lost on next execution!
// TODO: This file should be excluded from (not only VSCode) auto-importing.
// @see https://github.com/Microsoft/vscode/issues/40248
// @see https://github.com/microsoft/TypeScript/issues/35395
// @see https://stackoverflow.com/questions/47796545/how-to-disable-auto-import-from-specific-files-in-vscode
import * as React from 'react';
import { IVector, Vector } from 'xyzt';
import { Abstract2dArt } from './26-Abstract2dArt';
export declare type IListStyle = 'unordered' | 'ordered' | 'none';
/**
* @collboard-modules-sdk
*/
export declare class TextArt extends Abstract2dArt {
content: string;
color: string;
fontSize: number;
bold: boolean;
italic: boolean;
underline: boolean;
listStyle: IListStyle;
point1: IVector;
static serializeName: string;
static manifest: {
name: string;
};
private textInput;
private tempText;
constructor(
content: string,
color: string,
fontSize: number,
bold: boolean,
italic: boolean,
underline: boolean,
listStyle: IListStyle,
point1: IVector,
);
get size(): Vector;
get topLeftCorner(): Vector;
get bottomRightCorner(): Vector;
isNear(point2: IVector): boolean;
get acceptedAttributes(): string[];
setTempText(): void;
renderTextField(onKeyPress: (event: React.KeyboardEvent<HTMLDivElement>) => void): JSX.Element;
render(/* TODO: ✨ Add is prefix */ selected: boolean): JSX.Element;
}
/**
* Note: number is just a file prefix to feep it on the top of file list.
*/
|
/**
* Merges content values with those coming from another source
*/
public synchronized <TYPE> void mergeWith(ContentValues other) {
if (setValues == null)
setValues = new ContentValues();
setValues.putAll(other);
} |
/// Update the box which contains buttons for opening pages (left side).
pub fn update_toc(&self, app_runtime: AppRuntime, book: &mut EpubBook) {
// Clear the whole box before adding new elements
for child in self.left_content_box.children() {
self.left_content_box.remove(&child);
}
// Get the spine from the epub doc and make the buttons
for spine_item in &book.doc.spine {
let ch = gtk::LinkButton::new(spine_item);
let new_chap = book
.doc
.resource_uri_to_chapter(&book
.doc
.resources
.get(spine_item)
.unwrap()
.0
);
ch.set_label(&book.current_chapter_file_name(spine_item));
ch.connect_activate_link(glib::clone!(@strong app_runtime => move |_| {
app_runtime.update_state_with(move |state| {
// Open the requested page
state.open_page_send(new_chap.unwrap());
// Close the toc revealer
state.ui.toggle_toc();
});
// Inhibit because the link is not a real link
gtk::Inhibit(true)
}));
self.left_content_box.add(&ch);
}
self.left_content_box.show_all();
} |
<filename>vendor/github.com/IBM-Cloud/terraform-provider-ibm/ibm/resource_ibm_multi_vlan_firewall.go<gh_stars>1000+
// Copyright IBM Corp. 2017, 2021 All Rights Reserved.
// Licensed under the Mozilla Public License v2.0
package ibm
import (
"fmt"
"log"
"strconv"
"strings"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/softlayer/softlayer-go/datatypes"
"github.com/softlayer/softlayer-go/filter"
"github.com/softlayer/softlayer-go/helpers/location"
"github.com/softlayer/softlayer-go/helpers/product"
"github.com/softlayer/softlayer-go/services"
"github.com/softlayer/softlayer-go/sl"
)
func resourceIBMMultiVlanFirewall() *schema.Resource {
return &schema.Resource{
Create: resourceIBMNetworkMultiVlanCreate,
Read: resourceIBMMultiVlanFirewallRead,
Delete: resourceIBMFirewallDelete,
Update: resourceIBMMultiVlanFirewallUpdate,
Exists: resourceIBMMultiVLanFirewallExists,
Importer: &schema.ResourceImporter{},
Schema: map[string]*schema.Schema{
"datacenter": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
Description: "Datacenter name",
},
"pod": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
return strings.TrimSpace(old) == strings.TrimSpace(new)
},
Description: "POD name",
},
"name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
Description: "name",
},
"public_vlan_id": {
Type: schema.TypeInt,
Computed: true,
Description: "Public VLAN id",
},
"private_vlan_id": {
Type: schema.TypeInt,
Computed: true,
Description: "Private VLAN id",
},
"firewall_type": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validateAllowedStringValue([]string{"FortiGate Firewall Appliance HA Option", "FortiGate Security Appliance"}),
Description: "Firewall type",
},
"public_ip": {
Type: schema.TypeString,
Computed: true,
Description: "Public IP Address",
},
"public_ipv6": {
Type: schema.TypeString,
Computed: true,
Description: "Public IPV6 IP",
},
"private_ip": {
Type: schema.TypeString,
Computed: true,
Description: "Private IP Address",
},
"username": {
Type: schema.TypeString,
Computed: true,
Description: "<NAME>",
},
"password": {
Type: schema.TypeString,
Computed: true,
Sensitive: true,
Description: "Password",
},
"addon_configuration": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Optional: true,
Description: `High Availability - [Web Filtering Add-on, NGFW Add-on, AV Add-on] or [Web Filtering Add-on, NGFW Add-on, AV Add-on]`,
},
},
}
}
const (
productPackageFilter = `{"keyName":{"operation":"FIREWALL_APPLIANCE"}}`
complexType = "SoftLayer_Container_Product_Order_Network_Protection_Firewall_Dedicated"
productPackageServiceMask = "description,prices.locationGroupId,prices.id"
mandatoryFirewallType = "FortiGate Security Appliance"
multiVlansMask = "id,customerManagedFlag,datacenter.name,bandwidthAllocation"
)
func resourceIBMNetworkMultiVlanCreate(d *schema.ResourceData, meta interface{}) error {
sess := meta.(ClientSession).SoftLayerSession()
name := d.Get("name").(string)
FirewallType := d.Get("firewall_type").(string)
datacenter := d.Get("datacenter").(string)
pod := d.Get("pod").(string)
podName := datacenter + "." + pod
PodService := services.GetNetworkPodService(sess)
podMask := `frontendRouterId,name`
// 1.Getting the router ID
routerids, err := PodService.Filter(filter.Path("datacenterName").Eq(datacenter).Build()).Mask(podMask).GetAllObjects()
if err != nil {
return fmt.Errorf("Encountered problem trying to get the router ID: %s", err)
}
var routerid int
for _, iterate := range routerids {
if *iterate.Name == podName {
routerid = *iterate.FrontendRouterId
}
}
//2.Get the datacenter id
dc, err := location.GetDatacenterByName(sess, datacenter, "id")
if err != nil {
return fmt.Errorf("Encountered problem trying to get the Datacenter ID: %s", err)
}
locationservice := services.GetLocationService(sess)
//3. get the pricegroups that the datacenter belongs to
priceidds, _ := locationservice.Id(*dc.Id).GetPriceGroups()
var listofpriceids []int
//store all the pricegroups a datacenter belongs to
for _, priceidd := range priceidds {
listofpriceids = append(listofpriceids, *priceidd.Id)
}
//4.get the addons that are specified
var addonconfigurations []interface{}
if _, ok := d.GetOk("addon_configuration"); ok {
addonconfigurations, ok = d.Get("addon_configuration").([]interface{})
}
var actualaddons []string
for _, addons := range addonconfigurations {
actualaddons = append(actualaddons, addons.(string))
}
//appending the 20000GB Bandwidth item as it is mandatory
actualaddons = append(actualaddons, FirewallType, "20000 GB Bandwidth Allotment")
//appending the Fortigate Security Appliance as it is mandatory parameter for placing an order
if FirewallType != mandatoryFirewallType {
actualaddons = append(actualaddons, mandatoryFirewallType)
}
//5. Getting the priceids of items which have to be ordered
priceItems := []datatypes.Product_Item_Price{}
for _, addon := range actualaddons {
actualpriceid, err := product.GetPriceIDByPackageIdandLocationGroups(sess, listofpriceids, 863, addon)
if err != nil || actualpriceid == 0 {
return fmt.Errorf("Encountered problem trying to get priceIds of items which have to be ordered: %s", err)
}
priceItem := datatypes.Product_Item_Price{
Id: &actualpriceid,
}
priceItems = append(priceItems, priceItem)
}
//6.Get the package ID
productpackageservice, _ := services.GetProductPackageService(sess).Filter(productPackageFilter).Mask(`id`).GetAllObjects()
var productid int
for _, packageid := range productpackageservice {
productid = *packageid.Id
}
//7. Populate the container which needs to be sent for Verify order and Place order
productOrderContainer := datatypes.Container_Product_Order_Network_Protection_Firewall_Dedicated{
Container_Product_Order: datatypes.Container_Product_Order{
PackageId: &productid,
Prices: priceItems,
Quantity: sl.Int(1),
Location: &datacenter,
ComplexType: sl.String(complexType),
},
Name: sl.String(name),
RouterId: &routerid,
}
//8.Calling verify order
_, err = services.GetProductOrderService(sess.SetRetries(0)).
VerifyOrder(&productOrderContainer)
if err != nil {
return fmt.Errorf("Error during Verify order for Creating: %s", err)
}
//9.Calling place order
receipt, err := services.GetProductOrderService(sess.SetRetries(0)).
PlaceOrder(&productOrderContainer, sl.Bool(false))
if err != nil {
return fmt.Errorf("Error during Place order for Creating: %s", err)
}
_, vlan, _, err := findDedicatedFirewallByOrderId(sess, *receipt.OrderId, d)
if err != nil {
return fmt.Errorf("Error during creation of dedicated hardware firewall: %s", err)
}
id := *vlan.NetworkFirewall.Id
d.SetId(fmt.Sprintf("%d", id))
log.Printf("[INFO] Firewall ID: %s", d.Id())
return resourceIBMMultiVlanFirewallRead(d, meta)
}
func resourceIBMMultiVlanFirewallRead(d *schema.ResourceData, meta interface{}) error {
sess := meta.(ClientSession).SoftLayerSession()
fwID, _ := strconv.Atoi(d.Id())
firewalls, err := services.GetAccountService(sess).
Filter(filter.Build(
filter.Path("networkGateways.networkFirewall.id").
Eq(strconv.Itoa(fwID)))).
Mask(multiVlanMask).
GetNetworkGateways()
if err != nil {
return fmt.Errorf("Error retrieving firewall information: %s", err)
}
d.Set("datacenter", *firewalls[0].NetworkFirewall.Datacenter.Name)
if *firewalls[0].NetworkFirewall.CustomerManagedFlag && *firewalls[0].MemberCount == 1 {
d.Set("firewall_type", "FortiGate Security Appliance")
} else if *firewalls[0].NetworkFirewall.CustomerManagedFlag && *firewalls[0].MemberCount > 1 {
d.Set("firewall_type", "FortiGate Firewall Appliance HA Option")
}
addonConfiguration := make([]interface{}, 0, len(firewalls[0].NetworkFirewall.BillingItem.ActiveChildren))
for _, elem := range firewalls[0].NetworkFirewall.BillingItem.ActiveChildren {
if *elem.Description != "20000 GB Bandwidth Allotment" && *elem.Description != "FortiGate Firewall Appliance HA Option" {
addonConfiguration = append(addonConfiguration, *elem.Description)
}
}
if len(addonConfiguration) > 0 {
d.Set("addon_configuration", addonConfiguration)
}
pod := *firewalls[0].NetworkFirewall.BillingItem.Notes
pod = "pod" + strings.SplitAfter(pod, "pod")[1]
d.Set("pod", &pod)
d.Set("name", *firewalls[0].Name)
d.Set("public_ip", *firewalls[0].PublicIpAddress.IpAddress)
d.Set("public_ipv6", firewalls[0].PublicIpv6Address.IpAddress)
d.Set("private_ip", *firewalls[0].PrivateIpAddress.IpAddress)
d.Set("public_vlan_id", *firewalls[0].PublicVlan.Id)
d.Set("private_vlan_id", *firewalls[0].PrivateVlan.Id)
d.Set("username", *firewalls[0].NetworkFirewall.ManagementCredentials.Username)
d.Set("password", *firewalls[0].NetworkFirewall.ManagementCredentials.Password)
return nil
}
func resourceIBMMultiVlanFirewallUpdate(d *schema.ResourceData, meta interface{}) error {
if d.HasChange("addon_configuration") {
sess := meta.(ClientSession).SoftLayerSession()
fwID, _ := strconv.Atoi(d.Id())
old, new := d.GetChange("addon_configuration")
oldaddons := old.([]interface{})
newaddons := new.([]interface{})
var oldaddon, newaddon, add []string
for _, v := range oldaddons {
oldaddon = append(oldaddon, v.(string))
}
for _, v := range newaddons {
newaddon = append(newaddon, v.(string))
}
// 1. Remove old addons no longer appearing in the new set
// 2. Add new addons not already provisioned
remove := listdifference(oldaddon, newaddon)
add = listdifference(newaddon, oldaddon)
if len(remove) > 0 {
firewalls, err := services.GetAccountService(sess).
Filter(filter.Build(
filter.Path("networkGateways.networkFirewall.id").
Eq(strconv.Itoa(fwID)))).
Mask(multiVlanMask).
GetNetworkGateways()
if err != nil {
return fmt.Errorf("Some error occured while fetching the information of the Multi-Vlan Firewall")
}
for _, i := range remove {
for _, j := range firewalls[0].NetworkFirewall.BillingItem.ActiveChildren {
if i == *j.Description {
cancelimmediately := true
cancelAssociatedBillingItems := false
reason := "No longer needed"
customerNote := "No longer needed"
billingitemservice, err := services.GetBillingItemService(sess).Id(*j.Id).CancelItem(&cancelimmediately, &cancelAssociatedBillingItems, &reason, &customerNote)
if err != nil || !billingitemservice {
return fmt.Errorf("Error while cancelling the addon")
}
}
}
}
}
if len(add) > 0 {
datacentername, ok := d.GetOk("datacenter")
if !ok {
return fmt.Errorf("The attribute datacenter is not defined")
}
//2.Get the datacenter id
dc, err := location.GetDatacenterByName(sess, datacentername.(string), "id")
if err != nil {
return fmt.Errorf("Datacenter not found")
}
locationservice := services.GetLocationService(sess)
//3. get the pricegroups that the datacenter belongs to
priceidds, _ := locationservice.Id(*dc.Id).GetPriceGroups()
var listofpriceids []int
//store all the pricegroups a datacenter belongs to
for _, priceidd := range priceidds {
listofpriceids = append(listofpriceids, *priceidd.Id)
}
priceItems := []datatypes.Product_Item_Price{}
for _, addon := range add {
actualpriceid, err := product.GetPriceIDByPackageIdandLocationGroups(sess, listofpriceids, 863, addon)
if err != nil || actualpriceid == 0 {
return fmt.Errorf("The addon or the firewall is not available for the datacenter you have selected. Please enter a different datacenter")
}
priceItem := datatypes.Product_Item_Price{
Id: &actualpriceid,
}
priceItems = append(priceItems, priceItem)
}
//6.Get the package ID
productpackageservice, _ := services.GetProductPackageService(sess).Filter(productPackageFilter).Mask(`id`).GetAllObjects()
var productid int
for _, packageid := range productpackageservice {
productid = *packageid.Id
}
var properties []datatypes.Container_Product_Order_Property
t := time.Now()
upgradeproductOrderContainer := datatypes.Container_Product_Order_Network_Protection_Firewall_Dedicated_Upgrade{
Container_Product_Order_Network_Protection_Firewall_Dedicated: datatypes.Container_Product_Order_Network_Protection_Firewall_Dedicated{
Container_Product_Order: datatypes.Container_Product_Order{
PackageId: &productid,
Prices: priceItems,
ComplexType: sl.String(complexType),
Properties: append(properties, datatypes.Container_Product_Order_Property{
Name: sl.String("MAINTENANCE_WINDOW"),
Value: sl.String(time.Date(t.Year(), t.Month(), t.Day(), t.Hour(), t.Minute(), t.Second(), 0, t.Location()).UTC().String()),
}),
},
},
FirewallId: &fwID,
}
//8.Calling verify order
_, err = services.GetProductOrderService(sess.SetRetries(0)).
VerifyOrder(&upgradeproductOrderContainer)
if err != nil {
return fmt.Errorf("Error during Verify order for Updating: %s", err)
}
//9.Calling place order
receipt, err := services.GetProductOrderService(sess.SetRetries(0)).
PlaceOrder(&upgradeproductOrderContainer, sl.Bool(false))
if err != nil {
return fmt.Errorf("Error during Place order for Updating: %s", err)
}
_, _, _, err = findDedicatedFirewallByOrderId(sess, *receipt.OrderId, d)
if err != nil {
return fmt.Errorf("Error during creation of dedicated hardware firewall: %s", err)
}
}
}
return resourceIBMMultiVlanFirewallRead(d, meta)
}
func resourceIBMMultiVLanFirewallExists(d *schema.ResourceData, meta interface{}) (bool, error) {
sess := meta.(ClientSession).SoftLayerSession()
fwID, _ := strconv.Atoi(d.Id())
firewalls, err := services.GetAccountService(sess).
Filter(filter.Build(
filter.Path("networkGateways.networkFirewall.id").
Eq(strconv.Itoa(fwID)))).
Mask(multiVlanMask).
GetNetworkGateways()
if err != nil {
return false, fmt.Errorf("Error retrieving firewall information: %s", err)
}
if firewalls[0].NetworkFirewall.BillingItem == nil {
return false, nil
}
return true, nil
}
//This function takes two lists and returns the difference between the two lists
//listdifference([1,2] [2,3]) = [1]
func listdifference(a, b []string) []string {
mb := map[string]bool{}
for _, x := range b {
mb[x] = true
}
ab := []string{}
for _, x := range a {
if _, ok := mb[x]; !ok {
ab = append(ab, x)
}
}
return ab
}
|
// Find matching font from |font_set| for the given font family.
FcPattern* MatchFont(FcFontSet* font_set,
FcChar8* post_config_family,
const std::string& family) {
FcPattern* match = NULL;
for (int i = 0; i < font_set->nfont; ++i) {
FcPattern* current = font_set->fonts[i];
FcBool is_scalable;
if (FcPatternGetBool(current, FC_SCALABLE, 0,
&is_scalable) != FcResultMatch ||
!is_scalable) {
continue;
}
FcChar8* c_filename;
if (FcPatternGetString(current, FC_FILE, 0, &c_filename) != FcResultMatch)
continue;
if (access(reinterpret_cast<char*>(c_filename), R_OK) != 0)
continue;
match = current;
break;
}
if (match && !IsFallbackFontAllowed(family)) {
bool acceptable_substitute = false;
for (int id = 0; id < 255; ++id) {
FcChar8* post_match_family;
if (FcPatternGetString(match, FC_FAMILY, id, &post_match_family) !=
FcResultMatch)
break;
acceptable_substitute =
(strcasecmp(reinterpret_cast<char*>(post_config_family),
reinterpret_cast<char*>(post_match_family)) == 0 ||
strcasecmp(family.c_str(),
reinterpret_cast<char*>(post_match_family)) == 0) ||
IsMetricCompatibleReplacement(family.c_str(),
reinterpret_cast<char*>(post_match_family));
if (acceptable_substitute)
break;
}
if (!acceptable_substitute)
return NULL;
}
return match;
} |
/**
* Run some tests specific for {@link AStarBidirection}
*
* @author Peter Karich
* @see RoutingAlgorithmTest for test cases covering standard node- and edge-based routing with this algorithm
* @see EdgeBasedRoutingAlgorithmTest for test cases covering routing with turn costs with this algorithm
*/
public class AStarBidirectionTest {
private final EncodingManager encodingManager = EncodingManager.create("car");
private final FlagEncoder carEncoder = encodingManager.getEncoder("car");
@Test
public void testInitFromAndTo() {
doTestInitFromAndTo(TraversalMode.NODE_BASED);
doTestInitFromAndTo(TraversalMode.EDGE_BASED);
}
private void doTestInitFromAndTo(final TraversalMode traversalMode) {
Graph g = new GraphBuilder(encodingManager).create();
g.edge(0, 1, 1, true);
updateDistancesFor(g, 0, 0.00, 0.00);
updateDistancesFor(g, 1, 0.01, 0.01);
final AtomicReference<SPTEntry> fromRef = new AtomicReference<>();
final AtomicReference<SPTEntry> toRef = new AtomicReference<>();
AStarBidirection astar = new AStarBidirection(g, new ShortestWeighting(carEncoder), traversalMode) {
@Override
public void init(int from, double fromWeight, int to, double toWeight) {
super.init(from, fromWeight, to, toWeight);
fromRef.set(currFrom);
toRef.set(currTo);
}
};
astar.init(0, 1, 1, 0.5);
assertEquals(1, ((AStar.AStarEntry) fromRef.get()).weightOfVisitedPath, .1);
assertEquals(787.3, fromRef.get().weight, .1);
assertEquals(0.5, ((AStar.AStarEntry) toRef.get()).weightOfVisitedPath, .1);
assertEquals(786.8, toRef.get().weight, .1);
}
} |
<reponame>usmile-ok/pangu
package main_test
import (
`github.com/pangum/pangu`
)
const filepathBanner = `./baner/github.png`
func bannerWithFilepath() {
panic(pangu.New(
pangu.Name("example"),
pangu.Banner(filepathBanner, pangu.BannerTypeFilepath),
).Run(newBootstrap))
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.