text:
import React from 'react';
import axios from 'axios';
import * as toastify from '../../functions/Toastify';

import { Link, browserHistory } from 'react-router';
import { Card, CardActions, CardHeader, CardMedia, CardTitle, CardText } from 'material-ui/Card';
import { isoToShortDate, fullDateToIsoDate, numberWithCommas } from '../../functions.js';
import { calculateROI, calculateYield, calculateTotalMonths, getPropertyTypeName, propertyTypes, getPropertyUrl } from '../../functions/propertiesFuncs';
import { getBranchName } from '../../functions/BranchesFuncs';
import { IsNumber } from '../../functions/Validations';
import FlatButton from 'material-ui/FlatButton';
import HomeIcon from '../icons/Home.png';
import PriceIcon from '../icons/Money Bag Filled-50.png';
import TotalReturn from '../icons/Return.png';
import Yield from '../icons/yield.png';
import TotalMonth from '../icons/Month.png';
import ROI from '../ROI';
import PWIcon from '../icons/PWIcon.jpg';
import FloatingActionButton from 'material-ui/FloatingActionButton';
import EditBtn from 'material-ui/svg-icons/content/create';
import DatePicker from 'material-ui/DatePicker';
import SelectField from 'material-ui/SelectField';
import MenuItem from 'material-ui/MenuItem';

import styled from 'styled-components';

import TextField from 'material-ui/TextField';
import RaisedButton from 'material-ui/RaisedButton';
import { RadioButton, RadioButtonGroup } from 'material-ui/RadioButton';
import Divider from 'material-ui/Divider';

const stylesRB = {
  block: {
    maxWidth: 250
  },
  radioButton: {
    marginBottom: 16,
    width: '150px',
    display: 'inline-block'
  }
};

const styles = {
  block: {
    maxWidth: 250
  },
  toggle: {
    marginBottom: 16
  },
  thumbOff: {
    backgroundColor: '#ffcccc'
  },
  trackOff: {
    backgroundColor: '#ff9d9d'
  },
  thumbSwitched: {
    backgroundColor: 'red'
  },
  trackSwitched: {
    backgroundColor: '#ff9d9d'
  },
  labelStyle: {
    color: 'red'
  }
};

const SectionContainer = styled.div`
margin-bottom: 20px;
  .col-md-10 {
    padding-left: 35px;
    margin-bottom: 50px;
  }
  .col-md-5 {
        padding: 10px;
  }

  .col-md-7 {
    padding: 10px;
  }
  p {
    color: #484848 !important;
    font-family: Circular,-apple-system,BlinkMacSystemFont,Roboto,Helvetica Neue,sans-serif !important;
    font-size: 17px !important;
    font-weight: 300 !important;
    letter-spacing: 0.2px !important;
    line-height: 22px !important;
    // text-align: center;
  }
  .col-md-2 {
    padding: 0px;
  }

  .name {
    font-weight: 700 !important;
    color: #484848 !important;
    font-family: Circular,-apple-system,BlinkMacSystemFont,Roboto,Helvetica Neue,sans-serif !important;
    margin: 0px !important;
    word-wrap: break-word !important;
    font-size: 36px !important;
    line-height: 44px !important;
    letter-spacing: -0.6px !important;
    padding-top: 6px !important;
    margin-bottom: 10px;
    padding-bottom: 10px;
    display: block;
  }

  .title {
    color: #484848 !important;
    font-family: Circular,-apple-system,BlinkMacSystemFont,Roboto,Helvetica Neue,sans-serif !important;
    font-size: 17px !important;
    font-weight: 300 !important;
    letter-spacing: 0.2px !important;
    line-height: 22px !important;
  }
  h4 {
    font-size: 22px !important;
    font-weight: 400 !important;
    border-bottom: 1px #e5e5e5 solid;
    padding-bottom: 10px;
    letter-spacing: -0.2px !important;
    line-height: 28px !important;
    padding-bottom: 10px;
    color: #484848 !important;
    font-family: Circular,-apple-system,BlinkMacSystemFont,Roboto,Helvetica Neue,sans-serif !important;
    font-size: 17px !important;
    font-weight: 300 !important;
    letter-spacing: 0.2px !important;
    line-height: 22px !important;
  }

  h5 {
    color: #484848 !important;
    font-family: Circular,-apple-system,BlinkMacSystemFont,Roboto,Helvetica Neue,sans-serif !important;
    font-size: 17px !important;
    font-weight: 300 !important;
    letter-spacing: 0.2px !important;
    line-height: 22px !important;
  }

  .IconRowDivider {
    text-align: center;
    border-top: 1px solid #dce0e0;
    display: flex;
    justify-content: space-around;
    padding: 10px;

    img {
      margin: 6px auto;
      display: block;
    }
  }
`;

const borderBottom = {
  borderBottom: '1px solid rgb(234, 233, 233)',
  marginBottom: '22px',
  paddingBottom: '10px',
  paddingTop: '14px'
};

export default class UnitHeader extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      notConnectedPWPropertiesList: [],
      notConnectedPWUnitsList: [],
      editMode: false,

      PropertyId: props.property.PropertyId,
      PWBuildingID: props.property.PWBuildingID,
      PWUnitID: props.property.PWUnitID,
      PropertyName: props.property.PropertyName,
      BranchId: props.property.BranchId,
      PropertyType: props.property.PropertyType,
      NumOfUnits: props.property.NumOfUnits,
      NumOfBedrooms: props.property.NumOfBedrooms,
      NumOfBathrooms: props.property.NumOfBathrooms,
      Sqft: props.property.Sqft,
      VacantOrOccupied: props.property.VacantOrOccupied,
      TargetRent: props.property.TargetRent,
      CountyYearlyTax: props.property.CountyYearlyTax,
      CitySchoolYearlyTax: props.property.CitySchoolYearlyTax,
      InvestmentAmount: props.property.InvestmentAmount,
      // TotalReturn: props.property.TotalReturn,
      InvestmentDate: props.property.InvestmentDate,
      Active: props.property.Active
    };
    this.setNewValueToState = this.setNewValueToState.bind(this);
  }

  componentWillMount() {
    this.getNotConnectedPWProperties();
    this.getNotConnectedPWUnits();
  }

  editSection() {
    this.setState({ editMode: !this.state.editMode });
  }

  disconnectPWPropertyConnection() {
    this.setState({ PWBuildingID: 0, PWUnitID: 0 }, () => { toastify.notifyWarn(toastify.messages.disconnectedPWProperty) })
  }

  setNewValueToState(event) {
    switch (event.target.name) {
      case 'PropertyType':
        this.setState({ PropertyType: event.target.value });
        this.disconnectPWPropertyConnection();
        break;
      case 'Active':
        this.setState({ Active: event.target.value });
        break;
      case 'VacantOrOccupied':
        this.setState({ VacantOrOccupied: event.target.value });
        break;
      case 'BranchId':
        this.setState({ BranchId: event.target.value });
        break;

      default:
        break;
    }

    switch (event.target.id) {
      case 'PropertyName':
        this.setState({ PropertyName: event.target.value });
        break;
      case 'BranchId':
        this.setState({ BranchId: event.target.value });
        break;
      case 'NumOfUnits':
        if (IsNumber(event.target.value)) {
          this.setState({ NumOfUnits: event.target.value });
        } else {
          event.target.value = this.state.NumOfUnits;
        }
        break;
      case 'NumOfBedrooms':
        if (IsNumber(event.target.value)) {
          this.setState({ NumOfBedrooms: event.target.value });
        } else {
          event.target.value = this.state.NumOfBedrooms;
        }
        break;
      case 'NumOfBathrooms':
        if (IsNumber(event.target.value)) {
          this.setState({ NumOfBathrooms: event.target.value });
        } else {
          event.target.value = this.state.NumOfBathrooms;
        }
        break;
      case 'Sqft':
        if (IsNumber(event.target.value)) {
          this.setState({ Sqft: event.target.value });
        } else {
          event.target.value = this.state.Sqft;
        }
        break;
      case 'VacantOrOccupied':
        this.setState({ VacantOrOccupied: event.target.value });
        break;
      case 'TargetRent':
        if (IsNumber(event.target.value)) {
          this.setState({ TargetRent: event.target.value });
        } else {
          event.target.value = this.state.TargetRent;
        }
        break;
      case 'CountyYearlyTax':
        if (IsNumber(event.target.value)) {
          this.setState({ CountyYearlyTax: event.target.value });
        } else {
          event.target.value = this.state.CountyYearlyTax;
        }
        break;
      case 'CitySchoolYearlyTax':
        if (IsNumber(event.target.value)) {
          this.setState({ CitySchoolYearlyTax: event.target.value });
        } else {
          event.target.value = this.state.CitySchoolYearlyTax;
        }
        break;
      case 'InvestmentAmount':
        if (IsNumber(event.target.value)) {
          this.setState({ InvestmentAmount: event.target.value });
        } else {
          event.target.value = this.state.InvestmentAmount;
        }
        break;
      case 'TotalReturn':
        if (IsNumber(event.target.value)) {
          this.setState({ TotalReturn: event.target.value });
        } else {
          event.target.value = this.state.TotalReturn;
        }
        break;
      case 'InvestmentDate':
        this.setState({ InvestmentDate: event.target.value });
        break;
      case 'Active':
        this.setState({ Active: event.target.value });
        break;
    }
  }

  getNotConnectedPWProperties() {
    axios.get('http://54.190.49.213/index.php/api/properties/getNotConnectedPWProperties', {
      params: {
        id: this.state.BranchId,
        PWPropertyID: this.state.PWBuildingID
      }
    }).then(response => {
      this.setState({
        notConnectedPWPropertiesList: response.data
      });
    })
      .catch(error => {
      });
  }

  getNotConnectedPWUnits() {
    axios.get('http://54.190.49.213/index.php/api/properties/getNotConnectedPWPUnits', {
      params: {
        id: this.state.BranchId,
        PWPropertyID: this.state.PWBuildingID
      }
    }).then(response => {
      this.setState({
        notConnectedPWUnitsList: response.data
      });
    })
      .catch(error => {
      });
  }

  updateSection() {
    axios({
      method: 'post',
      url: 'http://54.190.49.213/index.php/api/properties/editProperty',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      data: {
        propertyId: this.state.PropertyId,
        propertyName: this.state.PropertyName,
        branchId: this.state.BranchId,
        numOfUnits: this.state.NumOfUnits,
        numOfBedrooms: this.state.NumOfBedrooms,
        numOfBathrooms: this.state.NumOfBathrooms,
        sqft: this.state.Sqft,
        vacantOrOccupied: this.state.VacantOrOccupied,
        targetRent: this.state.TargetRent,
        countyYearlyTax: this.state.CountyYearlyTax,
        citySchoolYearlyTax: this.state.CitySchoolYearlyTax,
        investmentAmount: this.state.InvestmentAmount,
        totalReturn: this.state.TotalReturn,
        investmentDate: this.state.InvestmentDate,
        active: this.state.Active,
        propertyType: this.state.PropertyType,
        PWBuildingID: this.state.PWBuildingID,
        PWUnitID: this.state.PWUnitID
      }
    }).then(res => {
      toastify.notifySuccess(toastify.messages.updateSuccess);
      this.handlePropertyTypeChange();
      this.setState({ editMode: false });
      this.props.reRenderPropertyData();
      // This.props.handler(this.state, 'marketing');
    })
      .catch(error => {
        toastify.notifyErorr(toastify.messages.updateError);
      });
  }

  handlePropertyTypeChange() {
    if (this.props.property.PropertyType != this.state.PropertyType) {
      const propUrl = getPropertyUrl(this.state.PropertyType, this.props.property.PropertyId);
      browserHistory.push(propUrl);
    }
  }

  getSelectedPWPropertyValue() {
    let indexVal;

    if (this.state.PropertyType == propertyTypes.Unit) {
      indexVal = this.state.notConnectedPWUnitsList.findIndex(x => x.PWUnitID == this.state.PWUnitID);
    } else {
      indexVal = this.state.notConnectedPWPropertiesList.findIndex(x => x.PWBuildingID == this.state.PWBuildingID);
    }

    return indexVal;
  }

  renderCardBlock() {
    if (this.state.editMode) {
      return (

              Property Type:

              <RadioButtonGroup
                onChange={this.setNewValueToState}
                name="PropertyType"
                fullWidth={true}
                defaultSelected={this.state.PropertyType}>
                <RadioButton
                  value="1"
                  label="Building"
                  style={stylesRB.radioButton}
                />
                <RadioButton
                  value="2"
                  label="Unit"
                  style={stylesRB.radioButton}
                />
                <RadioButton
                  value="3"
                  label="Single Home"
                  style={stylesRB.radioButton}
                />
              </RadioButtonGroup>
              <Divider />

              Property In PW:

              <SelectField
                maxHeight={277}
                fullWidth={true}
                disabled={!(this.state.PropertyType > 0)}
                errorText={!(this.state.PropertyType > 0) && 'Select Property Type'}
                value={this.getSelectedPWPropertyValue()}
                onChange={(event, index, value) => {
                  if (this.state.PropertyType == propertyTypes.Unit) {
                    this.setState({
                      PWBuildingID: this.state.notConnectedPWUnitsList[value].PWBuildingID,
                      PWUnitID: (this.state.notConnectedPWUnitsList[value].PWUnitID == null ||
                        this.state.PropertyType == 1) ?
                        0 :
                        this.state.notConnectedPWUnitsList[value].PWUnitID
                    });
                  } else {
                    this.setState({
                      PWBuildingID: this.state.notConnectedPWPropertiesList[value].PWBuildingID,
                      PWUnitID: (this.state.PropertyType == 1) ? 0 :
                        this.state.notConnectedPWPropertiesList[value].PWBuildingID
                    });
                  }
                }}
              >
                {this.renderPWMenuItems()}
              </SelectField>

              Property Name:

              <TextField
                id={'PropertyName'}
                onChange={this.setNewValueToState}
                defaultValue={this.state.PropertyName}
                fullWidth={true}
              />

              Active:

              <RadioButtonGroup
                onChange={this.setNewValueToState}
                name="Active"
                fullWidth={true}
                defaultSelected={this.state.Active}>
                <RadioButton
                  value="1"
                  label="ACTIVE"
                  style={stylesRB.radioButton}
                />
                <RadioButton
                  value="0"
                  label="NOT ACTIVE"
                  style={stylesRB.radioButton}
                />
              </RadioButtonGroup>
              <Divider />

              Vacant Or Occupied:

              <RadioButtonGroup
                onChange={this.setNewValueToState}
                name="VacantOrOccupied"
                fullWidth={true}
                defaultSelected={this.state.VacantOrOccupied}>
                <RadioButton
                  value="VACANT"
                  label="VACANT"
                  style={stylesRB.radioButton}
                />
                <RadioButton
                  value="OCCUPIED"
                  label="OCCUPIED"
                  style={stylesRB.radioButton}
                />
              </RadioButtonGroup>
              <Divider />

              Branch:

              <RadioButtonGroup
                onChange={this.setNewValueToState}
                name="BranchId"
                fullWidth={true}
                defaultSelected={this.state.BranchId}>
                <RadioButton
                  value="1"
                  label="Rochester"
                  style={stylesRB.radioButton}
                />
                <RadioButton
                  value="2"
                  label="Cleveland"
                  style={stylesRB.radioButton}
                />
                <RadioButton
                  value="3"
                  label="Columbus"
                  style={stylesRB.radioButton}
                />
                <RadioButton
                  value="4"
                  label="Jacksonville"
                  style={stylesRB.radioButton}
                />
              </RadioButtonGroup>
              <Divider />

              Num Of Bedrooms:

              <TextField
                id={'NumOfBedrooms'}
                onChange={this.setNewValueToState}
                defaultValue={numberWithCommas(this.state.NumOfBedrooms)}
                fullWidth={true}
              />

              Num Of Bathrooms:

              <TextField
                id={'NumOfBathrooms'}
                onChange={this.setNewValueToState}
                defaultValue={numberWithCommas(this.state.NumOfBathrooms)}
                fullWidth={true}
              />

              Sqft:

              <TextField
                id={'Sqft'}
                onChange={this.setNewValueToState}
                defaultValue={numberWithCommas(this.state.Sqft)}
                fullWidth={true}
              />

              Target Rent:

              <TextField
                id={'TargetRent'}
                onChange={this.setNewValueToState}
                defaultValue={numberWithCommas(this.state.TargetRent)}
                fullWidth={true}
              />

              <RaisedButton className="updateSectionsBtn" label="Cancel" onClick={() => {
                this.setState({ editMode: false });
              }} />
              <RaisedButton className="updateSectionsBtn" label="Save" primary={true} onClick={this.updateSection.bind(this)} />

      );
    }

    return (

  {(this.state.Active == 1) ? 'ACTIVE' : 'NOT ACTIVE'}

Property Type:  {getPropertyTypeName(this.state.PropertyType)}

Branch:  {getBranchName(this.state.BranchId)}

            {/*
Num Of Units:  {this.state.NumOfUnits}
 */}

Sqft:  {numberWithCommas(this.state.Sqft)}

  {this.state.VacantOrOccupied}

Num Of Bedrooms:  {numberWithCommas(this.state.NumOfBedrooms)}

Num Of Bathrooms:  {numberWithCommas(this.state.NumOfBathrooms)}

Target Rent:  {numberWithCommas(this.state.TargetRent)}

    );
  }

  renderSectionHeader() {
    return (

 Property Details
         <FloatingActionButton onClick={this.editSection.bind(this)} mini={true} className="addEditBtn" >
            <EditBtn />
          </FloatingActionButton>

);
  }

  render() {
    return (

        <SectionContainer>

 {this.props.property.PropertyName}

            {this.renderSectionHeader()}
            {this.renderCardBlock()}

        </SectionContainer>

    );
  }

  renderPWMenuItems() {
    if (this.state.PropertyType == propertyTypes.Unit) {
      return (
        this.state.notConnectedPWUnitsList.map((item, index) => (
          this.renderPWPropertyMenuItem(item, index)
        ))
      );
    }

    return (
      this.state.notConnectedPWPropertiesList.map((item, index) => (
        this.renderPWPropertyMenuItem(item, index)
      ))
    );
  }

  renderPWPropertyMenuItem(item, index) {
    if (this.state.PropertyType == propertyTypes.Unit && item.UnitDetails != null) {
      return (<MenuItem value={index} primaryText={item.PropertyAddress + ' - Unit Details: ' + item.UnitDetails} />);
    } else if (this.state.PropertyType == propertyTypes.SingleFamilyHome && item.UnitDetails == null) {
      return (<MenuItem value={index} primaryText={item.PropertyAddress} />);
    } else if ((this.state.PropertyType == propertyTypes.Building)) {
      if (index == 0) {
        return (<MenuItem value={index} primaryText={item.PropertyAddress} />);
      } else if (item.PWBuildingID != this.state.notConnectedPWPropertiesList[index - 1].PWBuildingID) {
        return (<MenuItem value={index} primaryText={item.PropertyAddress} />);
      }

      return false;
    }
  }

}


text:
/* eslint-env jest */
import {
  check,
  File,
  findPort,
  hasRedbox,
  killApp,
  launchApp,
} from 'next-test-utils'
import webdriver from 'next-webdriver'
import { join } from 'path'

const appDir = join(__dirname, '../')

describe('no duplicate compile error output', () => {
  it('should not show compile error on page refresh', async () => {
    let stderr = ''

    const appPort = await findPort()
    const app = await launchApp(appDir, appPort, {
      env: { __NEXT_TEST_WITH_DEVTOOL: true },
      onStderr(msg) {
        stderr += msg || ''
      },
    })

    const browser = await webdriver(appPort, '/')

    await browser.waitForElementByCss('#a')

    const f = new File(join(appDir, 'pages', 'index.js'))
    f.replace('
hello
', '
hello
')

    try {
      // Wait for compile error:
      expect(await hasRedbox(browser, true)).toBe(true)

      await browser.refresh()

      // Wait for compile error to re-appear:
      expect(await hasRedbox(browser, true)).toBe(true)
    } finally {
      f.restore()
    }

    // Wait for compile error to disappear:
    await check(
      () => hasRedbox(browser, false).then((r) => (r ? 'yes' : 'no')),
      /no/
    )
    await browser.waitForElementByCss('#a')

    function getRegexCount(str, regex) {
      return (str.match(regex) || []).length
    }

    const correctMessagesRegex =
      /error - [^\r\n]+\r?\n[^\r\n]+Unexpected token/g
    const totalMessagesRegex = /Unexpected token/g

    const correctMessages = getRegexCount(stderr, correctMessagesRegex)
    const totalMessages = getRegexCount(stderr, totalMessagesRegex)

    expect(correctMessages).toBeGreaterThanOrEqual(1)
    expect(correctMessages).toBe(totalMessages)

    await killApp(app)
  })
})

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="UTF-8" ?>
<!--
 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.
-->

<!--
 This is the Solr schema file. This file should be named "schema.xml" and
 should be in the conf directory under the solr home
 (i.e. ./solr/conf/schema.xml by default)
 or located where the classloader for the Solr webapp can find it.

 This example schema is the recommended starting point for users.
 It should be kept correct and concise, usable out-of-the-box.

 For more information, on how to customize this file, please see
 http://wiki.apache.org/solr/SchemaXml

 PERFORMANCE NOTE: this schema includes many optional features and should not
 be used for benchmarking.  To improve performance one could
  - set stored="false" for all fields possible (esp large fields) when you
    only need to search on the field but don't need to return the original
    value.
  - set indexed="false" if you don't need to search on the field, but only
    return the field as a result of searching on other indexed fields.
  - remove all unneeded copyField statements
  - for best index size and searching performance, set "index" to false
    for all general text fields, use copyField to copy them to the
    catchall "text" field, and use that for searching.
  - For maximum indexing performance, use the StreamingUpdateSolrServer
    java client.
  - Remember to run the JVM in server mode, and use a higher logging level
    that avoids logging every request
-->

<schema name="Debug Schema" version="1.5">
  <!-- attribute "name" is the name of this schema and is only used for display purposes.
       version="x.y" is Solr's version number for the schema syntax and
       semantics.  It should not normally be changed by applications.

       1.0: multiValued attribute did not exist, all fields are multiValued
            by nature
       1.1: multiValued attribute introduced, false by default
       1.2: omitTermFreqAndPositions attribute introduced, true by default
            except for text fields.
       1.3: removed optional field compress feature
       1.4: autoGeneratePhraseQueries attribute introduced to drive QueryParser
            behavior when a single string produces multiple tokens.  Defaults
            to off for version >= 1.4
       1.5: omitNorms defaults to true for primitive field types
            (int, float, boolean, string...)
     -->

  <fields>
    <!-- Valid attributes for fields:
     name: mandatory - the name for the field
     type: mandatory - the name of a field type from the
       <types> fieldType section
     indexed: true if this field should be indexed (searchable or sortable)
     stored: true if this field should be retrievable
     docValues: true if this field should have doc values. Doc values are
       useful for faceting, grouping, sorting and function queries. Although not
       required, doc values will make the index faster to load, more
       NRT-friendly and more memory-efficient. They however come with some
       limitations: they are currently only supported by StrField, UUIDField
       and all Trie*Fields, and depending on the field type, they might
       require the field to be single-valued, be required or have a default
       value (check the documentation of the field type you're interested in
       for more information)
     multiValued: true if this field may contain multiple values per document
     omitNorms: (expert) set to true to omit the norms associated with
       this field (this disables length normalization and index-time
       boosting for the field, and saves some memory).  Only full-text
       fields or fields that need an index-time boost need norms.
       Norms are omitted for primitive (non-analyzed) types by default.
     termVectors: [false] set to true to store the term vector for a
       given field.
       When using MoreLikeThis, fields used for similarity should be
       stored for best performance.
     termPositions: Store position information with the term vector.
       This will increase storage costs.
     termOffsets: Store offset information with the term vector. This
       will increase storage costs.
     required: The field is required.  It will throw an error if the
       value does not exist
     default: a value that should be used if no value is specified
       when adding a document.
    -->

    <!-- field names should consist of alphanumeric or underscore characters only and
      not start with a digit.  This is not currently strictly enforced,
      but other field names will not have first class support from all components
      and back compatibility is not guaranteed.  Names with both leading and
      trailing underscores (e.g. _version_) are reserved.
    -->

   <field name="id" type="string" indexed="true" stored="true" required="true" multiValued="false" />
   <field name="user_friends_count" type="tint" indexed="true" stored="true" />
   <field name="user_location" type="lowercase" indexed="true" stored="true" />
   <field name="user_description" type="text_en" indexed="true" stored="false"/>
   <field name="user_statuses_count" type="tint" indexed="true" stored="true" />
   <field name="user_followers_count" type="tint" indexed="true" stored="true"/>
   <field name="user_name" type="text_en" indexed="true" stored="true" />
   <field name="user_screen_name" type="text_en" indexed="true" stored="true" />
   <field name="created_at" type="tdate" indexed="true" stored="true" />
   <field name="text" type="text_en" indexed="true" stored="true" multiValued="true" />
   <field name="retweet_count" type="tint" indexed="true" stored="true" />
   <field name="retweeted" type="boolean" indexed="true" stored="false" />
   <field name="in_reply_to_user_id" type="long" indexed="true" stored="true" />
   <field name="source" type="lowercase" indexed="true" stored="true" />
   <field name="in_reply_to_status_id" type="long" indexed="true" stored="true" multiValued="true"/>
   <field name="media_url_https" type="string" indexed="false" stored="true" />
   <field name="expanded_url" type="string" indexed="false" stored="true" />

   <!-- file metadata -->
   <field name="file_download_url" type="string" indexed="false" stored="true" />
   <field name="file_upload_url" type="string" indexed="false" stored="true" />
   <field name="file_scheme" type="string" indexed="true" stored="true" />
   <field name="file_host" type="string" indexed="true" stored="true" />
   <field name="file_port" type="int" indexed="true" stored="true" />
   <field name="file_path" type="string" indexed="true" stored="true" />
   <field name="file_name" type="string" indexed="true" stored="true" />
   <field name="file_length" type="tlong" indexed="true" stored="true" />
   <field name="file_last_modified" type="tlong" indexed="true" stored="true" />
   <field name="file_owner" type="string" indexed="true" stored="true" />
   <field name="file_group" type="string" indexed="true" stored="true" />
   <field name="file_permissions_user" type="string" indexed="true" stored="true" />
   <field name="file_permissions_group" type="string" indexed="true" stored="true" />
   <field name="file_permissions_other" type="string" indexed="true" stored="true" />
   <field name="file_permissions_stickybit" type="boolean" indexed="true" stored="true" />

   <!-- tika metadata -->
   <field name="content_type" type="lowercase" indexed="true" stored="true" />

   <field name="_version_" type="long" indexed="true" stored="true"/>
   <dynamicField name="ignored_*" type="ignored"/>

  </fields>

  <!-- Field to use to determine and enforce document uniqueness.
      Unless this field is marked with required="false", it will be a required field
  -->
  <uniqueKey>id</uniqueKey>

  <!-- DEPRECATED: The defaultSearchField is consulted by various query parsers when
   parsing a query string that isn't explicit about the field.  Machine (non-user)
   generated queries are best made explicit, or they can use the "df" request parameter
   which takes precedence over this.
   Note: Un-commenting defaultSearchField will be insufficient if your request handler
   in solrconfig.xml defines "df", which takes precedence. That would need to be removed.
  <defaultSearchField>text</defaultSearchField> -->

  <defaultSearchField>text</defaultSearchField>

  <!-- DEPRECATED: The defaultOperator (AND|OR) is consulted by various query parsers
   when parsing a query string to determine if a clause of the query should be marked as
   required or optional, assuming the clause isn't already marked by some operator.
   The default is OR, which is generally assumed so it is not a good idea to change it
   globally here.  The "q.op" request parameter takes precedence over this.
   <solrQueryParser defaultOperator="OR"/> -->

  <!-- copyField commands copy one field to another at the time a document
        is added to the index.  It's used either to index the same field differently,
        or to add multiple fields to the same field for easier/faster searching.  -->

  <!--copyField source="message" dest="text" /-->
  <!--copyField source="*_t" dest="text" maxChars="3000"/-->
  -->

  <!-- copy name to alphaNameSort, a field designed for sorting by name -->
  <!-- <copyField source="name" dest="alphaNameSort"/> -->

  <types>
    <!-- field type definitions. The "name" attribute is
       just a label to be used by field definitions.  The "class"
       attribute and any other attributes determine the real
       behavior of the fieldType.
         Class names starting with "solr" refer to java classes in a
       standard package such as org.apache.solr.analysis
    -->

    <!-- The StrField type is not analyzed, but indexed/stored verbatim.
       It supports doc values but in that case the field needs to be
       single-valued and either required or have a default value.
      -->
    <fieldType name="string" class="solr.StrField" sortMissingLast="true"/>

    <!-- boolean type: "true" or "false" -->
    <fieldType name="boolean" class="solr.BoolField" sortMissingLast="true"/>

    <!-- sortMissingLast and sortMissingFirst attributes are optional attributes are
         currently supported on types that are sorted internally as strings
         and on numeric types.
	     This includes "string","boolean", and, as of 3.5 (and 4.x),
	     int, float, long, date, double, including the "Trie" variants.
       - If sortMissingLast="true", then a sort on this field will cause documents
         without the field to come after documents with the field,
         regardless of the requested sort order (asc or desc).
       - If sortMissingFirst="true", then a sort on this field will cause documents
         without the field to come before documents with the field,
         regardless of the requested sort order.
       - If sortMissingLast="false" and sortMissingFirst="false" (the default),
         then default lucene sorting will be used which places docs without the
         field first in an ascending sort and last in a descending sort.
    -->

    <!--
      Default numeric field types. For faster range queries, consider the tint/tfloat/tlong/tdouble types.

      These fields support doc values, but they require the field to be
      single-valued and either be required or have a default value.
    -->
    <fieldType name="int" class="solr.TrieIntField" precisionStep="0" positionIncrementGap="0"/>
    <fieldType name="float" class="solr.TrieFloatField" precisionStep="0" positionIncrementGap="0"/>
    <fieldType name="long" class="solr.TrieLongField" precisionStep="0" positionIncrementGap="0"/>
    <fieldType name="double" class="solr.TrieDoubleField" precisionStep="0" positionIncrementGap="0"/>

    <!--
      Numeric field types that index each value at various levels of precision
      to accelerate range queries when the number of values between the range
      endpoints is large. See the javadoc for NumericRangeQuery for internal
      implementation details.

      Smaller precisionStep values (specified in bits) will lead to more tokens
      indexed per value, slightly larger index size, and faster range queries.
      A precisionStep of 0 disables indexing at different precision levels.
    -->
    <fieldType name="tint" class="solr.TrieIntField" precisionStep="8" positionIncrementGap="0"/>
    <fieldType name="tfloat" class="solr.TrieFloatField" precisionStep="8" positionIncrementGap="0"/>
    <fieldType name="tlong" class="solr.TrieLongField" precisionStep="8" positionIncrementGap="0"/>
    <fieldType name="tdouble" class="solr.TrieDoubleField" precisionStep="8" positionIncrementGap="0"/>

    <!-- The format for this date field is of the form 1995-12-31T23:59:59Z, and
         is a more restricted form of the canonical representation of dateTime
         http://www.w3.org/TR/xmlschema-2/#dateTime
         The trailing "Z" designates UTC time and is mandatory.
         Optional fractional seconds are allowed: 1995-12-31T23:59:59.999Z
         All other components are mandatory.

         Expressions can also be used to denote calculations that should be
         performed relative to "NOW" to determine the value, ie...

               NOW/HOUR
                  ... Round to the start of the current hour
               NOW-1DAY
                  ... Exactly 1 day prior to now
               NOW/DAY+6MONTHS+3DAYS
                  ... 6 months and 3 days in the future from the start of
                      the current day

         Consult the DateField javadocs for more information.

         Note: For faster range queries, consider the tdate type
      -->
    <fieldType name="date" class="solr.TrieDateField" precisionStep="0" positionIncrementGap="0"/>

    <!-- A Trie based date field for faster date range queries and date faceting. -->
    <fieldType name="tdate" class="solr.TrieDateField" precisionStep="6" positionIncrementGap="0"/>

    <!--Binary data type. The data should be sent/retrieved in as Base64 encoded Strings -->
    <fieldtype name="binary" class="solr.BinaryField"/>

    <!-- solr.TextField allows the specification of custom text analyzers
         specified as a tokenizer and a list of token filters. Different
         analyzers may be specified for indexing and querying.

         The optional positionIncrementGap puts space between multiple fields of
         this type on the same document, with the purpose of preventing false phrase
         matching across fields.

         For more info on customizing your analyzer chain, please see
         http://wiki.apache.org/solr/AnalyzersTokenizersTokenFilters
     -->

    <!-- One can also specify an existing Analyzer class that has a
         default constructor via the class attribute on the analyzer element.
         Example:
    <fieldType name="text_greek" class="solr.TextField">
      <analyzer class="org.apache.lucene.analysis.el.GreekAnalyzer"/>
    </fieldType>
    -->

    <!-- A text field that only splits on whitespace for exact matching of words -->
    <fieldType name="text_ws" class="solr.TextField" positionIncrementGap="100">
      <analyzer>
        <tokenizer class="solr.WhitespaceTokenizerFactory"/>
      </analyzer>
    </fieldType>

    <!-- A general text field that has reasonable, generic
         cross-language defaults: it tokenizes with StandardTokenizer,
	 removes stop words from case-insensitive "stopwords.txt"
	 (empty by default), and down cases.  At query time only, it
	 also applies synonyms. -->
    <fieldType name="text_general" class="solr.TextField" positionIncrementGap="100">
      <analyzer type="index">
        <tokenizer class="solr.StandardTokenizerFactory"/>
        <filter class="solr.StopFilterFactory" ignoreCase="true" words="stopwords.txt"/>
        <!-- in this example, we will only use synonyms at query time
        <filter class="solr.SynonymFilterFactory" synonyms="index_synonyms.txt" ignoreCase="true" expand="false"/>
        -->
        <filter class="solr.LowerCaseFilterFactory"/>
      </analyzer>
      <analyzer type="query">
        <tokenizer class="solr.StandardTokenizerFactory"/>
        <filter class="solr.StopFilterFactory" ignoreCase="true" words="stopwords.txt"/>
        <filter class="solr.SynonymFilterFactory" synonyms="synonyms.txt" ignoreCase="true" expand="true"/>
        <filter class="solr.LowerCaseFilterFactory"/>
      </analyzer>
    </fieldType>

    <!-- A text field with defaults appropriate for English: it
         tokenizes with StandardTokenizer, removes English stop words
         (lang/stopwords_en.txt), down cases, protects words from protwords.txt, and
         finally applies Porter's stemming.  The query time analyzer
         also applies synonyms from synonyms.txt. -->
    <fieldType name="text_en" class="solr.TextField" positionIncrementGap="100">
      <analyzer type="index">
        <tokenizer class="solr.StandardTokenizerFactory"/>
        <!-- in this example, we will only use synonyms at query time
        <filter class="solr.SynonymFilterFactory" synonyms="index_synonyms.txt" ignoreCase="true" expand="false"/>
        -->
        <!-- Case insensitive stop word removal.
        -->
        <filter class="solr.StopFilterFactory"
                ignoreCase="true"
                words="lang/stopwords_en.txt"
                />
        <filter class="solr.LowerCaseFilterFactory"/>
        <filter class="solr.EnglishPossessiveFilterFactory"/>
        <filter class="solr.KeywordMarkerFilterFactory" protected="protwords.txt"/>
        <!-- Optionally you may want to use this less aggressive stemmer instead of PorterStemFilterFactory:
              <filter class="solr.EnglishMinimalStemFilterFactory"/>
        -->
        <filter class="solr.PorterStemFilterFactory"/>
      </analyzer>
      <analyzer type="query">
        <tokenizer class="solr.StandardTokenizerFactory"/>
        <filter class="solr.SynonymFilterFactory" synonyms="synonyms.txt" ignoreCase="true" expand="true"/>
        <filter class="solr.StopFilterFactory"
                ignoreCase="true"
                words="lang/stopwords_en.txt"
                />
        <filter class="solr.LowerCaseFilterFactory"/>
        <filter class="solr.EnglishPossessiveFilterFactory"/>
        <filter class="solr.KeywordMarkerFilterFactory" protected="protwords.txt"/>
        <!-- Optionally you may want to use this less aggressive stemmer instead of PorterStemFilterFactory:
              <filter class="solr.EnglishMinimalStemFilterFactory"/>
        -->
        <filter class="solr.PorterStemFilterFactory"/>
      </analyzer>
    </fieldType>

    <!-- A text field with defaults appropriate for English, plus
	 aggressive word-splitting and autophrase features enabled.
	 This field is just like text_en, except it adds
	 WordDelimiterFilter to enable splitting and matching of
	 words on case-change, alpha numeric boundaries, and
	 non-alphanumeric chars.  This means certain compound word
	 cases will work, for example query "wi fi" will match
	 document "WiFi" or "wi-fi".
        -->
    <fieldType name="text_en_splitting" class="solr.TextField" positionIncrementGap="100"
               autoGeneratePhraseQueries="true">
      <analyzer type="index">
        <tokenizer class="solr.WhitespaceTokenizerFactory"/>
        <!-- in this example, we will only use synonyms at query time
        <filter class="solr.SynonymFilterFactory" synonyms="index_synonyms.txt" ignoreCase="true" expand="false"/>
        -->
        <!-- Case insensitive stop word removal.
        -->
        <filter class="solr.StopFilterFactory"
                ignoreCase="true"
                words="lang/stopwords_en.txt"
                />
        <filter class="solr.WordDelimiterFilterFactory" generateWordParts="1" generateNumberParts="1" catenateWords="1"
                catenateNumbers="1" catenateAll="0" splitOnCaseChange="1"/>
        <filter class="solr.LowerCaseFilterFactory"/>
        <filter class="solr.KeywordMarkerFilterFactory" protected="protwords.txt"/>
        <filter class="solr.PorterStemFilterFactory"/>
      </analyzer>
      <analyzer type="query">
        <tokenizer class="solr.WhitespaceTokenizerFactory"/>
        <filter class="solr.SynonymFilterFactory" synonyms="synonyms.txt" ignoreCase="true" expand="true"/>
        <filter class="solr.StopFilterFactory"
                ignoreCase="true"
                words="lang/stopwords_en.txt"
                />
        <filter class="solr.WordDelimiterFilterFactory" generateWordParts="1" generateNumberParts="1" catenateWords="0"
                catenateNumbers="0" catenateAll="0" splitOnCaseChange="1"/>
        <filter class="solr.LowerCaseFilterFactory"/>
        <filter class="solr.KeywordMarkerFilterFactory" protected="protwords.txt"/>
        <filter class="solr.PorterStemFilterFactory"/>
      </analyzer>
    </fieldType>

    <!-- Less flexible matching, but less false matches.  Probably not ideal for product names,
         but may be good for SKUs.  Can insert dashes in the wrong place and still match. -->
    <fieldType name="text_en_splitting_tight" class="solr.TextField" positionIncrementGap="100"
               autoGeneratePhraseQueries="true">
      <analyzer>
        <tokenizer class="solr.WhitespaceTokenizerFactory"/>
        <filter class="solr.SynonymFilterFactory" synonyms="synonyms.txt" ignoreCase="true" expand="false"/>
        <filter class="solr.StopFilterFactory" ignoreCase="true" words="lang/stopwords_en.txt"/>
        <filter class="solr.WordDelimiterFilterFactory" generateWordParts="0" generateNumberParts="0" catenateWords="1"
                catenateNumbers="1" catenateAll="0"/>
        <filter class="solr.LowerCaseFilterFactory"/>
        <filter class="solr.KeywordMarkerFilterFactory" protected="protwords.txt"/>
        <filter class="solr.EnglishMinimalStemFilterFactory"/>
        <!-- this filter can remove any duplicate tokens that appear at the same position - sometimes
             possible with WordDelimiterFilter in conjuncton with stemming. -->
        <filter class="solr.RemoveDuplicatesTokenFilterFactory"/>
      </analyzer>
    </fieldType>

    <!-- Just like text_general except it reverses the characters of
	 each token, to enable more efficient leading wildcard queries. -->
    <fieldType name="text_general_rev" class="solr.TextField" positionIncrementGap="100">
      <analyzer type="index">
        <tokenizer class="solr.StandardTokenizerFactory"/>
        <filter class="solr.StopFilterFactory" ignoreCase="true" words="stopwords.txt"/>
        <filter class="solr.LowerCaseFilterFactory"/>
        <filter class="solr.ReversedWildcardFilterFactory" withOriginal="true"
                maxPosAsterisk="3" maxPosQuestion="2" maxFractionAsterisk="0.33"/>
      </analyzer>
      <analyzer type="query">
        <tokenizer class="solr.StandardTokenizerFactory"/>
        <filter class="solr.SynonymFilterFactory" synonyms="synonyms.txt" ignoreCase="true" expand="true"/>
        <filter class="solr.StopFilterFactory" ignoreCase="true" words="stopwords.txt"/>
        <filter class="solr.LowerCaseFilterFactory"/>
      </analyzer>
    </fieldType>

    <!-- charFilter + WhitespaceTokenizer  -->
    <!--
    <fieldType name="text_char_norm" class="solr.TextField" positionIncrementGap="100" >
      <analyzer>
        <charFilter class="solr.MappingCharFilterFactory" mapping="mapping-ISOLatin1Accent.txt"/>
        <tokenizer class="solr.WhitespaceTokenizerFactory"/>
      </analyzer>
    </fieldType>
    -->

    <!-- This is an example of using the KeywordTokenizer along
         With various TokenFilterFactories to produce a sortable field
         that does not include some properties of the source text
      -->
    <fieldType name="alphaOnlySort" class="solr.TextField" sortMissingLast="true" omitNorms="true">
      <analyzer>
        <!-- KeywordTokenizer does no actual tokenizing, so the entire
             input string is preserved as a single token
          -->
        <tokenizer class="solr.KeywordTokenizerFactory"/>
        <!-- The LowerCase TokenFilter does what you expect, which can be
             when you want your sorting to be case insensitive
          -->
        <filter class="solr.LowerCaseFilterFactory"/>
        <!-- The TrimFilter removes any leading or trailing whitespace -->
        <filter class="solr.TrimFilterFactory"/>
        <!-- The PatternReplaceFilter gives you the flexibility to use
             Java Regular expression to replace any sequence of characters
             matching a pattern with an arbitrary replacement string,
             which may include back references to portions of the original
             string matched by the pattern.

             See the Java Regular Expression documentation for more
             information on pattern and replacement string syntax.

             http://java.sun.com/j2se/1.6.0/docs/api/java/util/regex/package-summary.html
          -->
        <filter class="solr.PatternReplaceFilterFactory"
                pattern="([^a-z])" replacement="" replace="all"
                />
      </analyzer>
    </fieldType>

    <fieldtype name="phonetic" stored="false" indexed="true" class="solr.TextField">
      <analyzer>
        <tokenizer class="solr.StandardTokenizerFactory"/>
        <filter class="solr.DoubleMetaphoneFilterFactory" inject="false"/>
      </analyzer>
    </fieldtype>

    <!-- lowercases the entire field value, keeping it as a single token.  -->
    <fieldType name="lowercase" class="solr.TextField" positionIncrementGap="100">
      <analyzer>
        <tokenizer class="solr.KeywordTokenizerFactory"/>
        <filter class="solr.LowerCaseFilterFactory"/>
      </analyzer>
    </fieldType>

    <!-- since fields of this type are by default not stored or indexed,
         any data added to them will be ignored outright.  -->
    <fieldtype name="ignored" stored="false" indexed="false" multiValued="true" class="solr.StrField"/>

  </types>

  <!-- Similarity is the scoring routine for each document vs. a query.
       A custom Similarity or SimilarityFactory may be specified here, but
       the default is fine for most applications.
       For more info: http://wiki.apache.org/solr/SchemaXml#Similarity
    -->
  <!--
     <similarity class="com.example.solr.CustomSimilarityFactory">
       <str name="paramkey">param value</str>
     </similarity>
    -->

</schema>


text:
#include <linux/types.h>

/*  ----------------------------------- Host OS */
#include <dspbridge/host_os.h>

/*  ----------------------------------- DSP/BIOS Bridge */
#include <dspbridge/dbdefs.h>

/*  ----------------------------------- Trace & Debug */
#include <dspbridge/dbc.h>

/*  ----------------------------------- OS Adaptation Layer */
#include <dspbridge/ntfy.h>

/*  ----------------------------------- Platform Manager */
#include <dspbridge/chnl.h>
#include <dspbridge/dev.h>
#include <dspbridge/drv.h>

#include <dspbridge/proc.h>
#include <dspbridge/strm.h>

/*  ----------------------------------- Resource Manager */
#include <dspbridge/disp.h>
#include <dspbridge/mgr.h>
#include <dspbridge/node.h>
#include <dspbridge/rmm.h>

/*  ----------------------------------- Others */
#include <dspbridge/msg.h>
#include <dspbridge/cmm.h>
#include <dspbridge/io.h>

/*  ----------------------------------- This */
#include <dspbridge/dspapi.h>
#include <dspbridge/dbdcd.h>

#include <dspbridge/resourcecleanup.h>

/*  ----------------------------------- Defines, Data Structures, Typedefs */
#define MAX_TRACEBUFLEN 255
#define MAX_LOADARGS    16
#define MAX_NODES       64
#define MAX_STREAMS     16
#define MAX_BUFS	64

/* Used to get dspbridge ioctl table */
#define DB_GET_IOC_TABLE(cmd)	(DB_GET_MODULE(cmd) >> DB_MODULE_SHIFT)

/* Device IOCtl function pointer */
struct api_cmd {
	u32(*fxn) (union trapped_args *args, void *pr_ctxt);
	u32 index;
};

/*  ----------------------------------- Globals */
static u32 api_c_refs;

/*
 *  Function tables.
 *  The order of these functions MUST be the same as the order of the command
 *  numbers defined in dspapi-ioctl.h  This is how an IOCTL number in user mode
 *  turns into a function call in kernel mode.
 */

/* MGR wrapper functions */
static struct api_cmd mgr_cmd[] = {
	{mgrwrap_enum_node_info},	/* MGR_ENUMNODE_INFO */
	{mgrwrap_enum_proc_info},	/* MGR_ENUMPROC_INFO */
	{mgrwrap_register_object},	/* MGR_REGISTEROBJECT */
	{mgrwrap_unregister_object},	/* MGR_UNREGISTEROBJECT */
	{mgrwrap_wait_for_bridge_events},	/* MGR_WAIT */
	{mgrwrap_get_process_resources_info},	/* MGR_GET_PROC_RES */
};

/* PROC wrapper functions */
static struct api_cmd proc_cmd[] = {
	{procwrap_attach},	/* PROC_ATTACH */
	{procwrap_ctrl},	/* PROC_CTRL */
	{procwrap_detach},	/* PROC_DETACH */
	{procwrap_enum_node_info},	/* PROC_ENUMNODE */
	{procwrap_enum_resources},	/* PROC_ENUMRESOURCES */
	{procwrap_get_state},	/* PROC_GET_STATE */
	{procwrap_get_trace},	/* PROC_GET_TRACE */
	{procwrap_load},	/* PROC_LOAD */
	{procwrap_register_notify},	/* PROC_REGISTERNOTIFY */
	{procwrap_start},	/* PROC_START */
	{procwrap_reserve_memory},	/* PROC_RSVMEM */
	{procwrap_un_reserve_memory},	/* PROC_UNRSVMEM */
	{procwrap_map},		/* PROC_MAPMEM */
	{procwrap_un_map},	/* PROC_UNMAPMEM */
	{procwrap_flush_memory},	/* PROC_FLUSHMEMORY */
	{procwrap_stop},	/* PROC_STOP */
	{procwrap_invalidate_memory},	/* PROC_INVALIDATEMEMORY */
	{procwrap_begin_dma},	/* PROC_BEGINDMA */
	{procwrap_end_dma},	/* PROC_ENDDMA */
};

/* NODE wrapper functions */
static struct api_cmd node_cmd[] = {
	{nodewrap_allocate},	/* NODE_ALLOCATE */
	{nodewrap_alloc_msg_buf},	/* NODE_ALLOCMSGBUF */
	{nodewrap_change_priority},	/* NODE_CHANGEPRIORITY */
	{nodewrap_connect},	/* NODE_CONNECT */
	{nodewrap_create},	/* NODE_CREATE */
	{nodewrap_delete},	/* NODE_DELETE */
	{nodewrap_free_msg_buf},	/* NODE_FREEMSGBUF */
	{nodewrap_get_attr},	/* NODE_GETATTR */
	{nodewrap_get_message},	/* NODE_GETMESSAGE */
	{nodewrap_pause},	/* NODE_PAUSE */
	{nodewrap_put_message},	/* NODE_PUTMESSAGE */
	{nodewrap_register_notify},	/* NODE_REGISTERNOTIFY */
	{nodewrap_run},		/* NODE_RUN */
	{nodewrap_terminate},	/* NODE_TERMINATE */
	{nodewrap_get_uuid_props},	/* NODE_GETUUIDPROPS */
};

/* STRM wrapper functions */
static struct api_cmd strm_cmd[] = {
	{strmwrap_allocate_buffer},	/* STRM_ALLOCATEBUFFER */
	{strmwrap_close},	/* STRM_CLOSE */
	{strmwrap_free_buffer},	/* STRM_FREEBUFFER */
	{strmwrap_get_event_handle},	/* STRM_GETEVENTHANDLE */
	{strmwrap_get_info},	/* STRM_GETINFO */
	{strmwrap_idle},	/* STRM_IDLE */
	{strmwrap_issue},	/* STRM_ISSUE */
	{strmwrap_open},	/* STRM_OPEN */
	{strmwrap_reclaim},	/* STRM_RECLAIM */
	{strmwrap_register_notify},	/* STRM_REGISTERNOTIFY */
	{strmwrap_select},	/* STRM_SELECT */
};

/* CMM wrapper functions */
static struct api_cmd cmm_cmd[] = {
	{cmmwrap_calloc_buf},	/* CMM_ALLOCBUF */
	{cmmwrap_free_buf},	/* CMM_FREEBUF */
	{cmmwrap_get_handle},	/* CMM_GETHANDLE */
	{cmmwrap_get_info},	/* CMM_GETINFO */
};

/* Array used to store ioctl table sizes. It can hold up to 8 entries */
static u8 size_cmd[] = {
	ARRAY_SIZE(mgr_cmd),
	ARRAY_SIZE(proc_cmd),
	ARRAY_SIZE(node_cmd),
	ARRAY_SIZE(strm_cmd),
	ARRAY_SIZE(cmm_cmd),
};

static inline void _cp_fm_usr(void *to, const void __user * from,
			      int *err, unsigned long bytes)
{
	if (*err)
		return;

	if (unlikely(!from)) {
		*err = -EFAULT;
		return;
	}

	if (unlikely(copy_from_user(to, from, bytes)))
		*err = -EFAULT;
}

#define CP_FM_USR(to, from, err, n)				\
	_cp_fm_usr(to, from, &(err), (n) * sizeof(*(to)))

static inline void _cp_to_usr(void __user *to, const void *from,
			      int *err, unsigned long bytes)
{
	if (*err)
		return;

	if (unlikely(!to)) {
		*err = -EFAULT;
		return;
	}

	if (unlikely(copy_to_user(to, from, bytes)))
		*err = -EFAULT;
}

#define CP_TO_USR(to, from, err, n)				\
	_cp_to_usr(to, from, &(err), (n) * sizeof(*(from)))

/*
 *  ======== api_call_dev_ioctl ========
 *  Purpose:
 *      Call the (wrapper) function for the corresponding API IOCTL.
 */
inline int api_call_dev_ioctl(u32 cmd, union trapped_args *args,
				      u32 *result, void *pr_ctxt)
{
	u32(*ioctl_cmd) (union trapped_args *args, void *pr_ctxt) = NULL;
	int i;

	if (_IOC_TYPE(cmd) != DB) {
		pr_err("%s: Incompatible dspbridge ioctl number\n", __func__);
		goto err;
	}

	if (DB_GET_IOC_TABLE(cmd) > ARRAY_SIZE(size_cmd)) {
		pr_err("%s: undefined ioctl module\n", __func__);
		goto err;
	}

	/* Check the size of the required cmd table */
	i = DB_GET_IOC(cmd);
	if (i > size_cmd[DB_GET_IOC_TABLE(cmd)]) {
		pr_err("%s: requested ioctl %d out of bounds for table %d\n",
		       __func__, i, DB_GET_IOC_TABLE(cmd));
		goto err;
	}

	switch (DB_GET_MODULE(cmd)) {
	case DB_MGR:
		ioctl_cmd = mgr_cmd[i].fxn;
		break;
	case DB_PROC:
		ioctl_cmd = proc_cmd[i].fxn;
		break;
	case DB_NODE:
		ioctl_cmd = node_cmd[i].fxn;
		break;
	case DB_STRM:
		ioctl_cmd = strm_cmd[i].fxn;
		break;
	case DB_CMM:
		ioctl_cmd = cmm_cmd[i].fxn;
		break;
	}

	if (!ioctl_cmd) {
		pr_err("%s: requested ioctl not defined\n", __func__);
		goto err;
	} else {
		*result = (*ioctl_cmd) (args, pr_ctxt);
	}

	return 0;

err:
	return -EINVAL;
}

/*
 *  ======== api_exit ========
 */
void api_exit(void)
{
	DBC_REQUIRE(api_c_refs > 0);
	api_c_refs--;

	if (api_c_refs == 0) {
		/* Release all modules initialized in api_init(). */
		cod_exit();
		dev_exit();
		chnl_exit();
		msg_exit();
		io_exit();
		strm_exit();
		disp_exit();
		node_exit();
		proc_exit();
		mgr_exit();
		rmm_exit();
		drv_exit();
	}
	DBC_ENSURE(api_c_refs >= 0);
}

/*
 *  ======== api_init ========
 *  Purpose:
 *      Module initialization used by Bridge API.
 */
bool api_init(void)
{
	bool ret = true;
	bool fdrv, fdev, fcod, fchnl, fmsg, fio;
	bool fmgr, fproc, fnode, fdisp, fstrm, frmm;

	if (api_c_refs == 0) {
		/* initialize driver and other modules */
		fdrv = drv_init();
		fmgr = mgr_init();
		fproc = proc_init();
		fnode = node_init();
		fdisp = disp_init();
		fstrm = strm_init();
		frmm = rmm_init();
		fchnl = chnl_init();
		fmsg = msg_mod_init();
		fio = io_init();
		fdev = dev_init();
		fcod = cod_init();
		ret = fdrv && fdev && fchnl && fcod && fmsg && fio;
		ret = ret && fmgr && fproc && frmm;
		if (!ret) {
			if (fdrv)
				drv_exit();

			if (fmgr)
				mgr_exit();

			if (fstrm)
				strm_exit();

			if (fproc)
				proc_exit();

			if (fnode)
				node_exit();

			if (fdisp)
				disp_exit();

			if (fchnl)
				chnl_exit();

			if (fmsg)
				msg_exit();

			if (fio)
				io_exit();

			if (fdev)
				dev_exit();

			if (fcod)
				cod_exit();

			if (frmm)
				rmm_exit();

		}
	}
	if (ret)
		api_c_refs++;

	return ret;
}

/*
 *  ======== api_init_complete2 ========
 *  Purpose:
 *      Perform any required bridge initialization which cannot
 *      be performed in api_init() or dev_start_device() due
 *      to the fact that some services are not yet
 *      completely initialized.
 *  Parameters:
 *  Returns:
 *      0:	Allow this device to load
 *      -EPERM:      Failure.
 *  Requires:
 *      Bridge API initialized.
 *  Ensures:
 */
int api_init_complete2(void)
{
	int status = 0;
	struct cfg_devnode *dev_node;
	struct dev_object *hdev_obj;
	struct drv_data *drv_datap;
	u8 dev_type;

	DBC_REQUIRE(api_c_refs > 0);

	/*  Walk the list of DevObjects, get each devnode, and attempting to
	 *  autostart the board. Note that this requires COF loading, which
	 *  requires KFILE. */
	for (hdev_obj = dev_get_first(); hdev_obj != NULL;
	     hdev_obj = dev_get_next(hdev_obj)) {
		if (dev_get_dev_node(hdev_obj, &dev_node))
			continue;

		if (dev_get_dev_type(hdev_obj, &dev_type))
			continue;

		if ((dev_type == DSP_UNIT) || (dev_type == IVA_UNIT)) {
			drv_datap = dev_get_drvdata(bridge);

			if (drv_datap && drv_datap->base_img)
				proc_auto_start(dev_node, hdev_obj);
		}
	}

	return status;
}

/* TODO: Remove deprecated and not implemented ioctl wrappers */

/*
 * ======== mgrwrap_enum_node_info ========
 */
u32 mgrwrap_enum_node_info(union trapped_args *args, void *pr_ctxt)
{
	u8 *pndb_props;
	u32 num_nodes;
	int status = 0;
	u32 size = args->args_mgr_enumnode_info.ndb_props_size;

	if (size < sizeof(struct dsp_ndbprops))
		return -EINVAL;

	pndb_props = kmalloc(size, GFP_KERNEL);
	if (pndb_props == NULL)
		status = -ENOMEM;

	if (!status) {
		status =
		    mgr_enum_node_info(args->args_mgr_enumnode_info.node_id,
				       (struct dsp_ndbprops *)pndb_props, size,
				       &num_nodes);
	}
	CP_TO_USR(args->args_mgr_enumnode_info.ndb_props, pndb_props, status,
		  size);
	CP_TO_USR(args->args_mgr_enumnode_info.num_nodes, &num_nodes, status,
		  1);
	kfree(pndb_props);

	return status;
}

/*
 * ======== mgrwrap_enum_proc_info ========
 */
u32 mgrwrap_enum_proc_info(union trapped_args *args, void *pr_ctxt)
{
	u8 *processor_info;
	u8 num_procs;
	int status = 0;
	u32 size = args->args_mgr_enumproc_info.processor_info_size;

	if (size < sizeof(struct dsp_processorinfo))
		return -EINVAL;

	processor_info = kmalloc(size, GFP_KERNEL);
	if (processor_info == NULL)
		status = -ENOMEM;

	if (!status) {
		status =
		    mgr_enum_processor_info(args->args_mgr_enumproc_info.
					    processor_id,
					    (struct dsp_processorinfo *)
					    processor_info, size, &num_procs);
	}
	CP_TO_USR(args->args_mgr_enumproc_info.processor_info, processor_info,
		  status, size);
	CP_TO_USR(args->args_mgr_enumproc_info.num_procs, &num_procs,
		  status, 1);
	kfree(processor_info);

	return status;
}

#define WRAP_MAP2CALLER(x) x
/*
 * ======== mgrwrap_register_object ========
 */
u32 mgrwrap_register_object(union trapped_args *args, void *pr_ctxt)
{
	u32 ret;
	struct dsp_uuid uuid_obj;
	u32 path_size = 0;
	char *psz_path_name = NULL;
	int status = 0;

	CP_FM_USR(&uuid_obj, args->args_mgr_registerobject.uuid_obj, status, 1);
	if (status)
		goto func_end;
	/* path_size is increased by 1 to accommodate NULL */
	path_size = strlen_user((char *)
				args->args_mgr_registerobject.sz_path_name) +
	    1;
	psz_path_name = kmalloc(path_size, GFP_KERNEL);
	if (!psz_path_name) {
		status = -ENOMEM;
		goto func_end;
	}
	ret = strncpy_from_user(psz_path_name,
				(char *)args->args_mgr_registerobject.
				sz_path_name, path_size);
	if (!ret) {
		status = -EFAULT;
		goto func_end;
	}

	if (args->args_mgr_registerobject.obj_type >= DSP_DCDMAXOBJTYPE) {
		status = -EINVAL;
		goto func_end;
	}

	status = dcd_register_object(&uuid_obj,
				     args->args_mgr_registerobject.obj_type,
				     (char *)psz_path_name);
func_end:
	kfree(psz_path_name);
	return status;
}

/*
 * ======== mgrwrap_unregister_object ========
 */
u32 mgrwrap_unregister_object(union trapped_args *args, void *pr_ctxt)
{
	int status = 0;
	struct dsp_uuid uuid_obj;

	CP_FM_USR(&uuid_obj, args->args_mgr_registerobject.uuid_obj, status, 1);
	if (status)
		goto func_end;

	status = dcd_unregister_object(&uuid_obj,
				       args->args_mgr_unregisterobject.
				       obj_type);
func_end:
	return status;

}

/*
 * ======== mgrwrap_wait_for_bridge_events ========
 */
u32 mgrwrap_wait_for_bridge_events(union trapped_args *args, void *pr_ctxt)
{
	int status = 0;
	struct dsp_notification *anotifications[MAX_EVENTS];
	struct dsp_notification notifications[MAX_EVENTS];
	u32 index, i;
	u32 count = args->args_mgr_wait.count;

	if (count > MAX_EVENTS)
		status = -EINVAL;

	/* get the array of pointers to user structures */
	CP_FM_USR(anotifications, args->args_mgr_wait.anotifications,
		  status, count);
	/* get the events */
	for (i = 0; i < count; i++) {
		CP_FM_USR(&notifications[i], anotifications[i], status, 1);
		if (status || !notifications[i].handle) {
			status = -EINVAL;
			break;
		}
		/* set the array of pointers to kernel structures */
		anotifications[i] = &notifications[i];
	}
	if (!status) {
		status = mgr_wait_for_bridge_events(anotifications, count,
							 &index,
							 args->args_mgr_wait.
							 timeout);
	}
	CP_TO_USR(args->args_mgr_wait.index, &index, status, 1);
	return status;
}

/*
 * ======== MGRWRAP_GetProcessResourceInfo ========
 */
u32 __deprecated mgrwrap_get_process_resources_info(union trapped_args * args,
						    void *pr_ctxt)
{
	pr_err("%s: deprecated dspbridge ioctl\n", __func__);
	return 0;
}

/*
 * ======== procwrap_attach ========
 */
u32 procwrap_attach(union trapped_args *args, void *pr_ctxt)
{
	void *processor;
	int status = 0;
	struct dsp_processorattrin proc_attr_in, *attr_in = NULL;

	/* Optional argument */
	if (args->args_proc_attach.attr_in) {
		CP_FM_USR(&proc_attr_in, args->args_proc_attach.attr_in, status,
			  1);
		if (!status)
			attr_in = &proc_attr_in;
		else
			goto func_end;

	}
	status = proc_attach(args->args_proc_attach.processor_id, attr_in,
			     &processor, pr_ctxt);
	CP_TO_USR(args->args_proc_attach.ph_processor, &processor, status, 1);
func_end:
	return status;
}

/*
 * ======== procwrap_ctrl ========
 */
u32 procwrap_ctrl(union trapped_args *args, void *pr_ctxt)
{
	u32 cb_data_size, __user * psize = (u32 __user *)
	    args->args_proc_ctrl.args;
	u8 *pargs = NULL;
	int status = 0;
	void *hprocessor = ((struct process_context *)pr_ctxt)->processor;

	if (psize) {
		if (get_user(cb_data_size, psize)) {
			status = -EPERM;
			goto func_end;
		}
		cb_data_size += sizeof(u32);
		pargs = kmalloc(cb_data_size, GFP_KERNEL);
		if (pargs == NULL) {
			status = -ENOMEM;
			goto func_end;
		}

		CP_FM_USR(pargs, args->args_proc_ctrl.args, status,
			  cb_data_size);
	}
	if (!status) {
		status = proc_ctrl(hprocessor,
				   args->args_proc_ctrl.cmd,
				   (struct dsp_cbdata *)pargs);
	}

	/* CP_TO_USR(args->args_proc_ctrl.args, pargs, status, 1); */
	kfree(pargs);
func_end:
	return status;
}

/*
 * ======== procwrap_detach ========
 */
u32 __deprecated procwrap_detach(union trapped_args * args, void *pr_ctxt)
{
	/* proc_detach called at bridge_release only */
	pr_err("%s: deprecated dspbridge ioctl\n", __func__);
	return 0;
}

/*
 * ======== procwrap_enum_node_info ========
 */
u32 procwrap_enum_node_info(union trapped_args *args, void *pr_ctxt)
{
	int status;
	void *node_tab[MAX_NODES];
	u32 num_nodes;
	u32 alloc_cnt;
	void *hprocessor = ((struct process_context *)pr_ctxt)->processor;

	if (!args->args_proc_enumnode_info.node_tab_size)
		return -EINVAL;

	status = proc_enum_nodes(hprocessor,
				 node_tab,
				 args->args_proc_enumnode_info.node_tab_size,
				 &num_nodes, &alloc_cnt);
	CP_TO_USR(args->args_proc_enumnode_info.node_tab, node_tab, status,
		  num_nodes);
	CP_TO_USR(args->args_proc_enumnode_info.num_nodes, &num_nodes,
		  status, 1);
	CP_TO_USR(args->args_proc_enumnode_info.allocated, &alloc_cnt,
		  status, 1);
	return status;
}

u32 procwrap_end_dma(union trapped_args *args, void *pr_ctxt)
{
	int status;

	if (args->args_proc_dma.dir >= DMA_NONE)
		return -EINVAL;

	status = proc_end_dma(pr_ctxt,
				   args->args_proc_dma.mpu_addr,
				   args->args_proc_dma.size,
				   args->args_proc_dma.dir);
	return status;
}

u32 procwrap_begin_dma(union trapped_args *args, void *pr_ctxt)
{
	int status;

	if (args->args_proc_dma.dir >= DMA_NONE)
		return -EINVAL;

	status = proc_begin_dma(pr_ctxt,
				   args->args_proc_dma.mpu_addr,
				   args->args_proc_dma.size,
				   args->args_proc_dma.dir);
	return status;
}

/*
 * ======== procwrap_flush_memory ========
 */
u32 procwrap_flush_memory(union trapped_args *args, void *pr_ctxt)
{
	int status;

	if (args->args_proc_flushmemory.flags >
	    PROC_WRITEBACK_INVALIDATE_MEM)
		return -EINVAL;

	status = proc_flush_memory(pr_ctxt,
				   args->args_proc_flushmemory.mpu_addr,
				   args->args_proc_flushmemory.size,
				   args->args_proc_flushmemory.flags);
	return status;
}

/*
 * ======== procwrap_invalidate_memory ========
 */
u32 procwrap_invalidate_memory(union trapped_args *args, void *pr_ctxt)
{
	int status;

	status =
	    proc_invalidate_memory(pr_ctxt,
				   args->args_proc_invalidatememory.mpu_addr,
				   args->args_proc_invalidatememory.size);
	return status;
}

/*
 * ======== procwrap_enum_resources ========
 */
u32 procwrap_enum_resources(union trapped_args *args, void *pr_ctxt)
{
	int status = 0;
	struct dsp_resourceinfo resource_info;
	void *hprocessor = ((struct process_context *)pr_ctxt)->processor;

	if (args->args_proc_enumresources.resource_info_size <
	    sizeof(struct dsp_resourceinfo))
		return -EINVAL;

	status =
	    proc_get_resource_info(hprocessor,
				   args->args_proc_enumresources.resource_type,
				   &resource_info,
				   args->args_proc_enumresources.
				   resource_info_size);

	CP_TO_USR(args->args_proc_enumresources.resource_info, &resource_info,
		  status, 1);

	return status;

}

/*
 * ======== procwrap_get_state ========
 */
u32 procwrap_get_state(union trapped_args *args, void *pr_ctxt)
{
	int status;
	struct dsp_processorstate proc_state;
	void *hprocessor = ((struct process_context *)pr_ctxt)->processor;

	if (args->args_proc_getstate.state_info_size <
	    sizeof(struct dsp_processorstate))
		return -EINVAL;

	status = proc_get_state(hprocessor, &proc_state,
			   args->args_proc_getstate.state_info_size);
	CP_TO_USR(args->args_proc_getstate.proc_state_obj, &proc_state, status,
		  1);
	return status;

}

/*
 * ======== procwrap_get_trace ========
 */
u32 procwrap_get_trace(union trapped_args *args, void *pr_ctxt)
{
	int status;
	u8 *pbuf;
	void *hprocessor = ((struct process_context *)pr_ctxt)->processor;

	if (args->args_proc_gettrace.max_size > MAX_TRACEBUFLEN)
		return -EINVAL;

	pbuf = kzalloc(args->args_proc_gettrace.max_size, GFP_KERNEL);
	if (pbuf != NULL) {
		status = proc_get_trace(hprocessor, pbuf,
					args->args_proc_gettrace.max_size);
	} else {
		status = -ENOMEM;
	}
	CP_TO_USR(args->args_proc_gettrace.buf, pbuf, status,
		  args->args_proc_gettrace.max_size);
	kfree(pbuf);

	return status;
}

/*
 * ======== procwrap_load ========
 */
u32 procwrap_load(union trapped_args *args, void *pr_ctxt)
{
	s32 i, len;
	int status = 0;
	char *temp;
	s32 count = args->args_proc_load.argc_index;
	u8 **argv = NULL, **envp = NULL;
	void *hprocessor = ((struct process_context *)pr_ctxt)->processor;

	if (count <= 0 || count > MAX_LOADARGS) {
		status = -EINVAL;
		goto func_cont;
	}

	argv = kmalloc(count * sizeof(u8 *), GFP_KERNEL);
	if (!argv) {
		status = -ENOMEM;
		goto func_cont;
	}

	CP_FM_USR(argv, args->args_proc_load.user_args, status, count);
	if (status) {
		kfree(argv);
		argv = NULL;
		goto func_cont;
	}

	for (i = 0; i < count; i++) {
		if (argv[i]) {
			/* User space pointer to argument */
			temp = (char *)argv[i];
			/* len is increased by 1 to accommodate NULL */
			len = strlen_user((char *)temp) + 1;
			/* Kernel space pointer to argument */
			argv[i] = kmalloc(len, GFP_KERNEL);
			if (argv[i]) {
				CP_FM_USR(argv[i], temp, status, len);
				if (status) {
					kfree(argv[i]);
					argv[i] = NULL;
					goto func_cont;
				}
			} else {
				status = -ENOMEM;
				goto func_cont;
			}
		}
	}
	/* TODO: validate this */
	if (args->args_proc_load.user_envp) {
		/* number of elements in the envp array including NULL */
		count = 0;
		do {
			if (get_user(temp,
				     args->args_proc_load.user_envp + count)) {
				status = -EFAULT;
				goto func_cont;
			}
			count++;
		} while (temp);
		envp = kmalloc(count * sizeof(u8 *), GFP_KERNEL);
		if (!envp) {
			status = -ENOMEM;
			goto func_cont;
		}

		CP_FM_USR(envp, args->args_proc_load.user_envp, status, count);
		if (status) {
			kfree(envp);
			envp = NULL;
			goto func_cont;
		}
		for (i = 0; envp[i]; i++) {
			/* User space pointer to argument */
			temp = (char *)envp[i];
			/* len is increased by 1 to accommodate NULL */
			len = strlen_user((char *)temp) + 1;
			/* Kernel space pointer to argument */
			envp[i] = kmalloc(len, GFP_KERNEL);
			if (envp[i]) {
				CP_FM_USR(envp[i], temp, status, len);
				if (status) {
					kfree(envp[i]);
					envp[i] = NULL;
					goto func_cont;
				}
			} else {
				status = -ENOMEM;
				goto func_cont;
			}
		}
	}

	if (!status) {
		status = proc_load(hprocessor,
				   args->args_proc_load.argc_index,
				   (const char **)argv, (const char **)envp);
	}
func_cont:
	if (envp) {
		i = 0;
		while (envp[i])
			kfree(envp[i++]);

		kfree(envp);
	}

	if (argv) {
		count = args->args_proc_load.argc_index;
		for (i = 0; (i < count) && argv[i]; i++)
			kfree(argv[i]);

		kfree(argv);
	}

	return status;
}

/*
 * ======== procwrap_map ========
 */
u32 procwrap_map(union trapped_args *args, void *pr_ctxt)
{
	int status;
	void *map_addr;
	void *hprocessor = ((struct process_context *)pr_ctxt)->processor;

	if (!args->args_proc_mapmem.size)
		return -EINVAL;

	status = proc_map(args->args_proc_mapmem.processor,
			  args->args_proc_mapmem.mpu_addr,
			  args->args_proc_mapmem.size,
			  args->args_proc_mapmem.req_addr, &map_addr,
			  args->args_proc_mapmem.map_attr, pr_ctxt);
	if (!status) {
		if (put_user(map_addr, args->args_proc_mapmem.map_addr)) {
			status = -EINVAL;
			proc_un_map(hprocessor, map_addr, pr_ctxt);
		}

	}
	return status;
}

/*
 * ======== procwrap_register_notify ========
 */
u32 procwrap_register_notify(union trapped_args *args, void *pr_ctxt)
{
	int status;
	struct dsp_notification notification;
	void *hprocessor = ((struct process_context *)pr_ctxt)->processor;

	/* Initialize the notification data structure */
	notification.name = NULL;
	notification.handle = NULL;

	status = proc_register_notify(hprocessor,
				 args->args_proc_register_notify.event_mask,
				 args->args_proc_register_notify.notify_type,
				 &notification);
	CP_TO_USR(args->args_proc_register_notify.notification, &notification,
		  status, 1);
	return status;
}

/*
 * ======== procwrap_reserve_memory ========
 */
u32 procwrap_reserve_memory(union trapped_args *args, void *pr_ctxt)
{
	int status;
	void *prsv_addr;
	void *hprocessor = ((struct process_context *)pr_ctxt)->processor;

	if ((args->args_proc_rsvmem.size <= 0) ||
	    (args->args_proc_rsvmem.size & (PG_SIZE4K - 1)) != 0)
		return -EINVAL;

	status = proc_reserve_memory(hprocessor,
				     args->args_proc_rsvmem.size, &prsv_addr,
				     pr_ctxt);
	if (!status) {
		if (put_user(prsv_addr, args->args_proc_rsvmem.rsv_addr)) {
			status = -EINVAL;
			proc_un_reserve_memory(args->args_proc_rsvmem.
					       processor, prsv_addr, pr_ctxt);
		}
	}
	return status;
}

/*
 * ======== procwrap_start ========
 */
u32 procwrap_start(union trapped_args *args, void *pr_ctxt)
{
	u32 ret;

	ret = proc_start(((struct process_context *)pr_ctxt)->processor);
	return ret;
}

/*
 * ======== procwrap_un_map ========
 */
u32 procwrap_un_map(union trapped_args *args, void *pr_ctxt)
{
	int status;

	status = proc_un_map(((struct process_context *)pr_ctxt)->processor,
			     args->args_proc_unmapmem.map_addr, pr_ctxt);
	return status;
}

/*
 * ======== procwrap_un_reserve_memory ========
 */
u32 procwrap_un_reserve_memory(union trapped_args *args, void *pr_ctxt)
{
	int status;
	void *hprocessor = ((struct process_context *)pr_ctxt)->processor;

	status = proc_un_reserve_memory(hprocessor,
					args->args_proc_unrsvmem.rsv_addr,
					pr_ctxt);
	return status;
}

/*
 * ======== procwrap_stop ========
 */
u32 procwrap_stop(union trapped_args *args, void *pr_ctxt)
{
	u32 ret;

	ret = proc_stop(((struct process_context *)pr_ctxt)->processor);

	return ret;
}

/*
 * ======== find_handle =========
 */
inline void find_node_handle(struct node_res_object **noderes,
				void *pr_ctxt, void *hnode)
{
	rcu_read_lock();
	*noderes = idr_find(((struct process_context *)pr_ctxt)->node_id,
								(int)hnode - 1);
	rcu_read_unlock();
	return;
}

/*
 * ======== nodewrap_allocate ========
 */
u32 nodewrap_allocate(union trapped_args *args, void *pr_ctxt)
{
	int status = 0;
	struct dsp_uuid node_uuid;
	u32 cb_data_size = 0;
	u32 __user *psize = (u32 __user *) args->args_node_allocate.args;
	u8 *pargs = NULL;
	struct dsp_nodeattrin proc_attr_in, *attr_in = NULL;
	struct node_res_object *node_res;
	int nodeid;
	void *hprocessor = ((struct process_context *)pr_ctxt)->processor;

	/* Optional argument */
	if (psize) {
		if (get_user(cb_data_size, psize))
			status = -EPERM;

		cb_data_size += sizeof(u32);
		if (!status) {
			pargs = kmalloc(cb_data_size, GFP_KERNEL);
			if (pargs == NULL)
				status = -ENOMEM;

		}
		CP_FM_USR(pargs, args->args_node_allocate.args, status,
			  cb_data_size);
	}
	CP_FM_USR(&node_uuid, args->args_node_allocate.node_id_ptr, status, 1);
	if (status)
		goto func_cont;
	/* Optional argument */
	if (args->args_node_allocate.attr_in) {
		CP_FM_USR(&proc_attr_in, args->args_node_allocate.attr_in,
			  status, 1);
		if (!status)
			attr_in = &proc_attr_in;
		else
			status = -ENOMEM;

	}
	if (!status) {
		status = node_allocate(hprocessor,
				       &node_uuid, (struct dsp_cbdata *)pargs,
				       attr_in, &node_res, pr_ctxt);
	}
	if (!status) {
		nodeid = node_res->id + 1;
		CP_TO_USR(args->args_node_allocate.node, &nodeid,
			status, 1);
		if (status) {
			status = -EFAULT;
			node_delete(node_res, pr_ctxt);
		}
	}
func_cont:
	kfree(pargs);

	return status;
}

/*
 *  ======== nodewrap_alloc_msg_buf ========
 */
u32 nodewrap_alloc_msg_buf(union trapped_args *args, void *pr_ctxt)
{
	int status = 0;
	struct dsp_bufferattr *pattr = NULL;
	struct dsp_bufferattr attr;
	u8 *pbuffer = NULL;
	struct node_res_object *node_res;

	find_node_handle(&node_res,  pr_ctxt,
				args->args_node_allocmsgbuf.node);

	if (!node_res)
		return -EFAULT;

	if (!args->args_node_allocmsgbuf.size)
		return -EINVAL;

	if (args->args_node_allocmsgbuf.attr) {	/* Optional argument */
		CP_FM_USR(&attr, args->args_node_allocmsgbuf.attr, status, 1);
		if (!status)
			pattr = &attr;

	}
	/* argument */
	CP_FM_USR(&pbuffer, args->args_node_allocmsgbuf.buffer, status, 1);
	if (!status) {
		status = node_alloc_msg_buf(node_res->node,
					    args->args_node_allocmsgbuf.size,
					    pattr, &pbuffer);
	}
	CP_TO_USR(args->args_node_allocmsgbuf.buffer, &pbuffer, status, 1);
	return status;
}

/*
 * ======== nodewrap_change_priority ========
 */
u32 nodewrap_change_priority(union trapped_args *args, void *pr_ctxt)
{
	u32 ret;
	struct node_res_object *node_res;

	find_node_handle(&node_res, pr_ctxt,
				args->args_node_changepriority.node);

	if (!node_res)
		return -EFAULT;

	ret = node_change_priority(node_res->node,
				   args->args_node_changepriority.prio);

	return ret;
}

/*
 * ======== nodewrap_connect ========
 */
u32 nodewrap_connect(union trapped_args *args, void *pr_ctxt)
{
	int status = 0;
	struct dsp_strmattr attrs;
	struct dsp_strmattr *pattrs = NULL;
	u32 cb_data_size;
	u32 __user *psize = (u32 __user *) args->args_node_connect.conn_param;
	u8 *pargs = NULL;
	struct node_res_object *node_res1, *node_res2;
	struct node_object *node1 = NULL, *node2 = NULL;

	if ((int)args->args_node_connect.node != DSP_HGPPNODE) {
		find_node_handle(&node_res1, pr_ctxt,
				args->args_node_connect.node);
		if (node_res1)
			node1 = node_res1->node;
	} else {
		node1 = args->args_node_connect.node;
	}

	if ((int)args->args_node_connect.other_node != DSP_HGPPNODE) {
		find_node_handle(&node_res2, pr_ctxt,
				args->args_node_connect.other_node);
		if (node_res2)
			node2 = node_res2->node;
	} else {
		node2 = args->args_node_connect.other_node;
	}

	if (!node1 || !node2)
		return -EFAULT;

	/* Optional argument */
	if (psize) {
		if (get_user(cb_data_size, psize))
			status = -EPERM;

		cb_data_size += sizeof(u32);
		if (!status) {
			pargs = kmalloc(cb_data_size, GFP_KERNEL);
			if (pargs == NULL) {
				status = -ENOMEM;
				goto func_cont;
			}

		}
		CP_FM_USR(pargs, args->args_node_connect.conn_param, status,
			  cb_data_size);
		if (status)
			goto func_cont;
	}
	if (args->args_node_connect.attrs) {	/* Optional argument */
		CP_FM_USR(&attrs, args->args_node_connect.attrs, status, 1);
		if (!status)
			pattrs = &attrs;

	}
	if (!status) {
		status = node_connect(node1,
				      args->args_node_connect.stream_id,
				      node2,
				      args->args_node_connect.other_stream,
				      pattrs, (struct dsp_cbdata *)pargs);
	}
func_cont:
	kfree(pargs);

	return status;
}

/*
 * ======== nodewrap_create ========
 */
u32 nodewrap_create(union trapped_args *args, void *pr_ctxt)
{
	u32 ret;
	struct node_res_object *node_res;

	find_node_handle(&node_res, pr_ctxt, args->args_node_create.node);

	if (!node_res)
		return -EFAULT;

	ret = node_create(node_res->node);

	return ret;
}

/*
 * ======== nodewrap_delete ========
 */
u32 nodewrap_delete(union trapped_args *args, void *pr_ctxt)
{
	u32 ret;
	struct node_res_object *node_res;

	find_node_handle(&node_res, pr_ctxt, args->args_node_delete.node);

	if (!node_res)
		return -EFAULT;

	ret = node_delete(node_res, pr_ctxt);

	return ret;
}

/*
 *  ======== nodewrap_free_msg_buf ========
 */
u32 nodewrap_free_msg_buf(union trapped_args *args, void *pr_ctxt)
{
	int status = 0;
	struct dsp_bufferattr *pattr = NULL;
	struct dsp_bufferattr attr;
	struct node_res_object *node_res;

	find_node_handle(&node_res, pr_ctxt, args->args_node_freemsgbuf.node);

	if (!node_res)
		return -EFAULT;

	if (args->args_node_freemsgbuf.attr) {	/* Optional argument */
		CP_FM_USR(&attr, args->args_node_freemsgbuf.attr, status, 1);
		if (!status)
			pattr = &attr;

	}

	if (!args->args_node_freemsgbuf.buffer)
		return -EFAULT;

	if (!status) {
		status = node_free_msg_buf(node_res->node,
					   args->args_node_freemsgbuf.buffer,
					   pattr);
	}

	return status;
}

/*
 * ======== nodewrap_get_attr ========
 */
u32 nodewrap_get_attr(union trapped_args *args, void *pr_ctxt)
{
	int status = 0;
	struct dsp_nodeattr attr;
	struct node_res_object *node_res;

	find_node_handle(&node_res, pr_ctxt, args->args_node_getattr.node);

	if (!node_res)
		return -EFAULT;

	status = node_get_attr(node_res->node, &attr,
			       args->args_node_getattr.attr_size);
	CP_TO_USR(args->args_node_getattr.attr, &attr, status, 1);

	return status;
}

/*
 * ======== nodewrap_get_message ========
 */
u32 nodewrap_get_message(union trapped_args *args, void *pr_ctxt)
{
	int status;
	struct dsp_msg msg;
	struct node_res_object *node_res;

	find_node_handle(&node_res, pr_ctxt, args->args_node_getmessage.node);

	if (!node_res)
		return -EFAULT;

	status = node_get_message(node_res->node, &msg,
				  args->args_node_getmessage.timeout);

	CP_TO_USR(args->args_node_getmessage.message, &msg, status, 1);

	return status;
}

/*
 * ======== nodewrap_pause ========
 */
u32 nodewrap_pause(union trapped_args *args, void *pr_ctxt)
{
	u32 ret;
	struct node_res_object *node_res;

	find_node_handle(&node_res, pr_ctxt, args->args_node_pause.node);

	if (!node_res)
		return -EFAULT;

	ret = node_pause(node_res->node);

	return ret;
}

/*
 * ======== nodewrap_put_message ========
 */
u32 nodewrap_put_message(union trapped_args *args, void *pr_ctxt)
{
	int status = 0;
	struct dsp_msg msg;
	struct node_res_object *node_res;

	find_node_handle(&node_res, pr_ctxt, args->args_node_putmessage.node);

	if (!node_res)
		return -EFAULT;

	CP_FM_USR(&msg, args->args_node_putmessage.message, status, 1);

	if (!status) {
		status =
		    node_put_message(node_res->node, &msg,
				     args->args_node_putmessage.timeout);
	}

	return status;
}

/*
 * ======== nodewrap_register_notify ========
 */
u32 nodewrap_register_notify(union trapped_args *args, void *pr_ctxt)
{
	int status = 0;
	struct dsp_notification notification;
	struct node_res_object *node_res;

	find_node_handle(&node_res, pr_ctxt,
			args->args_node_registernotify.node);

	if (!node_res)
		return -EFAULT;

	/* Initialize the notification data structure */
	notification.name = NULL;
	notification.handle = NULL;

	if (!args->args_proc_register_notify.event_mask)
		CP_FM_USR(&notification,
			  args->args_proc_register_notify.notification,
			  status, 1);

	status = node_register_notify(node_res->node,
				      args->args_node_registernotify.event_mask,
				      args->args_node_registernotify.
				      notify_type, &notification);
	CP_TO_USR(args->args_node_registernotify.notification, &notification,
		  status, 1);
	return status;
}

/*
 * ======== nodewrap_run ========
 */
u32 nodewrap_run(union trapped_args *args, void *pr_ctxt)
{
	u32 ret;
	struct node_res_object *node_res;

	find_node_handle(&node_res, pr_ctxt, args->args_node_run.node);

	if (!node_res)
		return -EFAULT;

	ret = node_run(node_res->node);

	return ret;
}

/*
 * ======== nodewrap_terminate ========
 */
u32 nodewrap_terminate(union trapped_args *args, void *pr_ctxt)
{
	int status;
	int tempstatus;
	struct node_res_object *node_res;

	find_node_handle(&node_res, pr_ctxt, args->args_node_terminate.node);

	if (!node_res)
		return -EFAULT;

	status = node_terminate(node_res->node, &tempstatus);

	CP_TO_USR(args->args_node_terminate.status, &tempstatus, status, 1);

	return status;
}

/*
 * ======== nodewrap_get_uuid_props ========
 */
u32 nodewrap_get_uuid_props(union trapped_args *args, void *pr_ctxt)
{
	int status = 0;
	struct dsp_uuid node_uuid;
	struct dsp_ndbprops *pnode_props = NULL;
	void *hprocessor = ((struct process_context *)pr_ctxt)->processor;

	CP_FM_USR(&node_uuid, args->args_node_getuuidprops.node_id_ptr, status,
		  1);
	if (status)
		goto func_cont;
	pnode_props = kmalloc(sizeof(struct dsp_ndbprops), GFP_KERNEL);
	if (pnode_props != NULL) {
		status =
		    node_get_uuid_props(hprocessor, &node_uuid, pnode_props);
		CP_TO_USR(args->args_node_getuuidprops.node_props, pnode_props,
			  status, 1);
	} else
		status = -ENOMEM;
func_cont:
	kfree(pnode_props);
	return status;
}

/*
 * ======== find_strm_handle =========
 */
inline void find_strm_handle(struct strm_res_object **strmres,
				void *pr_ctxt, void *hstream)
{
	rcu_read_lock();
	*strmres = idr_find(((struct process_context *)pr_ctxt)->stream_id,
							(int)hstream - 1);
	rcu_read_unlock();
	return;
}

/*
 * ======== strmwrap_allocate_buffer ========
 */
u32 strmwrap_allocate_buffer(union trapped_args *args, void *pr_ctxt)
{
	int status;
	u8 **ap_buffer = NULL;
	u32 num_bufs = args->args_strm_allocatebuffer.num_bufs;
	struct strm_res_object *strm_res;

	find_strm_handle(&strm_res, pr_ctxt,
		args->args_strm_allocatebuffer.stream);

	if (!strm_res)
		return -EFAULT;

	if (num_bufs > MAX_BUFS)
		return -EINVAL;

	ap_buffer = kmalloc((num_bufs * sizeof(u8 *)), GFP_KERNEL);
	if (ap_buffer == NULL)
		return -ENOMEM;

	status = strm_allocate_buffer(strm_res,
				      args->args_strm_allocatebuffer.size,
				      ap_buffer, num_bufs, pr_ctxt);
	if (!status) {
		CP_TO_USR(args->args_strm_allocatebuffer.ap_buffer, ap_buffer,
			  status, num_bufs);
		if (status) {
			status = -EFAULT;
			strm_free_buffer(strm_res,
					 ap_buffer, num_bufs, pr_ctxt);
		}
	}
	kfree(ap_buffer);

	return status;
}

/*
 * ======== strmwrap_close ========
 */
u32 strmwrap_close(union trapped_args *args, void *pr_ctxt)
{
	struct strm_res_object *strm_res;

	find_strm_handle(&strm_res, pr_ctxt, args->args_strm_close.stream);

	if (!strm_res)
		return -EFAULT;

	return strm_close(strm_res, pr_ctxt);
}

/*
 * ======== strmwrap_free_buffer ========
 */
u32 strmwrap_free_buffer(union trapped_args *args, void *pr_ctxt)
{
	int status = 0;
	u8 **ap_buffer = NULL;
	u32 num_bufs = args->args_strm_freebuffer.num_bufs;
	struct strm_res_object *strm_res;

	find_strm_handle(&strm_res, pr_ctxt,
			args->args_strm_freebuffer.stream);

	if (!strm_res)
		return -EFAULT;

	if (num_bufs > MAX_BUFS)
		return -EINVAL;

	ap_buffer = kmalloc((num_bufs * sizeof(u8 *)), GFP_KERNEL);
	if (ap_buffer == NULL)
		return -ENOMEM;

	CP_FM_USR(ap_buffer, args->args_strm_freebuffer.ap_buffer, status,
		  num_bufs);

	if (!status)
		status = strm_free_buffer(strm_res,
					  ap_buffer, num_bufs, pr_ctxt);

	CP_TO_USR(args->args_strm_freebuffer.ap_buffer, ap_buffer, status,
		  num_bufs);
	kfree(ap_buffer);

	return status;
}

/*
 * ======== strmwrap_get_event_handle ========
 */
u32 __deprecated strmwrap_get_event_handle(union trapped_args * args,
					   void *pr_ctxt)
{
	pr_err("%s: deprecated dspbridge ioctl\n", __func__);
	return -ENOSYS;
}

/*
 * ======== strmwrap_get_info ========
 */
u32 strmwrap_get_info(union trapped_args *args, void *pr_ctxt)
{
	int status = 0;
	struct stream_info strm_info;
	struct dsp_streaminfo user;
	struct dsp_streaminfo *temp;
	struct strm_res_object *strm_res;

	find_strm_handle(&strm_res, pr_ctxt,
			args->args_strm_getinfo.stream);

	if (!strm_res)
		return -EFAULT;

	CP_FM_USR(&strm_info, args->args_strm_getinfo.stream_info, status, 1);
	temp = strm_info.user_strm;

	strm_info.user_strm = &user;

	if (!status) {
		status = strm_get_info(strm_res->stream,
				       &strm_info,
				       args->args_strm_getinfo.
				       stream_info_size);
	}
	CP_TO_USR(temp, strm_info.user_strm, status, 1);
	strm_info.user_strm = temp;
	CP_TO_USR(args->args_strm_getinfo.stream_info, &strm_info, status, 1);
	return status;
}

/*
 * ======== strmwrap_idle ========
 */
u32 strmwrap_idle(union trapped_args *args, void *pr_ctxt)
{
	u32 ret;
	struct strm_res_object *strm_res;

	find_strm_handle(&strm_res, pr_ctxt, args->args_strm_idle.stream);

	if (!strm_res)
		return -EFAULT;

	ret = strm_idle(strm_res->stream, args->args_strm_idle.flush_flag);

	return ret;
}

/*
 * ======== strmwrap_issue ========
 */
u32 strmwrap_issue(union trapped_args *args, void *pr_ctxt)
{
	int status = 0;
	struct strm_res_object *strm_res;

	find_strm_handle(&strm_res, pr_ctxt, args->args_strm_issue.stream);

	if (!strm_res)
		return -EFAULT;

	if (!args->args_strm_issue.buffer)
		return -EFAULT;

	/* No need of doing CP_FM_USR for the user buffer (pbuffer)
	   as this is done in Bridge internal function bridge_chnl_add_io_req
	   in chnl_sm.c */
	status = strm_issue(strm_res->stream,
			    args->args_strm_issue.buffer,
			    args->args_strm_issue.bytes,
			    args->args_strm_issue.buf_size,
			    args->args_strm_issue.arg);

	return status;
}

/*
 * ======== strmwrap_open ========
 */
u32 strmwrap_open(union trapped_args *args, void *pr_ctxt)
{
	int status = 0;
	struct strm_attr attr;
	struct strm_res_object *strm_res_obj;
	struct dsp_streamattrin strm_attr_in;
	struct node_res_object *node_res;
	int strmid;

	find_node_handle(&node_res, pr_ctxt, args->args_strm_open.node);

	if (!node_res)
		return -EFAULT;

	CP_FM_USR(&attr, args->args_strm_open.attr_in, status, 1);

	if (attr.stream_attr_in != NULL) {	/* Optional argument */
		CP_FM_USR(&strm_attr_in, attr.stream_attr_in, status, 1);
		if (!status) {
			attr.stream_attr_in = &strm_attr_in;
			if (attr.stream_attr_in->strm_mode == STRMMODE_LDMA)
				return -ENOSYS;
		}

	}
	status = strm_open(node_res->node,
			   args->args_strm_open.direction,
			   args->args_strm_open.index, &attr, &strm_res_obj,
			   pr_ctxt);
	if (!status) {
		strmid = strm_res_obj->id + 1;
		CP_TO_USR(args->args_strm_open.stream, &strmid, status, 1);
	}
	return status;
}

/*
 * ======== strmwrap_reclaim ========
 */
u32 strmwrap_reclaim(union trapped_args *args, void *pr_ctxt)
{
	int status = 0;
	u8 *buf_ptr;
	u32 ul_bytes;
	u32 dw_arg;
	u32 ul_buf_size;
	struct strm_res_object *strm_res;

	find_strm_handle(&strm_res, pr_ctxt, args->args_strm_reclaim.stream);

	if (!strm_res)
		return -EFAULT;

	status = strm_reclaim(strm_res->stream, &buf_ptr,
			      &ul_bytes, &ul_buf_size, &dw_arg);
	CP_TO_USR(args->args_strm_reclaim.buf_ptr, &buf_ptr, status, 1);
	CP_TO_USR(args->args_strm_reclaim.bytes, &ul_bytes, status, 1);
	CP_TO_USR(args->args_strm_reclaim.arg, &dw_arg, status, 1);

	if (args->args_strm_reclaim.buf_size_ptr != NULL) {
		CP_TO_USR(args->args_strm_reclaim.buf_size_ptr, &ul_buf_size,
			  status, 1);
	}

	return status;
}

/*
 * ======== strmwrap_register_notify ========
 */
u32 strmwrap_register_notify(union trapped_args *args, void *pr_ctxt)
{
	int status = 0;
	struct dsp_notification notification;
	struct strm_res_object *strm_res;

	find_strm_handle(&strm_res, pr_ctxt,
			args->args_strm_registernotify.stream);

	if (!strm_res)
		return -EFAULT;

	/* Initialize the notification data structure */
	notification.name = NULL;
	notification.handle = NULL;

	status = strm_register_notify(strm_res->stream,
				      args->args_strm_registernotify.event_mask,
				      args->args_strm_registernotify.
				      notify_type, &notification);
	CP_TO_USR(args->args_strm_registernotify.notification, &notification,
		  status, 1);

	return status;
}

/*
 * ======== strmwrap_select ========
 */
u32 strmwrap_select(union trapped_args *args, void *pr_ctxt)
{
	u32 mask;
	struct strm_object *strm_tab[MAX_STREAMS];
	int status = 0;
	struct strm_res_object *strm_res;
	int *ids[MAX_STREAMS];
	int i;

	if (args->args_strm_select.strm_num > MAX_STREAMS)
		return -EINVAL;

	CP_FM_USR(ids, args->args_strm_select.stream_tab, status,
		args->args_strm_select.strm_num);

	if (status)
		return status;

	for (i = 0; i < args->args_strm_select.strm_num; i++) {
		find_strm_handle(&strm_res, pr_ctxt, ids[i]);

		if (!strm_res)
			return -EFAULT;

		strm_tab[i] = strm_res->stream;
	}

	if (!status) {
		status = strm_select(strm_tab, args->args_strm_select.strm_num,
				     &mask, args->args_strm_select.timeout);
	}
	CP_TO_USR(args->args_strm_select.mask, &mask, status, 1);
	return status;
}

/* CMM */

/*
 * ======== cmmwrap_calloc_buf ========
 */
u32 __deprecated cmmwrap_calloc_buf(union trapped_args * args, void *pr_ctxt)
{
	/* This operation is done in kernel */
	pr_err("%s: deprecated dspbridge ioctl\n", __func__);
	return -ENOSYS;
}

/*
 * ======== cmmwrap_free_buf ========
 */
u32 __deprecated cmmwrap_free_buf(union trapped_args * args, void *pr_ctxt)
{
	/* This operation is done in kernel */
	pr_err("%s: deprecated dspbridge ioctl\n", __func__);
	return -ENOSYS;
}

/*
 * ======== cmmwrap_get_handle ========
 */
u32 cmmwrap_get_handle(union trapped_args *args, void *pr_ctxt)
{
	int status = 0;
	struct cmm_object *hcmm_mgr;
	void *hprocessor = ((struct process_context *)pr_ctxt)->processor;

	status = cmm_get_handle(hprocessor, &hcmm_mgr);

	CP_TO_USR(args->args_cmm_gethandle.cmm_mgr, &hcmm_mgr, status, 1);

	return status;
}

/*
 * ======== cmmwrap_get_info ========
 */
u32 cmmwrap_get_info(union trapped_args *args, void *pr_ctxt)
{
	int status = 0;
	struct cmm_info cmm_info_obj;

	status = cmm_get_info(args->args_cmm_getinfo.cmm_mgr, &cmm_info_obj);

	CP_TO_USR(args->args_cmm_getinfo.cmm_info_obj, &cmm_info_obj, status,
		  1);

	return status;
}


text:
(function(){

  // compat with ie8 in case this gets picked up elsewhere
  var objectCreate = Object.create || function(parent) {
    function F() {}
    F.prototype = parent;
    return new F();
  };

  var RawHandlebars = Handlebars.create();

  RawHandlebars.helper = function() {};
  RawHandlebars.helpers = objectCreate(Handlebars.helpers);

  RawHandlebars.helpers.get = function(context, options){
    var firstContext =  options.contexts[0];
    var val = firstContext[context];

    if (val && val.isDescriptor) { return Em.get(firstContext, context); }
    val = val === undefined ? Em.get(firstContext, context): val;
    return val;
  };

  // adds compatability so this works with stringParams
  var stringCompatHelper = function(fn){

    var old = RawHandlebars.helpers[fn];
    RawHandlebars.helpers[fn] = function(context,options){
      return old.apply(this, [
          RawHandlebars.helpers.get(context,options),
          options
      ]);
    };
  };

  // #each .. in support
  RawHandlebars.registerHelper('each', function(localName,inKeyword,contextName,options){
    var list = Em.get(this, contextName);
    var output = [];
    var innerContext = Object.create(this);
    for (var i=0; i<list.length; i++) {
      innerContext[localName] = list[i];
      output.push(options.fn(innerContext));
    }
    return output.join('');
  });

  stringCompatHelper("if");
  stringCompatHelper("unless");
  stringCompatHelper("with");

  if (Handlebars.Compiler) {
    RawHandlebars.Compiler = function() {};
    RawHandlebars.Compiler.prototype = objectCreate(Handlebars.Compiler.prototype);
    RawHandlebars.Compiler.prototype.compiler = RawHandlebars.Compiler;

    RawHandlebars.JavaScriptCompiler = function() {};

    RawHandlebars.JavaScriptCompiler.prototype = objectCreate(Handlebars.JavaScriptCompiler.prototype);
    RawHandlebars.JavaScriptCompiler.prototype.compiler = RawHandlebars.JavaScriptCompiler;
    RawHandlebars.JavaScriptCompiler.prototype.namespace = "Nilavu.EmberCompatHandlebars";

    function replaceGet(ast) {
      var visitor = new Handlebars.Visitor();
      visitor.mutating = true;

      visitor.MustacheStatement = function(mustache) {
        if (!(mustache.params.length || mustache.hash)) {
          mustache.params[0] = mustache.path;
          mustache.path = {
            type: "PathExpression",
            data: false,
            depth: mustache.path.depth,
            parts: ["get"],
            original: "get",
            loc: mustache.path.loc,
            strict: true,
            falsy: true
          };
        }
        return Handlebars.Visitor.prototype.MustacheStatement.call(this, mustache);
      };
      visitor.accept(ast);
    }

    RawHandlebars.precompile = function(value, asObject) {
      var ast = Handlebars.parse(value);
      replaceGet(ast);

      var options = {
        knownHelpers: {
          get: true
        },
        data: true,
        stringParams: true
      };

      asObject = asObject === undefined ? true : asObject;

      var environment = new RawHandlebars.Compiler().compile(ast, options);
      return new RawHandlebars.JavaScriptCompiler().compile(environment, options, undefined, asObject);
    };

    RawHandlebars.compile = function(string) {
      var ast = Handlebars.parse(string);
      replaceGet(ast);

      // this forces us to rewrite helpers
      var options = {  data: true, stringParams: true };
      var environment = new RawHandlebars.Compiler().compile(ast, options);
      var templateSpec = new RawHandlebars.JavaScriptCompiler().compile(environment, options, undefined, true);

      var template = RawHandlebars.template(templateSpec);
      template.isMethod = false;

      return template;
    };
  }

  RawHandlebars.get = function(ctx, property, options){
    if (options.types && options.data.view) {
      return options.data.view.getStream(property).value();
    } else {
      return Ember.get(ctx, property);
    }
  };

  Nilavu.EmberCompatHandlebars = RawHandlebars;

})();


text:
using NPOI.HWPF;
using System.Collections;

using NPOI.HWPF.UserModel;
using System.IO;
using NUnit.Framework;
namespace TestCases.HWPF.UserModel
{

    /**
     * Test the shapes handling
     */
    [TestFixture]
    public class TestShapes
    {

        /**
         * two shapes, second is a group
         */
        [Test]
        public void TestShapes1()
        {
            HWPFDocument doc = HWPFTestDataSamples.OpenSampleFile("WithArtShapes.doc");

            IList shapes = doc.GetShapesTable().GetAllShapes();
            IList vshapes = doc.GetShapesTable().GetVisibleShapes();

            Assert.AreEqual(2, shapes.Count);
            Assert.AreEqual(2, vshapes.Count);

            Shape s1 = (Shape)shapes[0];
            Shape s2 = (Shape)shapes[1];

            Assert.AreEqual(3616, s1.Width);
            Assert.AreEqual(1738, s1.Height);
            Assert.AreEqual(true, s1.IsWithinDocument);

            Assert.AreEqual(4817, s2.Width);
            Assert.AreEqual(2164, s2.Height);
            Assert.AreEqual(true, s2.IsWithinDocument);

            // Re-serialisze, check still there
            MemoryStream baos = new MemoryStream();
            doc.Write(baos);
            MemoryStream bais = new MemoryStream(baos.ToArray());
            doc = new HWPFDocument(bais);

            shapes = doc.GetShapesTable().GetAllShapes();
            vshapes = doc.GetShapesTable().GetVisibleShapes();

            Assert.AreEqual(2, shapes.Count);
            Assert.AreEqual(2, vshapes.Count);

            s1 = (Shape)shapes[0];
            s2 = (Shape)shapes[1];

            Assert.AreEqual(3616, s1.Width);
            Assert.AreEqual(1738, s1.Height);
            Assert.AreEqual(true, s1.IsWithinDocument);

            Assert.AreEqual(4817, s2.Width);
            Assert.AreEqual(2164, s2.Height);
            Assert.AreEqual(true, s2.IsWithinDocument);
        }
    }
}