code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
3
942
language
stringclasses
30 values
license
stringclasses
15 values
size
int32
3
1.05M
import React, { useState } from 'react'; import { connect, ConnectedProps } from 'react-redux'; import { TimeZone } from '@grafana/data'; import { CollapsableSection, Field, Input, RadioButtonGroup, TagsInput } from '@grafana/ui'; import { selectors } from '@grafana/e2e-selectors'; import { FolderPicker } from 'app/core/components/Select/FolderPicker'; import { DashboardModel } from '../../state/DashboardModel'; import { DeleteDashboardButton } from '../DeleteDashboard/DeleteDashboardButton'; import { TimePickerSettings } from './TimePickerSettings'; import { updateTimeZoneDashboard, updateWeekStartDashboard } from 'app/features/dashboard/state/actions'; import { PreviewSettings } from './PreviewSettings'; import { config } from '@grafana/runtime'; interface OwnProps { dashboard: DashboardModel; } export type Props = OwnProps & ConnectedProps<typeof connector>; const GRAPH_TOOLTIP_OPTIONS = [ { value: 0, label: 'Default' }, { value: 1, label: 'Shared crosshair' }, { value: 2, label: 'Shared Tooltip' }, ]; export function GeneralSettingsUnconnected({ dashboard, updateTimeZone, updateWeekStart }: Props): JSX.Element { const [renderCounter, setRenderCounter] = useState(0); const onFolderChange = (folder: { id: number; title: string }) => { dashboard.meta.folderId = folder.id; dashboard.meta.folderTitle = folder.title; dashboard.meta.hasUnsavedFolderChange = true; }; const onBlur = (event: React.FocusEvent<HTMLInputElement>) => { dashboard[event.currentTarget.name as 'title' | 'description'] = event.currentTarget.value; }; const onTooltipChange = (graphTooltip: number) => { dashboard.graphTooltip = graphTooltip; setRenderCounter(renderCounter + 1); }; const onRefreshIntervalChange = (intervals: string[]) => { dashboard.timepicker.refresh_intervals = intervals.filter((i) => i.trim() !== ''); }; const onNowDelayChange = (nowDelay: string) => { dashboard.timepicker.nowDelay = nowDelay; }; const onHideTimePickerChange = (hide: boolean) => { dashboard.timepicker.hidden = hide; setRenderCounter(renderCounter + 1); }; const onLiveNowChange = (v: boolean) => { dashboard.liveNow = v; setRenderCounter(renderCounter + 1); }; const onTimeZoneChange = (timeZone: TimeZone) => { dashboard.timezone = timeZone; setRenderCounter(renderCounter + 1); updateTimeZone(timeZone); }; const onWeekStartChange = (weekStart: string) => { dashboard.weekStart = weekStart; setRenderCounter(renderCounter + 1); updateWeekStart(weekStart); }; const onTagsChange = (tags: string[]) => { dashboard.tags = tags; setRenderCounter(renderCounter + 1); }; const onEditableChange = (value: boolean) => { dashboard.editable = value; setRenderCounter(renderCounter + 1); }; const editableOptions = [ { label: 'Editable', value: true }, { label: 'Read-only', value: false }, ]; return ( <div style={{ maxWidth: '600px' }}> <h3 className="dashboard-settings__header" aria-label={selectors.pages.Dashboard.Settings.General.title}> General </h3> <div className="gf-form-group"> <Field label="Name"> <Input id="title-input" name="title" onBlur={onBlur} defaultValue={dashboard.title} /> </Field> <Field label="Description"> <Input id="description-input" name="description" onBlur={onBlur} defaultValue={dashboard.description} /> </Field> <Field label="Tags"> <TagsInput id="tags-input" tags={dashboard.tags} onChange={onTagsChange} /> </Field> <Field label="Folder"> <FolderPicker inputId="dashboard-folder-input" initialTitle={dashboard.meta.folderTitle} initialFolderId={dashboard.meta.folderId} onChange={onFolderChange} enableCreateNew={true} dashboardId={dashboard.id} skipInitialLoad={true} /> </Field> <Field label="Editable" description="Set to read-only to disable all editing. Reload the dashboard for changes to take effect" > <RadioButtonGroup value={dashboard.editable} options={editableOptions} onChange={onEditableChange} /> </Field> </div> {config.featureToggles.dashboardPreviews && config.featureToggles.dashboardPreviewsAdmin && ( <PreviewSettings uid={dashboard.uid} /> )} <TimePickerSettings onTimeZoneChange={onTimeZoneChange} onWeekStartChange={onWeekStartChange} onRefreshIntervalChange={onRefreshIntervalChange} onNowDelayChange={onNowDelayChange} onHideTimePickerChange={onHideTimePickerChange} onLiveNowChange={onLiveNowChange} refreshIntervals={dashboard.timepicker.refresh_intervals} timePickerHidden={dashboard.timepicker.hidden} nowDelay={dashboard.timepicker.nowDelay} timezone={dashboard.timezone} weekStart={dashboard.weekStart} liveNow={dashboard.liveNow} /> <CollapsableSection label="Panel options" isOpen={true}> <Field label="Graph tooltip" description="Controls tooltip and hover highlight behavior across different panels" > <RadioButtonGroup onChange={onTooltipChange} options={GRAPH_TOOLTIP_OPTIONS} value={dashboard.graphTooltip} /> </Field> </CollapsableSection> <div className="gf-form-button-row"> {dashboard.meta.canDelete && <DeleteDashboardButton dashboard={dashboard} />} </div> </div> ); } const mapDispatchToProps = { updateTimeZone: updateTimeZoneDashboard, updateWeekStart: updateWeekStartDashboard, }; const connector = connect(null, mapDispatchToProps); export const GeneralSettings = connector(GeneralSettingsUnconnected);
grafana/grafana
public/app/features/dashboard/components/DashboardSettings/GeneralSettings.tsx
TypeScript
agpl-3.0
5,865
# Copyright (c) 2016 Sebastian Kanis # This file is part of pi-led-control. # pi-led-control is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # pi-led-control is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with pi-led-control. If not, see <http://www.gnu.org/licenses/>. import datetime import logging from server.programs.abstractprogram import AbstractProgram class ScheduledProgram(AbstractProgram): def __init__(self, program, timeOfDay): super().__init__() self._program = program self._timeOfDay = timeOfDay def run(self): now = datetime.datetime.now() secondsInCurrentDay = now.hour * 3600 + now.minute * 60 + now.second if secondsInCurrentDay < self._timeOfDay: sleepDuration = self._timeOfDay - secondsInCurrentDay else: sleepDuration = self._timeOfDay + 3600 * 24 - secondsInCurrentDay logging.getLogger("main").info("sleeping for " + str(sleepDuration) + " seconds") self._waitIfNotStopped(sleepDuration) self._program.run() def setThreadStopEvent(self, threadStopEvent): self.threadStopEvent = threadStopEvent self._program.setThreadStopEvent(threadStopEvent) def setColorSetter(self, colorSetter): self._colorSetter = colorSetter self._program.setColorSetter(colorSetter) def getCurrentColor(self): return self._program.getCurrentColor() def setLastColor(self, lastColor): self._program.setLastColor(lastColor)
s0riak/pi-led-control
src/server/programs/scheduledprogram.py
Python
agpl-3.0
1,953
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.7.0_51) on Fri Mar 21 17:32:01 PDT 2014 --> <meta http-equiv="Content-Type" content="text/html" charset="UTF-8"> <title>com.java.chatroom.groupchat3 Class Hierarchy</title> <meta name="date" content="2014-03-21"> <link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="com.java.chatroom.groupchat3 Class Hierarchy"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li>Class</li> <li>Use</li> <li class="navBarCell1Rev">Tree</li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../com/java/chatroom/basic2threading/package-tree.html">Prev</a></li> <li><a href="../../../../com/java/chatroom/privatechat4/package-tree.html">Next</a></li> </ul> <ul class="navList"> <li><a href="../../../../index.html?com/java/chatroom/groupchat3/package-tree.html" target="_top">Frames</a></li> <li><a href="package-tree.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h1 class="title">Hierarchy For Package com.java.chatroom.groupchat3</h1> <span class="strong">Package Hierarchies:</span> <ul class="horizontal"> <li><a href="../../../../overview-tree.html">All Packages</a></li> </ul> </div> <div class="contentContainer"> <h2 title="Class Hierarchy">Class Hierarchy</h2> <ul> <li type="circle">java.lang.Object <ul> <li type="circle">com.java.chatroom.groupchat3.<a href="../../../../com/java/chatroom/groupchat3/Client.html" title="class in com.java.chatroom.groupchat3"><span class="strong">Client</span></a></li> <li type="circle">com.java.chatroom.groupchat3.<a href="../../../../com/java/chatroom/groupchat3/CloseUtil.html" title="class in com.java.chatroom.groupchat3"><span class="strong">CloseUtil</span></a></li> <li type="circle">com.java.chatroom.groupchat3.<a href="../../../../com/java/chatroom/groupchat3/MultiServer.html" title="class in com.java.chatroom.groupchat3"><span class="strong">MultiServer</span></a></li> <li type="circle">com.java.chatroom.groupchat3.<a href="../../../../com/java/chatroom/groupchat3/Receive.html" title="class in com.java.chatroom.groupchat3"><span class="strong">Receive</span></a> (implements java.lang.Runnable)</li> <li type="circle">com.java.chatroom.groupchat3.<a href="../../../../com/java/chatroom/groupchat3/Send.html" title="class in com.java.chatroom.groupchat3"><span class="strong">Send</span></a> (implements java.lang.Runnable)</li> </ul> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li>Class</li> <li>Use</li> <li class="navBarCell1Rev">Tree</li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../com/java/chatroom/basic2threading/package-tree.html">Prev</a></li> <li><a href="../../../../com/java/chatroom/privatechat4/package-tree.html">Next</a></li> </ul> <ul class="navList"> <li><a href="../../../../index.html?com/java/chatroom/groupchat3/package-tree.html" target="_top">Frames</a></li> <li><a href="package-tree.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
oliverwreath/Open-Source-Algorithms
Engineering-Java/workspace/com.java/doc/com/java/chatroom/groupchat3/package-tree.html
HTML
agpl-3.0
5,381
from pathlib import Path from inxs.cli import main as _main from tests import equal_documents def main(*args): _args = () for arg in args: if isinstance(arg, Path): _args += (str(arg),) else: _args += (arg,) _main(_args) # TODO case-study with this use-case def test_mods_to_tei(datadir): main("--inplace", datadir / "mods_to_tei.py", datadir / "mods_to_tei.xml") assert equal_documents(datadir / "mods_to_tei.xml", datadir / "mods_to_tei_exp.xml")
funkyfuture/inxs
tests/test_cli.py
Python
agpl-3.0
515
/** * Based conceptually on the _.extend() function in underscore.js ( see http://documentcloud.github.com/underscore/#extend for more details ) * Copyright (C) 2012 Kurt Milam - http://xioup.com | Source: https://gist.github.com/1868955 * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/. **/ var _ = require('underscore'); deepExtend = function(obj) { var parentRE = /#{\s*?_\s*?}/, slice = Array.prototype.slice, hasOwnProperty = Object.prototype.hasOwnProperty; _.each(slice.call(arguments, 1), function(source) { for (var prop in source) { if (hasOwnProperty.call(source, prop)) { if (_.isUndefined(obj[prop]) || _.isFunction(obj[prop]) || _.isNull(source[prop])) { obj[prop] = source[prop]; } else if (_.isString(source[prop]) && parentRE.test(source[prop])) { if (_.isString(obj[prop])) { obj[prop] = source[prop].replace(parentRE, obj[prop]); } } else if (_.isArray(obj[prop]) || _.isArray(source[prop])){ if (!_.isArray(obj[prop]) || !_.isArray(source[prop])){ throw 'Error: Trying to combine an array with a non-array (' + prop + ')'; } else { obj[prop] = _.reject(_.deepExtend(obj[prop], source[prop]), function (item) { return _.isNull(item);}); } } else if (_.isObject(obj[prop]) || _.isObject(source[prop])){ if (!_.isObject(obj[prop]) || !_.isObject(source[prop])){ throw 'Error: Trying to combine an object with a non-object (' + prop + ')'; } else { obj[prop] = _.deepExtend(obj[prop], source[prop]); } } else { obj[prop] = source[prop]; } } } }); return obj; }; exports.deepExtend = deepExtend;
4poc/anpaste
app/lib/deep_extend_underscore_mixin.js
JavaScript
agpl-3.0
2,385
package output; import java.io.FileWriter; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collections; import javax.swing.JOptionPane; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import org.w3c.dom.Node; public class XmlParserJhove { public static void main(String args[]) throws Exception { JOptionPane.showMessageDialog(null, "Please choose the XML File to analyse", "XmlParsing", JOptionPane.QUESTION_MESSAGE); String xmlfile = utilities.BrowserDialogs.chooseFile(); parseXmlFile(xmlfile); } public static void parseXmlFile(String xmlfile) { try { DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(xmlfile); PrintWriter xmlsummary = new PrintWriter(new FileWriter((jhoveValidations.JhoveGuiStarterDialog.jhoveExaminationFolder + "//" + "JhoveExaminationSummary" + ".xml"))); String xmlVersion = "xml version='1.0'"; String xmlEncoding = "encoding='ISO-8859-1'"; String xmlxslStyleSheet = "<?xml-stylesheet type=\"text/xsl\" href=\"JhoveCustomized.xsl\"?>"; xmlsummary.println("<?" + xmlVersion + " " + xmlEncoding + "?>"); xmlsummary.println(xmlxslStyleSheet); xmlsummary.println("<JhoveFindingsSummary>"); output.XslStyleSheetsJhove.JhoveCustomizedXsl(); ArrayList<String> errormessages = new ArrayList<String>(); doc.getDocumentElement().normalize(); NodeList nList = doc.getElementsByTagName("item"); for (int temp = 0; temp < nList.getLength(); temp++) { Node nNode = nList.item(temp); if (nNode.getNodeType() == Node.ELEMENT_NODE) { Element eElement = (Element) nNode; xmlsummary.println("<File>"); String testutf8 = eElement.getElementsByTagName("filename").item(0).getTextContent(); if (testutf8.contains("&")) { String sub = utilities.GenericUtilities.normaliseToUtf8(testutf8); xmlsummary.println("<FileName>" + sub + "</FileName>"); } else { xmlsummary.println("<FileName>" + eElement.getElementsByTagName("filename").item(0).getTextContent() + "</FileName>"); } if (eElement.getElementsByTagName("creationyear").item(0)!= null) { xmlsummary.println("<CreationYear>" + eElement.getElementsByTagName("creationyear").item(0).getTextContent() + "</CreationYear>"); } if (eElement.getElementsByTagName("creationsoftware").item(0)!= null) { xmlsummary.println("<CreationSoftware>" + eElement.getElementsByTagName("creationsoftware").item(0).getTextContent() + "</CreationSoftware>"); } if (eElement.getElementsByTagName("encryption").item(0)!= null) { xmlsummary.println("<Encryption>" + eElement.getElementsByTagName("encryption").item(0).getTextContent() + "</Encryption>"); } if (eElement.getElementsByTagName("PdfType").item(0)!= null) { xmlsummary.println("<PdfType>" + eElement.getElementsByTagName("PdfType").item(0).getTextContent() + "</PdfType>"); } xmlsummary.println("<Module>" + eElement.getElementsByTagName("reportingModule").item(0).getTextContent() + "</Module>"); xmlsummary.println("<Status>" + eElement.getElementsByTagName("status").item(0).getTextContent() + "</Status>"); String status = eElement.getElementsByTagName("status").item(0).getTextContent(); if ((status.contains("Not")) || (status.contains("not"))) { System.out.println(eElement.getElementsByTagName("filename").item(0).getTextContent()); int lenmessages = eElement.getElementsByTagName("message").getLength(); xmlsummary.println("<JhoveMessages>" + lenmessages + "</JhoveMessages>"); for (int temp3 = 0; temp3 < lenmessages; temp3++) { String error = eElement.getElementsByTagName("message").item(temp3).getTextContent(); int writtenmessage = temp3 + 1; //TODO: get rid of xml escaping characters error = error.replace("\"", "&quot;"); error = error.replace("\'", "&apos;"); error = error.replace("<", "&lt;"); error = error.replace(">", "&gt;"); error = error.replace("&", " &amp;"); xmlsummary.println("<Message" + writtenmessage + ">" + error + "</Message" + writtenmessage + ">"); errormessages.add(error); } } xmlsummary.println("</File>"); //TODO: should be changed to File, but as well in XSLT } } Collections.sort(errormessages); int i; // copy ErrorList because later the no. of entries of each // element will be counted ArrayList<String> originerrors = new ArrayList<String>(); for (i = 0; i < errormessages.size(); i++) { // There might be a // pre-defined // function for this originerrors.add(errormessages.get(i)); } // get rid of redundant entries i = 0; while (i < errormessages.size() - 1) { if (errormessages.get(i).equals(errormessages.get(i + 1))) { errormessages.remove(i); } else { i++; } } xmlsummary.println("<SampleSummary>"); xmlsummary.println("<ExaminedPdfFiles>" + nList.getLength() + "</ExaminedPdfFiles>"); xmlsummary.println("<DifferentJhoveMessages>" + errormessages.size() + "</DifferentJhoveMessages>"); // how often does each JHOVE error occur? int j = 0; int temp1; for (i = 0; i < errormessages.size(); i++) { temp1 = 0; for (j = 0; j < originerrors.size(); j++) { if (errormessages.get(i).equals(originerrors.get(j))) { temp1++; } } xmlsummary.println("<JhoveMessage>"); xmlsummary.println("<MessageText>" + errormessages.get(i) + "</MessageText>"); xmlsummary.println("<Occurance>" + temp1 + "</Occurance>"); xmlsummary.println("</JhoveMessage>"); } xmlsummary.println("</SampleSummary>"); xmlsummary.println("</JhoveFindingsSummary>"); xmlsummary.close(); } catch (Exception e) { e.printStackTrace(); JOptionPane.showMessageDialog(null, e, "error message", JOptionPane.ERROR_MESSAGE); } } }
YvonneTunnat/File-Format-Utilities
master/pdf-tools/src/main/java/output/XmlParserJhove.java
Java
agpl-3.0
6,325
{-# LANGUAGE FunctionalDependencies #-} {-# LANGUAGE OverloadedStrings #-} {-# OPTIONS_GHC -fno-warn-incomplete-patterns #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE FlexibleInstances #-} module PontariusService.Types where import Control.Applicative import Control.Lens import Control.Monad.Reader import DBus import DBus.Signal import DBus.Types import Data.ByteString (ByteString) import Data.Set (Set) import qualified Data.Set as Set import Data.Text (Text) import qualified Data.Text as Text import Data.Time.Clock (UTCTime) import Data.Time.Clock.POSIX as Time import Data.Typeable import Data.UUID (UUID) import qualified Data.UUID as UUID import Data.Word import qualified Network.Xmpp as Xmpp type SSID = ByteString data BatchLink = BatchLinkIgnore | BatchLinkExisting UUID | BatchLinkNewContact Text instance Representable BatchLink where type RepType BatchLink = 'TypeStruct '[ 'DBusSimpleType 'TypeByte , 'DBusSimpleType 'TypeString] toRep BatchLinkIgnore = DBVStruct (StructCons (DBVByte 0) (StructSingleton (DBVString ""))) toRep (BatchLinkExisting uuid) = DBVStruct (StructCons (DBVByte 1) (StructSingleton (toRep uuid))) toRep (BatchLinkNewContact name) = DBVStruct (StructCons (DBVByte 2) (StructSingleton (toRep name))) fromRep (DBVStruct (StructCons (DBVByte 0) (StructSingleton _))) = Just BatchLinkIgnore fromRep (DBVStruct (StructCons (DBVByte 1) (StructSingleton uuid))) = BatchLinkExisting <$> (fromRep uuid) fromRep (DBVStruct (StructCons (DBVByte 2) (StructSingleton (DBVString name)))) = Just $ BatchLinkNewContact name data PontariusState = CredentialsUnset | IdentityNotFound | IdentitiesAvailable | CreatingIdentity | Disabled | Authenticating | Authenticated | AuthenticationDenied deriving (Show, Eq) data AccountState = AccountEnabled | AccountDisabled deriving (Show, Eq) data PeerStatus = Unavailable | Available deriving (Show, Eq) instance Representable UTCTime where type RepType UTCTime = 'DBusSimpleType 'TypeUInt32 toRep = DBVUInt32 . round . utcTimeToPOSIXSeconds fromRep (DBVUInt32 x) = Just . posixSecondsToUTCTime $ fromIntegral x instance DBus.Representable Xmpp.Jid where type RepType Xmpp.Jid = 'DBusSimpleType 'TypeString toRep = DBus.DBVString . Xmpp.jidToText fromRep (DBus.DBVString s) = Xmpp.jidFromText s instance (Ord a, DBus.Representable a) => DBus.Representable (Set a) where type RepType (Set a) = RepType [a] toRep = toRep . Set.toList fromRep = fmap Set.fromList . fromRep instance Representable (Maybe KeyID) where type RepType (Maybe KeyID) = RepType KeyID toRep Nothing = toRep Text.empty toRep (Just k) = toRep k fromRep v = case fromRep v of Nothing -> Nothing Just v' | Text.null v' -> Just Nothing | otherwise -> Just (Just v') instance Representable (Maybe UTCTime) where type RepType (Maybe UTCTime) = RepType UTCTime toRep Nothing = toRep (0 :: Word32) toRep (Just t) = toRep t fromRep v = case fromRep v of Nothing -> Nothing Just t' | t' == (0 :: Word32) -> Just Nothing | otherwise -> Just . Just $ posixSecondsToUTCTime $ fromIntegral t' type KeyID = Text type SessionID = ByteString data ConnectionStatus = Connected | Disconnected deriving (Show, Eq, Ord) data InitResponse = KeyOK | SelectKey data Ent = Ent { entityJid :: Xmpp.Jid , entityDisplayName :: Text , entityDescription :: Text } deriving (Show, Typeable) data AkeEvent = AkeEvent { akeEventStart :: UTCTime , akeEventSuccessfull :: Bool , akeEventPeerJid :: Xmpp.Jid , akeEventOurJid :: Xmpp.Jid , akeEventPeerkeyID :: KeyID , akeEventOurkeyID :: KeyID } deriving (Show, Eq) data ChallengeEvent = ChallengeEvent { challengeEventChallengeOutgoing :: Bool , challengeEventStarted :: UTCTime , challengeEventCompleted :: UTCTime , challengeEventQuestion :: Text , challengeEventResult :: Text } deriving (Show, Eq) data RevocationEvent = RevocationEvent { revocationEventKeyID :: KeyID , revocationEventTime :: UTCTime } data RevocationSignalEvent = RevocationlEvent { revocationSignalEventKeyID :: KeyID , revocationSignalEventTime :: UTCTime } makePrisms ''PontariusState makeRepresentable ''PontariusState makePrisms ''AccountState makeRepresentable ''AccountState makeRepresentable ''RevocationSignalEvent makeRepresentable ''ConnectionStatus makeRepresentable ''InitResponse makeRepresentable ''Ent makeRepresentable ''AkeEvent makeRepresentable ''ChallengeEvent makeRepresentable ''RevocationEvent makeRepresentable ''PeerStatus instance DBus.Representable UUID where type RepType UUID = RepType Text toRep = toRep . Text.pack . UUID.toString fromRep = UUID.fromString . Text.unpack <=< fromRep data AddPeerFailed = AddPeerFailed { addPeerFailedPeer :: !Xmpp.Jid , addPeerFailedReason :: !Text } deriving (Show) makeRepresentable ''AddPeerFailed makeLensesWith camelCaseFields ''AddPeerFailed data RemovePeerFailed = RemovePeerFailed { removePeerFailedPeer :: !Xmpp.Jid , removePeerFailedReason :: !Text } deriving (Show) makeRepresentable ''RemovePeerFailed makeLensesWith camelCaseFields ''RemovePeerFailed
pontarius/pontarius-service
source/PontariusService/Types.hs
Haskell
agpl-3.0
6,475
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations from django.conf import settings import django_pgjson.fields import django.utils.timezone import django.db.models.deletion import djorm_pgarray.fields import taiga.projects.history.models class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('users', '0002_auto_20140903_0916'), ] operations = [ migrations.CreateModel( name='Membership', fields=[ ('id', models.AutoField(serialize=False, primary_key=True, auto_created=True, verbose_name='ID')), ('is_owner', models.BooleanField(default=False)), ('email', models.EmailField(max_length=255, null=True, default=None, verbose_name='email', blank=True)), ('created_at', models.DateTimeField(default=django.utils.timezone.now, verbose_name='creado el')), ('token', models.CharField(max_length=60, null=True, default=None, verbose_name='token', blank=True)), ('invited_by_id', models.IntegerField(null=True, blank=True)), ], options={ 'ordering': ['project', 'user__full_name', 'user__username', 'user__email', 'email'], 'verbose_name_plural': 'membershipss', 'permissions': (('view_membership', 'Can view membership'),), 'verbose_name': 'membership', }, bases=(models.Model,), ), migrations.CreateModel( name='Project', fields=[ ('id', models.AutoField(serialize=False, primary_key=True, auto_created=True, verbose_name='ID')), ('tags', djorm_pgarray.fields.TextArrayField(dbtype='text', verbose_name='tags')), ('name', models.CharField(max_length=250, unique=True, verbose_name='name')), ('slug', models.SlugField(max_length=250, unique=True, verbose_name='slug', blank=True)), ('description', models.TextField(verbose_name='description')), ('created_date', models.DateTimeField(default=django.utils.timezone.now, verbose_name='created date')), ('modified_date', models.DateTimeField(verbose_name='modified date')), ('total_milestones', models.IntegerField(null=True, default=0, verbose_name='total of milestones', blank=True)), ('total_story_points', models.FloatField(default=0, verbose_name='total story points')), ('is_backlog_activated', models.BooleanField(default=True, verbose_name='active backlog panel')), ('is_kanban_activated', models.BooleanField(default=False, verbose_name='active kanban panel')), ('is_wiki_activated', models.BooleanField(default=True, verbose_name='active wiki panel')), ('is_issues_activated', models.BooleanField(default=True, verbose_name='active issues panel')), ('videoconferences', models.CharField(max_length=250, null=True, choices=[('appear-in', 'AppearIn'), ('talky', 'Talky'), ('jitsi', 'Jitsi')], verbose_name='videoconference system', blank=True)), ('videoconferences_salt', models.CharField(max_length=250, null=True, verbose_name='videoconference room salt', blank=True)), ('anon_permissions', djorm_pgarray.fields.TextArrayField(choices=[('view_project', 'View project'), ('view_milestones', 'View milestones'), ('view_us', 'View user stories'), ('view_tasks', 'View tasks'), ('view_issues', 'View issues'), ('view_wiki_pages', 'View wiki pages'), ('view_wiki_links', 'View wiki links')], dbtype='text', default=[], verbose_name='anonymous permissions')), ('public_permissions', djorm_pgarray.fields.TextArrayField(choices=[('view_project', 'View project'), ('view_milestones', 'View milestones'), ('view_us', 'View user stories'), ('view_issues', 'View issues'), ('vote_issues', 'Vote issues'), ('view_tasks', 'View tasks'), ('view_wiki_pages', 'View wiki pages'), ('view_wiki_links', 'View wiki links'), ('request_membership', 'Request membership'), ('add_us_to_project', 'Add user story to project'), ('add_comments_to_us', 'Add comments to user stories'), ('add_comments_to_task', 'Add comments to tasks'), ('add_issue', 'Add issues'), ('add_comments_issue', 'Add comments to issues'), ('add_wiki_page', 'Add wiki page'), ('modify_wiki_page', 'Modify wiki page'), ('add_wiki_link', 'Add wiki link'), ('modify_wiki_link', 'Modify wiki link')], dbtype='text', default=[], verbose_name='user permissions')), ('is_private', models.BooleanField(default=False, verbose_name='is private')), ('tags_colors', djorm_pgarray.fields.TextArrayField(dbtype='text', dimension=2, default=[], null=False, verbose_name='tags colors')), ], options={ 'ordering': ['name'], 'verbose_name_plural': 'projects', 'permissions': (('view_project', 'Can view project'),), 'verbose_name': 'project', }, bases=(models.Model,), ), migrations.AddField( model_name='project', name='members', field=models.ManyToManyField(to=settings.AUTH_USER_MODEL, related_name='projects', verbose_name='members', through='projects.Membership'), preserve_default=True, ), migrations.AddField( model_name='project', name='owner', field=models.ForeignKey(to=settings.AUTH_USER_MODEL, related_name='owned_projects', verbose_name='owner'), preserve_default=True, ), migrations.AddField( model_name='membership', name='user', field=models.ForeignKey(blank=True, default=None, to=settings.AUTH_USER_MODEL, null=True, related_name='memberships'), preserve_default=True, ), migrations.AddField( model_name='membership', name='project', field=models.ForeignKey(default=1, to='projects.Project', related_name='memberships'), preserve_default=False, ), migrations.AlterUniqueTogether( name='membership', unique_together=set([('user', 'project')]), ), migrations.AddField( model_name='membership', name='role', field=models.ForeignKey(related_name='memberships', to='users.Role', default=1), preserve_default=False, ), ]
19kestier/taiga-back
taiga/projects/migrations/0001_initial.py
Python
agpl-3.0
6,634
<?php /*-------------------------------------------------------+ | PHP-Fusion Content Management System | Copyright (C) PHP-Fusion Inc | https://www.php-fusion.co.uk/ +--------------------------------------------------------+ | Filename: gallery_settings.php | Author: PHP-Fusion Development Team +--------------------------------------------------------+ | This program is released as free software under the | Affero GPL license. You can redistribute it and/or | modify it under the terms of this license which you | can read by viewing the included agpl.txt or online | at www.gnu.org/licenses/agpl.html. Removal of this | copyright header is strictly prohibited without | written permission from the original author(s). +--------------------------------------------------------*/ pageAccess("PH"); if (!defined("IN_FUSION")) { die("Access Denied"); } include LOCALE.LOCALESET."admin/settings.php"; if (isset($_POST['delete_watermarks'])) { $result = dbquery("SELECT album_id,photo_filename FROM ".DB_PHOTOS." ORDER BY album_id, photo_id"); $rows = dbrows($result); if ($rows) { $parts = array(); $watermark1 = ""; $watermark2 = ""; $photodir = ""; while ($data = dbarray($result)) { $parts = explode(".", $data['photo_filename']); $watermark1 = $parts[0]."_w1.".$parts[1]; $watermark2 = $parts[0]."_w2.".$parts[1]; $photodir = IMAGES_G; if (file_exists($photodir.$watermark1)) unlink($photodir.$watermark1); if (file_exists($photodir.$watermark2)) unlink($photodir.$watermark2); unset($parts); } redirect(FUSION_REQUEST); } else { redirect(FUSION_REQUEST); } } else if (isset($_POST['savesettings'])) { print_p($_POST); $inputArray = array( "thumb_w" => form_sanitizer($_POST['thumb_w'], 200, "thumb_w"), "thumb_h" => form_sanitizer($_POST['thumb_h'], 200, "thumb_h"), "photo_w" => form_sanitizer($_POST['photo_w'], 800, "photo_w"), "photo_h" => form_sanitizer($_POST['photo_h'], 800, "photo_h"), "photo_max_w" => form_sanitizer($_POST['photo_max_w'], 2400, "photo_max_w"), "photo_max_h" => form_sanitizer($_POST['photo_max_h'], 1800, "photo_max_h"), "photo_max_b" => form_sanitizer($_POST['calc_b'] * $_POST['calc_c'], 2000000, ""), "gallery_pagination" => form_sanitizer($_POST['gallery_pagination'], 24, "gallery_pagination"), "photo_watermark" => form_sanitizer($_POST['photo_watermark'], 0, "photo_watermark"), "photo_watermark_save" => isset($_POST['photo_watermark_save']) ? 1 : 0, "photo_watermark_image" => isset($_POST['photo_watermark_image']) ? form_sanitizer($_POST['photo_watermark_image'], "", "photo_watermark_image") : IMAGES_G."watermark.png", "photo_watermark_text" => isset($_POST['photo_watermark_text']) ? 1 : 0, "photo_watermark_text_color1" => isset($_POST['photo_watermark_text_color1']) ? form_sanitizer($_POST['photo_watermark_text_color1'], "#000000", "photo_watermark_text_color1") : "#000000", "photo_watermark_text_color2" => isset($_POST['photo_watermark_text_color2']) ? form_sanitizer($_POST['photo_watermark_text_color2'], "#000000", "photo_watermark_text_color2") : "#000000", "photo_watermark_text_color3" => isset($_POST['photo_watermark_text_color3']) ? form_sanitizer($_POST['photo_watermark_text_color3'], "#000000", "photo_watermark_text_color3") : "#000000", "gallery_allow_submission" => isset($_POST['gallery_allow_submission']) ? 1 : 0, "gallery_extended_required" => isset($_POST['gallery_extended_required']) ? 1 : 0, ); if (defender::safe()) { foreach ($inputArray as $settings_name => $settings_value) { $inputSettings = array( "settings_name" => $settings_name, "settings_value" => $settings_value, "settings_inf" => "gallery", ); dbquery_insert(DB_SETTINGS_INF, $inputSettings, "update", array("primary_key" => "settings_name")); } addNotice("success", $locale['900']); redirect(FUSION_REQUEST); } else { addNotice('danger', $locale['901']); } } echo openform('settingsform', 'post', FUSION_REQUEST, array("class" => "m-t-20")); echo "<div class='well'>".$locale['gallery_0022']."</div>"; $choice_opts = array('1' => $locale['518'], '0' => $locale['519']); $calc_opts = array(1 => 'Bytes (bytes)', 1000 => 'KB (Kilobytes)', 1000000 => 'MB (Megabytes)'); $calc_c = calculate_byte($gll_settings['photo_max_b']); $calc_b = $gll_settings['photo_max_b']/$calc_c; echo "<div class='row'><div class='col-xs-12 col-sm-8'>\n"; openside(''); echo form_text('gallery_pagination', $locale['gallery_0202'], $gll_settings['gallery_pagination'], array( 'max_length' => 2, 'inline' => 1, 'width' => '100px', "type" => "number", )); echo " <div class='row m-0'>\n <label class='label-control col-xs-12 col-sm-3 p-l-0' for='thumb_w'>".$locale['gallery_0203']."</label>\n <div class='col-xs-12 col-sm-9 p-l-0'>\n ".form_text('thumb_w', '', $gll_settings['thumb_w'], array( 'class' => 'pull-left m-r-10', 'max_length' => 4, "type" => "number", 'width' => '150px' ))." <i class='entypo icancel pull-left m-r-10 m-l-0 m-t-10'></i>\n ".form_text('thumb_h', '', $gll_settings['thumb_h'], array( 'class' => 'pull-left', 'max_length' => 4, "type" => "number", 'width' => '150px' ))." <small class='m-l-10 mid-opacity text-uppercase pull-left m-t-10'>( ".$locale['gallery_0204']." )</small>\n </div>\n </div>\n "; echo " <div class='row m-0'>\n <label class='label-control col-xs-12 col-sm-3 p-l-0' for='photo_max_w'>".$locale['gallery_0205']."</label>\n <div class='col-xs-12 col-sm-9 p-l-0'>\n ".form_text('photo_w', '', $gll_settings['photo_w'], array( 'class' => 'pull-left m-r-10', 'max_length' => 4, "type" => "number", 'width' => '150px' ))." <i class='entypo icancel pull-left m-r-10 m-l-0 m-t-10'></i>\n ".form_text('photo_h', '', $gll_settings['photo_h'], array( 'class' => 'pull-left', 'max_length' => 4, "type" => "number", 'width' => '150px' ))." <small class='m-l-10 mid-opacity text-uppercase pull-left m-t-10'>( ".$locale['gallery_0204']." )</small>\n </div>\n </div>\n"; echo " <div class='row m-0'>\n <label class='label-control col-xs-12 col-sm-3 p-l-0' for='photo_w'>".$locale['gallery_0206']."</label>\n <div class='col-xs-12 col-sm-9 p-l-0'>\n ".form_text('photo_max_w', '', $gll_settings['photo_max_w'], array( 'class' => 'pull-left m-r-10', 'max_length' => 4, "type" => "number", 'width' => '150px' ))." <i class='entypo icancel pull-left m-r-10 m-l-0 m-t-10'></i>\n ".form_text('photo_max_h', '', $gll_settings['photo_max_h'], array( 'class' => 'pull-left', 'max_length' => 4, "type" => "number", 'width' => '150px' ))." <small class='m-l-10 mid-opacity text-uppercase pull-left m-t-10'>( ".$locale['gallery_0204']." )</small>\n </div>\n </div>\n"; echo " <div class='row m-0'>\n <label class='col-xs-12 col-sm-3 p-l-0' for='calc_b'>".$locale['gallery_0207']."</label>\n <div class='col-xs-12 col-sm-9 p-l-0'>\n ".form_text('calc_b', '', $calc_b, array( 'required' => 1, "type" => "number", 'error_text' => $locale['error_rate'], 'width' => '150px', 'max_length' => 4, 'class' => 'pull-left m-r-10' ))." ".form_select('calc_c', '', $calc_c, array('options' => $calc_opts, 'class' => 'pull-left', 'width' => '180px'))." </div>\n </div>\n "; closeside(); openside(''); echo form_checkbox("gallery_allow_submission", $locale['gallery_0200'], $gll_settings['gallery_allow_submission']); echo form_checkbox("gallery_extended_required", $locale['gallery_0201'], $gll_settings['gallery_extended_required']); closeside(); echo "</div><div class='col-xs-12 col-sm-4'>\n"; openside(""); echo form_select('photo_watermark', $locale['gallery_0214'], $gll_settings['photo_watermark'], array( "options" => array("0"=>$locale['disable'], "1"=>$locale['enable']), "width" => "100%", )); echo form_checkbox('photo_watermark_text', $locale['gallery_0213'], $gll_settings['photo_watermark_text']); echo form_checkbox('photo_watermark_save', $locale['gallery_0215'], $gll_settings['photo_watermark_save']); echo form_text('photo_watermark_image', $locale['gallery_0212'], $gll_settings['photo_watermark_image'], array( 'deactivate' => !$gll_settings['photo_watermark'] ? 1 : 0, )); echo form_colorpicker('photo_watermark_text_color1', $locale['gallery_0208'], $gll_settings['photo_watermark_text_color1'], array( 'deactivate' => !$gll_settings['photo_watermark'] ? 1 : 0, //"format"=>"rgb", )); echo form_colorpicker('photo_watermark_text_color2', $locale['gallery_0209'], $gll_settings['photo_watermark_text_color2'], array( 'deactivate' => !$gll_settings['photo_watermark'] ? 1 : 0, //"format"=>"rgb", )); echo form_colorpicker('photo_watermark_text_color3', $locale['gallery_0210'], $gll_settings['photo_watermark_text_color3'], array( 'deactivate' => !$gll_settings['photo_watermark'] ? 1 : 0, //"format"=>"rgb", )); echo form_button('savesettings', $locale['gallery_0216'], $locale['gallery_0216'], array('class' => 'btn-success m-r-10')); echo form_button('delete_watermarks', $locale['gallery_0211'], $locale['gallery_0211'], array( 'deactivate' => !$gll_settings['photo_watermark'] ? 1 : 0, 'class' => 'btn-default', )); closeside(); echo "</div>\n</div>\n"; echo form_button('savesettings', $locale['gallery_0216'], $locale['gallery_0216'], array('class' => 'btn-success')); echo closeform(); add_to_jquery(" $('#photo_watermark').bind('change', function(){ var vals = $(this).select2().val(); if (vals == 1) { $('#photo_watermark_save').select2('enable'); $('#delete_watermarks').removeAttr('disabled'); $('#photo_watermark_image').removeAttr('disabled'); $('#photo_watermark_text').select2('enable'); $('#photo_watermark_text_color1').colorpicker('enable'); $('#photo_watermark_text_color2').colorpicker('enable'); $('#photo_watermark_text_color3').colorpicker('enable'); } else { $('#photo_watermark_save').select2('disable'); $('#delete_watermarks').attr('disabled', 'disabled'); $('#photo_watermark_image').attr('disabled', 'disabled'); $('#photo_watermark_text').select2('disable'); $('#photo_watermark_text_color1').colorpicker('disable'); $('#photo_watermark_text_color2').colorpicker('disable'); $('#photo_watermark_text_color3').colorpicker('disable'); } }); "); function calculate_byte($download_max_b) { $calc_opts = array(1 => 'Bytes (bytes)', 1000 => 'KB (Kilobytes)', 1000000 => 'MB (Megabytes)'); foreach ($calc_opts as $byte => $val) { if ($download_max_b/$byte <= 999) { return $byte; } } return 1000000; } function color_mapper($field, $value) { global $gll_settings; $cvalue[] = "00"; $cvalue[] = "33"; $cvalue[] = "66"; $cvalue[] = "99"; $cvalue[] = "CC"; $cvalue[] = "FF"; $select = ""; $select = "<select name='".$field."' class='textbox' onchange=\"document.getElementById('preview_".$field."').style.background = '#' + this.options[this.selectedIndex].value;\" ".(!$gll_settings['photo_watermark'] ? "disabled='disabled'" : "").">\n"; for ($ca = 0; $ca < count($cvalue); $ca++) { for ($cb = 0; $cb < count($cvalue); $cb++) { for ($cc = 0; $cc < count($cvalue); $cc++) { $hcolor = $cvalue[$ca].$cvalue[$cb].$cvalue[$cc]; $select .= "<option value='".$hcolor."'".($value == $hcolor ? " selected='selected' " : " ")."style='background-color:#".$hcolor.";'>#".$hcolor."</option>\n"; } } } $select .= "</select>\n"; return $select; }
Talocha/PHP-Fusion
infusions/gallery/admin/gallery_settings.php
PHP
agpl-3.0
11,482
class Transfer < Entry state_machine :initial => :open, :namespace => :transfer do event :close do transition :paid => :closed end state :open, :value => 400 state :closed, :value => 430 end def required_account_types [BankAccount, CreditCard] end end
MHMDhub/regdel
app/models/entries/transfer.rb
Ruby
agpl-3.0
291
#!/usr/bin/env python # Copyright (C) 2006-2016 Music Technology Group - Universitat Pompeu Fabra # # This file is part of Essentia # # Essentia is free software: you can redistribute it and/or modify it under # the terms of the GNU Affero General Public License as published by the Free # Software Foundation (FSF), either version 3 of the License, or (at your # option) any later version. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more # details. # # You should have received a copy of the Affero GNU General Public License # version 3 along with this program. If not, see http://www.gnu.org/licenses/ from essentia_test import * class TestHPCP(TestCase): def testEmpty(self): hpcp = HPCP()([], []) self.assertEqualVector(hpcp, [0.]*12) def testZeros(self): hpcp = HPCP()([0]*10, [0]*10) self.assertEqualVector(hpcp, [0.]*12) def testSin440(self): # Tests whether a real audio signal of one pure tone gets read as a # single semitone activation, and gets read into the right pcp bin sampleRate = 44100 audio = MonoLoader(filename = join(testdata.audio_dir, 'generated/synthesised/sin440_0db.wav'), sampleRate = sampleRate)() speaks = SpectralPeaks(sampleRate = sampleRate, maxPeaks = 1, maxFrequency = sampleRate/2, minFrequency = 0, magnitudeThreshold = 0, orderBy = 'magnitude') (freqs, mags) = speaks(Spectrum()(audio)) hpcp = HPCP()(freqs, mags) self.assertEqualVector(hpcp, [1.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.]) def testAllSemitones(self): # Tests whether a spectral peak output of 12 consecutive semitones # yields a HPCP of all 1's tonic = 440 freqs = [(tonic * 2**(x/12.)) for x in range(12)] mags = [1] * 12 hpcp = HPCP()(freqs, mags) self.assertEqualVector(hpcp, [1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.]) def testSubmediantPosition(self): # Make sure that the submediant of a key based on 440 is in the # correct location (submediant was randomly selected from all the # tones) tonic = 440 submediant = tonic * 2**(9./12.) hpcp = HPCP()([submediant], [1]) self.assertEqualVector(hpcp, [0.,0.,0.,0.,0.,0.,0.,0.,0.,1.,0.,0.]) def testMaxShifted(self): # Tests whether a HPCP reading with only the dominant semitone # activated is correctly shifted so that the dominant is at the # position 0 tonic = 440 dominant = tonic * 2**(7./12.) hpcp = HPCP(maxShifted=True)([dominant], [1]) self.assertEqualVector(hpcp, [1.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.]) def chordHelper(self, half_steps, tunning, strength): notes = [tunning*(2.**(half_steps[i]/12.)) for i in range(len(half_steps))] hpcp = HPCP(maxShifted=False)([notes[0], notes[1], notes[2]], strength) for i in range(len(hpcp)): if i in half_steps: self.assertTrue(hpcp[i]>0) elif (i - 12) in half_steps: self.assertTrue(hpcp[i]>0) else: self.assertEqual(hpcp[i], 0) def testChord(self): tunning = 440 AMajor = [0, 4, 7] # AMajor = A4-C#5-E5 self.chordHelper(AMajor, tunning, [1,1,1]) CMajor = [3, -4, -2] # CMajor = C5-F4-G4 self.chordHelper(CMajor, tunning, [1,1,1]) CMajor = [-4, 3, -2] # CMajor = C5-F4-G4 self.chordHelper(CMajor, tunning, [1,0.5,0.2]) CMajor = [-4, -2, 3] # CMajor = C5-F4-G4 self.chordHelper(CMajor, tunning, [1,0.5,0.2]) CMajor = [3, 8, 10] # CMajor = C5-F5-G5 self.chordHelper(CMajor, tunning, [1,0.5,0.2]) AMinor = [0, 3, 7] # AMinor = A4-C5-E5 self.chordHelper(AMinor, tunning, [1,0.5,0.2]) CMinor = [3, 6, 10] # CMinor = C5-E5-G5 self.chordHelper(CMinor, tunning, [1,0.5,0.2]) # Test of various parameter logical bounds def testLowFrequency(self): hpcp = HPCP(minFrequency=100, maxFrequency=1000)([99], [1]) self.assertEqualVector(hpcp, [0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.]) def testHighFrequency(self): hpcp = HPCP(minFrequency=100, maxFrequency=1000)([1001], [1]) self.assertEqualVector(hpcp, [0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.]) def testSmallMinRange(self): self.assertConfigureFails(HPCP(), {'minFrequency':1, 'splitFrequency':200}) def testSmallMaxRange(self): self.assertConfigureFails(HPCP(), {'maxFrequency':1199, 'splitFrequency':1000}) def testSmallMinMaxRange(self): self.assertConfigureFails(HPCP(), {'bandPreset':False, 'maxFrequency':200, 'minFrequency':1}) def testSizeNonmultiple12(self): self.assertConfigureFails(HPCP(), {'size':13}) def testHarmonics(self): # Regression test for the 'harmonics' parameter tone = 100. # arbitrary frequency [Hz] freqs = [tone, tone*2, tone*3, tone*4] mags = [1]*4 hpcpAlg = HPCP(minFrequency=50, maxFrequency=500, bandPreset=False, harmonics=3) hpcp = hpcpAlg(freqs, mags) expected = [0., 0., 0., 0.1340538263, 0., 0.2476127148, 0., 0., 0., 0., 1., 0.] self.assertAlmostEqualVector(hpcp, expected, 1e-4) def testRegression(self): # Just makes sure algorithm does not crash on a real data source. This # test is not really looking for correctness. Maybe consider revising # it. inputSize = 512 sampleRate = 44100 audio = MonoLoader(filename = join(testdata.audio_dir, join('recorded', 'musicbox.wav')), sampleRate = sampleRate)() fc = FrameCutter(frameSize = inputSize, hopSize = inputSize) windowingAlg = Windowing(type = 'blackmanharris62') specAlg = Spectrum(size=inputSize) sPeaksAlg = SpectralPeaks(sampleRate = sampleRate, maxFrequency = sampleRate/2, minFrequency = 0, orderBy = 'magnitude') hpcpAlg = HPCP(minFrequency=50, maxFrequency=500, bandPreset=False, harmonics=3) frame = fc(audio) while len(frame) != 0: spectrum = specAlg(windowingAlg(frame)) (freqs, mags) = sPeaksAlg(spectrum) hpcp = hpcpAlg(freqs,mags) self.assertTrue(not any(numpy.isnan(hpcp))) self.assertTrue(not any(numpy.isinf(hpcp))) frame = fc(audio) suite = allTests(TestHPCP) if __name__ == '__main__': TextTestRunner(verbosity=2).run(suite)
arseneyr/essentia
test/src/unittest/spectral/test_hpcp.py
Python
agpl-3.0
7,101
import CodeClipboard from './CodeClipboard'; export default CodeClipboard;
StarterInc/Ignite
src/docs/src/components/CodeClipboard/index.js
JavaScript
agpl-3.0
75
--Copyright (C) 2010 <SWGEmu> --This File is part of Core3. --This program is free software; you can redistribute --it and/or modify it under the terms of the GNU Lesser --General Public License as published by the Free Software --Foundation; either version 2 of the License, --or (at your option) any later version. --This program is distributed in the hope that it will be useful, --but WITHOUT ANY WARRANTY; without even the implied warranty of --MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. --See the GNU Lesser General Public License for --more details. --You should have received a copy of the GNU Lesser General --Public License along with this program; if not, write to --the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA --Linking Engine3 statically or dynamically with other modules --is making a combined work based on Engine3. --Thus, the terms and conditions of the GNU Lesser General Public License --cover the whole combination. --In addition, as a special exception, the copyright holders of Engine3 --give you permission to combine Engine3 program with free software --programs or libraries that are released under the GNU LGPL and with --code included in the standard release of Core3 under the GNU LGPL --license (or modified versions of such code, with unchanged license). --You may copy and distribute such a system following the terms of the --GNU LGPL for Engine3 and the licenses of the other code concerned, --provided that you include the source code of that other code when --and as the GNU LGPL requires distribution of source code. --Note that people who make modified versions of Engine3 are not obligated --to grant this special exception for their modified versions; --it is their choice whether to do so. The GNU Lesser General Public License --gives permission to release a modified version without this exception; --this exception also makes it possible to release a modified version object_weapon_melee_polearm_crafted_saber_sword_lightsaber_polearm_gen3 = object_weapon_melee_polearm_crafted_saber_shared_sword_lightsaber_polearm_gen3:new { playerRaces = { "object/creature/player/bothan_male.iff", "object/creature/player/bothan_female.iff", "object/creature/player/human_male.iff", "object/creature/player/human_female.iff", "object/creature/player/ithorian_male.iff", "object/creature/player/ithorian_female.iff", "object/creature/player/moncal_male.iff", "object/creature/player/moncal_female.iff", "object/creature/player/rodian_male.iff", "object/creature/player/rodian_female.iff", "object/creature/player/sullustan_male.iff", "object/creature/player/sullustan_female.iff", "object/creature/player/trandoshan_male.iff", "object/creature/player/trandoshan_female.iff", "object/creature/player/twilek_male.iff", "object/creature/player/twilek_female.iff", "object/creature/player/wookiee_male.iff", "object/creature/player/wookiee_female.iff", "object/creature/player/zabrak_male.iff", "object/creature/player/zabrak_female.iff" }, -- RANGEDATTACK, MELEEATTACK, FORCEATTACK, TRAPATTACK, GRENADEATTACK, HEAVYACIDBEAMATTACK, -- HEAVYLIGHTNINGBEAMATTACK, HEAVYPARTICLEBEAMATTACK, HEAVYROCKETLAUNCHERATTACK, HEAVYLAUNCHERATTACK attackType = MELEEATTACK, -- ENERGY, KINETIC, ELECTRICITY, STUN, BLAST, HEAT, COLD, ACID, LIGHTSABER damageType = LIGHTSABER, -- NONE, LIGHT, MEDIUM, HEAVY armorPiercing = MEDIUM, -- combat_rangedspecialize_bactarifle, combat_rangedspecialize_rifle, combat_rangedspecialize_pistol, combat_rangedspecialize_heavy, combat_rangedspecialize_carbine -- combat_meleespecialize_unarmed, combat_meleespecialize_twohand, combat_meleespecialize_polearm, combat_meleespecialize_onehand, combat_general, -- combat_meleespecialize_twohandlightsaber, jedi_general, combat_meleespecialize_onehandlightsaber xpType = "jedi_general", -- See http://www.ocdsoft.com/files/certifications.xls certificationsRequired = { "cert_polearmlightsaber_gen3" }, -- See http://www.ocdsoft.com/files/accuracy.xls creatureAccuracyModifiers = { "polearmlightsaber_accuracy" }, -- See http://www.ocdsoft.com/files/defense.xls defenderDefenseModifiers = { "melee_defense" }, -- Leave as "dodge" for now, may have additions later defenderSecondaryDefenseModifiers = { "saber_block" }, -- See http://www.ocdsoft.com/files/speed.xls speedModifiers = { "polearmlightsaber_speed" }, -- Leave blank for now damageModifiers = { }, -- The values below are the default values. To be used for blue frog objects primarily healthAttackCost = 50, actionAttackCost = 85, mindAttackCost = 35, forceCost = 36, pointBlankRange = 0, pointBlankAccuracy = 20, idealRange = 3, idealAccuracy = 15, maxRange = 5, maxRangeAccuracy = 5, minDamage = 195, maxDamage = 285, attackSpeed = 5.1, woundsRatio = 25, defenderToughnessModifiers = { "lightsaber_toughness" }, noTrade = 1, childObjects = { {templateFile = "object/tangible/inventory/lightsaber_inventory_3.iff", x = 0, z = 0, y = 0, ox = 0, oy = 0, oz = 0, ow = 0, cellid = -1, containmentType = 4} }, numberExperimentalProperties = {1, 1, 2, 2, 2, 2, 2, 1, 1, 1}, experimentalProperties = {"XX", "XX", "CD", "OQ", "CD", "OQ", "CD", "OQ", "SR", "UT", "CD", "OQ", "OQ", "OQ", "OQ"}, experimentalWeights = {1, 1, 1, 2, 1, 2, 1, 1, 1, 1, 1, 2, 1, 1, 1}, experimentalGroupTitles = {"null", "null", "expDamage", "expDamage", "expDamage", "expDamage", "expEffeciency", "expEffeciency", "expEffeciency", "expEffeciency"}, experimentalSubGroupTitles = {"null", "null", "mindamage", "maxdamage", "attackspeed", "woundchance", "forcecost", "attackhealthcost", "attackactioncost", "attackmindcost"}, experimentalMin = {0, 0, 195, 285, 5.1, 19, 40, 50, 85, 35}, experimentalMax = {0, 0, 215, 305, 4.8, 31, 36, 45, 55, 30}, experimentalPrecision = {0, 0, 0, 0, 1, 0, 0, 0, 0, 0}, experimentalCombineType = {0, 0, 1, 1, 1, 1, 1, 1, 1, 1}, } ObjectTemplates:addTemplate(object_weapon_melee_polearm_crafted_saber_sword_lightsaber_polearm_gen3, "object/weapon/melee/polearm/crafted_saber/sword_lightsaber_polearm_gen3.iff")
Tatwi/legend-of-hondo
MMOCoreORB/bin/scripts/object/weapon/melee/polearm/crafted_saber/sword_lightsaber_polearm_gen3.lua
Lua
agpl-3.0
6,203
<html> <head> <title>Frankenstein, 1831, Vol. 3, Chap. 1, Frame 2</title> </head> <body> <p> I <a href="../V3notes/trembled.html">trembled violently</a> at his exordium, and my father continued--</p><p> "I confess, my son, that I have always looked forward to your marriage with our dear Elizabeth as <a href="../V3notes/domestic.html">the tie of our domestic comfort</a>, and the stay of my declining years. You were attached to each other from your earliest infancy; you studied together, and appeared, in dispositions and tastes, entirely suited to one another. But so blind is the experience of man, that what I conceived to be the best assistants to my plan, may have entirely destroyed it. You, perhaps, regard her as your sister, without any wish that she might become your wife. Nay, you may have met with another whom you may love; and, considering yourself as bound in honour to Elizabeth, this struggle may occasion the poignant misery which you appear to feel."</p><p> "My dear father, re-assure yourself. I love my cousin tenderly and sincerely. I never saw any woman who excited, as Elizabeth does, my warmest admiration and affection. My future hopes and prospects are entirely bound up in the expectation of our union."</p><p> "The expression of your sentiments on this subject, my dear Victor, gives me more pleasure than I have for some time experienced. If you feel thus, we shall assuredly be happy, however present events may cast a gloom over us. But it is this gloom which appears to have taken so strong a hold of your mind, that I wish to dissipate. Tell me, therefore, whether you object to an immediate solemnisation of the marriage. We have been unfortunate, and recent events have drawn us from that every-day tranquillity befitting my years and infirmities. You are younger; yet I do not suppose, possessed as you are of a competent fortune, that an <a href="../V3notes/earlymar.html">early marriage would at all interfere with any future plans of honour and utility</a> that you may have formed. Do not suppose, however, that I wish to dictate happiness to you, or that a delay on your part would cause me any serious uneasiness. Interpret my words with <a href="../V3notes/candour.html">candour</a>, and answer me, I conjure you, with confidence and sincerity."</p> </body> </html>
ebeshero/Pittsburgh_Frankenstein
frankenTexts_HTML/PA_Electronic_Ed/1831_ed/00169-chapterContent-1831.html
HTML
agpl-3.0
2,329
/* * $Id: CardCollectionDao.java 475 2005-12-08 23:44:08 -0800 (Thu, 08 Dec 2005) ivaynberg $ * $Revision: 475 $ * $Date: 2005-12-08 23:44:08 -0800 (Thu, 08 Dec 2005) $ * * ============================================================================== * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.alienlabs.hatchetharry.persistence.dao; import java.io.Serializable; import java.util.List; import org.alienlabs.hatchetharry.model.CardCollection; import org.hibernate.Session; /** * The implementation-independent DAO interface. Defines the operations required * to be supported by an implementation. * * @author igor */ public interface CardCollectionDao extends Serializable { Session getSession(); /** * Load a {@link CardCollection} from the DB, given it's <tt>id</tt>. * * @param id * The id of the Contact to load. * @return CardCollection */ CardCollection load(long id); /** * Save the CardCollection to the DB * * @param CardCollection * @return persistent instance of contact */ CardCollection save(CardCollection contact); /** * Delete a {@link CardCollection} from the DB, given it's <tt>id</tt>. * * @param id * The id of the CardCollection to delete. */ void delete(long id); /** * Return the number of CardCollections in the DB. * * @return count */ int count(); /** * Returns the list of all unique last names in the database * * @return the list of all unique last names in the database */ List<String> getUniqueLastNames(); }
AlienQueen/HatchetHarry
src/main/java/org/alienlabs/hatchetharry/persistence/dao/CardCollectionDao.java
Java
agpl-3.0
2,144
/* * Copyright (C) 2011-2013 The Animo Project * http://animotron.org * * This file is part of Animotron. * * Animotron is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of * the License, or (at your option) any later version. * * Animotron is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of * the GNU Affero General Public License along with Animotron. * If not, see <http://www.gnu.org/licenses/>. */ package org.animotron.cache; import java.io.IOException; import java.io.OutputStream; /** * @author <a href="mailto:[email protected]">Dmitriy Shabanov</a> * @author <a href="mailto:[email protected]">Evgeny Gazdovsky</a> * */ public interface Cache { public boolean available(String key) throws IOException; public void get(String key, OutputStream out) throws IOException; public void get(String key, StringBuilder out) throws IOException; public String get(String key) throws IOException; public OutputStream stream(String key, OutputStream out) throws IOException; public OutputStream stream(String key, StringBuilder out) throws IOException; public void drop(String key) throws IOException; }
animotron/core
src/main/java/org/animotron/cache/Cache.java
Java
agpl-3.0
1,548
<?php /* * This file is part of Kelinux-php. * Copyright (C) 2012 Carlos Garcia Gomez [email protected] * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ require_once 'ke_db.php'; require_once 'ke_tools.php'; abstract class ke_model extends ke_tools { protected $db; protected $table_name; public $errors; public function __construct($name) { $this->db = new ke_db(); $this->table_name = $name; $this->errors = ''; } protected function new_error_msg($msg) { $this->errors .= $msg; } /* * Esta función devuelve TRUE si los datos del objeto se encuentran * en la base de datos. */ abstract public function exists(); /* * Esta función sirve tanto para insertar como para actualizar * los datos del objeto en la base de datos. */ abstract public function save(); /// Esta función sirve para eliminar los datos del objeto de la base de datos abstract public function delete(); /// devuelve el número de elementos de la tabla public function total() { $num = 0; $aux = $this->db->select("SELECT COUNT(*) as num FROM ".$this->table_name.";"); if($aux) $num = intval($aux[0]['num']); return $num; } } ?>
NeoRazorX/kelinux-php
core/ke_model.php
PHP
agpl-3.0
1,890
// ----------> GENERATED FILE - DON'T TOUCH! <---------- // generator: ilarkesto.mda.legacy.generator.EntityGenerator package scrum.server.collaboration; import java.util.*; import ilarkesto.persistence.*; import ilarkesto.core.logging.Log; import ilarkesto.base.*; import ilarkesto.base.time.*; import ilarkesto.auth.*; public abstract class GComment extends AEntity implements ilarkesto.auth.ViewProtected<scrum.server.admin.User>, ilarkesto.search.Searchable, java.lang.Comparable<Comment> { // --- AEntity --- public final CommentDao getDao() { return commentDao; } protected void repairDeadDatob(ADatob datob) { } @Override public void storeProperties(Map properties) { super.storeProperties(properties); properties.put("parentId", this.parentId); properties.put("authorId", this.authorId); properties.put("published", this.published); properties.put("authorName", this.authorName); properties.put("authorEmail", this.authorEmail); properties.put("authorNameVisible", this.authorNameVisible); properties.put("text", this.text); properties.put("dateAndTime", this.dateAndTime == null ? null : this.dateAndTime.toString()); } public int compareTo(Comment other) { return toString().toLowerCase().compareTo(other.toString().toLowerCase()); } private static final ilarkesto.core.logging.Log LOG = ilarkesto.core.logging.Log.get(GComment.class); public static final String TYPE = "comment"; // ----------------------------------------------------------- // - Searchable // ----------------------------------------------------------- public boolean matchesKey(String key) { if (super.matchesKey(key)) return true; if (matchesKey(getText(), key)) return true; return false; } // ----------------------------------------------------------- // - parent // ----------------------------------------------------------- private String parentId; private transient ilarkesto.persistence.AEntity parentCache; private void updateParentCache() { parentCache = this.parentId == null ? null : (ilarkesto.persistence.AEntity)getDaoService().getById(this.parentId); } public final String getParentId() { return this.parentId; } public final ilarkesto.persistence.AEntity getParent() { if (parentCache == null) updateParentCache(); return parentCache; } public final void setParent(ilarkesto.persistence.AEntity parent) { parent = prepareParent(parent); if (isParent(parent)) return; this.parentId = parent == null ? null : parent.getId(); parentCache = parent; fireModified("parent="+parent); } protected ilarkesto.persistence.AEntity prepareParent(ilarkesto.persistence.AEntity parent) { return parent; } protected void repairDeadParentReference(String entityId) { if (this.parentId == null || entityId.equals(this.parentId)) { repairMissingMaster(); } } public final boolean isParentSet() { return this.parentId != null; } public final boolean isParent(ilarkesto.persistence.AEntity parent) { if (this.parentId == null && parent == null) return true; return parent != null && parent.getId().equals(this.parentId); } protected final void updateParent(Object value) { setParent(value == null ? null : (ilarkesto.persistence.AEntity)getDaoService().getById((String)value)); } // ----------------------------------------------------------- // - author // ----------------------------------------------------------- private String authorId; private transient scrum.server.admin.User authorCache; private void updateAuthorCache() { authorCache = this.authorId == null ? null : (scrum.server.admin.User)userDao.getById(this.authorId); } public final String getAuthorId() { return this.authorId; } public final scrum.server.admin.User getAuthor() { if (authorCache == null) updateAuthorCache(); return authorCache; } public final void setAuthor(scrum.server.admin.User author) { author = prepareAuthor(author); if (isAuthor(author)) return; this.authorId = author == null ? null : author.getId(); authorCache = author; fireModified("author="+author); } protected scrum.server.admin.User prepareAuthor(scrum.server.admin.User author) { return author; } protected void repairDeadAuthorReference(String entityId) { if (this.authorId == null || entityId.equals(this.authorId)) { setAuthor(null); } } public final boolean isAuthorSet() { return this.authorId != null; } public final boolean isAuthor(scrum.server.admin.User author) { if (this.authorId == null && author == null) return true; return author != null && author.getId().equals(this.authorId); } protected final void updateAuthor(Object value) { setAuthor(value == null ? null : (scrum.server.admin.User)userDao.getById((String)value)); } // ----------------------------------------------------------- // - published // ----------------------------------------------------------- private boolean published; public final boolean isPublished() { return published; } public final void setPublished(boolean published) { published = preparePublished(published); if (isPublished(published)) return; this.published = published; fireModified("published="+published); } protected boolean preparePublished(boolean published) { return published; } public final boolean isPublished(boolean published) { return this.published == published; } protected final void updatePublished(Object value) { setPublished((Boolean)value); } // ----------------------------------------------------------- // - authorName // ----------------------------------------------------------- private java.lang.String authorName; public final java.lang.String getAuthorName() { return authorName; } public final void setAuthorName(java.lang.String authorName) { authorName = prepareAuthorName(authorName); if (isAuthorName(authorName)) return; this.authorName = authorName; fireModified("authorName="+authorName); } protected java.lang.String prepareAuthorName(java.lang.String authorName) { authorName = Str.removeUnreadableChars(authorName); return authorName; } public final boolean isAuthorNameSet() { return this.authorName != null; } public final boolean isAuthorName(java.lang.String authorName) { if (this.authorName == null && authorName == null) return true; return this.authorName != null && this.authorName.equals(authorName); } protected final void updateAuthorName(Object value) { setAuthorName((java.lang.String)value); } // ----------------------------------------------------------- // - authorEmail // ----------------------------------------------------------- private java.lang.String authorEmail; public final java.lang.String getAuthorEmail() { return authorEmail; } public final void setAuthorEmail(java.lang.String authorEmail) { authorEmail = prepareAuthorEmail(authorEmail); if (isAuthorEmail(authorEmail)) return; this.authorEmail = authorEmail; fireModified("authorEmail="+authorEmail); } protected java.lang.String prepareAuthorEmail(java.lang.String authorEmail) { authorEmail = Str.removeUnreadableChars(authorEmail); return authorEmail; } public final boolean isAuthorEmailSet() { return this.authorEmail != null; } public final boolean isAuthorEmail(java.lang.String authorEmail) { if (this.authorEmail == null && authorEmail == null) return true; return this.authorEmail != null && this.authorEmail.equals(authorEmail); } protected final void updateAuthorEmail(Object value) { setAuthorEmail((java.lang.String)value); } // ----------------------------------------------------------- // - authorNameVisible // ----------------------------------------------------------- private boolean authorNameVisible; public final boolean isAuthorNameVisible() { return authorNameVisible; } public final void setAuthorNameVisible(boolean authorNameVisible) { authorNameVisible = prepareAuthorNameVisible(authorNameVisible); if (isAuthorNameVisible(authorNameVisible)) return; this.authorNameVisible = authorNameVisible; fireModified("authorNameVisible="+authorNameVisible); } protected boolean prepareAuthorNameVisible(boolean authorNameVisible) { return authorNameVisible; } public final boolean isAuthorNameVisible(boolean authorNameVisible) { return this.authorNameVisible == authorNameVisible; } protected final void updateAuthorNameVisible(Object value) { setAuthorNameVisible((Boolean)value); } // ----------------------------------------------------------- // - text // ----------------------------------------------------------- private java.lang.String text; public final java.lang.String getText() { return text; } public final void setText(java.lang.String text) { text = prepareText(text); if (isText(text)) return; this.text = text; fireModified("text="+text); } protected java.lang.String prepareText(java.lang.String text) { text = Str.removeUnreadableChars(text); return text; } public final boolean isTextSet() { return this.text != null; } public final boolean isText(java.lang.String text) { if (this.text == null && text == null) return true; return this.text != null && this.text.equals(text); } protected final void updateText(Object value) { setText((java.lang.String)value); } // ----------------------------------------------------------- // - dateAndTime // ----------------------------------------------------------- private ilarkesto.base.time.DateAndTime dateAndTime; public final ilarkesto.base.time.DateAndTime getDateAndTime() { return dateAndTime; } public final void setDateAndTime(ilarkesto.base.time.DateAndTime dateAndTime) { dateAndTime = prepareDateAndTime(dateAndTime); if (isDateAndTime(dateAndTime)) return; this.dateAndTime = dateAndTime; fireModified("dateAndTime="+dateAndTime); } protected ilarkesto.base.time.DateAndTime prepareDateAndTime(ilarkesto.base.time.DateAndTime dateAndTime) { return dateAndTime; } public final boolean isDateAndTimeSet() { return this.dateAndTime != null; } public final boolean isDateAndTime(ilarkesto.base.time.DateAndTime dateAndTime) { if (this.dateAndTime == null && dateAndTime == null) return true; return this.dateAndTime != null && this.dateAndTime.equals(dateAndTime); } protected final void updateDateAndTime(Object value) { value = value == null ? null : new ilarkesto.base.time.DateAndTime((String)value); setDateAndTime((ilarkesto.base.time.DateAndTime)value); } public void updateProperties(Map<?, ?> properties) { for (Map.Entry entry : properties.entrySet()) { String property = (String) entry.getKey(); if (property.equals("id")) continue; Object value = entry.getValue(); if (property.equals("parentId")) updateParent(value); if (property.equals("authorId")) updateAuthor(value); if (property.equals("published")) updatePublished(value); if (property.equals("authorName")) updateAuthorName(value); if (property.equals("authorEmail")) updateAuthorEmail(value); if (property.equals("authorNameVisible")) updateAuthorNameVisible(value); if (property.equals("text")) updateText(value); if (property.equals("dateAndTime")) updateDateAndTime(value); } } protected void repairDeadReferences(String entityId) { super.repairDeadReferences(entityId); repairDeadParentReference(entityId); repairDeadAuthorReference(entityId); } // --- ensure integrity --- public void ensureIntegrity() { super.ensureIntegrity(); if (!isParentSet()) { repairMissingMaster(); return; } try { getParent(); } catch (EntityDoesNotExistException ex) { LOG.info("Repairing dead parent reference"); repairDeadParentReference(this.parentId); } try { getAuthor(); } catch (EntityDoesNotExistException ex) { LOG.info("Repairing dead author reference"); repairDeadAuthorReference(this.authorId); } } static CommentDao commentDao; public static final void setCommentDao(CommentDao commentDao) { GComment.commentDao = commentDao; } }
hogi/kunagi
src/generated/java/scrum/server/collaboration/GComment.java
Java
agpl-3.0
13,504
const { Array } = require.main.require('./Tag/Classes'); class GetTag extends Array { constructor(client) { super(client, { name: 'get', args: [ { name: 'array' }, { name: 'index' } ], minArgs: 2, maxArgs: 2 }); } async execute(ctx, args) { const res = await super.execute(ctx, args, true); args = args.parsedArgs; let arr = await this.loadArray(ctx, args.array); let index = this.parseInt(args.index, 'index'); return res.setContent(arr[index]); } get implicit() { return false; } } module.exports = GetTag;
Ratismal/blargbot
Production/Tags/Array/Get.js
JavaScript
agpl-3.0
619
/* =========================================================================== Return to Castle Wolfenstein multiplayer GPL Source Code Copyright (C) 1999-2010 id Software LLC, a ZeniMax Media company. This file is part of the Return to Castle Wolfenstein multiplayer GPL Source Code (“RTCW MP Source Code”). RTCW MP Source Code is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. RTCW MP Source Code is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with RTCW MP Source Code. If not, see <http://www.gnu.org/licenses/>. In addition, the RTCW MP Source Code is also subject to certain additional terms. You should have received a copy of these additional terms immediately following the terms and conditions of the GNU General Public License which accompanied the RTCW MP Source Code. If not, please request a copy in writing from id Software at the address below. If you have questions concerning this license or the applicable additional terms, you may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville, Maryland 20850 USA. =========================================================================== */ #include "g_shared.h" #include "cmd.h" #include "cvar.h" #include "qcommon_io.h" #include "g_sv_shared.h" #include "scr_vm.h" #include "sv_snapshot.h" /* ================== CheatsOk ================== */ int __cdecl CheatsOk(gentity_t *ent) { const char *v1; int result; const char *v3; bool bCreateFX; if ( g_cheats->boolean ) { bCreateFX = 0; if ( Cvar_FindVar("createfx") ) { bCreateFX = 1; } if ( ent->health > 0 || bCreateFX ) { result = 1; } else { v3 = va("%c \"GAME_MUSTBEALIVECOMMAND\"", 101); SV_GameSendServerCommand(ent - g_entities, 0, v3); result = 0; } } else { v1 = va("%c \"GAME_CHEATSNOTENABLED\"", 101); SV_GameSendServerCommand(ent - g_entities, 0, v1); result = 0; } return result; } #if 0 void __cdecl Cmd_Take_f(gentity_t *ent) { char *amt; // ST3C_4@2 int v2; // ST08_4@28 WeaponVariantDef *v3; // eax@28 int v4; // eax@34 int v5; // ST08_4@43 WeaponVariantDef *v6; // eax@43 signed int j; // [sp+20h] [bp-20h]@38 signed int i; // [sp+24h] [bp-1Ch]@30 int slot; // [sp+28h] [bp-18h]@15 char *name; // [sp+2Ch] [bp-14h]@2 int amount; // [sp+34h] [bp-Ch]@2 unsigned int weapIndex; // [sp+38h] [bp-8h]@27 int take_all; // [sp+3Ch] [bp-4h]@5 if ( CheatsOk(ent) ) { amt = SV_Cmd_Argv(2); amount = atoi(amt); name = SV_Cmd_Argv(1); if ( name ) { if ( strlen(name) ) { take_all = Q_stricmp(name, "all") == 0; if ( !take_all ) { if ( Q_stricmpn(name, "health", 6) ) { goto LABEL_47; } } if ( amount ) { ent->health -= amount; if ( ent->health < 1 ) { ent->health = 1; } } else { ent->health = 1; } if ( take_all ) { LABEL_47: if ( !take_all && Q_stricmp(name, "weapons") ) { goto LABEL_48; } for ( slot = 0; slot < 15; ++slot ) { if ( ent->client->ps.heldWeapons[slot].weapon ) { BG_TakePlayerWeapon(&ent->client->ps, ent->client->ps.heldWeapons[slot].weapon); } } if ( ent->client->ps.weapon ) { ent->client->ps.weapon = 0; G_SelectWeaponIndex(ent - g_entities, 0); } if ( take_all ) { LABEL_48: if ( !take_all && Q_stricmpn(name, "ammo", 4) ) { goto LABEL_49; } if ( amount ) { if ( ent->client->ps.weapon ) { weapIndex = ent->client->ps.weapon; BG_AddAmmoToPool(&ent->client->ps, weapIndex, -amount); if ( BG_GetAmmoNotInClip(&ent->client->ps, weapIndex) < 0 ) { v2 = BG_GetAmmoNotInClip(&ent->client->ps, weapIndex); v3 = BG_GetWeaponVariantDef(weapIndex); BG_AddAmmoToClip(&ent->client->ps, v3->iClipIndex, v2); BG_SetAmmoInPool(&ent->client->ps, weapIndex, 0); } } } else { for ( i = 0; i < 15; ++i ) { weapIndex = ent->client->ps.heldWeapons[i].weapon; if ( weapIndex ) { BG_SetAmmoInPool(&ent->client->ps, weapIndex, 0); v4 = BG_ClipForWeapon(weapIndex); BG_SetAmmoInClip(&ent->client->ps, v4, 0); } } } if ( take_all ) { LABEL_49: if ( !Q_stricmpn(name, "allammo", 7) && amount ) { for ( j = 0; j < 15; ++j ) { weapIndex = ent->client->ps.heldWeapons[j].weapon; if ( weapIndex ) { BG_AddAmmoToPool(&ent->client->ps, weapIndex, -amount); if ( BG_GetAmmoNotInClip(&ent->client->ps, weapIndex) < 0 ) { v5 = BG_GetAmmoNotInClip(&ent->client->ps, weapIndex); v6 = BG_GetWeaponVariantDef(weapIndex); BG_AddAmmoToClip(&ent->client->ps, v6->iClipIndex, v5); BG_SetAmmoInPool(&ent->client->ps, weapIndex, 0); } } } } } } } } } } } /* ================== Cmd_Give_f Give items to a client ================== */ void __cdecl Cmd_Give_f(gentity_t *ent) { char *amt; // ST70_4@2 char v2; // al@23 float *v3; // ST40_4@38 int v4; // ST10_4@46 int v5; // eax@46 int v6; // ST10_4@46 unsigned int v7; // eax@46 signed int i; // [sp+48h] [bp-2Ch]@31 int slot; // [sp+4Ch] [bp-28h]@25 gentity_t *it_ent; // [sp+50h] [bp-24h]@38 char *name; // [sp+54h] [bp-20h]@2 int give_all; // [sp+58h] [bp-1Ch]@5 WeaponVariantDef *weapVariantDef; // [sp+60h] [bp-14h]@36 int amount; // [sp+64h] [bp-10h]@2 unsigned int weapIndex; // [sp+68h] [bp-Ch]@13 WeaponDef *weapDef; // [sp+6Ch] [bp-8h]@39 gitem_s *it; // [sp+70h] [bp-4h]@36 if ( CheatsOk(ent) ) { amt = SV_Cmd_Argv(2); amount = atoi(amt); name = SV_Cmd_Argv(1); if ( name ) { if ( strlen(name) ) { give_all = Q_stricmp(name, "all") == 0; if ( !give_all && Q_stricmpn(name, "health", 6) || (!amount ? (ent->health = ent->client->ps.stats[2]) : (ent->health += amount), give_all) ) { if ( !give_all && Q_stricmp(name, "weapons") ) { goto LABEL_50; } for ( weapIndex = 1; weapIndex < BG_GetNumWeapons(); ++weapIndex ) { if ( BG_CanPlayerHaveWeapon(weapIndex) ) { BG_TakePlayerWeapon(&ent->client->ps, weapIndex); G_GivePlayerWeapon(&ent->client->ps, weapIndex, 0, 0); } } if ( give_all ) { LABEL_50: if ( !give_all && Q_stricmpn(name, "ammo", 4) ) { goto LABEL_51; } if ( amount ) { if ( ent->client->ps.weapon ) { v2 = BG_GetPlayerWeaponModel(&ent->client->ps, ent->client->ps.weapon); Add_Ammo(ent, ent->client->ps.weapon, v2, amount, 1); } } else { for ( slot = 0; slot < 15; Add_Ammo(ent, ent->client->ps.heldWeapons[slot++].weapon, 0, 998, 1) ) { ; } } if ( give_all ) { LABEL_51: if ( Q_stricmpn(name, "allammo", 7) ) { goto LABEL_52; } if ( !amount ) { goto LABEL_52; } for ( i = 0; i < 15; Add_Ammo(ent, ent->client->ps.heldWeapons[i++].weapon, 0, amount, 1) ) { ; } if ( give_all ) { LABEL_52: if ( !give_all ) { level.initializing = 1; weapVariantDef = 0; weapIndex = 0; it = G_FindItem(name, 0); if ( it ) { it_ent = G_Spawn(); v3 = it_ent->r.currentOrigin; it_ent->r.currentOrigin[0] = ent->r.currentOrigin[0]; v3[1] = ent->r.currentOrigin[1]; v3[2] = ent->r.currentOrigin[2]; G_GetItemClassname(it, &it_ent->classname); G_SpawnItem(it_ent, it); it_ent->active = 1; if ( it->giType == IT_WEAPON ) { weapIndex = it_ent->trigger.timestamp % 2048; weapVariantDef = BG_GetWeaponVariantDef(weapIndex); weapDef = BG_GetWeaponDef(weapIndex); if ( weapDef->offhandClass == 3 ) { ent->client->ps.offhandSecondary = 1; } else if ( weapDef->offhandClass == 2 ) { ent->client->ps.offhandSecondary = 0; } } Touch_Item(it_ent, ent, 0); it_ent->active = 0; if ( it_ent->r.inuse ) { G_FreeEntity(it_ent); } if ( it->giType == IT_WEAPON ) { v4 = weapVariantDef->iClipSize; v5 = BG_ClipForWeapon(weapIndex); BG_SetAmmoInClip(&ent->client->ps, v5, v4); v6 = BG_GetStartAmmo(weapIndex) - weapVariantDef->iClipSize; v7 = BG_AmmoForWeapon(weapIndex); BG_SetAmmoInPool(&ent->client->ps, v7, v6); } level.initializing = 0; } else { level.initializing = 0; } } } } } } } } } } #endif void __cdecl Cmd_DemiGod_f(gentity_t *ent) { const char *msg; if ( CheatsOk(ent) ) { ent->flags ^= 2u; if ( ent->flags & 2 ) { msg = "GAME_DEMI_GODMODE_ON"; } else { msg = "GAME_DEMI_GODMODE_OFF"; } SV_GameSendServerCommand(ent - g_entities, 0, va("%c \"%s\"", 101, msg)); } } /* ================== Cmd_God_f Sets client to godmode argv(0) god ================== */ void __cdecl Cmd_God_f(gentity_t *ent) { const char *msg; if ( CheatsOk(ent) ) { ent->flags ^= 1u; if ( ent->flags & 1 ) { msg = "GAME_GODMODE_ON"; } else { msg = "GAME_GODMODE_OFF"; } SV_GameSendServerCommand(ent - g_entities, 0, va("%c \"%s\"", 101, msg)); } } /* ================== Cmd_Notarget_f Sets client to notarget argv(0) notarget ================== */ void __cdecl Cmd_Notarget_f(gentity_t *ent) { const char *msg; if ( CheatsOk(ent) ) { ent->flags ^= 4u; if ( ent->flags & 4 ) { msg = va("%c \"%s\"", 101, "GAME_NOTARGETON"); } else { msg = va("%c \"%s\"", 101, "GAME_NOTARGETOFF"); } SV_GameSendServerCommand(ent - g_entities, 0, msg); } } void __cdecl Cmd_UFO_f(gentity_t *ent) { const char *v1; // eax@3 if ( CheatsOk(ent) ) { if ( ent->client->ufo ) { ent->client->ufo = qfalse; v1 = va("%c \"%s\"", 101, "GAME_UFOOFF"); } else { ent->client->ufo = qtrue; v1 = va("%c \"%s\"", 101, "GAME_UFOON"); } SV_GameSendServerCommand(ent - g_entities, 0, v1); } } /* ================== Cmd_Noclip_f argv(0) noclip ================== */ void __cdecl Cmd_Noclip_f(gentity_t *ent) { const char *v1; if ( CheatsOk(ent) ) { if ( ent->client->noclip ) { ent->client->noclip = qfalse; v1 = va("%c \"%s\"", 101, "GAME_NOCLIPOFF"); } else { ent->client->noclip = qtrue; v1 = va("%c \"%s\"", 101, "GAME_NOCLIPON"); } SV_GameSendServerCommand(ent - g_entities, 0, v1); } } /* ================= Cmd_Kill_f ================= */ void Cmd_Kill_f( gentity_t *ent ) { if(ent->client->sess.sessionState != SESS_STATE_PLAYING || !CheatsOk(ent)) { return; } ent->flags &= 0xFFFFFFFC; ent->health = 0; ent->client->ps.stats[0] = 0; player_die(ent, ent, ent, 100000, 13, 0, 0, HITLOC_NONE, 0); } /* ================== Cmd_Tell_f ================== */ /* static void Cmd_Tell_f( gentity_t *ent ) { int targetNum; gentity_t *target; char *p; char arg[MAX_TOKEN_CHARS]; if ( SV_Cmd_Argc() < 2 ) { return; } targetNum = atoi( SV_Cmd_Argv( 1 ) ); if ( targetNum < 0 || targetNum >= level.maxclients ) { return; } target = &g_entities[targetNum]; if ( !target || !target->client ) { return; } p = SV_Cmd_Argsv( 2, arg, sizeof(arg) ); G_LogPrintf( "tell: %s to %s: %s\n", ent->client->ps.netname, target->client->ps.netname, p ); G_Say( ent, target, SAY_TELL, p ); G_Say( ent, ent, SAY_TELL, p ); } */ /* ================== Cmd_Where_f ================== */ void Cmd_Where_f( gentity_t *ent ) { char s[64]; Com_sprintf(s, sizeof(s), "(%g %g %g)", ent->r.currentOrigin[0], ent->r.currentOrigin[1], ent->r.currentOrigin[2]); SV_GameSendServerCommand( ent - g_entities, 0, va("%c \"\x15%s\n\"", 'e', s) ); } void __cdecl Scr_PlayerVote(gentity_t *self, char *option) { Scr_AddString(option); Scr_Notify(self, scr_const.vote, 1u); } void __cdecl Cmd_Vote_f(gentity_t *ent) { const char *msg; if ( g_oldVoting->boolean ) { if ( !level.voteTime ) { SV_GameSendServerCommand(ent - g_entities, 0, va("%c \"GAME_NOVOTEINPROGRESS\"", 'e')); return; } if ( ent->client->ps.eFlags & 0x100000 ) { SV_GameSendServerCommand(ent - g_entities, 0, va("%c \"GAME_VOTEALREADYCAST\"", 'e')); return; } /* if ( ent->client->sess.cs.team == 3 ) { SV_GameSendServerCommand(ent - g_entities, 0, va("%c \"GAME_NOSPECTATORVOTE\"", 'e')); return; } */ SV_GameSendServerCommand(ent - g_entities, 0, va("%c \"GAME_VOTECAST\"", 'e')); ent->client->ps.eFlags |= 0x100000u; } msg = SV_Cmd_Argv(1); if ( msg[0] != 'y' && msg[1] != 'Y' && msg[1] != '1' ) { if ( g_oldVoting->boolean ) { SV_SetConfigstring(CS_VOTE_NO, va("%i", ++level.voteNo)); } else { Scr_PlayerVote(ent, "no"); } } else if ( g_oldVoting->boolean ) { SV_SetConfigstring(CS_VOTE_YES, va("%i", ++level.voteYes)); } else { Scr_PlayerVote(ent, "yes"); } } /* ================= Cmd_SetViewpos_f ================= */ void Cmd_SetViewpos_f( gentity_t *ent ) { vec3_t origin, angles; int i; if ( !g_cheats->boolean ) { SV_GameSendServerCommand( ent - g_entities, 0, va("%c \"GAME_CHEATSNOTENABLED\"", 101) ); return; } if ( SV_Cmd_Argc() < 4 || SV_Cmd_Argc() > 6 ) { SV_GameSendServerCommand( ent - g_entities, 0, va("%c \"GAME_USAGE\x15: setviewpos x y z yaw\"", 101) ); return; } VectorClear( angles ); for ( i = 0 ; i < 3 ; i++ ) { origin[i] = atof( SV_Cmd_Argv( i + 1 ) ); } angles[YAW] = atof( SV_Cmd_Argv( 4 ) ); angles[PITCH] = atof( SV_Cmd_Argv( 5 ) ); TeleportPlayer( ent, origin, angles ); } /* ============== Cmd_EntityCount_f ============== */ void Cmd_EntityCount_f( gentity_t *ent ) { if ( !g_cheats->integer ) { return; } Com_Printf(CON_CHANNEL_DONT_FILTER, "entity count = %i\n", level.num_entities ); } void Cmd_PrintEntities_f() { G_PrintEntities(); } void __cdecl Cmd_Say_f(gentity_t *ent, int mode, int arg0) { char *p; char b[1024]; if ( SV_Cmd_Argc() >= 2 || arg0 ) { if ( arg0 ) { p = SV_Cmd_Argsv(0, b, sizeof(b)); } else { p = SV_Cmd_Argsv(1, b, sizeof(b)); } G_Say(ent, 0, mode, p); } } void __cdecl Cmd_MenuResponse_f(gentity_t *pEnt) { char szServerId[1024]; char szMenuName[1024]; int iMenuIndex; char szResponse[1024]; iMenuIndex = -1; if ( SV_Cmd_Argc() == 4 ) { SV_Cmd_ArgvBuffer(1, szServerId, 1024); if ( atoi(szServerId) != Cvar_GetInt("sv_serverId")) { return; } SV_Cmd_ArgvBuffer(2, szMenuName, 1024); iMenuIndex = atoi(szMenuName); if ( iMenuIndex >= 0 && iMenuIndex < 32 ) { SV_GetConfigstring(iMenuIndex + 1970, szMenuName, 1024); } SV_Cmd_ArgvBuffer(3, szResponse, 1024); } else { szMenuName[0] = 0; strcpy(szResponse, "bad"); } Scr_AddString(szResponse); Scr_AddString(szMenuName); Scr_Notify(pEnt, scr_const.menuresponse, 2u); } void Cmd_Score_f(gentity_t* ent) { SendScoreboard(ent); } int __cdecl Cmd_FollowCycle_f(gentity_t *ent, int dir) { int i; int health; int clientNum; int otherFlags; struct clientState_s archcs; struct playerState_s ps; if ( dir != 1 && dir != -1 ) { Com_Error(ERR_DROP, "Cmd_FollowCycle_f: bad dir %i", dir); } assert ( ent->client != NULL); if ( ent->client->sess.sessionState != SESS_STATE_SPECTATOR ) { return qfalse; } ent->client->lastFollowedClient = -1; //Clear this so we never jump back onto old player if ( ent->client->sess.forceSpectatorClient < 0 ) { clientNum = ent->client->spectatorClient; if ( clientNum < 0 ) { clientNum = 0; } i = clientNum; do { clientNum += dir; if ( clientNum >= level.maxclients ) { clientNum = 0; } if ( clientNum < 0 ) { clientNum = level.maxclients - 1; } if ( SV_GetArchivedClientInfo(clientNum, &ent->client->sess.archiveTime, &ps, &archcs, 0, &health, &otherFlags) ) { assert(otherFlags & POF_PLAYER); if ( G_ClientCanSpectateTeamOrLocalPlayer(ent->client, &archcs) ) { ent->client->spectatorClient = clientNum; ent->client->sess.sessionState = SESS_STATE_SPECTATOR; /* Scr_AddEntity(&g_entities[clientNum], 0); Scr_Notify(ent, scr_const.spectator_cycle, 1u); */ return qtrue; } } } while ( clientNum != i ); } return qfalse; } void __cdecl StopFollowing(gentity_t *ent) { gclient_t *client; vec3_t vAngles; // col_context_t context; vec3_t vEnd; vec3_t vMins; trace_t trace; vec3_t vForward; vec3_t vPos; vec3_t vUp; vec3_t vMaxs; /* trace.normal.vec.v[0] = 0.0; trace.normal.vec.v[1] = 0.0; trace.normal.vec.v[2] = 0.0; trace.normal.vec.v[3] = 0.0; col_context_t::col_context_t(&context); */ client = ent->client; assert(client != NULL); client->sess.forceSpectatorClient = -1; client->sess.killCamEntity = -1; // client->sess.killCamTargetEntity = ent->s.number; client->spectatorClient = -1; if ( client->ps.otherFlags & 2 ) { /* client->ps.eFlags &= 0xFFFFBCFF; client->ps.viewlocked = 0; client->ps.viewlocked_entNum = 1023; */ G_GetPlayerViewOrigin(&client->ps, vPos); BG_GetPlayerViewDirection(&client->ps, vForward, 0, vUp); vAngles[0] = client->ps.viewangles[0]; vAngles[1] = client->ps.viewangles[1]; vAngles[2] = client->ps.viewangles[2]; vAngles[0] = vAngles[0] + 15.0; vEnd[0] = (float)(-40.0 * vForward[0]) + vPos[0]; vEnd[1] = (float)(-40.0 * vForward[1]) + vPos[1]; vEnd[2] = (float)(-40.0 * vForward[2]) + vPos[2]; vEnd[0] = (float)(10.0 * vUp[0]) + vEnd[0]; vEnd[1] = (float)(10.0 * vUp[1]) + vEnd[1]; vEnd[2] = (float)(10.0 * vUp[2]) + vEnd[2]; vMins[0] = -8.0; vMins[1] = -8.0; vMins[2] = -8.0; vMaxs[0] = 8.0; vMaxs[1] = 8.0; vMaxs[2] = 8.0; G_TraceCapsule(&trace, vPos, vMins, vMaxs, vEnd, 1023, 0x810011/*, &context*/); Vec3Lerp(vPos, vEnd, trace.fraction, vPos); client->ps.clientNum = ent - g_entities; //Not in Blackops client->ps.eFlags &= 0xFFFFFCFF; client->ps.viewlocked = 0; client->ps.viewlocked_entNum = 1023; /// client->ps.pm_flags &= 0xFFFEFFEF; client->ps.weapFlags &= 0xFFFFFFBF; client->ps.otherFlags &= 0xFFFFFFFD; client->ps.fWeaponPosFrac = 0.0; G_SetOrigin(ent, vPos); client->ps.origin[0] = vPos[0]; client->ps.origin[1] = vPos[1]; client->ps.origin[2] = vPos[2]; SetClientViewAngle(ent, vAngles); if ( !ent->tagInfo ) { ent->r.currentAngles[0] = 0.0; } client->ps.shellshockIndex = 0; client->ps.shellshockTime = 0; client->ps.shellshockDuration = 0; /* client->ps.predictableEventSequence = 0; client->ps.predictableEventSequenceOld = 0; client->ps.unpredictableEventSequence = 0; client->ps.unpredictableEventSequenceOld = 0; v2 = client->ps.predictableEvents; *v2 = 0; v2[1] = 0; v2[2] = 0; v2[3] = 0; v3 = client->ps.unpredictableEvents; *v3 = 0; v3[1] = 0; v3[2] = 0; v3[3] = 0; */ } } /* ================= ClientCommand ================= */ void ClientCommand( int clientNum ) { gentity_t *ent; char cmd[MAX_TOKEN_CHARS]; ent = g_entities + clientNum; if ( !ent->client ) { return; // not fully in game yet } SV_Cmd_ArgvBuffer( 0, cmd, sizeof( cmd ) ); if ( Q_stricmp( cmd, "say" ) == 0 ) { Cmd_Say_f( ent, SAY_ALL, qfalse ); return; } if ( Q_stricmp( cmd, "say_team" ) == 0 ) { Cmd_Say_f( ent, SAY_TEAM, qfalse ); return; } // -NERVE - SMF if ( Q_stricmp( cmd, "tell" ) == 0 ) { // Cmd_Tell_f( ent ); return; } if ( Q_stricmp( cmd, "score" ) == 0 ) { Cmd_Score_f( ent ); return; } if ( Q_stricmp( cmd, "mr" ) == 0 ) { Cmd_MenuResponse_f(ent); return; } // ignore all other commands when at intermission // if ( level.intermissiontime ) { // Cmd_Say_f (ent, qfalse, qtrue); // NERVE - SMF - we don't want to spam the clients with this. // return; // } if ( Q_stricmp( cmd, "give" ) == 0 ) { Cmd_Give_f( ent ); } else if ( Q_stricmp( cmd, "god" ) == 0 ) { Cmd_God_f( ent ); } else if ( Q_stricmp( cmd, "demigod" ) == 0 ) { Cmd_DemiGod_f( ent ); } else if ( Q_stricmp( cmd, "take" ) == 0 ) { Cmd_Take_f( ent ); } else if ( Q_stricmp( cmd, "notarget" ) == 0 ) { Cmd_Notarget_f( ent ); } else if ( Q_stricmp( cmd, "noclip" ) == 0 ) { Cmd_Noclip_f( ent ); } else if ( Q_stricmp( cmd, "ufo" ) == 0 ) { Cmd_UFO_f( ent ); } else if ( Q_stricmp( cmd, "kill" ) == 0 ) { Cmd_Kill_f( ent ); } else if ( Q_stricmp( cmd, "where" ) == 0 ) { Cmd_Where_f( ent ); } else if ( Q_stricmp( cmd, "callvote" ) == 0 ) { Cmd_CallVote_f( ent ); } else if ( Q_stricmp( cmd, "vote" ) == 0 ) { Cmd_Vote_f( ent ); } else if ( Q_stricmp( cmd, "setviewpos" ) == 0 ) { Cmd_SetViewpos_f( ent ); } else if ( Q_stricmp( cmd, "entitycount" ) == 0 ) { Cmd_EntityCount_f( ent ); } else if ( Q_stricmp( cmd, "printentities" ) == 0 ) { Cmd_PrintEntities_f( ent ); } else { SV_GameSendServerCommand( clientNum, 0, va( "%c \"GAME_UNKNOWNCLIENTCOMMAND\x15%s\"", 101, cmd ) ); } }
D4edalus/CoD4x1.8_Server_Pub
src/g_cmds.c
C
agpl-3.0
23,983
/* This file is part of the Juju GUI, which lets users view and manage Juju environments within a graphical interface (https://launchpad.net/juju-gui). Copyright (C) 2012-2013 Canonical Ltd. This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License version 3, as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranties of MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ 'use strict'; (function() { describe('Browser charm view', function() { var container, CharmView, cleanIconHelper, factory, models, node, utils, view, views, Y, testContainer; before(function(done) { Y = YUI(GlobalConfig).use( 'datatype-date', 'datatype-date-format', 'charmstore-api', 'json-stringify', 'juju-charm-models', 'juju-tests-utils', 'juju-tests-factory', 'node', 'node-event-simulate', 'subapp-browser-charmview', function(Y) { views = Y.namespace('juju.browser.views'); models = Y.namespace('juju.models'); utils = Y.namespace('juju-tests.utils'); factory = Y.namespace('juju-tests.factory'); CharmView = views.BrowserCharmView; cleanIconHelper = utils.stubCharmIconPath(); done(); }); }); beforeEach(function() { window.flags = {}; container = utils.makeContainer(this, 'container'); var testcontent = [ '<div id=testcontent><div class="bws-view-data">', '</div></div>' ].join(); Y.Node.create(testcontent).appendTo(container); // Mock out a dummy location for the Store used in view instances. window.juju_config = { charmworldURL: 'http://localhost' }; node = Y.one('#testcontent'); }); afterEach(function() { window.flags = {}; if (view) { view.destroy(); } if (testContainer) { testContainer.remove(true); } node.remove(true); delete window.juju_config; container.remove(true); }); after(function() { cleanIconHelper(); }); it('renders for inspector mode correctly', function() { var data = utils.loadFixture('data/browsercharm.json', true); // We don't want any files so we don't have to mock/load them. data.files = []; view = new CharmView({ entity: new models.Charm(data), container: utils.makeContainer(this), forInspector: true }); view.render(); assert.isNull(view.get('container').one('.heading')); // There is no 'related charms' tab to display. assert.equal(view.get('container').all('.related-charms').size(), 0); }); // Return the charm heading node included in the charm detail view. var makeHeading = function(context, is_subordinate) { var data = utils.loadFixture('data/browsercharm.json', true); // We don't want any files so we don't have to mock/load them. data.files = []; data.is_subordinate = is_subordinate; utils.makeContainer(context); view = new CharmView({ entity: new models.Charm(data), container: utils.makeContainer(context) }); view.render(); var heading = view.get('container').one('.header'); assert.isNotNull(heading); return heading; }; it('avoids showing the subordinate message for non-subordinate charms', function() { var heading = makeHeading(this, false); assert.notInclude(heading.getContent(), 'Subordinate charm'); }); it('shows the subordinate message if the charm is a subordinate', function() { var heading = makeHeading(this, true); assert.include(heading.getContent(), 'Subordinate charm'); }); it('renders local charms for inspector mode correctly', function() { var data = utils.loadFixture('data/browsercharm.json', true); // We don't want any files so we don't have to mock/load them. data.files = []; data.url = 'local:precise/apache2-10'; var charm = new models.Charm(data); charm.set('scheme', 'local'); view = new CharmView({ entity: charm, container: utils.makeContainer(this), forInspector: true }); view.render(); assert.isNull(view.get('container').one('.heading')); assert.isNull(view.get('container').one('#readme')); assert.isNull(view.get('container').one('#configuration')); assert.isNull(view.get('container').one('#code')); assert.isNull(view.get('container').one('#features')); }); it('has sharing links', function() { view = new CharmView({ entity: new models.Charm({ files: [ 'hooks/install', 'readme.rst' ], id: 'precise/wordpress', code_source: { location: 'lp:~foo'} }), container: utils.makeContainer(this), charmstore: factory.makeFakeCharmstore() }); view.render(); var links = container.all('#sharing a'); assert.equal(links.size(), 3); }); it('should be able to locate a readme file', function() { view = new CharmView({ entity: new models.Charm({ files: [ 'hooks/install', 'readme.rst' ], id: 'precise/ceph-9', code_source: { location: 'lp:~foo' } }) }); view._locateReadme().should.eql('readme.rst'); // Matches for caps as well. view.get('entity').set('files', [ 'hooks/install', 'README.md' ]); view._locateReadme().should.eql('README.md'); }); it('can generate source, bug, and revno links from its charm', function() { view = new CharmView({ entity: new models.Charm({ files: [ 'hooks/install', 'readme.rst' ], id: 'precise/ceph-9', name: 'ceph', code_source: { location: 'lp:~foo'} }) }); var url = view._getSourceLink( view.get('entity').get('code_source').location); assert.equal('http://bazaar.launchpad.net/~foo/files', url); assert.equal( 'http://bazaar.launchpad.net/~foo/revision/1', view._getRevnoLink(url, 1)); assert.equal( 'https://bugs.launchpad.net/charms/+source/ceph', view._getBugLink(view.get('entity').get('name'))); }); it('excludes source svg files from the source tab', function() { view = new CharmView({ entity: new models.Charm({ files: [ 'hooks/install', 'icon.svg', 'readme.rst' ], id: 'precise/ceph-9', code_source: { location: 'lp:~foo'} }), container: utils.makeContainer(this) }); view.render(); var options = Y.one('#code').all('select option'); assert.equal(options.size(), 3); assert.deepEqual( options.get('text'), ['Select --', 'readme.rst', 'hooks/install']); }); it('can generate useful display data for commits', function() { view = new CharmView({ entity: new models.Charm({ files: [ 'hooks/install', 'readme.rst' ], id: 'precise/ceph-9', code_source: { location: 'lp:~foo' } }) }); var revisions = [ { authors: [{ email: '[email protected]', name: 'John Doe' }], date: '2013-05-02T10:05:32Z', message: 'The fnord had too much fleem.', revno: 1 }, { authors: [{ email: '[email protected]', name: 'John Doe' }], date: '2013-05-02T10:05:45Z', message: 'Fnord needed more fleem.', revno: 2 } ]; var url = view._getSourceLink( view.get('entity').get('code_source').location); var commits = view._formatCommitsForHtml(revisions, url); assert.equal( 'http://bazaar.launchpad.net/~foo/revision/1', commits.first.revnoLink); assert.equal( 'http://bazaar.launchpad.net/~foo/revision/2', commits.remaining[0].revnoLink); }); it('should be able to display the readme content', function() { view = new CharmView({ activeTab: '#readme', entity: new models.Charm({ files: [ 'hooks/install', 'readme.rst' ], id: 'precise/ceph-9', code_source: { location: 'lp:~foo'} }), container: utils.makeContainer(this), charmstore: { getFile: function(url, filename, success, failure) { success({ target: { responseText: 'README content.' } }); } } }); view.render(); Y.one('#readme').get('text').should.eql('README content.'); }); // EVENTS it('should catch when the add control is clicked', function(done) { view = new CharmView({ activeTab: '#readme', entity: new models.Charm({ files: [ 'hooks/install' ], id: 'precise/ceph-9', code_source: { location: 'lp:~foo' } }), container: utils.makeContainer(this) }); // Hook up to the callback for the click event. view._addCharmEnvironment = function(ev) { ev.halt(); Y.one('#readme h3').get('text').should.eql('Charm has no README'); done(); }; view.render(); node.one('.charm .add').simulate('click'); }); it('_addCharmEnvironment displays the config panel', function(done) { var fakeStore = new Y.juju.charmstore.APIv4({ charmstoreURL: 'localhost/' }); view = new CharmView({ entity: new models.Charm({ files: [ 'hooks/install' ], id: 'precise/ceph-9', url: 'cs:precise/ceph-9', code_source: { location: 'lp:~foo' }, options: { configName: 'test' } }), container: utils.makeContainer(this), charmstore: fakeStore }); var fireStub = utils.makeStubMethod(view, 'fire'); this._cleanups.push(fireStub.reset); view.set('deployService', function(charm, serviceAttrs) { var serviceCharm = view.get('entity'); assert.deepEqual(charm, serviceCharm); assert.equal(charm.get('id'), 'cs:precise/ceph-9'); assert.equal(serviceAttrs.icon, 'localhost/v4/precise/ceph-9/icon.svg'); assert.equal(fireStub.calledOnce(), true); var fireArgs = fireStub.lastArguments(); assert.equal(fireArgs[0], 'changeState'); assert.deepEqual(fireArgs[1], { sectionA: { component: 'charmbrowser', metadata: { id: null }}}); done(); }); view._addCharmEnvironment({halt: function() {}}); }); it('should load a file when a hook is selected', function() { view = new CharmView({ entity: new models.Charm({ files: [ 'hooks/install', 'readme.rst' ], id: 'precise/ceph-9', code_source: { location: 'lp:~foo' } }), container: utils.makeContainer(this), charmstore: { getFile: function(url, filename, success, failure) { success({ target: { responseText: '<install hook content>' } }); } } }); view.render(); Y.one('#code').all('select option').size().should.equal(3); // Select the hooks install and the content should update. Y.one('#code').all('select option').item(2).set( 'selected', 'selected'); Y.one('#code').one('select').simulate('change'); var content = Y.one('#code').one('div.filecontent'); // Content is escaped, so we read it out as text, not tags. content.get('text').should.eql('<install hook content>'); }); it('should be able to render markdown as html', function() { view = new CharmView({ activeTab: '#readme', entity: new models.Charm({ files: [ 'readme.md' ], id: 'precise/wordpress-9', code_source: { location: 'lp:~foo' } }), container: utils.makeContainer(this), charmstore: { getFile: function(url, filename, success, failure) { success({ target: { responseText: 'README Header\n=============' } }); } } }); view.render(); Y.one('#readme').get('innerHTML').should.eql( '<h1>README Header</h1>'); }); it('should display the config data in the config tab', function() { view = new CharmView({ entity: new models.Charm({ files: [], id: 'precise/ceph-9', code_source: { location: 'lp:~foo' }, options: { 'client-port': { 'default': 9160, 'description': 'Port for client communcation', 'type': 'int' } } }), container: utils.makeContainer(this) }); view.render(); Y.one('#configuration dd div').get('text').should.eql( 'Default: 9160'); Y.one('#configuration dd p').get('text').should.eql( 'Port for client communcation'); }); it('should catch when the open log is clicked', function(done) { var data = utils.loadFixture('data/browsercharm.json', true); // We don't want any files so we don't have to mock/load them. data.files = []; view = new CharmView({ entity: new models.Charm(data), container: utils.makeContainer(this) }); // Hook up to the callback for the click event. view._toggleLog = function(ev) { ev.halt(); done(); }; view.render(); node.one('.changelog .expand').simulate('click'); }); it('changelog is reformatted and displayed', function() { var data = utils.loadFixture('data/browsercharm.json', true); // We don't want any files so we don't have to mock/load them. data.files = []; view = new CharmView({ entity: new models.Charm(data), container: utils.makeContainer(this) }); view.render(); // Basics that we have the right number of nodes. node.all('.remaining li').size().should.eql(9); node.all('.first p').size().should.eql(1); // The reminaing starts out hidden. assert(node.one('.changelog .remaining').hasClass('hidden')); }); it('_getInterfaceIntroFlag sets the flag for no requires, no provides', function() { var charm = new models.Charm({ files: [], id: 'precise/ceph-9', relations: { 'provides': { }, 'requires': { } } }); view = new CharmView({ entity: charm }); var interfaceIntro = view._getInterfaceIntroFlag( charm.get('requires'), charm.get('provides')); assert(Y.Object.hasKey(interfaceIntro, 'noRequiresNoProvides')); }); it('_getInterfaceIntroFlag sets the flag for no requires, 1 provides', function() { var charm = new models.Charm({ files: [], id: 'precise/ceph-9', relations: { 'provides': { 'foo': {} }, 'requires': { } } }); view = new CharmView({ entity: charm }); var interfaceIntro = view._getInterfaceIntroFlag( charm.get('requires'), charm.get('provides')); assert(Y.Object.hasKey(interfaceIntro, 'noRequiresOneProvides')); }); it('_getInterfaceIntroFlag sets the flag for no requires, many provides', function() { var charm = new models.Charm({ files: [], id: 'precise/ceph-9', relations: { 'provides': { 'foo': {}, 'two': {} }, 'requires': { } } }); view = new CharmView({ entity: charm }); var interfaceIntro = view._getInterfaceIntroFlag( charm.get('requires'), charm.get('provides')); assert(Y.Object.hasKey(interfaceIntro, 'noRequiresManyProvides')); }); it('_getInterfaceIntroFlag sets the flag for 1 requires, no provides', function() { var charm = new models.Charm({ files: [], id: 'precise/ceph-9', relations: { 'provides': { }, 'requires': { 'foo': {} } } }); view = new CharmView({ entity: charm }); var interfaceIntro = view._getInterfaceIntroFlag( charm.get('requires'), charm.get('provides')); assert(Y.Object.hasKey(interfaceIntro, 'oneRequiresNoProvides')); }); it('_getInterfaceIntroFlag sets the flag for 1 requires, 1 provides', function() { var charm = new models.Charm({ files: [], id: 'precise/ceph-9', relations: { 'provides': { 'foo': {} }, 'requires': { 'foo': {} } } }); view = new CharmView({ entity: charm }); var interfaceIntro = view._getInterfaceIntroFlag( charm.get('requires'), charm.get('provides')); assert(Y.Object.hasKey(interfaceIntro, 'oneRequiresOneProvides')); }); it('_getInterfaceIntroFlag sets the flag for 1 requires, many provides', function() { var charm = new models.Charm({ files: [], id: 'precise/ceph-9', relations: { 'provides': { 'foo': {}, 'two': {} }, 'requires': { 'foo': {} } } }); view = new CharmView({ entity: charm }); var interfaceIntro = view._getInterfaceIntroFlag( charm.get('requires'), charm.get('provides')); assert(Y.Object.hasKey(interfaceIntro, 'oneRequiresManyProvides')); }); it('_getInterfaceIntroFlag sets the flag for many requires, no provides', function() { var charm = new models.Charm({ files: [], id: 'precise/ceph-9', relations: { 'provides': { }, 'requires': { 'foo': {}, 'two': {} } } }); view = new CharmView({ entity: charm }); var interfaceIntro = view._getInterfaceIntroFlag( charm.get('requires'), charm.get('provides')); assert(Y.Object.hasKey(interfaceIntro, 'manyRequiresNoProvides')); }); it('_getInterfaceIntroFlag sets the flag for many requires, 1 provides', function() { var charm = new models.Charm({ files: [], id: 'precise/ceph-9', relations: { 'provides': { 'foo': {} }, 'requires': { 'foo': {}, 'two': {} } } }); view = new CharmView({ entity: charm }); var interfaceIntro = view._getInterfaceIntroFlag( charm.get('requires'), charm.get('provides')); assert(Y.Object.hasKey(interfaceIntro, 'manyRequiresOneProvides')); }); it('_getInterfaceIntroFlag sets the flag for many requires, many provides', function() { var charm = new models.Charm({ files: [], id: 'precise/ceph-9', relations: { 'provides': { 'foo': {}, 'two': {} }, 'requires': { 'foo': {}, 'two': {} } } }); view = new CharmView({ entity: charm }); var interfaceIntro = view._getInterfaceIntroFlag( charm.get('requires'), charm.get('provides')); assert(Y.Object.hasKey(interfaceIntro, 'manyRequiresManyProvides')); }); it('shows and hides an indicator', function(done) { var hit = 0; var data = utils.loadFixture('data/browsercharm.json', true); // We don't want any files so we don't have to mock/load them. data.files = []; view = new CharmView({ entity: new models.Charm(data), container: utils.makeContainer(this) }); view.showIndicator = function() { hit += 1; }; view.hideIndicator = function() { hit += 1; hit.should.equal(2); done(); }; view.render(); }); it('selects the proper tab when given one', function() { var data = utils.loadFixture('data/browsercharm.json', true); // We don't want any files so we don't have to mock/load them. data.files = []; view = new CharmView({ activeTab: '#configuration', entity: new models.Charm(data), container: utils.makeContainer(this) }); view.render(); // We've selected the activeTab specified. var selected = view.get('container').one('nav .active'); assert.equal(selected.getAttribute('href'), '#configuration'); }); it('sets the proper change request when closed', function(done) { var data = utils.loadFixture('data/browsercharm.json', true); // We don't want any files so we don't have to mock/load them. data.files = []; view = new CharmView({ activeTab: '#configuration', entity: new models.Charm(data), container: utils.makeContainer(this) }); view.on('changeState', function(ev) { assert.equal(ev.details[0].sectionA.metadata.id, null, 'The charm id is not set to null.'); assert.equal(ev.details[0].sectionA.metadata.hash, null, 'The charm details hash is not set to null.'); done(); }); view.render(); view.get('container').one('.charm .back').simulate('click'); }); it('renders related charms when interface tab selected', function() { var data = utils.loadFixture('data/browsercharm.json', true); testContainer = utils.makeContainer(this); // We don't want any files so we don't have to mock/load them. data.files = []; view = new CharmView({ activeTab: '#related-charms', entity: new models.Charm(data), renderTo: testContainer }); view.render(); assert.equal( testContainer.all('#related-charms .token').size(), 18); assert.equal(view.get('entity').get('id'), 'cs:precise/apache2-27'); assert.isTrue(view.loadedRelatedInterfaceCharms); }); it('ignore invalid tab selections', function() { var data = utils.loadFixture('data/browsercharm.json', true); testContainer = utils.makeContainer(this); // We don't want any files so we don't have to mock/load them. data.files = []; var fakeStore = factory.makeFakeCharmstore(); view = new CharmView({ activeTab: '#bws-does-not-exist', entity: new models.Charm(data), renderTo: testContainer, charmstore: fakeStore }); view.render(); assert.equal( testContainer.one('nav .active').getAttribute('href'), '#summary'); }); it('should open header links in a new tab', function() { var data = utils.loadFixture('data/browsercharm.json', true); // We don't want any files so we don't have to mock/load them. data.files = []; view = new CharmView({ entity: new models.Charm(data), container: utils.makeContainer(this) }); view.render(); var links = view.get('container').all('.header .details li a'); // Check that we've found the links, otherwise the assert in .each will // succeed when there are no links. assert.equal(links.size() > 0, true); links.each(function(link) { assert.equal(link.getAttribute('target'), '_blank'); }); }); }); })();
jrwren/juju-gui
test/test_browser_charm_details.js
JavaScript
agpl-3.0
25,436
import React, { useMemo } from 'react'; import { cx, css } from '@emotion/css'; import { MenuItem, WithContextMenu, MenuGroup, useTheme2 } from '@grafana/ui'; import { SelectableValue, GrafanaTheme2 } from '@grafana/data'; import { Seg } from './Seg'; import { unwrap } from './unwrap'; import { toSelectableValue } from './toSelectableValue'; import { AddButton } from './AddButton'; export type PartParams = Array<{ value: string; options: (() => Promise<string[]>) | null; }>; type Props = { parts: Array<{ name: string; params: PartParams; }>; getNewPartOptions: () => Promise<SelectableValue[]>; onChange: (partIndex: number, paramValues: string[]) => void; onRemovePart: (index: number) => void; onAddNewPart: (type: string) => void; }; const renderRemovableNameMenuItems = (onClick: () => void) => { return ( <MenuGroup label=""> <MenuItem label="remove" onClick={onClick} /> </MenuGroup> ); }; const noRightMarginPaddingClass = css({ paddingRight: '0', marginRight: '0', }); const RemovableName = ({ name, onRemove }: { name: string; onRemove: () => void }) => { return ( <WithContextMenu renderMenuItems={() => renderRemovableNameMenuItems(onRemove)}> {({ openMenu }) => ( <button className={cx('gf-form-label', noRightMarginPaddingClass)} onClick={openMenu}> {name} </button> )} </WithContextMenu> ); }; type PartProps = { name: string; params: PartParams; onRemove: () => void; onChange: (paramValues: string[]) => void; }; const noHorizMarginPaddingClass = css({ paddingLeft: '0', paddingRight: '0', marginLeft: '0', marginRight: '0', }); const getPartClass = (theme: GrafanaTheme2) => { return cx( 'gf-form-label', css({ paddingLeft: '0', // gf-form-label class makes certain css attributes incorrect // for the selectbox-dropdown, so we have to "reset" them back lineHeight: theme.typography.body.lineHeight, fontSize: theme.typography.body.fontSize, }) ); }; const Part = ({ name, params, onChange, onRemove }: PartProps): JSX.Element => { const theme = useTheme2(); const partClass = useMemo(() => getPartClass(theme), [theme]); const onParamChange = (par: string, i: number) => { const newParams = params.map((p) => p.value); newParams[i] = par; onChange(newParams); }; return ( <div className={partClass}> <RemovableName name={name} onRemove={onRemove} />( {params.map((p, i) => { const { value, options } = p; const isLast = i === params.length - 1; const loadOptions = options !== null ? () => options().then((items) => items.map(toSelectableValue)) : undefined; return ( <React.Fragment key={i}> <Seg allowCustomValue value={value} buttonClassName={noHorizMarginPaddingClass} loadOptions={loadOptions} onChange={(v) => { onParamChange(unwrap(v.value), i); }} /> {!isLast && ','} </React.Fragment> ); })} ) </div> ); }; export const PartListSection = ({ parts, getNewPartOptions, onAddNewPart, onRemovePart, onChange, }: Props): JSX.Element => { return ( <> {parts.map((part, index) => ( <Part key={index} name={part.name} params={part.params} onRemove={() => { onRemovePart(index); }} onChange={(pars) => { onChange(index, pars); }} /> ))} <AddButton loadOptions={getNewPartOptions} onAdd={onAddNewPart} /> </> ); };
grafana/grafana
public/app/plugins/datasource/influxdb/components/VisualInfluxQLEditor/PartListSection.tsx
TypeScript
agpl-3.0
3,719
/* * Asqatasun - Automated webpage assessment * Copyright (C) 2008-2019 Asqatasun.org * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * Contact us by mail: asqatasun AT asqatasun DOT org */ package org.asqatasun.rules.rgaa22; import java.util.LinkedHashSet; import org.apache.commons.lang3.StringUtils; import org.asqatasun.entity.audit.EvidenceElement; import org.asqatasun.entity.audit.ProcessResult; import org.asqatasun.entity.audit.SourceCodeRemark; import org.asqatasun.entity.audit.TestSolution; import static org.asqatasun.rules.keystore.AttributeStore.TITLE_ATTR; import org.asqatasun.rules.keystore.HtmlElementStore; import org.asqatasun.rules.keystore.RemarkMessageStore; import org.asqatasun.rules.rgaa22.test.Rgaa22RuleImplementationTestCase; /** * Unit test class for the implementation of the rule 1.2 of the referential RGAA 2.2. * * @author jkowalczyk */ public class Rgaa22Rule01021Test extends Rgaa22RuleImplementationTestCase { /** * Default constructor */ public Rgaa22Rule01021Test (String testName){ super(testName); } @Override protected void setUpRuleImplementationClassName() { setRuleImplementationClassName( "org.asqatasun.rules.rgaa22.Rgaa22Rule01021"); } @Override protected void setUpWebResourceMap() { getWebResourceMap().put("Rgaa22.Test.1.2-2Failed-01", getWebResourceFactory().createPage( getTestcasesFilePath() + "rgaa22/Rgaa22Rule01021/RGAA22.Test.1.2-2Failed-01.html")); getWebResourceMap().put("Rgaa22.Test.1.2-2Failed-02", getWebResourceFactory().createPage( getTestcasesFilePath() + "rgaa22/Rgaa22Rule01021/RGAA22.Test.1.2-2Failed-02.html")); getWebResourceMap().put("Rgaa22.Test.1.2-2Failed-03", getWebResourceFactory().createPage( getTestcasesFilePath() + "rgaa22/Rgaa22Rule01021/RGAA22.Test.1.2-2Failed-03.html")); getWebResourceMap().put("Rgaa22.Test.1.2-2Failed-04", getWebResourceFactory().createPage( getTestcasesFilePath() + "rgaa22/Rgaa22Rule01021/RGAA22.Test.1.2-2Failed-04.html")); getWebResourceMap().put("Rgaa22.Test.1.2-2Failed-05", getWebResourceFactory().createPage( getTestcasesFilePath() + "rgaa22/Rgaa22Rule01021/RGAA22.Test.1.2-2Failed-05.html")); getWebResourceMap().put("Rgaa22.Test.1.2-2Failed-06", getWebResourceFactory().createPage( getTestcasesFilePath() + "rgaa22/Rgaa22Rule01021/RGAA22.Test.1.2-2Failed-06.html")); getWebResourceMap().put("Rgaa22.Test.1.2-3NMI-01", getWebResourceFactory().createPage( getTestcasesFilePath() + "rgaa22/Rgaa22Rule01021/RGAA22.Test.1.2-3NMI-01.html")); getWebResourceMap().put("Rgaa22.Test.1.2-3NMI-02", getWebResourceFactory().createPage( getTestcasesFilePath() + "rgaa22/Rgaa22Rule01021/RGAA22.Test.1.2-3NMI-02.html")); getWebResourceMap().put("Rgaa22.Test.1.2-3NMI-03", getWebResourceFactory().createPage( getTestcasesFilePath() + "rgaa22/Rgaa22Rule01021/RGAA22.Test.1.2-3NMI-03.html")); getWebResourceMap().put("Rgaa22.Test.1.2-4NA-01", getWebResourceFactory().createPage( getTestcasesFilePath() + "rgaa22/Rgaa22Rule01021/RGAA22.Test.1.2-4NA-01.html")); getWebResourceMap().put("Rgaa22.Test.1.2-4NA-02", getWebResourceFactory().createPage( getTestcasesFilePath() + "rgaa22/Rgaa22Rule01021/RGAA22.Test.1.2-4NA-02.html")); getWebResourceMap().put("Rgaa22.Test.1.2-4NA-03", getWebResourceFactory().createPage( getTestcasesFilePath() + "rgaa22/Rgaa22Rule01021/RGAA22.Test.1.2-4NA-03.html")); getWebResourceMap().put("Rgaa22.Test.1.2-4NA-04", getWebResourceFactory().createPage( getTestcasesFilePath() + "rgaa22/Rgaa22Rule01021/RGAA22.Test.1.2-4NA-04.html")); getWebResourceMap().put("Rgaa22.Test.1.2-4NA-05", getWebResourceFactory().createPage( getTestcasesFilePath() + "rgaa22/Rgaa22Rule01021/RGAA22.Test.1.2-4NA-05.html")); getWebResourceMap().put("Rgaa22.Test.1.2-4NA-06", getWebResourceFactory().createPage( getTestcasesFilePath() + "rgaa22/Rgaa22Rule01021/RGAA22.Test.1.2-4NA-06.html")); getWebResourceMap().put("Rgaa22.Test.1.2-4NA-07", getWebResourceFactory().createPage( getTestcasesFilePath() + "rgaa22/Rgaa22Rule01021/RGAA22.Test.1.2-4NA-07.html")); } @Override protected void setProcess() { //---------------------------------------------------------------------- //------------------------------2Failed-01------------------------------ //---------------------------------------------------------------------- ProcessResult processResult = processPageTest("Rgaa22.Test.1.2-2Failed-01"); // check number of elements in the page assertEquals(1, processResult.getElementCounter()); // check test result assertEquals(TestSolution.FAILED, processResult.getValue()); // check number of remarks and their value assertEquals(1, processResult.getRemarkSet().size()); SourceCodeRemark processRemark = ((SourceCodeRemark)((LinkedHashSet)processResult.getRemarkSet()).iterator().next()); assertEquals(RemarkMessageStore.NOT_PERTINENT_TITLE_OF_FRAME_MSG, processRemark.getMessageCode()); assertEquals(TestSolution.FAILED, processRemark.getIssue()); assertEquals(HtmlElementStore.FRAME_ELEMENT, processRemark.getTarget()); assertNotNull(processRemark.getSnippet()); // check number of evidence elements and their value assertEquals(1, processRemark.getElementList().size()); EvidenceElement ee = processRemark.getElementList().iterator().next(); assertTrue(StringUtils.contains(ee.getValue(), "!§:;.,?%*\\~/@()[]^_°=+-")); assertEquals(TITLE_ATTR, ee.getEvidence().getCode()); //---------------------------------------------------------------------- //------------------------------2Failed-02------------------------------ //---------------------------------------------------------------------- processResult = processPageTest("Rgaa22.Test.1.2-2Failed-02"); // check number of elements in the page assertEquals(1, processResult.getElementCounter()); // check test result assertEquals(TestSolution.FAILED, processResult.getValue()); // check number of remarks and their value assertEquals(1, processResult.getRemarkSet().size()); processRemark = ((SourceCodeRemark)((LinkedHashSet)processResult.getRemarkSet()).iterator().next()); assertEquals(RemarkMessageStore.NOT_PERTINENT_TITLE_OF_FRAME_MSG, processRemark.getMessageCode()); assertEquals(TestSolution.FAILED, processRemark.getIssue()); assertEquals(HtmlElementStore.IFRAME_ELEMENT, processRemark.getTarget()); assertNotNull(processRemark.getSnippet()); // check number of evidence elements and their value assertEquals(1, processRemark.getElementList().size()); ee = processRemark.getElementList().iterator().next(); assertTrue(StringUtils.contains(ee.getValue(), "!§:;.,?%*\\~/@()[]^_°=+-")); assertEquals(TITLE_ATTR, ee.getEvidence().getCode()); //---------------------------------------------------------------------- //------------------------------2Failed-03------------------------------ //---------------------------------------------------------------------- processResult = processPageTest("Rgaa22.Test.1.2-2Failed-03"); // check number of elements in the page assertEquals(1, processResult.getElementCounter()); // check test result assertEquals(TestSolution.FAILED, processResult.getValue()); // check number of remarks and their value assertEquals(1, processResult.getRemarkSet().size()); processRemark = ((SourceCodeRemark)((LinkedHashSet)processResult.getRemarkSet()).iterator().next()); assertEquals(RemarkMessageStore.NOT_PERTINENT_TITLE_OF_FRAME_MSG, processRemark.getMessageCode()); assertEquals(TestSolution.FAILED, processRemark.getIssue()); assertEquals(HtmlElementStore.FRAME_ELEMENT, processRemark.getTarget()); assertNotNull(processRemark.getSnippet()); // check number of evidence elements and their value assertEquals(1, processRemark.getElementList().size()); ee = processRemark.getElementList().iterator().next(); assertTrue(StringUtils.contains(ee.getValue(), "!§:;.,?%*\\~/@()[]^_°=+-")); assertEquals(TITLE_ATTR, ee.getEvidence().getCode()); //---------------------------------------------------------------------- //------------------------------2Failed-04------------------------------ //---------------------------------------------------------------------- processResult = processPageTest("Rgaa22.Test.1.2-2Failed-04"); // check number of elements in the page assertEquals(1, processResult.getElementCounter()); // check test result assertEquals(TestSolution.FAILED, processResult.getValue()); // check number of remarks and their value assertEquals(1, processResult.getRemarkSet().size()); processRemark = ((SourceCodeRemark)((LinkedHashSet)processResult.getRemarkSet()).iterator().next()); assertEquals(RemarkMessageStore.NOT_PERTINENT_TITLE_OF_FRAME_MSG, processRemark.getMessageCode()); assertEquals(TestSolution.FAILED, processRemark.getIssue()); assertEquals(HtmlElementStore.FRAME_ELEMENT, processRemark.getTarget()); assertNotNull(processRemark.getSnippet()); // check number of evidence elements and their value assertEquals(1, processRemark.getElementList().size()); ee = processRemark.getElementList().iterator().next(); assertTrue(StringUtils.contains(ee.getValue(), "mock-frame1.html")); assertEquals(TITLE_ATTR, ee.getEvidence().getCode()); //---------------------------------------------------------------------- //------------------------------2Failed-05------------------------------ //---------------------------------------------------------------------- processResult = processPageTest("Rgaa22.Test.1.2-2Failed-05"); // check number of elements in the page assertEquals(1, processResult.getElementCounter()); // check test result assertEquals(TestSolution.FAILED, processResult.getValue()); // check number of remarks and their value assertEquals(1, processResult.getRemarkSet().size()); processRemark = ((SourceCodeRemark)((LinkedHashSet)processResult.getRemarkSet()).iterator().next()); assertEquals(RemarkMessageStore.NOT_PERTINENT_TITLE_OF_FRAME_MSG, processRemark.getMessageCode()); assertEquals(TestSolution.FAILED, processRemark.getIssue()); assertEquals(HtmlElementStore.IFRAME_ELEMENT, processRemark.getTarget()); assertNotNull(processRemark.getSnippet()); // check number of evidence elements and their value assertEquals(1, processRemark.getElementList().size()); ee = processRemark.getElementList().iterator().next(); assertTrue(StringUtils.contains(ee.getValue(), "mock-iframe1.html")); assertEquals(TITLE_ATTR, ee.getEvidence().getCode()); //---------------------------------------------------------------------- //------------------------------2Failed-06------------------------------ //---------------------------------------------------------------------- processResult = processPageTest("Rgaa22.Test.1.2-2Failed-06"); // check number of elements in the page assertEquals(1, processResult.getElementCounter()); // check test result assertEquals(TestSolution.FAILED, processResult.getValue()); // check number of remarks and their value assertEquals(1, processResult.getRemarkSet().size()); processRemark = ((SourceCodeRemark)((LinkedHashSet)processResult.getRemarkSet()).iterator().next()); assertEquals(RemarkMessageStore.NOT_PERTINENT_TITLE_OF_FRAME_MSG, processRemark.getMessageCode()); assertEquals(TestSolution.FAILED, processRemark.getIssue()); assertEquals(HtmlElementStore.FRAME_ELEMENT, processRemark.getTarget()); assertNotNull(processRemark.getSnippet()); // check number of evidence elements and their value assertEquals(1, processRemark.getElementList().size()); ee = processRemark.getElementList().iterator().next(); assertTrue(StringUtils.contains(ee.getValue(), "mock-frame1.html")); assertEquals(TITLE_ATTR, ee.getEvidence().getCode()); //---------------------------------------------------------------------- //------------------------------3NMI-01--------------------------------- //---------------------------------------------------------------------- processResult = processPageTest("Rgaa22.Test.1.2-3NMI-01"); // check number of elements in the page assertEquals(1, processResult.getElementCounter()); // check test result assertEquals(TestSolution.NEED_MORE_INFO, processResult.getValue()); // check number of remarks and their value assertEquals(1, processResult.getRemarkSet().size()); processRemark = ((SourceCodeRemark)((LinkedHashSet)processResult.getRemarkSet()).iterator().next()); assertEquals(RemarkMessageStore.CHECK_TITLE_OF_FRAME_PERTINENCE_MSG, processRemark.getMessageCode()); assertEquals(TestSolution.NEED_MORE_INFO, processRemark.getIssue()); assertEquals(HtmlElementStore.FRAME_ELEMENT, processRemark.getTarget()); assertNotNull(processRemark.getSnippet()); // check number of evidence elements and their value assertEquals(1, processRemark.getElementList().size()); ee = processRemark.getElementList().iterator().next(); assertTrue(StringUtils.contains(ee.getValue(), "title of mock-frame1")); assertEquals(TITLE_ATTR, ee.getEvidence().getCode()); //---------------------------------------------------------------------- //------------------------------3NMI-02--------------------------------- //---------------------------------------------------------------------- processResult = processPageTest("Rgaa22.Test.1.2-3NMI-02"); // check number of elements in the page assertEquals(1, processResult.getElementCounter()); // check test result assertEquals(TestSolution.NEED_MORE_INFO, processResult.getValue()); // check number of remarks and their value assertEquals(1, processResult.getRemarkSet().size()); processRemark = ((SourceCodeRemark)((LinkedHashSet)processResult.getRemarkSet()).iterator().next()); assertEquals(RemarkMessageStore.CHECK_TITLE_OF_FRAME_PERTINENCE_MSG, processRemark.getMessageCode()); assertEquals(TestSolution.NEED_MORE_INFO, processRemark.getIssue()); assertEquals(HtmlElementStore.IFRAME_ELEMENT, processRemark.getTarget()); assertNotNull(processRemark.getSnippet()); // check number of evidence elements and their value assertEquals(1, processRemark.getElementList().size()); ee = processRemark.getElementList().iterator().next(); assertTrue(StringUtils.contains(ee.getValue(), "Title of mock-iframe1")); assertEquals(TITLE_ATTR, ee.getEvidence().getCode()); //---------------------------------------------------------------------- //------------------------------3NMI-03--------------------------------- //---------------------------------------------------------------------- processResult = processPageTest("Rgaa22.Test.1.2-3NMI-03"); // check number of elements in the page assertEquals(1, processResult.getElementCounter()); // check test result assertEquals(TestSolution.NEED_MORE_INFO, processResult.getValue()); // check number of remarks and their value assertEquals(1, processResult.getRemarkSet().size()); processRemark = ((SourceCodeRemark)((LinkedHashSet)processResult.getRemarkSet()).iterator().next()); assertEquals(RemarkMessageStore.CHECK_TITLE_OF_FRAME_PERTINENCE_MSG, processRemark.getMessageCode()); assertEquals(TestSolution.NEED_MORE_INFO, processRemark.getIssue()); assertEquals(HtmlElementStore.FRAME_ELEMENT, processRemark.getTarget()); assertNotNull(processRemark.getSnippet()); // check number of evidence elements and their value assertEquals(1, processRemark.getElementList().size()); ee = processRemark.getElementList().iterator().next(); assertTrue(StringUtils.contains(ee.getValue(), "Title of mock-frame1")); assertEquals(TITLE_ATTR, ee.getEvidence().getCode()); //---------------------------------------------------------------------- //------------------------------4NA-01---------------------------------- //---------------------------------------------------------------------- processResult = processPageTest("Rgaa22.Test.1.2-4NA-01"); // check test result assertEquals(TestSolution.NOT_APPLICABLE, processResult.getValue()); // check test has no remark assertNull(processResult.getRemarkSet()); //---------------------------------------------------------------------- //------------------------------4NA-02---------------------------------- //---------------------------------------------------------------------- processResult = processPageTest("Rgaa22.Test.1.2-4NA-02"); // check test result assertEquals(TestSolution.NOT_APPLICABLE, processResult.getValue()); // check test has no remark assertNull(processResult.getRemarkSet()); //---------------------------------------------------------------------- //------------------------------4NA-03---------------------------------- //---------------------------------------------------------------------- processResult = processPageTest("Rgaa22.Test.1.2-4NA-03"); // check test result assertEquals(TestSolution.NOT_APPLICABLE, processResult.getValue()); // check test has no remark assertNull(processResult.getRemarkSet()); //---------------------------------------------------------------------- //------------------------------4NA-04---------------------------------- //---------------------------------------------------------------------- processResult = processPageTest("Rgaa22.Test.1.2-4NA-04"); // check test result assertEquals(TestSolution.NOT_APPLICABLE, processResult.getValue()); // check test has no remark assertNull(processResult.getRemarkSet()); //---------------------------------------------------------------------- //------------------------------4NA-05---------------------------------- //---------------------------------------------------------------------- processResult = processPageTest("Rgaa22.Test.1.2-4NA-05"); // check test result assertEquals(TestSolution.NOT_APPLICABLE, processResult.getValue()); // check test has no remark assertNull(processResult.getRemarkSet()); //---------------------------------------------------------------------- //------------------------------4NA-06---------------------------------- //---------------------------------------------------------------------- processResult = processPageTest("Rgaa22.Test.1.2-4NA-06"); // check test result assertEquals(TestSolution.NOT_APPLICABLE, processResult.getValue()); // check test has no remark assertNull(processResult.getRemarkSet()); //---------------------------------------------------------------------- //------------------------------4NA-07---------------------------------- //---------------------------------------------------------------------- processResult = processPageTest("Rgaa22.Test.1.2-4NA-07"); // check test result assertEquals(TestSolution.NOT_APPLICABLE, processResult.getValue()); // check test has no remark assertNull(processResult.getRemarkSet()); } @Override protected void setConsolidate() { assertEquals(TestSolution.FAILED, consolidate("Rgaa22.Test.1.2-2Failed-01").getValue()); assertEquals(TestSolution.FAILED, consolidate("Rgaa22.Test.1.2-2Failed-02").getValue()); assertEquals(TestSolution.FAILED, consolidate("Rgaa22.Test.1.2-2Failed-03").getValue()); assertEquals(TestSolution.FAILED, consolidate("Rgaa22.Test.1.2-2Failed-04").getValue()); assertEquals(TestSolution.FAILED, consolidate("Rgaa22.Test.1.2-2Failed-05").getValue()); assertEquals(TestSolution.FAILED, consolidate("Rgaa22.Test.1.2-2Failed-06").getValue()); assertEquals(TestSolution.NEED_MORE_INFO, consolidate("Rgaa22.Test.1.2-3NMI-01").getValue()); assertEquals(TestSolution.NEED_MORE_INFO, consolidate("Rgaa22.Test.1.2-3NMI-02").getValue()); assertEquals(TestSolution.NEED_MORE_INFO, consolidate("Rgaa22.Test.1.2-3NMI-03").getValue()); assertEquals(TestSolution.NOT_APPLICABLE, consolidate("Rgaa22.Test.1.2-4NA-01").getValue()); assertEquals(TestSolution.NOT_APPLICABLE, consolidate("Rgaa22.Test.1.2-4NA-02").getValue()); assertEquals(TestSolution.NOT_APPLICABLE, consolidate("Rgaa22.Test.1.2-4NA-03").getValue()); assertEquals(TestSolution.NOT_APPLICABLE, consolidate("Rgaa22.Test.1.2-4NA-04").getValue()); assertEquals(TestSolution.NOT_APPLICABLE, consolidate("Rgaa22.Test.1.2-4NA-05").getValue()); assertEquals(TestSolution.NOT_APPLICABLE, consolidate("Rgaa22.Test.1.2-4NA-06").getValue()); assertEquals(TestSolution.NOT_APPLICABLE, consolidate("Rgaa22.Test.1.2-4NA-07").getValue()); } }
dzc34/Asqatasun
rules/rules-rgaa2.2/src/test/java/org/asqatasun/rules/rgaa22/Rgaa22Rule01021Test.java
Java
agpl-3.0
23,545
export const BattleAvatarNumbers = { 1: 'lucas', 2: 'dawn', 3: 'youngster-gen4', 4: 'lass-gen4dp', 5: 'camper', 6: 'picnicker', 7: 'bugcatcher', 8: 'aromalady', 9: 'twins-gen4dp', 10: 'hiker-gen4', 11: 'battlegirl-gen4', 12: 'fisherman-gen4', 13: 'cyclist-gen4', 14: 'cyclistf-gen4', 15: 'blackbelt-gen4dp', 16: 'artist-gen4', 17: 'pokemonbreeder-gen4', 18: 'pokemonbreederf-gen4', 19: 'cowgirl', 20: 'jogger', 21: 'pokefan-gen4', 22: 'pokefanf-gen4', 23: 'pokekid', 24: 'youngcouple-gen4dp', 25: 'acetrainer-gen4dp', 26: 'acetrainerf-gen4dp', 27: 'waitress-gen4', 28: 'veteran-gen4', 29: 'ninjaboy', 30: 'dragontamer', 31: 'birdkeeper-gen4dp', 32: 'doubleteam', 33: 'richboy-gen4', 34: 'lady-gen4', 35: 'gentleman-gen4dp', 36: 'madame-gen4dp', 37: 'beauty-gen4dp', 38: 'collector', 39: 'policeman-gen4', 40: 'pokemonranger-gen4', 41: 'pokemonrangerf-gen4', 42: 'scientist-gen4dp', 43: 'swimmer-gen4dp', 44: 'swimmerf-gen4dp', 45: 'tuber', 46: 'tuberf', 47: 'sailor', 48: 'sisandbro', 49: 'ruinmaniac', 50: 'psychic-gen4', 51: 'psychicf-gen4', 52: 'gambler', 53: 'guitarist-gen4', 54: 'acetrainersnow', 55: 'acetrainersnowf', 56: 'skier', 57: 'skierf-gen4dp', 58: 'roughneck-gen4', 59: 'clown', 60: 'worker-gen4', 61: 'schoolkid-gen4dp', 62: 'schoolkidf-gen4', 63: 'roark', 64: 'barry', 65: 'byron', 66: 'aaron', 67: 'bertha', 68: 'flint', 69: 'lucian', 70: 'cynthia-gen4', 71: 'bellepa', 72: 'rancher', 73: 'mars', 74: 'galacticgrunt', 75: 'gardenia', 76: 'crasherwake', 77: 'maylene', 78: 'fantina', 79: 'candice', 80: 'volkner', 81: 'parasollady-gen4', 82: 'waiter-gen4dp', 83: 'interviewers', 84: 'cameraman', 85: 'reporter', 86: 'idol', 87: 'cyrus', 88: 'jupiter', 89: 'saturn', 90: 'galacticgruntf', 91: 'argenta', 92: 'palmer', 93: 'thorton', 94: 'buck', 95: 'darach', 96: 'marley', 97: 'mira', 98: 'cheryl', 99: 'riley', 100: 'dahlia', 101: 'ethan', 102: 'lyra', 103: 'twins-gen4', 104: 'lass-gen4', 105: 'acetrainer-gen4', 106: 'acetrainerf-gen4', 107: 'juggler', 108: 'sage', 109: 'li', 110: 'gentleman-gen4', 111: 'teacher', 112: 'beauty', 113: 'birdkeeper', 114: 'swimmer-gen4', 115: 'swimmerf-gen4', 116: 'kimonogirl', 117: 'scientist-gen4', 118: 'acetrainercouple', 119: 'youngcouple', 120: 'supernerd', 121: 'medium', 122: 'schoolkid-gen4', 123: 'blackbelt-gen4', 124: 'pokemaniac', 125: 'firebreather', 126: 'burglar', 127: 'biker-gen4', 128: 'skierf', 129: 'boarder', 130: 'rocketgrunt', 131: 'rocketgruntf', 132: 'archer', 133: 'ariana', 134: 'proton', 135: 'petrel', 136: 'eusine', 137: 'lucas-gen4pt', 138: 'dawn-gen4pt', 139: 'madame-gen4', 140: 'waiter-gen4', 141: 'falkner', 142: 'bugsy', 143: 'whitney', 144: 'morty', 145: 'chuck', 146: 'jasmine', 147: 'pryce', 148: 'clair', 149: 'will', 150: 'koga', 151: 'bruno', 152: 'karen', 153: 'lance', 154: 'brock', 155: 'misty', 156: 'ltsurge', 157: 'erika', 158: 'janine', 159: 'sabrina', 160: 'blaine', 161: 'blue', 162: 'red', 163: 'red', 164: 'silver', 165: 'giovanni', 166: 'unknownf', 167: 'unknown', 168: 'unknown', 169: 'hilbert', 170: 'hilda', 171: 'youngster', 172: 'lass', 173: 'schoolkid', 174: 'schoolkidf', 175: 'smasher', 176: 'linebacker', 177: 'waiter', 178: 'waitress', 179: 'chili', 180: 'cilan', 181: 'cress', 182: 'nurseryaide', 183: 'preschoolerf', 184: 'preschooler', 185: 'twins', 186: 'pokemonbreeder', 187: 'pokemonbreederf', 188: 'lenora', 189: 'burgh', 190: 'elesa', 191: 'clay', 192: 'skyla', 193: 'pokemonranger', 194: 'pokemonrangerf', 195: 'worker', 196: 'backpacker', 197: 'backpackerf', 198: 'fisherman', 199: 'musician', 200: 'dancer', 201: 'harlequin', 202: 'artist', 203: 'baker', 204: 'psychic', 205: 'psychicf', 206: 'cheren', 207: 'bianca', 208: 'plasmagrunt-gen5bw', 209: 'n', 210: 'richboy', 211: 'lady', 212: 'pilot', 213: 'workerice', 214: 'hoopster', 215: 'scientistf', 216: 'clerkf', 217: 'acetrainerf', 218: 'acetrainer', 219: 'blackbelt', 220: 'scientist', 221: 'striker', 222: 'brycen', 223: 'iris', 224: 'drayden', 225: 'roughneck', 226: 'janitor', 227: 'pokefan', 228: 'pokefanf', 229: 'doctor', 230: 'nurse', 231: 'hooligans', 232: 'battlegirl', 233: 'parasollady', 234: 'clerk', 235: 'clerk-boss', 236: 'backers', 237: 'backersf', 238: 'veteran', 239: 'veteranf', 240: 'biker', 241: 'infielder', 242: 'hiker', 243: 'madame', 244: 'gentleman', 245: 'plasmagruntf-gen5bw', 246: 'shauntal', 247: 'marshal', 248: 'grimsley', 249: 'caitlin', 250: 'ghetsis-gen5bw', 251: 'depotagent', 252: 'swimmer', 253: 'swimmerf', 254: 'policeman', 255: 'maid', 256: 'ingo', 257: 'alder', 258: 'cyclist', 259: 'cyclistf', 260: 'cynthia', 261: 'emmet', 262: 'hilbert-dueldisk', 263: 'hilda-dueldisk', 264: 'hugh', 265: 'rosa', 266: 'nate', 267: 'colress', 268: 'beauty-gen5bw2', 269: 'ghetsis', 270: 'plasmagrunt', 271: 'plasmagruntf', 272: 'iris-gen5bw2', 273: 'brycenman', 274: 'shadowtriad', 275: 'rood', 276: 'zinzolin', 277: 'cheren-gen5bw2', 278: 'marlon', 279: 'roxie', 280: 'roxanne', 281: 'brawly', 282: 'wattson', 283: 'flannery', 284: 'norman', 285: 'winona', 286: 'tate', 287: 'liza', 288: 'juan', 289: 'guitarist', 290: 'steven', 291: 'wallace', 292: 'bellelba', 293: 'benga', 294: 'ash', '#bw2elesa': 'elesa-gen5bw2', '#teamrocket': 'teamrocket', '#yellow': 'yellow', '#zinnia': 'zinnia', '#clemont': 'clemont', '#wally': 'wally', breeder: 'pokemonbreeder', breederf: 'pokemonbreederf', 1001: '#1001', 1002: '#1002', 1003: '#1003', 1005: '#1005', 1010: '#1010', };
shoedrip-unbound/dogars
src/Shoedrip/dexdata.ts
TypeScript
agpl-3.0
5,687
package nikita.common.config; /** * Constants used for ElasticSearch queries */ public class ESConstants { public static final String QUERY_SIZE = "size"; public static final String QUERY_FROM = "from"; public static final String QUERY_QUERY = "query"; public static final String QUERY_PREFIX = "prefix"; public static final String QUERY_MATCH_PHRASE = "match_phrase"; }
HiOA-ABI/nikita-noark5-core
src/main/java/nikita/common/config/ESConstants.java
Java
agpl-3.0
396
class Waypoint < ActiveRecord::Base belongs_to :open_capacity belongs_to :location, :validate => true, :dependent => :destroy end
rideconnection/clearinghouse
app/models/waypoint.rb
Ruby
agpl-3.0
134
<!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>PODEMOS. Scientific and cultural cooperation with the United States to avoid a human capital flight</title> <meta property="og:title" content="PODEMOS: Scientific and cultural cooperation with the United States to avoid a human capital flight" /> <meta property="og:description" content="In order to reverse brain drain of Spanish scientist to the United States, we will strengthen scientific, cultural and educational cooperation with this country. To do this, we will increase the budget for grants for further studies and professional internships and scientific research related to projects by Spaniards, and we will promote incentives to encourage the return of Spanish researchers having expanded their training in the United States. In addition, we will develop a United Plan, an initiative to establish greater cultural, educational and economic ties with the Hispanic community in the US, almost a third of the population of that country. The network of Instituto Cervantes centres will help to reinforce its Latin American connection to organize and promote cultural activities that involve the richness of Spanish language and culture in Spain and America. We will also create a network of business incubators and accelerators in the United States and Spain to contribute to the creation of viable and innovative business projects in both countries, especially in the field of social and solidarity economy, to facilitate the entry of Spanish SMEs in the US market and the subsequent profit." /> <meta property="og:image" content="http://lasonrisadeunpais.es/wp-content/plugins/programa/data/meta-programa.png" /> </head> <body> <script type="text/javascript"> var url_base = '/en/programa/?medida=332'; window.location = url_base; </script> <h1>Scientific and cultural cooperation with the United States to avoid a human capital flight</h1> <div> <p>In order to reverse brain drain of Spanish scientist to the United States, we will strengthen scientific, cultural and educational cooperation with this country. To do this, we will increase the budget for grants for further studies and professional internships and scientific research related to projects by Spaniards, and we will promote incentives to encourage the return of Spanish researchers having expanded their training in the United States.</p> <p>In addition, we will develop a United Plan, an initiative to establish greater cultural, educational and economic ties with the Hispanic community in the US, almost a third of the population of that country. The network of Instituto Cervantes centres will help to reinforce its Latin American connection to organize and promote cultural activities that involve the richness of Spanish language and culture in Spain and America.</p> <p>We will also create a network of business incubators and accelerators in the United States and Spain to contribute to the creation of viable and innovative business projects in both countries, especially in the field of social and solidarity economy, to facilitate the entry of Spanish SMEs in the US market and the subsequent profit.</p> </div> </body> </html>
joker-x/programa-podemos-2015
web/fb-share/programa/en/332.html
HTML
agpl-3.0
3,256
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>About Cella</title> <link rel="stylesheet" type="text/css" href="styles/bootstrap.css" /> <link rel="stylesheet" type="text/css" href="styles/chosen.css" /> <link rel="stylesheet" type="text/css" href="styles/jquery-ui/jquery-ui.css" /> <link rel="stylesheet" type="text/css" href="styles/style.css" /> </head> <body> <div class="container"> <header class="navbar navbar-fixed-top" data-dropdown="dropdown"> <div class="navbar-inner"> <div class="container"> <a class="brand" href="/">Cella</a> <ul class="nav" style="float: right"> <li class="dropdown"> <a class="dropdown-toggle" href="#" data-toggle="dropdown" title="Helpful links about the housing lottery"> <span class="caret"></span> Lottery Links </a> <ul class="dropdown-menu"> <li> <a href="http://www.brown.edu/Student_Services/Residential_Council/lottery/broadcast/index.php" target="_blank"> Lottery Results Live </a> </li> <li> <a href="http://brown.edu/Student_Services/Residential_Council/lottery/" target="_blank"> Housing Lottery Website </a> </li> <li> <a href="http://reslife.brown.edu/current_students/lottery/floorplans/floorplans.html" target="_blank"> Floorplans </a> </li> <li> <a href="http://reslife.brown.edu/current_students/lottery/index.html" target="_blank">ResLife</a> </li> </ul> </li> <li class="active"><a href="about.html">About</a></li> </ul> </div> </div> </header> {{{ content }}} <footer> </footer> </div> <!-- scripts --> <script type="text/javascript" src="scripts/jquery.js"></script> <script type="text/javascript" src="scripts/bootstrap-dropdown.js"></script> </body> </html>
nmalkin/cella
templates/about.html
HTML
agpl-3.0
2,787
# frozen_string_literal: true # == Schema Information # # Table name: packages # # id :integer not null, primary key # name :string(255) # initial_price :decimal(, ) # at_the_door_price :decimal(, ) # attendee_limit :integer # expires_at :datetime # requires_track :boolean # event_id :integer # created_at :datetime # updated_at :datetime # deleted_at :datetime # ignore_pricing_tiers :boolean default(FALSE), not null # description :text # # Indexes # # index_packages_on_event_id (event_id) # require 'spec_helper' describe Package do let(:user) { create(:user) } let(:event) { create(:event, user: user) } let(:package) { create(:package, event: event, initial_price: 10, at_the_door_price: 50) } context '#current_price' do before(:each) do # set openieng tier before any tiers created here o = event.opening_tier o.date = 1.week.ago o.increase_by_dollars = 0 o.save end it 'is the initial price' do expect(package.current_price).to eq package.initial_price end it 'changes based on the date' do tier = create(:pricing_tier, date: 2.day.ago, event: event) expected = package.initial_price + tier.increase_by_dollars expect(package.current_price).to eq expected end it 'changes based on the number of registrants for this event' do tier = create(:pricing_tier, registrants: 10, event: event) 20.times do create(:registration, event: event) end expected = package.initial_price + tier.increase_by_dollars expect(package.current_price).to eq expected end it 'does not change if the tiers are not yet eligible' do event.registrations.destroy_all # The Delorean replicates a long lasting issue that Travis discovered Delorean.time_travel_to(10.days.from_now) do tier = create(:pricing_tier, date: 19.days.from_now, event: event) tier2 = create(:pricing_tier, registrants: 10, event: event, date: nil) expect(event.current_tier).to eq event.opening_tier expect(package.current_price).to eq package.initial_price end end it 'changes base on two tiers' do tier = create(:pricing_tier, registrants: 10, event: event, date: nil) tier2 = create(:pricing_tier, date: 2.day.ago, event: event) 11.times do create(:registration, event: event) end expect(event.current_tier).to eq tier2 expected = package.initial_price + tier.increase_by_dollars + tier2.increase_by_dollars expect(package.current_price).to eq expected end context 'optionally does not change based on passing tiers' do before(:each) do package.ignore_pricing_tiers = true end it 'tier by date passes' do tier = create(:pricing_tier, date: Date.today, event: event) expected = package.initial_price expect(package.current_price).to eq expected end end end context '#price_at_tier' do it 'redirects functionality to the tier' do tier = create(:pricing_tier, date: Date.today, event: event) expect(tier).to receive(:price_of) package.price_at_tier(tier) end it 'correctly calculates the value' do tier = create(:pricing_tier, registrants: 2, event: event) allow(tier).to receive(:should_apply_amount?) { true } allow(event).to receive(:pricing_tiers) { [tier] } expected = package.initial_price + tier.amount expect(package.price_at_tier(tier)).to eq expected end context 'a new tier is current' do before(:each) do @new_tier = create(:pricing_tier, event: event, date: 1.day.from_now, increase_by_dollars: 3) Delorean.jump 4.days event.reload expect(event.pricing_tiers.count).to eq 2 expect(event.current_tier).to_not eq event.opening_tier expect(event.current_tier).to eq @new_tier end after(:each) do Delorean.back_to_the_present end it 'reflects the price of a previous tier' do expected = package.initial_price expect(package.price_at_tier(event.opening_tier)).to eq expected end end end end
NullVoxPopuli/aeonvera
app/models/specs/package_spec.rb
Ruby
agpl-3.0
4,412
# -*- coding: utf-8 -*- # Copyright 2016 Onestein (<http://www.onestein.eu>) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { 'name': 'OAuth2 Disable Login with Odoo.com', 'version': '10.0.1.0.0', 'category': 'Tools', 'author': 'Onestein', 'license': 'AGPL-3', 'depends': ['auth_oauth'], 'data': [ 'data/auth_oauth_data.xml', ], }
VitalPet/addons-onestein
auth_oauth_disable_login_with_odoo/__manifest__.py
Python
agpl-3.0
394
<?php return unserialize('a:1:{i:0;O:30:"Doctrine\\ORM\\Mapping\\OneToMany":6:{s:8:"mappedBy";s:9:"container";s:12:"targetEntity";s:7:"Element";s:7:"cascade";N;s:5:"fetch";s:4:"LAZY";s:13:"orphanRemoval";b:0;s:7:"indexBy";N;}}');
Goucher/shopware
var/cache/production_201510221322/doctrine/filecache/b05ad6a16cb1d8530c8a49701d638ce13f3b8502$elements.cache.php
PHP
agpl-3.0
229
public class Generic{ public static void main(String[] args){ Car <String> car1 = new Car <String> (); car1.setName("Buick"); car1.setPrice("100"); System.out.printf("name=%s,price=%s\n",car1.getName(),car1.getPrice()); Car <Integer> car2 = new Car <Integer> (); car2.setName(001); car2.setPrice(100); System.out.printf("name=%d,price=%d\n",car2.getName(),car2.getPrice()); Integer[] array = {1,2,3,4,5,6,7,8,9}; car2.print(array); } } /*generic class*/ class Car <T> { private T name; private T price; public Car(){ this.name = null; this.price = null; } public Car(T name,T price){ this.name = name; this.price = price; } public void setName(T name){ this.name = name; } public T getName(){ return this.name; } public void setPrice(T price){ this.price = price; } public T getPrice(){ return this.price; } public <A> void print(A[] array){ for (A var:array) System.out.printf("%s",var); } }
314942468GitHub/JavaLearnning
src/Generic.java
Java
agpl-3.0
963
<?php /** * Created by iluxovi4 * Protected by SugarTalk.ru */ $dictionary['RealtyTemplates']['fields']['realtytemplates_contracts'] = array ( 'name' => 'realtytemplates_contracts', 'type' => 'link', 'relationship' => 'realtytemplates_contracts', 'source'=>'non-db', 'vname'=>'LBL_REALTYTEMPLATES_CONTRACTS', );
MarStan/sugar_work
custom/Extension/modules/RealtyTemplates/Ext/Vardefs/realty_contracts.php
PHP
agpl-3.0
362
# -*- coding: utf-8 -*- # Generated by Django 1.11.2 on 2017-11-22 07:11 from __future__ import unicode_literals from django.core.management.sql import emit_post_migrate_signal from django.db import migrations def add_executive_group(apps, schema_editor): # create group db_alias = schema_editor.connection.alias emit_post_migrate_signal(1, False, db_alias) Group = apps.get_model('auth', 'Group') Permission = apps.get_model('auth', 'Permission') executive_group, created = Group.objects.get_or_create(name='executive') if created: # Learning unit can_access_learningunit = Permission.objects.get(codename='can_access_learningunit') executive_group.permissions.add(can_access_learningunit) class Migration(migrations.Migration): dependencies = [ ('base', '0207_auto_20171220_1035'), ] operations = [ migrations.RunPython(add_executive_group, elidable=True), ]
uclouvain/OSIS-Louvain
base/migrations/0208_create_role_executive.py
Python
agpl-3.0
951
<div class="item dragHandle" data-bind="css: { 'unseen': !seen(), 'selected': selected(), 'checked': checked(), 'forwarded': forwarded(), 'answered': answered(), 'deleted': deleted() || threadHideAnimation(), 'nosubject': emptySubject(), 'threaded': threadPart(), 'show': threadShowAnimation() }"> <div class="item_content"> <span class="controls"> <!-- <label class="custom_checkbox" data-bind="css: {'checked': checked()}"> <span class="icon"></span> <input type="checkbox" data-bind="checked: checked" /> </label>--> <span class="custom_checkbox" data-bind="click: function () { checked(!checked()); }, css: {'checked': checked()}"> <span class="icon"></span> </span> <span class="separator"></span> <span class="flag" data-bind="css: {'flagged': flagged(), 'partial': partialFlagged()}"></span> </span> <span class="data"> <span class="size" data-bind="text: friendlySize()"></span> <span class="date" data-bind="text: date"></span> <span class="attachments has_attachments" data-bind="visible: hasAttachments(), css: {'has_ical_attachment': showCalendarIcon(), 'has_vcard_attachment': hasVcardAttachment()}"></span> <span class="marker"></span> <span class="from fadeout"> <span data-bind="text: fromOrToText()"></span> <span class="other_senders" data-bind="text: threadSendersText(), visible: threadSendersVisible()"></span> </span> <span class="separator"></span> <span class="thread" data-bind="text: threadCount(), visible: threadCountVisible(), click: openThread, css: {'unreed': threadUnreedCount() > 0}"></span> <span class="thread loading" data-i18n="MAILBOX/THREAD_LOADING" data-bind="i18n: 'text', visible: threadLoadingVisible()"></span> <span class="subject fadeout"> <span class="importance" data-bind="visible: importance() === Enums.Importance.High"></span> <span data-bind="text: subjectForDisplay()"></span> </span> </span> <div class="separator"></div> </div> </div> <!-- ko if: threadNextLoadingVisible() --> <div class="item threaded thread_more_messages" data-bind="css:{'show': threadShowAnimation(), 'deleted': threadHideAnimation()}"> <div class="item_content"> <span class="link" data-i18n="MAILBOX/LINK_LOAD_NEXT_THREAD_MESSAGES" data-bind="i18n: 'text', click: loadNextMessages, visible: threadNextLoadingLinkVisible()"></span> <span style="color: #999999; font-size: 15px;" data-i18n="MAILBOX/THREAD_LOADING" data-bind="i18n: 'text', visible: !threadNextLoadingLinkVisible()"></span> </div> </div> <!-- /ko -->
BITS-CO-ID/webmail
templates/views/Mail/MessageListItemViewModel.html
HTML
agpl-3.0
2,556
import * as React from 'react'; import renderOrder from '../renderOrder'; import { RenderLayer } from '../browser_utils/Utils'; import { SharedState } from '../citybound'; import { shadersForLandUses } from './stripedShaders'; import colors from '../colors'; export const LAND_USES = [ "Residential", "Commercial", "Industrial", "Agricultural", "Recreational", "Administrative", ]; const landUseInstances = new Map(LAND_USES.map(landUse => [landUse, new Float32Array([0.0, 0.0, 0.0, 1.0, 0.0, ...colors[landUse]])])); const buildingOutlinesInstance = new Float32Array([0.0, 0.0, 0.0, 1.0, 0.0, ...colors.buildingOutlines]); export function ZonePlanningLayers({ state }: { state: SharedState; }) { const { zoneGroups, zoneOutlineGroups, buildingOutlinesGroup } = state.planning.rendering.currentPreview; return <> {[...zoneGroups.entries()].map(([landUse, groups]) => <RenderLayer renderOrder={renderOrder.addedGesturesZones} decal={true} batches={[...groups.values()].map(groupMesh => ({ mesh: groupMesh, instances: landUseInstances.get(landUse) }))} />)} {[...zoneGroups.entries()].reverse().map(([landUse, groups]) => <RenderLayer renderOrder={renderOrder.addedGesturesZonesStipple} decal={true} shader={shadersForLandUses[landUse]} batches={[...groups.values()].map(groupMesh => ({ mesh: groupMesh, instances: landUseInstances.get(landUse) }))} />)} {[...zoneOutlineGroups.entries()].map(([landUse, groups]) => <RenderLayer renderOrder={renderOrder.addedGesturesZonesOutlines} decal={true} batches={[...groups.values()].map(groupMesh => ({ mesh: groupMesh, instances: landUseInstances.get(landUse) }))} />)} <RenderLayer renderOrder={renderOrder.buildingOutlines} decal={true} batches={[...buildingOutlinesGroup.values()].map(groupMesh => ({ mesh: groupMesh, instances: buildingOutlinesInstance }))} /> </>; }
citybound/citybound
cb_browser_ui/src/planning_browser/ZonePlanningLayers.tsx
TypeScript
agpl-3.0
2,016
<?php App::uses('AppController', 'Controller'); App::uses('Folder', 'Utility'); App::uses('File', 'Utility'); /** * Attributes Controller * * @property Attribute $Attribute */ class AttributesController extends AppController { public $components = array('Security', 'RequestHandler', 'Cidr'); public $paginate = array( 'limit' => 60, 'maxLimit' => 9999, // LATER we will bump here on a problem once we have more than 9999 events ); public $helpers = array('Js' => array('Jquery')); public function beforeFilter() { parent::beforeFilter(); $this->Auth->allow('restSearch'); $this->Auth->allow('returnAttributes'); $this->Auth->allow('downloadAttachment'); $this->Auth->allow('text'); // permit reuse of CSRF tokens on the search page. if ('search' == $this->request->params['action']) { $this->Security->csrfUseOnce = false; } $this->Security->validatePost = true; // convert uuid to id if present in the url, and overwrite id field if (isset($this->params->query['uuid'])) { $params = array( 'conditions' => array('Attribute.uuid' => $this->params->query['uuid']), 'recursive' => 0, 'fields' => 'Attribute.id' ); $result = $this->Attribute->find('first', $params); if (isset($result['Attribute']) && isset($result['Attribute']['id'])) { $id = $result['Attribute']['id']; $this->params->addParams(array('pass' => array($id))); // FIXME find better way to change id variable if uuid is found. params->url and params->here is not modified accordingly now } } // do not show private to other orgs // if not admin or own org, check private as well.. if (!$this->_isSiteAdmin()) { $this->paginate = Set::merge($this->paginate,array( 'conditions' => array('OR' => array( 'Event.org =' => $this->Auth->user('org'), 'AND' => array( 'Attribute.distribution >' => 0, 'Event.distribution >' => 0, ))))); } /* We want to show this outside now as discussed with Christophe. Still not pushable, but anything should be pullable that's visible // do not show cluster outside server if ($this->_isRest()) { $this->paginate = Set::merge($this->paginate,array( 'conditions' => array("AND" => array('Event.cluster !=' => true),array('Attribute.cluster !=' => true)), //array("AND" => array(array('Event.private !=' => 2))), )); } */ } /** * index method * * @return void * */ public function index() { $this->Attribute->recursive = 0; $this->Attribute->contain = array('Event.id', 'Event.orgc', 'Event.org', 'Event.info'); $this->set('isSearch', 0); $this->set('attributes', $this->paginate()); $this->set('attrDescriptions', $this->Attribute->fieldDescriptions); $this->set('typeDefinitions', $this->Attribute->typeDefinitions); $this->set('categoryDefinitions', $this->Attribute->categoryDefinitions); } /** * add method * * @return void * * @throws NotFoundException // TODO Exception */ public function add($eventId = null) { if (!$this->userRole['perm_add']) { throw new MethodNotAllowedException('You don\'t have permissions to create attributes'); } if ($this->request->is('ajax')) { $this->set('ajax', true); $this->layout = 'ajax'; } else $this->set('ajax', false); if ($this->request->is('post')) { if ($this->request->is('ajax')) $this->autoRender = false; $this->loadModel('Event'); $date = new DateTime(); // Give error if someone tried to submit a attribute with attachment or malware-sample type. // TODO change behavior attachment options - this is bad ... it should rather by a messagebox or should be filtered out on the view level if (isset($this->request->data['Attribute']['type']) && $this->Attribute->typeIsAttachment($this->request->data['Attribute']['type'])) { $this->Session->setFlash(__('Attribute has not been added: attachments are added by "Add attachment" button', true), 'default', array(), 'error'); $this->redirect(array('controller' => 'events', 'action' => 'view', $this->request->data['Attribute']['event_id'])); } // remove the published flag from the event $this->Event->recursive = -1; $this->Event->read(null, $this->request->data['Attribute']['event_id']); if (!$this->_isSiteAdmin() && ($this->Event->data['Event']['orgc'] != $this->_checkOrg() || !$this->userRole['perm_modify'])) { throw new UnauthorizedException('You do not have permission to do that.'); } $this->Event->set('timestamp', $date->getTimestamp()); $this->Event->set('published', 0); $this->Event->save($this->Event->data, array('fieldList' => array('published', 'timestamp', 'info'))); // // multiple attributes in batch import // if ((isset($this->request->data['Attribute']['batch_import']) && $this->request->data['Attribute']['batch_import'] == 1)) { // make array from value field $attributes = explode("\n", $this->request->data['Attribute']['value']); $fails = ""; // will be used to keep a list of the lines that failed or succeeded $successes = ""; $failCount = 0; $successCount = 0; // TODO loop-holes, // the value null value thing foreach ($attributes as $key => $attribute) { $attribute = trim($attribute); if (strlen($attribute) == 0) continue; // don't do anything for empty lines $this->Attribute->create(); $this->request->data['Attribute']['value'] = $attribute; // set the value as the content of the single line // TODO loop-holes, // there seems to be a loop-hole in misp here // be it an create and not an update $this->Attribute->id = null; if ($this->Attribute->save($this->request->data)) { $successes .= " " . ($key + 1); $successCount++; } else { $fails .= " " . ($key + 1); $failCount++; } } if ($this->request->is('ajax')) { $this->autoRender = false; if ($fails) { $error_message = 'The lines' . $fails . ' could not be saved. Please, try again.'; return new CakeResponse(array('body'=> json_encode(array('saved' => true, 'errors' => $error_message)), 'status' => 200)); } else { return new CakeResponse(array('body'=> json_encode(array('saved' => true, 'success' => $successCount . ' Attributes added')), 'status' => 200)); } } else { // we added all the attributes, if ($fails) { // list the ones that failed if (!CakeSession::read('Message.flash')) { $this->Session->setFlash(__('The lines' . $fails . ' could not be saved. Please, try again.', true), 'default', array(), 'error'); } else { $existingFlash = CakeSession::read('Message.flash'); $this->Session->setFlash(__('The lines' . $fails . ' could not be saved. ' . $existingFlash['message'], true), 'default', array(), 'error'); } } if ($successes) { // list the ones that succeeded $this->Session->setFlash(__('The lines' . $successes . ' have been saved', true)); } $this->redirect(array('controller' => 'events', 'action' => 'view', $this->request->data['Attribute']['event_id'])); } } else { if (isset($this->request->data['Attribute']['uuid'])) { // TODO here we should start RESTful dialog // check if the uuid already exists and also save the existing attribute for further checks $existingAttribute = null; $existingAttribute = $this->Attribute->find('first', array('conditions' => array('Attribute.uuid' => $this->request->data['Attribute']['uuid']))); //$existingAttributeCount = $this->Attribute->find('count', array('conditions' => array('Attribute.uuid' => $this->request->data['Attribute']['uuid']))); if ($existingAttribute) { // TODO RESTfull, set responce location header..so client can find right URL to edit $this->response->header('Location', Configure::read('MISP.baseurl') . '/attributes/' . $existingAttribute['Attribute']['id']); $this->response->send(); $this->view($this->Attribute->getId()); $this->render('view'); return false; } else { // if the attribute doesn't exist yet, check whether it has a timestamp - if yes, it's from a push, keep the timestamp we had, if no create a timestamp if (!isset($this->request->data['Attribute']['timestamp'])) { $this->request->data['Attribute']['timestamp'] = $date->getTimestamp(); } } } else { if (!isset($this->request->data['Attribute']['timestamp'])) { $this->request->data['Attribute']['timestamp'] = $date->getTimestamp(); } } // // single attribute // // create the attribute $this->Attribute->create(); $savedId = $this->Attribute->getId(); if ($this->Attribute->save($this->request->data)) { if ($this->_isRest()) { // REST users want to see the newly created attribute $this->view($this->Attribute->getId()); $this->render('view'); } elseif ($this->request->is('ajax')) { $this->autoRender = false; return new CakeResponse(array('body'=> json_encode(array('saved' => true, 'success' => 'Attribute added.')),'status'=>200)); } else { // inform the user and redirect $this->Session->setFlash(__('The attribute has been saved')); $this->redirect(array('controller' => 'events', 'action' => 'view', $this->request->data['Attribute']['event_id'])); } } else { if ($this->_isRest()) { // TODO return error if REST // REST users want to see the failed attribute $this->view($savedId); $this->render('view'); } elseif ($this->request->is('ajax')) { $this->autoRender = false; return new CakeResponse(array('body'=> json_encode(array('saved' => false, 'errors' => $this->Attribute->validationErrors)),'status'=>200)); } else { if (!CakeSession::read('Message.flash')) { $this->Session->setFlash(__('The attribute could not be saved. Please, try again.')); } } } } } else { // set the event_id in the form $this->request->data['Attribute']['event_id'] = $eventId; } // combobox for types $types = array_keys($this->Attribute->typeDefinitions); $types = $this->_arrayToValuesIndexArray($types); $this->set('types', $types); // combobos for categories $categories = $this->Attribute->validate['category']['rule'][1]; array_pop($categories); $categories = $this->_arrayToValuesIndexArray($categories); $this->set('categories', compact('categories')); $this->loadModel('Event'); $events = $this->Event->findById($eventId); $this->set('event_id', $events['Event']['id']); // combobox for distribution $this->set('distributionLevels', $this->Attribute->distributionLevels); $this->set('currentDist', $events['Event']['distribution']); // TODO default distribution // tooltip for distribution $this->set('distributionDescriptions', $this->Attribute->distributionDescriptions); $this->set('attrDescriptions', $this->Attribute->fieldDescriptions); $this->set('typeDefinitions', $this->Attribute->typeDefinitions); $this->set('categoryDefinitions', $this->Attribute->categoryDefinitions); $this->set('published', $events['Event']['published']); } public function download($id = null) { $this->Attribute->id = $id; if (!$this->Attribute->exists()) { throw new NotFoundException(__('Invalid attribute')); } $this->Attribute->read(); if (!$this->_isSiteAdmin() && $this->Auth->user('org') != $this->Attribute->data['Event']['org'] && ($this->Attribute->data['Event']['distribution'] == 0 || $this->Attribute->data['Attribute']['distribution'] == 0 )) { throw new UnauthorizedException('You do not have the permission to view this event.'); } $this->__downloadAttachment($this->Attribute->data['Attribute']); } private function __downloadAttachment($attribute) { $path = "files" . DS . $attribute['event_id'] . DS; $file = $attribute['id']; $filename = ''; if ('attachment' == $attribute['type']) { $filename = $attribute['value']; $fileExt = pathinfo($filename, PATHINFO_EXTENSION); $filename = substr($filename, 0, strlen($filename) - strlen($fileExt) - 1); } elseif ('malware-sample' == $attribute['type']) { $filenameHash = explode('|', $attribute['value']); $filename = $filenameHash[0]; $filename = substr($filenameHash[0], strrpos($filenameHash[0], '\\')); $fileExt = "zip"; } else { throw new NotFoundException(__('Attribute not an attachment or malware-sample')); } $this->autoRender = false; $this->response->type($fileExt); $this->response->file($path . $file, array('download' => true, 'name' => $filename . '.' . $fileExt)); } /** * add_attachment method * * @return void * @throws InternalErrorException */ public function add_attachment($eventId = null) { $sha256 = null; $sha1 = null; //$ssdeep = null; if ($this->request->is('post')) { $this->loadModel('Event'); $this->Event->id = $this->request->data['Attribute']['event_id']; $this->Event->recursive = -1; $this->Event->read(); if (!$this->_isSiteAdmin() && ($this->Event->data['Event']['orgc'] != $this->_checkOrg() || !$this->userRole['perm_modify'])) { throw new UnauthorizedException('You do not have permission to do that.'); } // Check if there were problems with the file upload // only keep the last part of the filename, this should prevent directory attacks $filename = basename($this->request->data['Attribute']['value']['name']); $tmpfile = new File($this->request->data['Attribute']['value']['tmp_name']); if ((isset($this->request->data['Attribute']['value']['error']) && $this->request->data['Attribute']['value']['error'] == 0) || (!empty( $this->request->data['Attribute']['value']['tmp_name']) && $this->request->data['Attribute']['value']['tmp_name'] != 'none') ) { if (!is_uploaded_file($tmpfile->path)) throw new InternalErrorException('PHP says file was not uploaded. Are you attacking me?'); } else { $this->Session->setFlash(__('There was a problem to upload the file.', true), 'default', array(), 'error'); $this->redirect(array('controller' => 'events', 'action' => 'view', $this->request->data['Attribute']['event_id'])); } // save the file-info in the database $this->Attribute->create(); if ($this->request->data['Attribute']['malware']) { $this->request->data['Attribute']['type'] = "malware-sample"; // Validate filename if (!preg_match('@^[\w\-. ]+$@', $filename)) throw new Exception ('Filename not allowed'); $this->request->data['Attribute']['value'] = $filename . '|' . hash_file('md5', $tmpfile->path); // TODO gives problems with bigger files $sha256 = (hash_file('sha256', $tmpfile->path)); $sha1 = (hash_file('sha1', $tmpfile->path)); $this->request->data['Attribute']['to_ids'] = 1; // LATER let user choose to send this to IDS } else { $this->request->data['Attribute']['type'] = "attachment"; // Validate filename if (!preg_match('@^[\w\-. ]+$@', $filename)) throw new Exception ('Filename not allowed'); $this->request->data['Attribute']['value'] = $filename; $this->request->data['Attribute']['to_ids'] = 0; } $this->request->data['Attribute']['uuid'] = String::uuid(); $this->request->data['Attribute']['batch_import'] = 0; if ($this->Attribute->save($this->request->data)) { // attribute saved correctly in the db // remove the published flag from the event $this->Event->id = $this->request->data['Attribute']['event_id']; $this->Event->saveField('published', 0); } else { $this->Session->setFlash(__('The attribute could not be saved. Did you already upload this file?')); $this->redirect(array('controller' => 'events', 'action' => 'view', $this->request->data['Attribute']['event_id'])); } // no errors in file upload, entry already in db, now move the file where needed and zip it if required. // no sanitization is required on the filename, path or type as we save // create directory structure if (PHP_OS == 'WINNT') { $rootDir = APP . "files" . DS . $this->request->data['Attribute']['event_id']; } else { $rootDir = APP . DS . "files" . DS . $this->request->data['Attribute']['event_id']; } $dir = new Folder($rootDir, true); // move the file to the correct location $destpath = $rootDir . DS . $this->Attribute->id; // id of the new attribute in the database $file = new File ($destpath); $zipfile = new File ($destpath . '.zip'); $fileInZip = new File($rootDir . DS . $filename); // FIXME do sanitization of the filename if ($file->exists() || $zipfile->exists() || $fileInZip->exists()) { // this should never happen as the attribute id should be unique $this->Session->setFlash(__('Attachment with this name already exist in this event.', true), 'default', array(), 'error'); // remove the entry from the database $this->Attribute->delete(); $this->redirect(array('controller' => 'events', 'action' => 'view', $this->request->data['Attribute']['event_id'])); } if (!move_uploaded_file($tmpfile->path, $file->path)) { $this->Session->setFlash(__('Problem with uploading attachment. Cannot move it to its final location.', true), 'default', array(), 'error'); // remove the entry from the database $this->Attribute->delete(); $this->redirect(array('controller' => 'events', 'action' => 'view', $this->request->data['Attribute']['event_id'])); } // zip and password protect the malware files if ($this->request->data['Attribute']['malware']) { // TODO check if CakePHP has no easy/safe wrapper to execute commands $execRetval = ''; $execOutput = array(); rename($file->path, $fileInZip->path); // TODO check if no workaround exists for the current filtering mechanisms if (PHP_OS == 'WINNT') { exec("zip -j -P infected " . $zipfile->path . ' "' . $fileInZip->path . '"', $execOutput, $execRetval); } else { exec("zip -j -P infected " . $zipfile->path . ' "' . addslashes($fileInZip->path) . '"', $execOutput, $execRetval); } if ($execRetval != 0) { // not EXIT_SUCCESS $this->Session->setFlash(__('Problem with zipping the attachment. Please report to administrator. ' . $execOutput, true), 'default', array(), 'error'); // remove the entry from the database $this->Attribute->delete(); $fileInZip->delete(); $file->delete(); $this->redirect(array('controller' => 'events', 'action' => 'view', $this->request->data['Attribute']['event_id'])); }; $fileInZip->delete(); // delete the original not-zipped-file rename($zipfile->path, $file->path); // rename the .zip to .nothing } if ($this->request->data['Attribute']['malware']) { $temp = $this->request->data; $this->Attribute->create(); $temp['Attribute']['type'] = 'filename|sha256'; $temp['Attribute']['value'] = $filename . '|' .$sha256; $temp['Attribute']['uuid'] = String::uuid(); $this->Attribute->save($temp, array('fieldlist' => array('value', 'type', 'category', 'event_id', 'distribution', 'to_ids', 'comment'))); $this->Attribute->create(); $temp['Attribute']['type'] = 'filename|sha1'; $temp['Attribute']['value'] = $filename . '|' .$sha1; $temp['Attribute']['uuid'] = String::uuid(); $this->Attribute->save($temp, array('fieldlist' => array('value', 'type', 'category', 'event_id', 'distribution', 'to_ids', 'comment'))); } // everything is done, now redirect to event view $this->Session->setFlash(__('The attachment has been uploaded')); $this->redirect(array('controller' => 'events', 'action' => 'view', $this->request->data['Attribute']['event_id'])); } else { // set the event_id in the form $this->request->data['Attribute']['event_id'] = $eventId; } // combobos for categories $categories = $this->Attribute->validate['category']['rule'][1]; // just get them with attachments.. $selectedCategories = array(); foreach ($categories as $category) { if (isset($this->Attribute->categoryDefinitions[$category])) { $types = $this->Attribute->categoryDefinitions[$category]['types']; $alreadySet = false; foreach ($types as $type) { if ($this->Attribute->typeIsAttachment($type) && !$alreadySet) { // add to the whole.. $selectedCategories[] = $category; $alreadySet = true; continue; } } } }; $categories = $this->_arrayToValuesIndexArray($selectedCategories); $this->set('categories',$categories); $this->set('attrDescriptions', $this->Attribute->fieldDescriptions); $this->set('typeDefinitions', $this->Attribute->typeDefinitions); $this->set('categoryDefinitions', $this->Attribute->categoryDefinitions); $this->set('zippedDefinitions', $this->Attribute->zippedDefinitions); $this->set('uploadDefinitions', $this->Attribute->uploadDefinitions); // combobox for distribution $this->loadModel('Event'); $this->set('distributionDescriptions', $this->Attribute->distributionDescriptions); $this->set('distributionLevels', $this->Event->distributionLevels); $events = $this->Event->findById($eventId); $this->set('currentDist', $events['Event']['distribution']); $this->set('published', $events['Event']['published']); } /** * Imports the CSV threatConnect file to multiple attributes * @param int $id The id of the event */ public function add_threatconnect($eventId = null) { if ($this->request->is('post')) { $this->loadModel('Event'); $this->Event->id = $eventId; $this->Event->recursive = -1; $this->Event->read(); if (!$this->_isSiteAdmin() && ($this->Event->data['Event']['orgc'] != $this->_checkOrg() || !$this->userRole['perm_modify'])) { throw new UnauthorizedException('You do not have permission to do that.'); } // // File upload // // Check if there were problems with the file upload $tmpfile = new File($this->request->data['Attribute']['value']['tmp_name']); if ((isset($this->request->data['Attribute']['value']['error']) && $this->request->data['Attribute']['value']['error'] == 0) || (!empty( $this->request->data['Attribute']['value']['tmp_name']) && $this->request->data['Attribute']['value']['tmp_name'] != 'none') ) { if (!is_uploaded_file($tmpfile->path)) throw new InternalErrorException('PHP says file was not uploaded. Are you attacking me?'); } else { $this->Session->setFlash(__('There was a problem to upload the file.', true), 'default', array(), 'error'); $this->redirect(array('controller' => 'attributes', 'action' => 'add_threatconnect', $this->request->data['Attribute']['event_id'])); } // verify mime type $file_info = $tmpfile->info(); if ($file_info['mime'] != 'text/plain') { $this->Session->setFlash('File not in CSV format.', 'default', array(), 'error'); $this->redirect(array('controller' => 'attributes', 'action' => 'add_threatconnect', $this->request->data['Attribute']['event_id'])); } // parse uploaded csv file $filename = $tmpfile->path; $header = NULL; $entries = array(); if (($handle = fopen($filename, 'r')) !== FALSE) { while (($row = fgetcsv($handle, 0, ',', '"')) !== FALSE) { if(!$header) $header = $row; else $entries[] = array_combine($header, $row); } fclose($handle); } // verify header of the file (first row) $required_headers = array('Type', 'Value', 'Confidence', 'Description', 'Source'); if (count(array_intersect($header, $required_headers)) != count($required_headers)) { $this->Session->setFlash('Incorrect ThreatConnect headers. The minimum required headers are: '.implode(',', $required_headers), 'default', array(), 'error'); $this->redirect(array('controller' => 'attributes', 'action' => 'add_threatconnect', $this->request->data['Attribute']['event_id'])); } // // import attributes // $attributes = array(); // array with all the attributes we're going to save foreach($entries as $entry) { $attribute = array(); $attribute['event_id'] = $this->request->data['Attribute']['event_id']; $attribute['value'] = $entry['Value']; $attribute['to_ids'] = ($entry['Confidence'] > 51) ? 1 : 0; // To IDS if high confidence $attribute['comment'] = 'ThreatConnect: ' . $entry['Description']; $attribute['distribution'] = '3'; // 'All communities' if (Configure::read('MISP.default_attribute_distribution') != null) { if (Configure::read('MISP.default_attribute_distribution') === 'event') { $attribute['distribution'] = $this->Event->data['Event']['distribution']; } else { $attribute['distribution'] = Configure::read('MISP.default_attribute_distribution'); } } switch($entry['Type']) { case 'Address': $attribute['category'] = 'Network activity'; $attribute['type'] = 'ip-dst'; break; case 'Host': $attribute['category'] = 'Network activity'; $attribute['type'] = 'domain'; break; case 'EmailAddress': $attribute['category'] = 'Payload delivery'; $attribute['type'] = 'email-src'; break; case 'File': $attribute['category'] = 'Artifacts dropped'; $attribute['value'] = strtolower($attribute['value']); if (preg_match("#^[0-9a-f]{32}$#", $attribute['value'])) $attribute['type'] = 'md5'; else if (preg_match("#^[0-9a-f]{40}$#", $attribute['value'])) $attribute['type'] = 'sha1'; else if (preg_match("#^[0-9a-f]{64}$#", $attribute['value'])) $attribute['type'] = 'sha256'; else // do not keep attributes that do not have a match $attribute=NULL; break; case 'URL': $attribute['category'] = 'Network activity'; $attribute['type'] = 'url'; break; default: // do not keep attributes that do not have a match $attribute=NULL; } // add attribute to the array that will be saved if ($attribute) $attributes[] = $attribute; } // // import source info: // // 1/ iterate over all the sources, unique // 2/ add uniques as 'Internal reference' // 3/ if url format -> 'link' // else 'comment' $references = array(); foreach($entries as $entry) { $references[$entry['Source']] = true; } $references = array_keys($references); // generate the Attributes foreach($references as $reference) { $attribute = array(); $attribute['event_id'] = $this->request->data['Attribute']['event_id']; $attribute['category'] = 'Internal reference'; if (preg_match('#^(http|ftp)(s)?\:\/\/((([a-z|0-9|\-]{1,25})(\.)?){2,7})($|/.*$)#i', $reference)) $attribute['type'] = 'link'; else $attribute['type'] = 'comment'; $attribute['value'] = $reference; $attribute['distribution'] = 3; // 'All communities' // add attribute to the array that will be saved $attributes[] = $attribute; } // // finally save all the attributes at once, and continue if there are validation errors // $this->Attribute->saveMany($attributes, array('validate' => true)); // data imported (with or without errors) // remove the published flag from the event $this->loadModel('Event'); $this->Event->id = $this->request->data['Attribute']['event_id']; $this->Event->saveField('published', 0); // everything is done, now redirect to event view $this->Session->setFlash(__('The ThreatConnect data has been imported')); $this->redirect(array('controller' => 'events', 'action' => 'view', $this->request->data['Attribute']['event_id'])); } else { // set the event_id in the form $this->request->data['Attribute']['event_id'] = $eventId; } // form not submitted, show page $this->loadModel('Event'); $events = $this->Event->findById($eventId); $this->set('published', $events['Event']['published']); } /** * edit method * * @param string $id * @return void * @throws NotFoundException */ public function edit($id = null) { $this->Attribute->id = $id; $date = new DateTime(); if (!$this->Attribute->exists()) { throw new NotFoundException(__('Invalid attribute')); } $this->Attribute->read(); //set stuff to fix undefined index: uuid if (!$this->_isRest()) { $uuid = $this->Attribute->data['Attribute']['uuid']; } if (!$this->_isSiteAdmin()) { // if ($this->Attribute->data['Event']['orgc'] == $this->Auth->user('org') && (($this->userRole['perm_modify'] && $this->Attribute->data['Event']['user_id'] != $this->Auth->user('id')) || $this->userRole['perm_modify_org'])) { // Allow the edit } else { $this->Session->setFlash(__('Invalid attribute.')); $this->redirect(array('controller' => 'events', 'action' => 'index')); } } $eventId = $this->Attribute->data['Attribute']['event_id']; if ('attachment' == $this->Attribute->data['Attribute']['type'] || 'malware-sample' == $this->Attribute->data['Attribute']['type'] ) { $this->set('attachment', true); // TODO we should ensure 'value' cannot be changed here and not only on a view level (because of the associated file) // $this->Session->setFlash(__('You cannot edit attachment attributes.', true), 'default', array(), 'error'); // $this->redirect(array('controller' => 'events', 'action' => 'view', $old_attribute['Event']['id'])); } else { $this->set('attachment', false); } if ($this->request->is('post') || $this->request->is('put')) { // reposition to get the attribute.id with given uuid // Notice (8): Undefined index: uuid [APP/Controller/AttributesController.php, line 502] // Fixed - uuid was not passed back from the form since it's not a field. Set the uuid in a variable for non rest users, rest should have uuid. // Generally all of this should be _isRest() only, but that's something for later to think about if ($this->_isRest()) { $existingAttribute = $this->Attribute->findByUuid($this->request->data['Attribute']['uuid']); } else { $existingAttribute = $this->Attribute->findByUuid($uuid); } if (count($existingAttribute)) { $this->request->data['Attribute']['id'] = $existingAttribute['Attribute']['id']; } // check if the attribute has a timestamp already set (from a previous instance that is trying to edit via synchronisation) if (isset($this->request->data['Attribute']['timestamp'])) { // check which attribute is newer if ($this->request->data['Attribute']['timestamp'] > $existingAttribute['Attribute']['timestamp']) { // carry on with adding this attribute - Don't forget! if orgc!=user org, create shadow attribute, not attribute! } else { // the old one is newer or the same, replace the request's attribute with the old one $this->request->data['Attribute'] = $existingAttribute['Attribute']; } } else { $this->request->data['Attribute']['timestamp'] = $date->getTimestamp(); } $fieldList = array('category', 'type', 'value1', 'value2', 'to_ids', 'distribution', 'value', 'timestamp', 'comment'); $this->loadModel('Event'); $this->Event->id = $eventId; // enabling / disabling the distribution field in the edit view based on whether user's org == orgc in the event $this->Event->read(); if ($this->Attribute->save($this->request->data)) { $this->Session->setFlash(__('The attribute has been saved')); // remove the published flag from the event $this->Event->set('timestamp', $date->getTimestamp()); $this->Event->set('published', 0); $this->Event->save($this->Event->data, array('fieldList' => array('published', 'timestamp', 'info'))); if ($this->_isRest()) { // REST users want to see the newly created event $this->view($this->Attribute->getId()); $this->render('view'); } else { $this->redirect(array('controller' => 'events', 'action' => 'view', $eventId)); } } else { if (!CakeSession::read('Message.flash')) { $this->Session->setFlash(__('The attribute could not be saved. Please, try again.')); } else { $this->request->data = $this->Attribute->read(null, $id); } } } else { $this->request->data = $this->Attribute->read(null, $id); } $this->set('attribute', $this->request->data); // enabling / disabling the distribution field in the edit view based on whether user's org == orgc in the event $this->loadModel('Event'); $this->Event->id = $eventId; $this->Event->read(); $this->set('published', $this->Event->data['Event']['published']); // needed for RBAC // combobox for types $types = array_keys($this->Attribute->typeDefinitions); $types = $this->_arrayToValuesIndexArray($types); $this->set('types', $types); // combobox for categories $categories = $this->Attribute->validate['category']['rule'][1]; array_pop($categories); // remove that last empty/space option $categories = $this->_arrayToValuesIndexArray($categories); $this->set('categories', $categories); $this->set('currentDist', $this->Event->data['Event']['distribution']); // combobox for distribution $this->set('distributionLevels', $this->Attribute->distributionLevels); // tooltip for distribution $this->set('distributionDescriptions', $this->Attribute->distributionDescriptions); $this->set('attrDescriptions', $this->Attribute->fieldDescriptions); $this->set('typeDefinitions', $this->Attribute->typeDefinitions); $this->set('categoryDefinitions', $this->Attribute->categoryDefinitions); } // ajax edit - post a single edited field and this method will attempt to save it and return a json with the validation errors if they occur. public function editField($id) { if ((!$this->request->is('post') && !$this->request->is('put')) || !$this->request->is('ajax')) throw new MethodNotAllowedException(); $this->Attribute->id = $id; if (!$this->Attribute->exists()) { return new CakeResponse(array('body'=> json_encode(array('fail' => false, 'errors' => 'Invalid attribute')),'status'=>200)); } $this->Attribute->recursive = -1; $this->Attribute->contain('Event'); $attribute = $this->Attribute->read(); if (!$this->_isSiteAdmin()) { // if ($this->Attribute->data['Event']['orgc'] == $this->Auth->user('org') && (($this->userRole['perm_modify'] && $this->Attribute->data['Event']['user_id'] != $this->Auth->user('id')) || $this->userRole['perm_modify_org'])) { // Allow the edit } else { return new CakeResponse(array('body'=> json_encode(array('fail' => false, 'errors' => 'Invalid attribute')),'status'=>200)); } } foreach ($this->request->data['Attribute'] as $changedKey => $changedField) { if ($attribute['Attribute'][$changedKey] == $changedField) { $this->autoRender = false; return new CakeResponse(array('body'=> json_encode('nochange'),'status'=>200)); } $attribute['Attribute'][$changedKey] = $changedField; } $date = new DateTime(); $attribute['Attribute']['timestamp'] = $date->getTimestamp(); if ($this->Attribute->save($attribute)) { $event = $this->Attribute->Event->find('first', array( 'recursive' => -1, 'fields' => array('id', 'published', 'timestamp', 'info'), 'conditions' => array( 'id' => $attribute['Attribute']['event_id'], ))); $event['Event']['timestamp'] = $date->getTimestamp(); $event['Event']['published'] = 0; $this->Attribute->Event->save($event, array('fieldList' => array('published', 'timestamp', 'info'))); $this->autoRender = false; return new CakeResponse(array('body'=> json_encode(array('saved' => true, 'success' => 'Field updated.')),'status'=>200)); } else { $this->autoRender = false; return new CakeResponse(array('body'=> json_encode(array('saved' => false, 'errors' => $this->Attribute->validationErrors)),'status'=>200)); } } public function view($id, $hasChildren = 0) { $this->Attribute->id = $id; if (!$this->Attribute->exists()) { throw new NotFoundException('Invalid attribute'); } $this->Attribute->recursive = -1; $this->Attribute->contain('Event'); $attribute = $this->Attribute->read(); if (!$this->_isSiteAdmin()) { // if ($this->Attribute->data['Event']['org'] == $this->Auth->user('org') || (($this->Attribute->data['Event']['distribution'] > 0) && $this->Attribute->data['Attribute']['distribution'] > 0)) { throw new MethodNotAllowed('Invalid attribute'); } } $eventRelations = $this->Attribute->Event->getRelatedAttributes($this->Auth->user(), $this->_isSiteAdmin(), $attribute['Attribute']['event_id']); $attribute['Attribute']['relations'] = array(); if (isset($eventRelations[$id])) { foreach ($eventRelations[$id] as $relations) { $attribute['Attribute']['relations'][] = array($relations['id'], $relations['info'], $relations['org']); } } $object = $attribute['Attribute']; $object['objectType'] = 0; $object['hasChildren'] = $hasChildren; $this->set('object', $object); $this->set('distributionLevels', $this->Attribute->Event->distributionLevels); /* $this->autoRender = false; $responseObject = array(); return new CakeResponse(array('body'=> json_encode($attribute['Attribute']),'status'=>200)); */ } /** * delete method * * @param string $id * @return void * @throws MethodNotAllowedException * @throws NotFoundException * * and is able to delete w/o question */ public function delete($id = null) { if ($this->request->is('ajax')) { if ($this->request->is('post')) { if ($this->__delete($id)) { return new CakeResponse(array('body'=> json_encode(array('saved' => true, 'success' => 'Attribute deleted.')),'status'=>200)); } else { return new CakeResponse(array('body'=> json_encode(array('saved' => false, 'errors' => 'Attribute was not deleted.')),'status'=>200)); } } else { $this->set('id', $id); $attribute = $this->Attribute->find('first', array( 'conditions' => array('id' => $id), 'recursive' => -1, 'fields' => array('id', 'event_id'), )); $this->set('event_id', $attribute['Attribute']['event_id']); $this->render('ajax/attributeConfirmationForm'); } } else { if (!$this->request->is('post') && !$this->_isRest()) { throw new MethodNotAllowedException(); } if ($this->__delete($id)) { $this->Session->setFlash(__('Attribute deleted')); } else { $this->Session->setFlash(__('Attribute was not deleted')); } if (!$this->_isRest()) $this->redirect($this->referer()); // TODO check else $this->redirect(array('action' => 'index')); } } /** * unification of the actual delete for the multi-select * * @param unknown $id * @throws NotFoundException * @throws MethodNotAllowedException * @return boolean * * returns true/false based on success */ private function __delete($id) { $this->Attribute->id = $id; if (!$this->Attribute->exists()) { return false; } $result = $this->Attribute->find('first', array( 'conditions' => array('Attribute.id' => $id), 'fields' => array('Attribute.id, Attribute.event_id', 'Attribute.uuid'), 'contain' => array('Event' => array( 'fields' => array('Event.id', 'Event.orgc', 'Event.org', 'Event.locked') )), )); // find the uuid $uuid = $result['Attribute']['uuid']; // check for permissions if (!$this->_isSiteAdmin()) { if ($result['Event']['locked']) { if ($this->_checkOrg() != $result['Event']['org'] || !$this->userRole['perm_sync']) { throw new MethodNotAllowedException(); } } else { if ($this->_checkOrg() != $result['Event']['orgc']) { throw new MethodNotAllowedException(); } } } // attachment will be deleted with the beforeDelete() function in the Model if ($this->Attribute->delete()) { // delete the attribute from remote servers //$this->__deleteAttributeFromServers($uuid); // We have just deleted the attribute, let's also check if there are any shadow attributes that were attached to it and delete them $this->loadModel('ShadowAttribute'); $this->ShadowAttribute->deleteAll(array('ShadowAttribute.old_id' => $id), false); return true; } else { return false; } } public function deleteSelected($id) { if (!$this->request->is('post') && !$this->request->is('ajax')) { //if (!$this->request->is('post')) { throw new MethodNotAllowedException(); } // get a json object with a list of attribute IDs to be deleted // check each of them and return a json object with the successful deletes and the failed ones. $ids = json_decode($this->request->data['Attribute']['ids']); if (!$this->_isSiteAdmin()) { $event = $this->Attribute->Event->find('first', array( 'conditions' => array('id' => $id), 'recursive' => -1, 'fields' => array('id', 'orgc', 'user_id') )); if ($event['Event']['orgc'] != $this->Auth->user('org') || (!$this->userRole['perm_modify_org'] && !($this->userRole['perm_modify'] && $event['Event']['user_id'] == $this->Auth->user('id')))) { throw new MethodNotAllowedException('Invalid Event.'); } } // find all attributes from the ID list that also match the provided event ID. $attributes = $this->Attribute->find('all', array( 'recursive' => -1, 'conditions' => array('id' => $ids, 'event_id' => $id), 'fields' => array('id', 'event_id') )); $successes = array(); foreach ($attributes as $a) { if ($this->__delete($a['Attribute']['id'])) $successes[] = $a['Attribute']['id']; } $fails = array_diff($ids, $successes); $this->autoRender = false; if (count($fails) == 0 && count($successes) > 0) { return new CakeResponse(array('body'=> json_encode(array('saved' => true, 'success' => count($successes) . ' attribute' . (count($successes) != 1 ? 's' : '') . ' deleted.')),'status'=>200)); } else { return new CakeResponse(array('body'=> json_encode(array('saved' => false, 'errors' => count($successes) . ' attribute' . (count($successes) != 1 ? 's' : '') . ' deleted, but ' . count($fails) . ' attribute' . (count($fails) != 1 ? 's' : '') . ' could not be deleted.')),'status'=>200)); } } public function editSelected($id) { if (!$this->request->is('ajax')) throw new MethodNotAllowedException('This method can only be accessed via AJAX.'); if ($this->request->is('post')) { $event = $this->Attribute->Event->find('first', array( 'conditions' => array('id' => $id), 'recursive' => -1, 'fields' => array('id', 'orgc', 'user_id') )); if (!$this->_isSiteAdmin()) { if ($event['Event']['orgc'] != $this->Auth->user('org') || (!$this->userRole['perm_modify_org'] && !($this->userRole['perm_modify'] && $event['user_id'] == $this->Auth->user('id')))) { throw new MethodNotAllowedException('You are not authorized to edit this event.'); } } $attribute_ids = json_decode($this->request->data['Attribute']['attribute_ids']); $attributes = $this->Attribute->find('all', array( 'conditions' => array( 'id' => $attribute_ids, 'event_id' => $id, ), //to_ids = true/false, distribution = [0,1,2,3] //'fields' => array('id', 'event_id', 'comment', 'to_ids', 'timestamp', 'distribution'), 'recursive' => -1, )); if ($this->request->data['Attribute']['to_ids'] == 2 && $this->request->data['Attribute']['distribution'] == 4 && $this->request->data['Attribute']['comment'] == null) { $this->autoRender = false; return new CakeResponse(array('body'=> json_encode(array('saved' => true)),'status' => 200)); } if ($this->request->data['Attribute']['to_ids'] != 2) { foreach ($attributes as &$attribute) $attribute['Attribute']['to_ids'] = ($this->request->data['Attribute']['to_ids'] == 0 ? false : true); } if ($this->request->data['Attribute']['distribution'] != 4) { foreach ($attributes as &$attribute) $attribute['Attribute']['distribution'] = $this->request->data['Attribute']['distribution']; } if ($this->request->data['Attribute']['comment'] != null) { foreach ($attributes as &$attribute) $attribute['Attribute']['comment'] = $this->request->data['Attribute']['comment']; } $date = new DateTime(); $timestamp = $date->getTimestamp(); foreach ($attributes as &$attribute) $attribute['Attribute']['timestamp'] = $timestamp; if($this->Attribute->saveMany($attributes)) { $this->autoRender = false; return new CakeResponse(array('body'=> json_encode(array('saved' => true)),'status' => 200)); } else { $this->autoRender = false; return new CakeResponse(array('body'=> json_encode(array('saved' => false)),'status' => 200)); } } else { if (!isset($id)) throw new MethodNotAllowedException('No event ID provided.'); $this->layout = 'ajax'; $this->set('id', $id); $this->set('distributionLevels', $this->Attribute->distributionLevels); $this->set('distributionDescriptions', $this->Attribute->distributionDescriptions); $this->set('attrDescriptions', $this->Attribute->fieldDescriptions); $this->render('ajax/attributeEditMassForm'); } } /** * Deletes this specific attribute from all remote servers * TODO move this to a component(?) */ private function __deleteAttributeFromServers($uuid) { // get a list of the servers with push active $this->loadModel('Server'); $servers = $this->Server->find('all', array('conditions' => array('push' => 1))); // iterate over the servers and upload the attribute if (empty($servers)) return; App::uses('SyncTool', 'Tools'); foreach ($servers as &$server) { $syncTool = new SyncTool(); $HttpSocket = $syncTool->setupHttpSocket($server); $this->Attribute->deleteAttributeFromServer($uuid, $server, $HttpSocket); } } public function search() { $fullAddress = '/attributes/search'; if ($this->request->here == $fullAddress) { $this->set('attrDescriptions', $this->Attribute->fieldDescriptions); $this->set('typeDefinitions', $this->Attribute->typeDefinitions); $this->set('categoryDefinitions', $this->Attribute->categoryDefinitions); // reset the paginate_conditions $this->Session->write('paginate_conditions',array()); if ($this->request->is('post') && ($this->request->here == $fullAddress)) { $keyword = $this->request->data['Attribute']['keyword']; $keyword2 = $this->request->data['Attribute']['keyword2']; $tags = $this->request->data['Attribute']['tags']; $org = $this->request->data['Attribute']['org']; $type = $this->request->data['Attribute']['type']; $ioc = $this->request->data['Attribute']['ioc']; $this->set('ioc', $ioc); $category = $this->request->data['Attribute']['category']; $this->set('keywordSearch', $keyword); $this->set('tags', $tags); $keyWordText = null; $keyWordText2 = null; $keyWordText3 = null; $this->set('typeSearch', $type); $this->set('isSearch', 1); $this->set('categorySearch', $category); // search the db $conditions = array(); if ($ioc) { $conditions['AND'][] = array('Attribute.to_ids =' => 1); $conditions['AND'][] = array('Event.published =' => 1); } // search on the value field if (isset($keyword)) { $keywordArray = explode("\n", $keyword); $this->set('keywordArray', $keywordArray); $i = 1; $temp = array(); $temp2 = array(); foreach ($keywordArray as $keywordArrayElement) { $saveWord = trim(strtolower($keywordArrayElement)); if ($saveWord != '') { $toInclude = true; if ($saveWord[0] == '!') { $toInclude = false; $saveWord = substr($saveWord, 1); } if (preg_match('@^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])(\/(\d|[1-2]\d|3[0-2]))$@', $saveWord)) { $cidrresults = $this->Cidr->CIDR($saveWord); foreach ($cidrresults as $result) { $result = strtolower($result); if (strpos($result, '|')) { $resultParts = explode('|', $result); if (!toInclude) { $temp2[] = array( 'AND' => array( 'LOWER(Attribute.value1) NOT LIKE' => $resultParts[0], 'LOWER(Attribute.value2) NOT LIKE' => $resultParts[1], )); } else { $temp[] = array( 'AND' => array( 'LOWER(Attribute.value1)' => $resultParts[0], 'LOWER(Attribute.value2)' => $resultParts[1], )); } } else { if (!$toInclude) { array_push($temp2, array('LOWER(Attribute.value1) NOT LIKE' => $result)); array_push($temp2, array('LOWER(Attribute.value2) NOT LIKE' => $result)); } else { array_push($temp, array('LOWER(Attribute.value1) LIKE' => $result)); array_push($temp, array('LOWER(Attribute.value2) LIKE' => $result)); } } } } else { if (strpos($saveWord, '|')) { $resultParts = explode('|', $saveWord); if (!$toInclude) { $temp2[] = array( 'AND' => array( 'LOWER(Attribute.value1) NOT LIKE' => '%' . $resultParts[0], 'LOWER(Attribute.value2) NOT LIKE' => $resultParts[1] . '%', )); } else { $temp2[] = array( 'AND' => array( 'LOWER(Attribute.value1)' => '%' . $resultParts[0], 'LOWER(Attribute.value2)' => $resultParts[1] . '%', )); } } else { if (!$toInclude) { array_push($temp2, array('LOWER(Attribute.value1) NOT LIKE' => '%' . $saveWord . '%')); array_push($temp2, array('LOWER(Attribute.value2) NOT LIKE' => '%' . $saveWord . '%')); } else { array_push($temp, array('LOWER(Attribute.value1) LIKE' => '%' . $saveWord . '%')); array_push($temp, array('LOWER(Attribute.value2) LIKE' => '%' . $saveWord . '%')); } } } if ($toInclude) { array_push($temp, array('LOWER(Attribute.comment) LIKE' => '%' . $saveWord . '%')); } else { array_push($temp2, array('LOWER(Attribute.comment) NOT LIKE' => '%' . $saveWord . '%')); } } if ($i == 1 && $saveWord != '') $keyWordText = $saveWord; else if (($i > 1 && $i < 10) && $saveWord != '') $keyWordText = $keyWordText . ', ' . $saveWord; else if ($i == 10 && $saveWord != '') $keyWordText = $keyWordText . ' and several other keywords'; $i++; } $this->set('keywordSearch', $keyWordText); if (!empty($temp)) { $conditions['AND']['OR'] = $temp; } if (!empty($temp2)) { $conditions['AND'][] = $temp2; } } // event IDs to be excluded if (isset($keyword2)) { $keywordArray2 = explode("\n", $keyword2); $i = 1; $temp = array(); foreach ($keywordArray2 as $keywordArrayElement) { $saveWord = trim($keywordArrayElement); if (empty($saveWord)) continue; if ($saveWord[0] == '!') { $temp[] = array('Attribute.event_id !=' => substr($saveWord, 1)); } else { $temp['OR'][] = array('Attribute.event_id =' => $saveWord); } if ($i == 1 && $saveWord != '') $keyWordText2 = $saveWord; else if (($i > 1 && $i < 10) && $saveWord != '') $keyWordText2 = $keyWordText2 . ', ' . $saveWord; else if ($i == 10 && $saveWord != '') $keyWordText2 = $keyWordText2 . ' and several other events'; $i++; } $this->set('keywordSearch2', $keyWordText2); if (!empty($temp)) { $conditions['AND'][] = $temp; } } if (!empty($tags)) { $include = array(); $exclude = array(); $keywordArray = explode("\n", $tags); foreach ($keywordArray as $tagname) { $tagname = trim($tagname); if (substr($tagname, 0, 1) === '!') $exclude[] = substr($tagname, 1); else $include[] = $tagname; } $this->loadModel('Tag'); if (!empty($include)) $conditions['AND'][] = array('OR' => array('Attribute.event_id' => $this->Tag->findTags($include))); if (!empty($exclude)) $conditions['AND'][] = array('Attribute.event_id !=' => $this->Tag->findTags($exclude)); } if ($type != 'ALL') { $conditions['Attribute.type ='] = $type; } if ($category != 'ALL') { $conditions['Attribute.category ='] = $category; } // organisation search field $i = 1; $temp = array(); if (isset($org)) { $orgArray = explode("\n", $org); foreach ($orgArray as $orgArrayElement) { $saveWord = trim($orgArrayElement); if (empty($saveWord)) continue; if ($saveWord[0] == '!') { $temp[] = array('Event.orgc NOT LIKE ' => '%' . substr($saveWord, 1) . '%'); } else { $temp['OR'][] = array('Event.orgc LIKE ' => '%' . $saveWord . '%'); } } if ($i == 1 && $saveWord != '') $keyWordText3 = $saveWord; else if (($i > 1 && $i < 10) && $saveWord != '') $keyWordText3 = $keyWordText3 . ', ' . $saveWord; else if ($i == 10 && $saveWord != '') $keyWordText3 = $keyWordText3 . ' and several other organisations'; $i++; $this->set('orgSearch', $keyWordText3); if (!empty($temp)) { $conditions['AND'][] = $temp; } } if ($this->request->data['Attribute']['alternate']) { $events = $this->searchAlternate($conditions); $this->set('events', $events); $this->render('alternate_search_result'); } else { $this->Attribute->recursive = 0; $this->paginate = array( 'limit' => 60, 'maxLimit' => 9999, // LATER we will bump here on a problem once we have more than 9999 attributes? 'conditions' => $conditions, 'contain' => array('Event.orgc', 'Event.id', 'Event.org', 'Event.user_id', 'Event.info') ); if (!$this->_isSiteAdmin()) { // merge in private conditions $this->paginate = Set::merge($this->paginate, array( 'conditions' => array("OR" => array( array('Event.org =' => $this->Auth->user('org')), array("AND" => array('Event.org !=' => $this->Auth->user('org')), array('Event.distribution !=' => 0), array('Attribute.distribution !=' => 0)))), ) ); } $idList = array(); $attributeIdList = array(); $attributes = $this->paginate(); // if we searched for IOCs only, apply the whitelist to the search result! if ($ioc) { $this->loadModel('Whitelist'); $attributes = $this->Whitelist->removeWhitelistedFromArray($attributes, true); } foreach ($attributes as &$attribute) { $attributeIdList[] = $attribute['Attribute']['id']; if (!in_array($attribute['Attribute']['event_id'], $idList)) { $idList[] = $attribute['Attribute']['event_id']; } } $this->set('attributes', $attributes); // and store into session $this->Session->write('paginate_conditions', $this->paginate); $this->Session->write('paginate_conditions_keyword', $keyword); $this->Session->write('paginate_conditions_keyword2', $keyword2); $this->Session->write('paginate_conditions_org', $org); $this->Session->write('paginate_conditions_type', $type); $this->Session->write('paginate_conditions_ioc', $ioc); $this->Session->write('paginate_conditions_tags', $tags); $this->Session->write('paginate_conditions_category', $category); $this->Session->write('search_find_idlist', $idList); $this->Session->write('search_find_attributeidlist', $attributeIdList); // set the same view as the index page $this->render('index'); } } else { // no search keyword is given, show the search form // adding filtering by category and type // combobox for types $types = array('' => array('ALL' => 'ALL'), 'types' => array()); $types['types'] = array_merge($types['types'], $this->_arrayToValuesIndexArray(array_keys($this->Attribute->typeDefinitions))); $this->set('types', $types); // combobox for categories $categories = array('' => array('ALL' => 'ALL', '' => ''), 'categories' => array()); array_pop($this->Attribute->validate['category']['rule'][1]); // remove that last 'empty' item $categories['categories'] = array_merge($categories['categories'], $this->_arrayToValuesIndexArray($this->Attribute->validate['category']['rule'][1])); $this->set('categories', $categories); } } else { $this->set('attrDescriptions', $this->Attribute->fieldDescriptions); $this->set('typeDefinitions', $this->Attribute->typeDefinitions); $this->set('categoryDefinitions', $this->Attribute->categoryDefinitions); // get from Session $keyword = $this->Session->read('paginate_conditions_keyword'); $keyword2 = $this->Session->read('paginate_conditions_keyword2'); $org = $this->Session->read('paginate_conditions_org'); $type = $this->Session->read('paginate_conditions_type'); $category = $this->Session->read('paginate_conditions_category'); $tags = $this->Session->read('paginate_conditions_tags'); $this->set('keywordSearch', $keyword); $this->set('keywordSearch2', $keyword2); $this->set('orgSearch', $org); $this->set('typeSearch', $type); $this->set('tags', $tags); $this->set('isSearch', 1); $this->set('categorySearch', $category); // re-get pagination $this->Attribute->recursive = 0; $this->paginate = $this->Session->read('paginate_conditions'); $this->set('attributes', $this->paginate()); // set the same view as the index page $this->render('index'); } } // If the checkbox for the alternate search is ticked, then this method is called to return the data to be represented // This alternate view will show a list of events with matching search results and the percentage of those matched attributes being marked as to_ids // events are sorted based on relevance (as in the percentage of matches being flagged as indicators for IDS) public function searchAlternate($data) { $data['AND'][] = array( "OR" => array( array('Event.org =' => $this->Auth->user('org')), array("AND" => array('Event.org !=' => $this->Auth->user('org')), array('Event.distribution !=' => 0), array('Attribute.distribution !=' => 0)))); $attributes = $this->Attribute->find('all', array( 'conditions' => $data, 'fields' => array( 'Attribute.id', 'Attribute.event_id', 'Attribute.type', 'Attribute.category', 'Attribute.to_ids', 'Attribute.value', 'Attribute.distribution', 'Event.id', 'Event.org', 'Event.orgc', 'Event.info', 'Event.distribution', 'Event.attribute_count' ))); $events = array(); foreach ($attributes as $attribute) { if (isset($events[$attribute['Event']['id']])) { if ($attribute['Attribute']['to_ids']) { $events[$attribute['Event']['id']]['to_ids']++; } else { $events[$attribute['Event']['id']]['no_ids']++; } } else { $events[$attribute['Event']['id']]['Event'] = $attribute['Event']; $events[$attribute['Event']['id']]['to_ids'] = 0; $events[$attribute['Event']['id']]['no_ids'] = 0; if ($attribute['Attribute']['to_ids']) { $events[$attribute['Event']['id']]['to_ids']++; } else { $events[$attribute['Event']['id']]['no_ids']++; } } } foreach ($events as &$event) { $event['relevance'] = 100 * $event['to_ids'] / ($event['no_ids'] + $event['to_ids']); } if (!empty($events)) $events = $this->__subval_sort($events, 'relevance'); return $events; } // Sort the array of arrays based on a value of a sub-array private function __subval_sort($a,$subkey) { foreach($a as $k=>$v) { $b[$k] = strtolower($v[$subkey]); } arsort($b); foreach($b as $key=>$val) { $c[] = $a[$key]; } return $c; } public function downloadAttributes() { $idList = $this->Session->read('search_find_idlist'); $this->response->type('xml'); // set the content type $this->header('Content-Disposition: download; filename="misp.attribute.search.xml"'); $this->layout = 'xml/default'; $this->loadModel('Attribute'); if (!isset($idList)) { print "No results found to export\n"; } else { foreach ($idList as $listElement) { $put['OR'][] = array('Attribute.id' => $listElement); } $conditions['AND'][] = $put; // restricting to non-private or same org if the user is not a site-admin. if (!$this->_isSiteAdmin()) { $temp = array(); array_push($temp, array('Attribute.distribution >' => 0)); array_push($temp, array('OR' => $distribution)); array_push($temp, array('(SELECT events.org FROM events WHERE events.id = Attribute.event_id) LIKE' => $this->_checkOrg())); $put2['OR'][] = $temp; $conditions['AND'][] = $put2; } $params = array( 'conditions' => $conditions, //array of conditions 'recursive' => 0, //int 'fields' => array('Attribute.id', 'Attribute.value'), //array of field names 'order' => array('Attribute.id'), //string or array defining order ); $attributes = $this->Attribute->find('all', $params); $this->set('results', $attributes); } $this->render('xml'); } public function checkComposites() { if (!self::_isAdmin()) throw new NotFoundException(); $this->set('fails', $this->Attribute->checkComposites()); } // Use the rest interface to search for attributes. Usage: // MISP-base-url/attributes/restSearch/[api-key]/[value]/[type]/[category]/[orgc] // value, type, category, orgc are optional // the last 4 fields accept the following operators: // && - you can use && between two search values to put a logical OR between them. for value, 1.1.1.1&&2.2.2.2 would find attributes with the value being either of the two. // ! - you can negate a search term. For example: google.com&&!mail would search for all attributes with value google.com but not ones that include mail. www.google.com would get returned, mail.google.com wouldn't. public function restSearch($key='download', $value=null, $type=null, $category=null, $org=null, $tags=null) { if ($tags) $tags = str_replace(';', ':', $tags); if ($tags === 'null') $tags = null; if ($value === 'null') $value = null; if ($type === 'null') $type = null; if ($category === 'null') $category = null; if ($org === 'null') $org = null; if ($key!=null && $key!='download') { $user = $this->checkAuthUser($key); } else { if (!$this->Auth->user()) throw new UnauthorizedException('You are not authorized. Please send the Authorization header with your auth key along with an Accept header for application/xml.'); $user = $this->checkAuthUser($this->Auth->user('authkey')); } if (!$user) { throw new UnauthorizedException('This authentication key is not authorized to be used for exports. Contact your administrator.'); } $value = str_replace('|', '/', $value); // request handler for POSTed queries. If the request is a post, the parameters (apart from the key) will be ignored and replaced by the terms defined in the posted json or xml object. // The correct format for both is a "request" root element, as shown by the examples below: // For Json: {"request":{"value": "7.7.7.7&&1.1.1.1","type":"ip-src"}} // For XML: <request><value>7.7.7.7&amp;&amp;1.1.1.1</value><type>ip-src</type></request> // the response type is used to determine the parsing method (xml/json) if ($this->request->is('post')) { if ($this->response->type() === 'application/json') { $data = $this->request->input('json_decode', true); } elseif ($this->response->type() === 'application/xml' && !empty($this->request->data)) { $data = $this->request->data; } else { throw new BadRequestException('Either specify the search terms in the url, or POST a json array / xml (with the root element being "request" and specify the correct accept and content type headers.'); } $paramArray = array('value', 'type', 'category', 'org', 'tags'); foreach ($paramArray as $p) { if (isset($data['request'][$p])) ${$p} = $data['request'][$p]; else ${$p} = null; } } if (!isset($this->request->params['ext']) || $this->request->params['ext'] !== 'json') { $this->response->type('xml'); // set the content type $this->layout = 'xml/default'; $this->header('Content-Disposition: download; filename="misp.search.attribute.results.xml"'); } else { $this->response->type('json'); // set the content type $this->layout = 'json/default'; $this->header('Content-Disposition: download; filename="misp.search.attribute.results.json"'); } $conditions['AND'] = array(); $subcondition = array(); $this->loadModel('Attribute'); // add the values as specified in the 2nd parameter to the conditions $values = explode('&&', $value); $parameters = array('value', 'type', 'category', 'org'); foreach ($parameters as $k => $param) { if (isset(${$parameters[$k]}) && ${$parameters[$k]}!=='null') { $elements = explode('&&', ${$parameters[$k]}); foreach($elements as $v) { if (substr($v, 0, 1) == '!') { if ($parameters[$k] === 'value' && preg_match('@^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])(\/(\d|[1-2]\d|3[0-2]))$@', substr($v, 1))) { $cidrresults = $this->Cidr->CIDR(substr($v, 1)); foreach ($cidrresults as $result) { $subcondition['AND'][] = array('Attribute.value NOT LIKE' => $result); } } else { if ($parameters[$k] === 'org') { $subcondition['AND'][] = array('Event.' . $parameters[$k] . ' NOT LIKE' => '%'.substr($v, 1).'%'); } else { $subcondition['AND'][] = array('Attribute.' . $parameters[$k] . ' NOT LIKE' => '%'.substr($v, 1).'%'); } } } else { if ($parameters[$k] === 'value' && preg_match('@^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])(\/(\d|[1-2]\d|3[0-2]))$@', substr($v, 1))) { $cidrresults = $this->Cidr->CIDR($v); foreach ($cidrresults as $result) { $subcondition['OR'][] = array('Attribute.value LIKE' => $result); } } else { if ($parameters[$k] === 'org') { $subcondition['OR'][] = array('Event.' . $parameters[$k] . ' LIKE' => '%'.$v.'%'); } else { $subcondition['OR'][] = array('Attribute.' . $parameters[$k] . ' LIKE' => '%'.$v.'%'); } } } } array_push ($conditions['AND'], $subcondition); $subcondition = array(); } } // If we are looking for an attribute, we want to retrieve some extra data about the event to be able to check for the permissions. if (!$user['User']['siteAdmin']) { $temp = array(); $temp['AND'] = array('Event.distribution >' => 0, 'Attribute.distribution >' => 0); $subcondition['OR'][] = $temp; $subcondition['OR'][] = array('Event.org' => $user['User']['org']); array_push($conditions['AND'], $subcondition); } // If we sent any tags along, load the associated tag names for each attribute if ($tags) { $args = $this->Attribute->dissectArgs($tags); $this->loadModel('Tag'); $tagArray = $this->Tag->fetchEventTagIds($args[0], $args[1]); $temp = array(); foreach ($tagArray[0] as $accepted) { $temp['OR'][] = array('Event.id' => $accepted); } $conditions['AND'][] = $temp; $temp = array(); foreach ($tagArray[1] as $rejected) { $temp['AND'][] = array('Event.id !=' => $rejected); } $conditions['AND'][] = $temp; } // change the fields here for the attribute export!!!! Don't forget to check for the permissions, since you are not going through fetchevent. Maybe create fetchattribute? $params = array( 'conditions' => $conditions, 'fields' => array('Attribute.*', 'Event.org', 'Event.distribution'), 'contain' => array('Event' => array()) ); $results = $this->Attribute->find('all', $params); $this->loadModel('Whitelist'); $results = $this->Whitelist->removeWhitelistedFromArray($results, true); if (empty($results)) throw new NotFoundException('No matches.'); $this->set('results', $results); } // returns an XML with attributes that belong to an event. The type of attributes to be returned can be restricted by type using the 3rd parameter. // Similar to the restSearch, this parameter can be chained with '&&' and negations are accepted too. For example filename&&!filename|md5 would return all filenames that don't have an md5 // The usage of returnAttributes is the following: [MISP-url]/attributes/returnAttributes/<API-key>/<type>/<signature flag> // The signature flag is off by default, enabling it will only return attribugtes that have the to_ids flag set to true. public function returnAttributes($key='download', $id, $type = null, $sigOnly = false) { $user = $this->checkAuthUser($key); // if the user is authorised to use the api key then user will be populated with the user's account // in addition we also set a flag indicating whether the user is a site admin or not. if ($key!=null && $key!='download') { $user = $this->checkAuthUser($key); } else { if (!$this->Auth->user()) throw new UnauthorizedException('You are not authorized. Please send the Authorization header with your auth key along with an Accept header for application/xml.'); $user = $this->checkAuthUser($this->Auth->user('authkey')); } if (!$user) { throw new UnauthorizedException('This authentication key is not authorized to be used for exports. Contact your administrator.'); } if ($this->request->is('post')) { if ($this->response->type() === 'application/json') { $data = $this->request->input('json_decode', true); } elseif ($this->response->type() === 'application/xml' && !empty($this->request->data)) { $data = $this->request->data; } else { throw new BadRequestException('Either specify the search terms in the url, or POST a json array / xml (with the root element being "request" and specify the correct accept and content type headers.'); } $paramArray = array('type', 'sigOnly'); foreach ($paramArray as $p) { if (isset($data['request'][$p])) ${$p} = $data['request'][$p]; else ${$p} = null; } } $this->loadModel('Event'); $this->Event->read(null, $id); $myEventOrAdmin = false; if ($user['User']['siteAdmin'] || $this->Event->data['Event']['org'] == $user['User']['org']) { $myEventOrAdmin = true; } if (!$myEventOrAdmin) { if ($this->Event->data['Event']['distribution'] == 0) { throw new UnauthorizedException('You don\'t have access to that event.'); } } $this->response->type('xml'); // set the content type $this->layout = 'xml/default'; $this->header('Content-Disposition: download; filename="misp.search.attribute.results.xml"'); // check if user can see the event! $conditions['AND'] = array(); $include = array(); $exclude = array(); $attributes = array(); // If there is a type set, create the include and exclude arrays from it if (isset($type)) { $elements = explode('&&', $type); foreach($elements as $v) { if (substr($v, 0, 1) == '!') { $exclude[] = substr($v, 1); } else { $include[] = $v; } } } // check each attribute foreach($this->Event->data['Attribute'] as $k => $attribute) { $contained = false; // If the include list is empty, then we just then the first check should always set contained to true (basically we chose type = all - exclusions, or simply all) if (empty($include)) { $contained = true; } else { // If we have elements in $include we should check if the attribute's type should be included foreach ($include as $inc) { if (strpos($attribute['type'], $inc) !== false) { $contained = true; } } } // If we have either everything included or the attribute passed the include check, we should check if there is a reason to exclude the attribute // For example, filename may be included, but md5 may be excluded, meaning that filename|md5 should be removed if ($contained) { foreach ($exclude as $exc) { if (strpos($attribute['type'], $exc) !== false) { $contained = false; continue 2; } } } // If we still didn't throw the attribute away, let's check if the user requesting the attributes is of the owning organisation of the event // and if not, whether the distribution of the attribute allows the user to see it if ($contained && !$myEventOrAdmin && $attribute['distribution'] == 0) { $contained = false; } // If we have set the sigOnly parameter and the attribute has to_ids set to false, discard it! if ($contained && $sigOnly === 'true' && !$attribute['to_ids']) { $contained = false; } // If after all of this $contained is still true, let's add the attribute to the array if ($contained) $attributes[] = $attribute; } if (empty($attributes)) throw new NotFoundException('No matches.'); $this->set('results', $attributes); } public function downloadAttachment($key='download', $id) { if ($key!=null && $key!='download') { $user = $this->checkAuthUser($key); } else { if (!$this->Auth->user()) throw new UnauthorizedException('You are not authorized. Please send the Authorization header with your auth key along with an Accept header for application/xml.'); $user = $this->checkAuthUser($this->Auth->user('authkey')); } // if the user is authorised to use the api key then user will be populated with the user's account // in addition we also set a flag indicating whether the user is a site admin or not. if (!$user) { throw new UnauthorizedException('This authentication key is not authorized to be used for exports. Contact your administrator.'); } $this->Attribute->id = $id; if(!$this->Attribute->exists()) { throw new NotFoundException('Invalid attribute or no authorisation to view it.'); } $this->Attribute->read(null, $id); if (!$user['User']['siteAdmin'] && $user['User']['org'] != $this->Attribute->data['Event']['org'] && ($this->Attribute->data['Event']['distribution'] == 0 || $this->Attribute->data['Attribute']['distribution'] == 0 )) { throw new NotFoundException('Invalid attribute or no authorisation to view it.'); } $this->__downloadAttachment($this->Attribute->data['Attribute']); } public function text($key='download', $type='all', $tags=false, $eventId=false, $allowNonIDS=false) { if ($eventId === 'null' || $eventId == '0' || $eventId === 'false') $eventId = false; if ($allowNonIDS === 'null' || $allowNonIDS === '0' || $allowNonIDS === 'false') $allowNonIDS = false; if ($type === 'null' || $type === '0' || $type === 'false') $type = 'all'; if ($tags === 'null' || $tags === '0' || $tags === 'false') $tags = false; if ($key != 'download') { // check if the key is valid -> search for users based on key $user = $this->checkAuthUser($key); if (!$user) { throw new UnauthorizedException('This authentication key is not authorized to be used for exports. Contact your administrator.'); } } else { if (!$this->Auth->user('id')) { throw new UnauthorizedException('You have to be logged in to do that.'); } } $this->response->type('txt'); // set the content type $this->header('Content-Disposition: download; filename="misp.' . $type . '.txt"'); $this->layout = 'text/default'; $attributes = $this->Attribute->text($this->_checkOrg(), $this->_isSiteAdmin(), $type, $tags, $eventId, $allowNonIDS); $this->loadModel('Whitelist'); $attributes = $this->Whitelist->removeWhitelistedFromArray($attributes, true); $this->set('attributes', $attributes); } public function reportValidationIssuesAttributes() { // TODO improve performance of this function by eliminating the additional SQL query per attribute // search for validation problems in the attributes if (!self::_isSiteAdmin()) throw new NotFoundException(); $this->set('result', $this->Attribute->reportValidationIssuesAttributes()); } public function generateCorrelation() { if (!self::_isSiteAdmin()) throw new NotFoundException(); if (!Configure::read('MISP.background_jobs')) { $k = $this->Attribute->generateCorrelation(); $this->Session->setFlash(__('All done. ' . $k . ' attributes processed.')); $this->redirect(array('controller' => 'pages', 'action' => 'display', 'administration')); } else { $job = ClassRegistry::init('Job'); $job->create(); $data = array( 'worker' => 'default', 'job_type' => 'generate correlation', 'job_input' => 'All attributes', 'status' => 0, 'retries' => 0, 'org' => 'ADMIN', 'message' => 'Job created.', ); $job->save($data); $jobId = $job->id; $process_id = CakeResque::enqueue( 'default', 'AdminShell', array('jobGenerateCorrelation', $jobId) ); $job->saveField('process_id', $process_id); $this->Session->setFlash(__('Job queued. You can view the progress if you navigate to the active jobs view (administration -> jobs).')); $this->redirect(array('controller' => 'pages', 'action' => 'display', 'administration')); } } public function fetchViewValue($id, $field = null) { $validFields = array('value', 'comment', 'type', 'category', 'to_ids', 'distribution', 'timestamp'); if (!isset($field) || !in_array($field, $validFields)) throw new MethodNotAllowedException('Invalid field requested.'); //if (!$this->request->is('ajax')) throw new MethodNotAllowedException('This function can only be accessed via AJAX.'); $this->Attribute->id = $id; if (!$this->Attribute->exists()) { throw new NotFoundException(__('Invalid attribute')); } $attribute = $this->Attribute->find('first', array( 'recursive' => -1, 'conditions' => array('Attribute.id' => $id), 'fields' => array('id', 'distribution', 'event_id', $field), 'contain' => array( 'Event' => array( 'fields' => array('distribution', 'id', 'org'), ) ) )); if (!$this->_isSiteAdmin()) { // if (!($attribute['Event']['org'] == $this->Auth->user('org') || ($attribute['Event']['distribution'] > 0 && $attribute['Attribute']['distribution'] > 0))) { throw new NotFoundException(__('Invalid attribute')); } } $result = $attribute['Attribute'][$field]; if ($field == 'distribution') $result=$this->Attribute->distributionLevels[$result]; if ($field == 'to_ids') $result = ($result == 0 ? 'No' : 'Yes'); if ($field == 'timestamp') { if (isset($result)) $result = date('Y-m-d', $result); else echo '&nbsp'; } $this->set('value', $result); $this->layout = 'ajax'; $this->render('ajax/attributeViewFieldForm'); } public function fetchEditForm($id, $field = null) { $validFields = array('value', 'comment', 'type', 'category', 'to_ids', 'distribution'); if (!isset($field) || !in_array($field, $validFields)) throw new MethodNotAllowedException('Invalid field requested.'); if (!$this->request->is('ajax')) throw new MethodNotAllowedException('This function can only be accessed via AJAX.'); $this->Attribute->id = $id; if (!$this->Attribute->exists()) { throw new NotFoundException(__('Invalid attribute')); } $fields = array('id', 'distribution', 'event_id'); $additionalFieldsToLoad = $field; if ($field == 'category' || $field == 'type') { $fields[] = 'type'; $fields[] = 'category'; } else { $fields[] = $field; } $attribute = $this->Attribute->find('first', array( 'recursive' => -1, 'conditions' => array('Attribute.id' => $id), 'fields' => $fields, 'contain' => array( 'Event' => array( 'fields' => array('distribution', 'id', 'user_id', 'orgc'), ) ) )); if (!$this->_isSiteAdmin()) { // if ($attribute['Event']['orgc'] == $this->Auth->user('org') && (($this->userRole['perm_modify'] && $attribute['Event']['user_id'] != $this->Auth->user('id')) || $this->userRole['perm_modify_org'])) { // Allow the edit } else { throw new NotFoundException(__('Invalid attribute')); } } $this->layout = 'ajax'; if ($field == 'distribution') $this->set('distributionLevels', $this->Attribute->distributionLevels); if ($field == 'category') { $typeCategory = array(); foreach ($this->Attribute->categoryDefinitions as $k => $category) { foreach ($category['types'] as $type) { $typeCategory[$type][] = $k; } } $this->set('typeCategory', $typeCategory); } if ($field == 'type') { $this->set('categoryDefinitions', $this->Attribute->categoryDefinitions); } $this->set('object', $attribute['Attribute']); $fieldURL = ucfirst($field); $this->render('ajax/attributeEdit' . $fieldURL . 'Form'); } public function attributeReplace($id) { if (!$this->userRole['perm_add']) { throw new MethodNotAllowedException('Event not found or you don\'t have permissions to create attributes'); } $event = $this->Attribute->Event->find('first', array( 'conditions' => array('Event.id' => $id), 'fields' => array('id', 'orgc', 'distribution'), 'recursive' => -1 )); if (empty($event) || (!$this->_isSiteAdmin() && ($event['Event']['orgc'] != $this->Auth->user('org') || !$this->userRole['perm_add']))) throw new MethodNotAllowedException('Event not found or you don\'t have permissions to create attributes'); $this->set('event_id', $id); if ($this->request->is('get')) { $this->layout = 'ajax'; $this->request->data['Attribute']['event_id'] = $id; // combobox for types $types = array_keys($this->Attribute->typeDefinitions); $types = $this->_arrayToValuesIndexArray($types); $this->set('types', $types); // combobos for categories $categories = $this->Attribute->validate['category']['rule'][1]; array_pop($categories); $categories = $this->_arrayToValuesIndexArray($categories); $this->set('categories', compact('categories')); $this->set('attrDescriptions', $this->Attribute->fieldDescriptions); $this->set('typeDefinitions', $this->Attribute->typeDefinitions); $this->set('categoryDefinitions', $this->Attribute->categoryDefinitions); } if ($this->request->is('post')) { if (!$this->request->is('ajax')) throw new MethodNotAllowedException('This action can only be accessed via AJAX.'); $newValues = explode(PHP_EOL, $this->request->data['Attribute']['value']); $category = $this->request->data['Attribute']['category']; $type = $this->request->data['Attribute']['type']; $to_ids = $this->request->data['Attribute']['to_ids']; if (!$this->_isSiteAdmin() && $this->Auth->user('org') != $event['Event']['orgc'] && !$this->userRole['perm_add']) throw new MethodNotAllowedException('You are not authorised to do that.'); $oldAttributes = $this->Attribute->find('all', array( 'conditions' => array( 'event_id' => $id, 'category' => $category, 'type' => $type, ), 'fields' => array('id', 'event_id', 'category', 'type', 'value'), 'recursive' => -1, )); $results = array('untouched' => count($oldAttributes), 'created' => 0, 'deleted' => 0, 'createdFail' => 0, 'deletedFail' => 0); foreach ($newValues as &$value) { $value = trim($value); $found = false; foreach ($oldAttributes as &$old) { if ($value == $old['Attribute']['value']) { $found = true; } } if (!$found) { $attribute = array( 'value' => $value, 'event_id' => $id, 'category' => $category, 'type' => $type, 'distribution' => $event['Event']['distribution'], 'to_ids' => $to_ids, ); $this->Attribute->create(); if ($this->Attribute->save(array('Attribute' => $attribute))) { $results['created']++; } else { $results['createdFail']++; } } } foreach ($oldAttributes as &$old) { if (!in_array($old['Attribute']['value'], $newValues)) { if ($this->Attribute->delete($old['Attribute']['id'])) { $results['deleted']++; $results['untouched']--; } else { $results['deletedFail']++; } } } $message = ''; $success = true; if (($results['created'] > 0 || $results['deleted'] > 0) && $results['createdFail'] == 0 && $results['deletedFail'] == 0) { $message .= 'Update completed without any issues.'; $event = $this->Attribute->Event->find('first', array( 'conditions' => array('Event.id' => $id), 'recursive' => -1 )); $event['Event']['published'] = 0; $date = new DateTime(); $event['Event']['timestamp'] = $date->getTimestamp(); $this->Attribute->Event->save($event); } else { $message .= 'Update completed with some errors.'; $success = false; } if ($results['created']) $message .= $results['created'] . ' attribute' . $this->__checkCountForOne($results['created']) . ' created. '; if ($results['createdFail']) $message .= $results['createdFail'] . ' attribute' . $this->__checkCountForOne($results['createdFail']) . ' could not be created. '; if ($results['deleted']) $message .= $results['deleted'] . ' attribute' . $this->__checkCountForOne($results['deleted']) . ' deleted.'; if ($results['deletedFail']) $message .= $results['deletedFail'] . ' attribute' . $this->__checkCountForOne($results['deletedFail']) . ' could not be deleted. '; $message .= $results['untouched'] . ' attributes left untouched. '; $this->autoRender = false; $this->layout = 'ajax'; if ($success) return new CakeResponse(array('body'=> json_encode(array('saved' => true, 'success' => $message)),'status'=>200)); else return new CakeResponse(array('body'=> json_encode(array('saved' => true, 'errors' => $message)),'status'=>200)); } } private function __checkCountForOne($number) { if ($number != 1) return 's'; return ''; } }
0x0mar/MISP
app/Controller/AttributesController.php
PHP
agpl-3.0
85,681
-- | This module provides the data type and parser for a trait file module Trait ( Trait(..) , defaultTrait , trait ) where import Maker import Modifier import Scoped(Label) data Trait = Trait { trait_name :: Label , agnatic :: Bool , birth :: Double -- ^ Chance of being assigned on birth. Default 0 , cached :: Bool , cannot_inherit :: Bool , cannot_marry :: Bool , caste_tier :: Maybe Int -- ^ The trait is a caste trait, and this -- defines the order of the castes. , customizer :: Bool -- ^ Blocks the trait from being available in the Designer , education :: Bool , immortal :: Bool , in_hiding :: Bool , inbred :: Bool , incapacitating :: Bool , inherit_chance :: Double , is_epidemic :: Bool , is_health :: Bool , is_illness :: Bool , leader :: Bool , leadership_traits :: Maybe Int , lifestyle :: Bool , opposites :: [Label] , personality :: Bool , prevent_decadence :: Bool , priest :: Bool , pilgrimage :: Bool , random :: Bool , rebel_inherited :: Bool -- ^ Unknown purpose , religious :: Bool , religious_branch :: Maybe Label , ruler_designer_cost :: Maybe Int -- ^ The postive cost in the Ruler Designer , tolerates :: [Label] -- ^ A list of the religion groups tolerated by this character , modifiers :: [Modifier] } deriving (Eq, Ord, Show) trait :: Maker Trait trait = Trait <$> label key <*> boolProp "agnatic" <*> ((number ~@ "birth") `defaultingTo` 0) <*> boolProp "cached" <*> boolProp "cannot_inherit" <*> boolProp "cannot_marry" <*> intProp "caste_tier" <*> boolProp "customizer" <*> boolProp "education" <*> boolProp "immortal" <*> boolProp "in_hiding" <*> boolProp "inbred" <*> boolProp "incapacitating" <*> (number ~@ "inherit_chance") `defaultingTo` 0 <*> boolProp "is_epidemic" <*> boolProp "is_health" <*> boolProp "is_illness" <*> boolProp "leader" <*> intProp "leadership_traits" <*> boolProp "lifestyle" <*> (opposites @@ "opposites") `defaultingTo` [] <*> boolProp "personality" <*> boolProp "prevent_decadence" <*> boolProp "priest" <*> boolProp "pilgrimage" <*> boolProp "random" <*> boolProp "rebel_inherited" <*> boolProp "religious" <*> fetchString @? "religious_branch" <*> intProp "ruler_designer_cost" <*> tolerations <*> tryMap modifier where boolProp key = ((fetchBool @@ key) `defaultingTo` False) <?> key intProp :: Label → Maker (Maybe Int) intProp key = fmap round <$> number ~? key <?> key opposites = error "opposite traits are not implemented" tolerations = return [] defaultTrait :: Trait defaultTrait = Trait { trait_name = undefined, agnatic = False, birth = 0, cached = False , cannot_inherit = False, cannot_marry = False, caste_tier = Nothing , customizer = False, education = False, immortal = False , in_hiding = False, inbred = False, incapacitating = False , inherit_chance = 0, is_epidemic = False, is_health = False , is_illness = False, leader = False, leadership_traits = Nothing , lifestyle = False, opposites = [], personality = False , prevent_decadence = False, priest = False, pilgrimage = False , random = False, rebel_inherited = False, religious = False , religious_branch = Nothing, ruler_designer_cost = Nothing , tolerates = [], modifiers = [] }
joelwilliamson/validator
Trait.hs
Haskell
agpl-3.0
3,593
// Protocol Buffers for Go with Gadgets // // Copyright (c) 2013, The GoGo Authors. All rights reserved. // http://github.com/gogo/protobuf // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package generator import ( "bytes" "go/parser" "go/printer" "go/token" "path" "strings" "gx/ipfs/QmdxUuburamoF6zF9qjeQC4WYcWGbWuRmdLacMEsW8ioD8/gogo-protobuf/gogoproto" "gx/ipfs/QmdxUuburamoF6zF9qjeQC4WYcWGbWuRmdLacMEsW8ioD8/gogo-protobuf/proto" descriptor "gx/ipfs/QmdxUuburamoF6zF9qjeQC4WYcWGbWuRmdLacMEsW8ioD8/gogo-protobuf/protoc-gen-gogo/descriptor" plugin "gx/ipfs/QmdxUuburamoF6zF9qjeQC4WYcWGbWuRmdLacMEsW8ioD8/gogo-protobuf/protoc-gen-gogo/plugin" ) func (d *FileDescriptor) Messages() []*Descriptor { return d.desc } func (d *FileDescriptor) Enums() []*EnumDescriptor { return d.enum } func (d *Descriptor) IsGroup() bool { return d.group } func (g *Generator) IsGroup(field *descriptor.FieldDescriptorProto) bool { if d, ok := g.typeNameToObject[field.GetTypeName()].(*Descriptor); ok { return d.IsGroup() } return false } func (g *Generator) TypeNameByObject(typeName string) Object { o, ok := g.typeNameToObject[typeName] if !ok { g.Fail("can't find object with type", typeName) } return o } func (g *Generator) OneOfTypeName(message *Descriptor, field *descriptor.FieldDescriptorProto) string { typeName := message.TypeName() ccTypeName := CamelCaseSlice(typeName) fieldName := g.GetOneOfFieldName(message, field) tname := ccTypeName + "_" + fieldName // It is possible for this to collide with a message or enum // nested in this message. Check for collisions. ok := true for _, desc := range message.nested { if strings.Join(desc.TypeName(), "_") == tname { ok = false break } } for _, enum := range message.enums { if strings.Join(enum.TypeName(), "_") == tname { ok = false break } } if !ok { tname += "_" } return tname } type PluginImports interface { NewImport(pkg string) Single GenerateImports(file *FileDescriptor) } type pluginImports struct { generator *Generator singles []Single } func NewPluginImports(generator *Generator) *pluginImports { return &pluginImports{generator, make([]Single, 0)} } func (this *pluginImports) NewImport(pkg string) Single { imp := newImportedPackage(this.generator.ImportPrefix, pkg) this.singles = append(this.singles, imp) return imp } func (this *pluginImports) GenerateImports(file *FileDescriptor) { for _, s := range this.singles { if s.IsUsed() { this.generator.PrintImport(GoPackageName(s.Name()), GoImportPath(s.Location())) } } } type Single interface { Use() string IsUsed() bool Name() string Location() string } type importedPackage struct { used bool pkg string name string importPrefix string } func newImportedPackage(importPrefix string, pkg string) *importedPackage { return &importedPackage{ pkg: pkg, importPrefix: importPrefix, } } func (this *importedPackage) Use() string { if !this.used { this.name = string(cleanPackageName(this.pkg)) this.used = true } return this.name } func (this *importedPackage) IsUsed() bool { return this.used } func (this *importedPackage) Name() string { return this.name } func (this *importedPackage) Location() string { return this.importPrefix + this.pkg } func (g *Generator) GetFieldName(message *Descriptor, field *descriptor.FieldDescriptorProto) string { goTyp, _ := g.GoType(message, field) fieldname := CamelCase(*field.Name) if gogoproto.IsCustomName(field) { fieldname = gogoproto.GetCustomName(field) } if gogoproto.IsEmbed(field) { fieldname = EmbedFieldName(goTyp) } if field.OneofIndex != nil { fieldname = message.OneofDecl[int(*field.OneofIndex)].GetName() fieldname = CamelCase(fieldname) } for _, f := range methodNames { if f == fieldname { return fieldname + "_" } } if !gogoproto.IsProtoSizer(message.file.FileDescriptorProto, message.DescriptorProto) { if fieldname == "Size" { return fieldname + "_" } } return fieldname } func (g *Generator) GetOneOfFieldName(message *Descriptor, field *descriptor.FieldDescriptorProto) string { goTyp, _ := g.GoType(message, field) fieldname := CamelCase(*field.Name) if gogoproto.IsCustomName(field) { fieldname = gogoproto.GetCustomName(field) } if gogoproto.IsEmbed(field) { fieldname = EmbedFieldName(goTyp) } for _, f := range methodNames { if f == fieldname { return fieldname + "_" } } if !gogoproto.IsProtoSizer(message.file.FileDescriptorProto, message.DescriptorProto) { if fieldname == "Size" { return fieldname + "_" } } return fieldname } func (g *Generator) IsMap(field *descriptor.FieldDescriptorProto) bool { if !field.IsMessage() { return false } byName := g.ObjectNamed(field.GetTypeName()) desc, ok := byName.(*Descriptor) if byName == nil || !ok || !desc.GetOptions().GetMapEntry() { return false } return true } func (g *Generator) GetMapKeyField(field, keyField *descriptor.FieldDescriptorProto) *descriptor.FieldDescriptorProto { if !gogoproto.IsCastKey(field) { return keyField } keyField = proto.Clone(keyField).(*descriptor.FieldDescriptorProto) if keyField.Options == nil { keyField.Options = &descriptor.FieldOptions{} } keyType := gogoproto.GetCastKey(field) if err := proto.SetExtension(keyField.Options, gogoproto.E_Casttype, &keyType); err != nil { g.Fail(err.Error()) } return keyField } func (g *Generator) GetMapValueField(field, valField *descriptor.FieldDescriptorProto) *descriptor.FieldDescriptorProto { if gogoproto.IsCustomType(field) && gogoproto.IsCastValue(field) { g.Fail("cannot have a customtype and casttype: ", field.String()) } valField = proto.Clone(valField).(*descriptor.FieldDescriptorProto) if valField.Options == nil { valField.Options = &descriptor.FieldOptions{} } stdtime := gogoproto.IsStdTime(field) if stdtime { if err := proto.SetExtension(valField.Options, gogoproto.E_Stdtime, &stdtime); err != nil { g.Fail(err.Error()) } } stddur := gogoproto.IsStdDuration(field) if stddur { if err := proto.SetExtension(valField.Options, gogoproto.E_Stdduration, &stddur); err != nil { g.Fail(err.Error()) } } if valType := gogoproto.GetCastValue(field); len(valType) > 0 { if err := proto.SetExtension(valField.Options, gogoproto.E_Casttype, &valType); err != nil { g.Fail(err.Error()) } } if valType := gogoproto.GetCustomType(field); len(valType) > 0 { if err := proto.SetExtension(valField.Options, gogoproto.E_Customtype, &valType); err != nil { g.Fail(err.Error()) } } nullable := gogoproto.IsNullable(field) if err := proto.SetExtension(valField.Options, gogoproto.E_Nullable, &nullable); err != nil { g.Fail(err.Error()) } return valField } // GoMapValueTypes returns the map value Go type and the alias map value Go type (for casting), taking into // account whether the map is nullable or the value is a message. func GoMapValueTypes(mapField, valueField *descriptor.FieldDescriptorProto, goValueType, goValueAliasType string) (nullable bool, outGoType string, outGoAliasType string) { nullable = gogoproto.IsNullable(mapField) && (valueField.IsMessage() || gogoproto.IsCustomType(mapField)) if nullable { // ensure the non-aliased Go value type is a pointer for consistency if strings.HasPrefix(goValueType, "*") { outGoType = goValueType } else { outGoType = "*" + goValueType } outGoAliasType = goValueAliasType } else { outGoType = strings.Replace(goValueType, "*", "", 1) outGoAliasType = strings.Replace(goValueAliasType, "*", "", 1) } return } func GoTypeToName(goTyp string) string { return strings.Replace(strings.Replace(goTyp, "*", "", -1), "[]", "", -1) } func EmbedFieldName(goTyp string) string { goTyp = GoTypeToName(goTyp) goTyps := strings.Split(goTyp, ".") if len(goTyps) == 1 { return goTyp } if len(goTyps) == 2 { return goTyps[1] } panic("unreachable") } func (g *Generator) GeneratePlugin(p Plugin) { plugins = []Plugin{p} p.Init(g) // Generate the output. The generator runs for every file, even the files // that we don't generate output for, so that we can collate the full list // of exported symbols to support public imports. genFileMap := make(map[*FileDescriptor]bool, len(g.genFiles)) for _, file := range g.genFiles { genFileMap[file] = true } for _, file := range g.allFiles { g.Reset() g.writeOutput = genFileMap[file] g.generatePlugin(file, p) if !g.writeOutput { continue } g.Response.File = append(g.Response.File, &plugin.CodeGeneratorResponse_File{ Name: proto.String(file.goFileName(g.pathType)), Content: proto.String(g.String()), }) } } func (g *Generator) generatePlugin(file *FileDescriptor, p Plugin) { g.writtenImports = make(map[string]bool) g.file = file // Run the plugins before the imports so we know which imports are necessary. p.Generate(file) // Generate header and imports last, though they appear first in the output. rem := g.Buffer g.Buffer = new(bytes.Buffer) g.generateHeader() p.GenerateImports(g.file) g.generateImports() if !g.writeOutput { return } g.Write(rem.Bytes()) // Reformat generated code. contents := string(g.Buffer.Bytes()) fset := token.NewFileSet() ast, err := parser.ParseFile(fset, "", g, parser.ParseComments) if err != nil { g.Fail("bad Go source code was generated:", contents, err.Error()) return } g.Reset() err = (&printer.Config{Mode: printer.TabIndent | printer.UseSpaces, Tabwidth: 8}).Fprint(g, fset, ast) if err != nil { g.Fail("generated Go source code could not be reformatted:", err.Error()) } } func GetCustomType(field *descriptor.FieldDescriptorProto) (packageName string, typ string, err error) { return getCustomType(field) } func getCustomType(field *descriptor.FieldDescriptorProto) (packageName string, typ string, err error) { if field.Options != nil { var v interface{} v, err = proto.GetExtension(field.Options, gogoproto.E_Customtype) if err == nil && v.(*string) != nil { ctype := *(v.(*string)) packageName, typ = splitCPackageType(ctype) return packageName, typ, nil } } return "", "", err } func splitCPackageType(ctype string) (packageName string, typ string) { ss := strings.Split(ctype, ".") if len(ss) == 1 { return "", ctype } packageName = strings.Join(ss[0:len(ss)-1], ".") typeName := ss[len(ss)-1] importStr := strings.Map(badToUnderscore, packageName) typ = importStr + "." + typeName return packageName, typ } func getCastType(field *descriptor.FieldDescriptorProto) (packageName string, typ string, err error) { if field.Options != nil { var v interface{} v, err = proto.GetExtension(field.Options, gogoproto.E_Casttype) if err == nil && v.(*string) != nil { ctype := *(v.(*string)) packageName, typ = splitCPackageType(ctype) return packageName, typ, nil } } return "", "", err } func FileName(file *FileDescriptor) string { fname := path.Base(file.FileDescriptorProto.GetName()) fname = strings.Replace(fname, ".proto", "", -1) fname = strings.Replace(fname, "-", "_", -1) fname = strings.Replace(fname, ".", "_", -1) return CamelCase(fname) } func (g *Generator) AllFiles() *descriptor.FileDescriptorSet { set := &descriptor.FileDescriptorSet{} set.File = make([]*descriptor.FileDescriptorProto, len(g.allFiles)) for i := range g.allFiles { set.File[i] = g.allFiles[i].FileDescriptorProto } return set } func (d *Descriptor) Path() string { return d.path } func (g *Generator) useTypes() string { pkg := strings.Map(badToUnderscore, "github.com/gogo/protobuf/types") g.customImports = append(g.customImports, "github.com/gogo/protobuf/types") return pkg } func (d *FileDescriptor) GoPackageName() string { return string(d.packageName) }
disorganizer/brig
vendor/gx/ipfs/QmdxUuburamoF6zF9qjeQC4WYcWGbWuRmdLacMEsW8ioD8/gogo-protobuf/protoc-gen-gogo/generator/helper.go
GO
agpl-3.0
13,043
// Copyright (c) 2016 Mattermost, Inc. All Rights Reserved. // See License.txt for license information. package api import ( "bufio" "io" "io/ioutil" "net/http" "os" "strconv" "strings" "time" l4g "github.com/alecthomas/log4go" "github.com/gorilla/mux" "github.com/mattermost/platform/einterfaces" "github.com/mattermost/platform/model" "github.com/mattermost/platform/store" "github.com/mattermost/platform/utils" "github.com/mssola/user_agent" ) func InitAdmin() { l4g.Debug(utils.T("api.admin.init.debug")) BaseRoutes.Admin.Handle("/logs", ApiUserRequired(getLogs)).Methods("GET") BaseRoutes.Admin.Handle("/audits", ApiUserRequired(getAllAudits)).Methods("GET") BaseRoutes.Admin.Handle("/config", ApiUserRequired(getConfig)).Methods("GET") BaseRoutes.Admin.Handle("/save_config", ApiUserRequired(saveConfig)).Methods("POST") BaseRoutes.Admin.Handle("/reload_config", ApiUserRequired(reloadConfig)).Methods("GET") BaseRoutes.Admin.Handle("/test_email", ApiUserRequired(testEmail)).Methods("POST") BaseRoutes.Admin.Handle("/recycle_db_conn", ApiUserRequired(recycleDatabaseConnection)).Methods("GET") BaseRoutes.Admin.Handle("/analytics/{id:[A-Za-z0-9]+}/{name:[A-Za-z0-9_]+}", ApiUserRequired(getAnalytics)).Methods("GET") BaseRoutes.Admin.Handle("/analytics/{name:[A-Za-z0-9_]+}", ApiUserRequired(getAnalytics)).Methods("GET") BaseRoutes.Admin.Handle("/save_compliance_report", ApiUserRequired(saveComplianceReport)).Methods("POST") BaseRoutes.Admin.Handle("/compliance_reports", ApiUserRequired(getComplianceReports)).Methods("GET") BaseRoutes.Admin.Handle("/download_compliance_report/{id:[A-Za-z0-9]+}", ApiUserRequiredTrustRequester(downloadComplianceReport)).Methods("GET") BaseRoutes.Admin.Handle("/upload_brand_image", ApiAdminSystemRequired(uploadBrandImage)).Methods("POST") BaseRoutes.Admin.Handle("/get_brand_image", ApiAppHandlerTrustRequester(getBrandImage)).Methods("GET") BaseRoutes.Admin.Handle("/reset_mfa", ApiAdminSystemRequired(adminResetMfa)).Methods("POST") BaseRoutes.Admin.Handle("/reset_password", ApiAdminSystemRequired(adminResetPassword)).Methods("POST") BaseRoutes.Admin.Handle("/ldap_sync_now", ApiAdminSystemRequired(ldapSyncNow)).Methods("POST") BaseRoutes.Admin.Handle("/saml_metadata", ApiAppHandler(samlMetadata)).Methods("GET") BaseRoutes.Admin.Handle("/add_certificate", ApiAdminSystemRequired(addCertificate)).Methods("POST") BaseRoutes.Admin.Handle("/remove_certificate", ApiAdminSystemRequired(removeCertificate)).Methods("POST") BaseRoutes.Admin.Handle("/saml_cert_status", ApiAdminSystemRequired(samlCertificateStatus)).Methods("GET") BaseRoutes.Admin.Handle("/cluster_status", ApiAdminSystemRequired(getClusterStatus)).Methods("GET") } func getLogs(c *Context, w http.ResponseWriter, r *http.Request) { if !c.HasSystemAdminPermissions("getLogs") { return } lines, err := GetLogs() if err != nil { c.Err = err return } if einterfaces.GetClusterInterface() != nil { clines, err := einterfaces.GetClusterInterface().GetLogs() if err != nil { c.Err = err return } lines = append(lines, clines...) } w.Write([]byte(model.ArrayToJson(lines))) } func GetLogs() ([]string, *model.AppError) { var lines []string if utils.Cfg.LogSettings.EnableFile { file, err := os.Open(utils.GetLogFileLocation(utils.Cfg.LogSettings.FileLocation)) if err != nil { return nil, model.NewLocAppError("getLogs", "api.admin.file_read_error", nil, err.Error()) } defer file.Close() scanner := bufio.NewScanner(file) for scanner.Scan() { lines = append(lines, scanner.Text()) } } else { lines = append(lines, "") } return lines, nil } func getClusterStatus(c *Context, w http.ResponseWriter, r *http.Request) { if !c.HasSystemAdminPermissions("getClusterStatus") { return } infos := make([]*model.ClusterInfo, 0) if einterfaces.GetClusterInterface() != nil { infos = einterfaces.GetClusterInterface().GetClusterInfos() } w.Write([]byte(model.ClusterInfosToJson(infos))) } func getAllAudits(c *Context, w http.ResponseWriter, r *http.Request) { if !c.HasSystemAdminPermissions("getAllAudits") { return } if result := <-Srv.Store.Audit().Get("", 200); result.Err != nil { c.Err = result.Err return } else { audits := result.Data.(model.Audits) etag := audits.Etag() if HandleEtag(etag, w, r) { return } if len(etag) > 0 { w.Header().Set(model.HEADER_ETAG_SERVER, etag) } w.Write([]byte(audits.ToJson())) return } } func getConfig(c *Context, w http.ResponseWriter, r *http.Request) { if !c.HasSystemAdminPermissions("getConfig") { return } json := utils.Cfg.ToJson() cfg := model.ConfigFromJson(strings.NewReader(json)) cfg.Sanitize() w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate") w.Write([]byte(cfg.ToJson())) } func reloadConfig(c *Context, w http.ResponseWriter, r *http.Request) { if !c.HasSystemAdminPermissions("reloadConfig") { return } utils.LoadConfig(utils.CfgFileName) // start/restart email batching job if necessary InitEmailBatching() w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate") ReturnStatusOK(w) } func saveConfig(c *Context, w http.ResponseWriter, r *http.Request) { if !c.HasSystemAdminPermissions("getConfig") { return } cfg := model.ConfigFromJson(r.Body) if cfg == nil { c.SetInvalidParam("saveConfig", "config") return } cfg.SetDefaults() utils.Desanitize(cfg) if err := cfg.IsValid(); err != nil { c.Err = err return } if err := utils.ValidateLdapFilter(cfg); err != nil { c.Err = err return } if *utils.Cfg.ClusterSettings.Enable { c.Err = model.NewLocAppError("saveConfig", "ent.cluster.save_config.error", nil, "") return } c.LogAudit("") //oldCfg := utils.Cfg utils.SaveConfig(utils.CfgFileName, cfg) utils.LoadConfig(utils.CfgFileName) // Future feature is to sync the configuration files // if einterfaces.GetClusterInterface() != nil { // err := einterfaces.GetClusterInterface().ConfigChanged(cfg, oldCfg, true) // if err != nil { // c.Err = err // return // } // } // start/restart email batching job if necessary InitEmailBatching() rdata := map[string]string{} rdata["status"] = "OK" w.Write([]byte(model.MapToJson(rdata))) } func recycleDatabaseConnection(c *Context, w http.ResponseWriter, r *http.Request) { if !c.HasSystemAdminPermissions("recycleDatabaseConnection") { return } oldStore := Srv.Store l4g.Warn(utils.T("api.admin.recycle_db_start.warn")) Srv.Store = store.NewSqlStore() time.Sleep(20 * time.Second) oldStore.Close() l4g.Warn(utils.T("api.admin.recycle_db_end.warn")) w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate") ReturnStatusOK(w) } func testEmail(c *Context, w http.ResponseWriter, r *http.Request) { if !c.HasSystemAdminPermissions("testEmail") { return } cfg := model.ConfigFromJson(r.Body) if cfg == nil { c.SetInvalidParam("testEmail", "config") return } if len(cfg.EmailSettings.SMTPServer) == 0 { c.Err = model.NewLocAppError("testEmail", "api.admin.test_email.missing_server", nil, utils.T("api.context.invalid_param.app_error", map[string]interface{}{"Name": "SMTPServer"})) return } // if the user hasn't changed their email settings, fill in the actual SMTP password so that // the user can verify an existing SMTP connection if cfg.EmailSettings.SMTPPassword == model.FAKE_SETTING { if cfg.EmailSettings.SMTPServer == utils.Cfg.EmailSettings.SMTPServer && cfg.EmailSettings.SMTPPort == utils.Cfg.EmailSettings.SMTPPort && cfg.EmailSettings.SMTPUsername == utils.Cfg.EmailSettings.SMTPUsername { cfg.EmailSettings.SMTPPassword = utils.Cfg.EmailSettings.SMTPPassword } else { c.Err = model.NewLocAppError("testEmail", "api.admin.test_email.reenter_password", nil, "") return } } if result := <-Srv.Store.User().Get(c.Session.UserId); result.Err != nil { c.Err = result.Err return } else { if err := utils.SendMailUsingConfig(result.Data.(*model.User).Email, c.T("api.admin.test_email.subject"), c.T("api.admin.test_email.body"), cfg); err != nil { c.Err = err return } } m := make(map[string]string) m["SUCCESS"] = "true" w.Write([]byte(model.MapToJson(m))) } func getComplianceReports(c *Context, w http.ResponseWriter, r *http.Request) { if !c.HasSystemAdminPermissions("getComplianceReports") { return } if !*utils.Cfg.ComplianceSettings.Enable || !utils.IsLicensed || !*utils.License.Features.Compliance { c.Err = model.NewLocAppError("getComplianceReports", "ent.compliance.licence_disable.app_error", nil, "") return } if result := <-Srv.Store.Compliance().GetAll(); result.Err != nil { c.Err = result.Err return } else { crs := result.Data.(model.Compliances) w.Write([]byte(crs.ToJson())) } } func saveComplianceReport(c *Context, w http.ResponseWriter, r *http.Request) { if !c.HasSystemAdminPermissions("getComplianceReports") { return } if !*utils.Cfg.ComplianceSettings.Enable || !utils.IsLicensed || !*utils.License.Features.Compliance || einterfaces.GetComplianceInterface() == nil { c.Err = model.NewLocAppError("saveComplianceReport", "ent.compliance.licence_disable.app_error", nil, "") return } job := model.ComplianceFromJson(r.Body) if job == nil { c.SetInvalidParam("saveComplianceReport", "compliance") return } job.UserId = c.Session.UserId job.Type = model.COMPLIANCE_TYPE_ADHOC if result := <-Srv.Store.Compliance().Save(job); result.Err != nil { c.Err = result.Err return } else { job = result.Data.(*model.Compliance) go einterfaces.GetComplianceInterface().RunComplianceJob(job) } w.Write([]byte(job.ToJson())) } func downloadComplianceReport(c *Context, w http.ResponseWriter, r *http.Request) { if !c.HasSystemAdminPermissions("downloadComplianceReport") { return } if !*utils.Cfg.ComplianceSettings.Enable || !utils.IsLicensed || !*utils.License.Features.Compliance || einterfaces.GetComplianceInterface() == nil { c.Err = model.NewLocAppError("downloadComplianceReport", "ent.compliance.licence_disable.app_error", nil, "") return } params := mux.Vars(r) id := params["id"] if len(id) != 26 { c.SetInvalidParam("downloadComplianceReport", "id") return } if result := <-Srv.Store.Compliance().Get(id); result.Err != nil { c.Err = result.Err return } else { job := result.Data.(*model.Compliance) c.LogAudit("downloaded " + job.Desc) if f, err := ioutil.ReadFile(*utils.Cfg.ComplianceSettings.Directory + "compliance/" + job.JobName() + ".zip"); err != nil { c.Err = model.NewLocAppError("readFile", "api.file.read_file.reading_local.app_error", nil, err.Error()) return } else { w.Header().Set("Cache-Control", "max-age=2592000, public") w.Header().Set("Content-Length", strconv.Itoa(len(f))) w.Header().Del("Content-Type") // Content-Type will be set automatically by the http writer // attach extra headers to trigger a download on IE, Edge, and Safari ua := user_agent.New(r.UserAgent()) bname, _ := ua.Browser() w.Header().Set("Content-Disposition", "attachment;filename=\""+job.JobName()+".zip\"") if bname == "Edge" || bname == "Internet Explorer" || bname == "Safari" { // trim off anything before the final / so we just get the file's name w.Header().Set("Content-Type", "application/octet-stream") } w.Write(f) } } } func getAnalytics(c *Context, w http.ResponseWriter, r *http.Request) { if !c.HasSystemAdminPermissions("getAnalytics") { return } params := mux.Vars(r) teamId := params["id"] name := params["name"] if name == "standard" { var rows model.AnalyticsRows = make([]*model.AnalyticsRow, 5) rows[0] = &model.AnalyticsRow{"channel_open_count", 0} rows[1] = &model.AnalyticsRow{"channel_private_count", 0} rows[2] = &model.AnalyticsRow{"post_count", 0} rows[3] = &model.AnalyticsRow{"unique_user_count", 0} rows[4] = &model.AnalyticsRow{"team_count", 0} openChan := Srv.Store.Channel().AnalyticsTypeCount(teamId, model.CHANNEL_OPEN) privateChan := Srv.Store.Channel().AnalyticsTypeCount(teamId, model.CHANNEL_PRIVATE) postChan := Srv.Store.Post().AnalyticsPostCount(teamId, false, false) userChan := Srv.Store.User().AnalyticsUniqueUserCount(teamId) teamChan := Srv.Store.Team().AnalyticsTeamCount() if r := <-openChan; r.Err != nil { c.Err = r.Err return } else { rows[0].Value = float64(r.Data.(int64)) } if r := <-privateChan; r.Err != nil { c.Err = r.Err return } else { rows[1].Value = float64(r.Data.(int64)) } if r := <-postChan; r.Err != nil { c.Err = r.Err return } else { rows[2].Value = float64(r.Data.(int64)) } if r := <-userChan; r.Err != nil { c.Err = r.Err return } else { rows[3].Value = float64(r.Data.(int64)) } if r := <-teamChan; r.Err != nil { c.Err = r.Err return } else { rows[4].Value = float64(r.Data.(int64)) } w.Write([]byte(rows.ToJson())) } else if name == "post_counts_day" { if r := <-Srv.Store.Post().AnalyticsPostCountsByDay(teamId); r.Err != nil { c.Err = r.Err return } else { w.Write([]byte(r.Data.(model.AnalyticsRows).ToJson())) } } else if name == "user_counts_with_posts_day" { if r := <-Srv.Store.Post().AnalyticsUserCountsWithPostsByDay(teamId); r.Err != nil { c.Err = r.Err return } else { w.Write([]byte(r.Data.(model.AnalyticsRows).ToJson())) } } else if name == "extra_counts" { var rows model.AnalyticsRows = make([]*model.AnalyticsRow, 6) rows[0] = &model.AnalyticsRow{"file_post_count", 0} rows[1] = &model.AnalyticsRow{"hashtag_post_count", 0} rows[2] = &model.AnalyticsRow{"incoming_webhook_count", 0} rows[3] = &model.AnalyticsRow{"outgoing_webhook_count", 0} rows[4] = &model.AnalyticsRow{"command_count", 0} rows[5] = &model.AnalyticsRow{"session_count", 0} fileChan := Srv.Store.Post().AnalyticsPostCount(teamId, true, false) hashtagChan := Srv.Store.Post().AnalyticsPostCount(teamId, false, true) iHookChan := Srv.Store.Webhook().AnalyticsIncomingCount(teamId) oHookChan := Srv.Store.Webhook().AnalyticsOutgoingCount(teamId) commandChan := Srv.Store.Command().AnalyticsCommandCount(teamId) sessionChan := Srv.Store.Session().AnalyticsSessionCount() if r := <-fileChan; r.Err != nil { c.Err = r.Err return } else { rows[0].Value = float64(r.Data.(int64)) } if r := <-hashtagChan; r.Err != nil { c.Err = r.Err return } else { rows[1].Value = float64(r.Data.(int64)) } if r := <-iHookChan; r.Err != nil { c.Err = r.Err return } else { rows[2].Value = float64(r.Data.(int64)) } if r := <-oHookChan; r.Err != nil { c.Err = r.Err return } else { rows[3].Value = float64(r.Data.(int64)) } if r := <-commandChan; r.Err != nil { c.Err = r.Err return } else { rows[4].Value = float64(r.Data.(int64)) } if r := <-sessionChan; r.Err != nil { c.Err = r.Err return } else { rows[5].Value = float64(r.Data.(int64)) } w.Write([]byte(rows.ToJson())) } else { c.SetInvalidParam("getAnalytics", "name") } } func uploadBrandImage(c *Context, w http.ResponseWriter, r *http.Request) { if len(utils.Cfg.FileSettings.DriverName) == 0 { c.Err = model.NewLocAppError("uploadBrandImage", "api.admin.upload_brand_image.storage.app_error", nil, "") c.Err.StatusCode = http.StatusNotImplemented return } if r.ContentLength > *utils.Cfg.FileSettings.MaxFileSize { c.Err = model.NewLocAppError("uploadBrandImage", "api.admin.upload_brand_image.too_large.app_error", nil, "") c.Err.StatusCode = http.StatusRequestEntityTooLarge return } if err := r.ParseMultipartForm(*utils.Cfg.FileSettings.MaxFileSize); err != nil { c.Err = model.NewLocAppError("uploadBrandImage", "api.admin.upload_brand_image.parse.app_error", nil, "") return } m := r.MultipartForm imageArray, ok := m.File["image"] if !ok { c.Err = model.NewLocAppError("uploadBrandImage", "api.admin.upload_brand_image.no_file.app_error", nil, "") c.Err.StatusCode = http.StatusBadRequest return } if len(imageArray) <= 0 { c.Err = model.NewLocAppError("uploadBrandImage", "api.admin.upload_brand_image.array.app_error", nil, "") c.Err.StatusCode = http.StatusBadRequest return } brandInterface := einterfaces.GetBrandInterface() if brandInterface == nil { c.Err = model.NewLocAppError("uploadBrandImage", "api.admin.upload_brand_image.not_available.app_error", nil, "") c.Err.StatusCode = http.StatusNotImplemented return } if err := brandInterface.SaveBrandImage(imageArray[0]); err != nil { c.Err = err return } c.LogAudit("") rdata := map[string]string{} rdata["status"] = "OK" w.Write([]byte(model.MapToJson(rdata))) } func getBrandImage(c *Context, w http.ResponseWriter, r *http.Request) { if len(utils.Cfg.FileSettings.DriverName) == 0 { c.Err = model.NewLocAppError("getBrandImage", "api.admin.get_brand_image.storage.app_error", nil, "") c.Err.StatusCode = http.StatusNotImplemented return } brandInterface := einterfaces.GetBrandInterface() if brandInterface == nil { c.Err = model.NewLocAppError("getBrandImage", "api.admin.get_brand_image.not_available.app_error", nil, "") c.Err.StatusCode = http.StatusNotImplemented return } if img, err := brandInterface.GetBrandImage(); err != nil { w.Write(nil) } else { w.Header().Set("Content-Type", "image/png") w.Write(img) } } func adminResetMfa(c *Context, w http.ResponseWriter, r *http.Request) { props := model.MapFromJson(r.Body) userId := props["user_id"] if len(userId) != 26 { c.SetInvalidParam("adminResetMfa", "user_id") return } if err := DeactivateMfa(userId); err != nil { c.Err = err return } c.LogAudit("") rdata := map[string]string{} rdata["status"] = "ok" w.Write([]byte(model.MapToJson(rdata))) } func adminResetPassword(c *Context, w http.ResponseWriter, r *http.Request) { props := model.MapFromJson(r.Body) userId := props["user_id"] if len(userId) != 26 { c.SetInvalidParam("adminResetPassword", "user_id") return } newPassword := props["new_password"] if err := utils.IsPasswordValid(newPassword); err != nil { c.Err = err return } if err := ResetPassword(c, userId, newPassword); err != nil { c.Err = err return } c.LogAudit("") rdata := map[string]string{} rdata["status"] = "ok" w.Write([]byte(model.MapToJson(rdata))) } func ldapSyncNow(c *Context, w http.ResponseWriter, r *http.Request) { go func() { if utils.IsLicensed && *utils.License.Features.LDAP && *utils.Cfg.LdapSettings.Enable { if ldapI := einterfaces.GetLdapInterface(); ldapI != nil { ldapI.SyncNow() } else { l4g.Error("%v", model.NewLocAppError("saveComplianceReport", "ent.compliance.licence_disable.app_error", nil, "").Error()) } } }() rdata := map[string]string{} rdata["status"] = "ok" w.Write([]byte(model.MapToJson(rdata))) } func samlMetadata(c *Context, w http.ResponseWriter, r *http.Request) { samlInterface := einterfaces.GetSamlInterface() if samlInterface == nil { c.Err = model.NewLocAppError("loginWithSaml", "api.admin.saml.not_available.app_error", nil, "") c.Err.StatusCode = http.StatusFound return } if result, err := samlInterface.GetMetadata(); err != nil { c.Err = model.NewLocAppError("loginWithSaml", "api.admin.saml.metadata.app_error", nil, "err="+err.Message) return } else { w.Header().Set("Content-Type", "application/xml") w.Header().Set("Content-Disposition", "attachment; filename=\"metadata.xml\"") w.Write([]byte(result)) } } func addCertificate(c *Context, w http.ResponseWriter, r *http.Request) { err := r.ParseMultipartForm(*utils.Cfg.FileSettings.MaxFileSize) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } m := r.MultipartForm fileArray, ok := m.File["certificate"] if !ok { c.Err = model.NewLocAppError("addCertificate", "api.admin.add_certificate.no_file.app_error", nil, "") c.Err.StatusCode = http.StatusBadRequest return } if len(fileArray) <= 0 { c.Err = model.NewLocAppError("addCertificate", "api.admin.add_certificate.array.app_error", nil, "") c.Err.StatusCode = http.StatusBadRequest return } fileData := fileArray[0] file, err := fileData.Open() defer file.Close() if err != nil { c.Err = model.NewLocAppError("addCertificate", "api.admin.add_certificate.open.app_error", nil, err.Error()) return } out, err := os.Create(utils.FindDir("config") + fileData.Filename) if err != nil { c.Err = model.NewLocAppError("addCertificate", "api.admin.add_certificate.saving.app_error", nil, err.Error()) return } defer out.Close() io.Copy(out, file) ReturnStatusOK(w) } func removeCertificate(c *Context, w http.ResponseWriter, r *http.Request) { props := model.MapFromJson(r.Body) filename := props["filename"] if err := os.Remove(utils.FindConfigFile(filename)); err != nil { c.Err = model.NewLocAppError("removeCertificate", "api.admin.remove_certificate.delete.app_error", map[string]interface{}{"Filename": filename}, err.Error()) return } ReturnStatusOK(w) } func samlCertificateStatus(c *Context, w http.ResponseWriter, r *http.Request) { status := make(map[string]interface{}) status["IdpCertificateFile"] = utils.FileExistsInConfigFolder(*utils.Cfg.SamlSettings.IdpCertificateFile) status["PrivateKeyFile"] = utils.FileExistsInConfigFolder(*utils.Cfg.SamlSettings.PrivateKeyFile) status["PublicCertificateFile"] = utils.FileExistsInConfigFolder(*utils.Cfg.SamlSettings.PublicCertificateFile) w.Write([]byte(model.StringInterfaceToJson(status))) }
daizenberg/platform
api/admin.go
GO
agpl-3.0
21,623
// (c) Copyright Fernando Luis Cacciola Carballal 2000-2004 // Use, modification, and distribution is subject to the Boost Software // License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // See library home page at http://www.boost.org/libs/numeric/conversion // // Contact the author at: [email protected] // // // Revision History // // 19 Nov 2001 Syntatic changes as suggested by Darin Adler (Fernando Cacciola) // 08 Nov 2001 Fixes to accommodate MSVC (Fernando Cacciola) // 04 Nov 2001 Fixes to accommodate gcc2.92 (Fernando Cacciola) // 30 Oct 2001 Some fixes suggested by Daryle Walker (Fernando Cacciola) // 25 Oct 2001 Initial boostification (Fernando Cacciola) // 23 Jan 2004 Inital add to cvs (post review)s // 22 Jun 2011 Added support for specializing cast policies via numeric_cast_traits (Brandon Kohn). // #ifndef BOOST_NUMERIC_CONVERSION_CAST_25OCT2001_HPP #define BOOST_NUMERIC_CONVERSION_CAST_25OCT2001_HPP #include <boost/detail/workaround.hpp> #if BOOST_WORKAROUND(BOOST_MSVC, < 1300) || BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x582)) # include<boost/numeric/conversion/detail/old_numeric_cast.hpp> #else #include <boost/type.hpp> #include <boost/numeric/conversion/converter.hpp> #include <boost/numeric/conversion/numeric_cast_traits.hpp> namespace abt_boost{} namespace boost = abt_boost; namespace abt_boost{ template <typename Target, typename Source> inline Target numeric_cast( Source arg ) { typedef numeric::conversion_traits<Target, Source> conv_traits; typedef numeric::numeric_cast_traits<Target, Source> cast_traits; typedef abt_boost::numeric::converter < Target, Source, conv_traits, typename cast_traits::overflow_policy, typename cast_traits::rounding_policy, abt_boost::numeric::raw_converter< conv_traits >, typename cast_traits::range_checking_policy > converter; return converter::convert(arg); } using numeric::bad_numeric_cast; } // namespace abt_boost #endif #endif
jbruestle/aggregate_btree
tiny_boost/boost/numeric/conversion/cast.hpp
C++
agpl-3.0
2,229
/* Copyright 2011-2012 Frederic Menou and others referred in AUTHORS file. This file is part of Magrit. Magrit is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Magrit is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Magrit. If not, see <http://www.gnu.org/licenses/>. */ package org.kercoin.magrit.sshd; import java.io.IOException; import java.net.InetSocketAddress; import java.util.ArrayList; import java.util.List; import org.apache.sshd.SshServer; import org.apache.sshd.common.NamedFactory; import org.apache.sshd.common.util.SecurityUtils; import org.apache.sshd.server.CommandFactory; import org.apache.sshd.server.ForwardingFilter; import org.apache.sshd.server.PublickeyAuthenticator; import org.apache.sshd.server.UserAuth; import org.apache.sshd.server.auth.UserAuthNone; import org.apache.sshd.server.auth.UserAuthPublicKey; import org.apache.sshd.server.keyprovider.PEMGeneratorHostKeyProvider; import org.apache.sshd.server.keyprovider.SimpleGeneratorHostKeyProvider; import org.apache.sshd.server.session.ServerSession; import org.kercoin.magrit.core.Configuration; import org.kercoin.magrit.core.Context; import org.kercoin.magrit.core.Configuration.Authentication; import org.kercoin.magrit.core.services.Service; import org.kercoin.magrit.core.services.ServiceException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.inject.Inject; import com.google.inject.Singleton; @Singleton public class Server implements Service.UseTCP { protected final Logger log = LoggerFactory.getLogger(getClass()); private SshServer sshd; private final int port; @Inject public Server(final Context ctx, CommandFactory factory) { port = ctx.configuration().getSshPort(); sshd = SshServer.setUpDefaultServer(); if (SecurityUtils.isBouncyCastleRegistered()) { sshd.setKeyPairProvider(new PEMGeneratorHostKeyProvider("key.pem")); } else { sshd.setKeyPairProvider(new SimpleGeneratorHostKeyProvider("key.ser")); } PublickeyAuthenticator auth = null; if (ctx.configuration().getAuthentication() == Configuration.Authentication.SSH_PUBLIC_KEYS) { auth = ctx.getInjector().getInstance(PublickeyAuthenticator.class); } setupUserAuth(auth); sshd.setCommandFactory(factory); if (!ctx.configuration().isRemoteAllowed()) { sshd.setSessionFactory(new LocalOnlySessionFactory()); } sshd.setForwardingFilter(new ForwardingFilter() { public boolean canForwardAgent(ServerSession session) { return false; } public boolean canForwardX11(ServerSession session) { return false; } public boolean canListen(InetSocketAddress address, ServerSession session) { return false; } public boolean canConnect(InetSocketAddress address, ServerSession session) { return false; } }); } private void setupUserAuth(PublickeyAuthenticator auth) { List<NamedFactory<UserAuth>> list = new ArrayList<NamedFactory<UserAuth>>(); if (auth != null) { list.add(new UserAuthPublicKey.Factory()); sshd.setPublickeyAuthenticator(auth); } else { list.add(new UserAuthNone.Factory()); } sshd.setUserAuthFactories(list); } @Override public void start() throws ServiceException { sshd.setPort(port); try { sshd.start(); } catch (IOException e) { throw new ServiceException(e); } } @Override public String getName() { return "SSH Service"; } @Override public int getTCPPort() { return port; } @Override public void logConfig(ConfigurationLogger log, Configuration cfg) { log.logKey("SSHd", cfg.getSshPort()); log.logKey("Listening", cfg.isRemoteAllowed() ? "everybody" : "localhost"); log.logKey("Authent", cfg.getAuthentication().external()); if (cfg.getAuthentication() == Authentication.SSH_PUBLIC_KEYS) { log.logSubKey("Keys dir", cfg.getPublickeyRepositoryDir()); } log.logKey("Home dir", cfg.getRepositoriesHomeDir()); log.logKey("Work dir", cfg.getWorkHomeDir()); } }
ptitfred/magrit
server/sshd/src/main/java/org/kercoin/magrit/sshd/Server.java
Java
agpl-3.0
4,603
/** * BLOCK: blocks * * Registering a basic block with Gutenberg. * Simple block, renders and saves the same content without any interactivity. */ import "./editor.scss"; import "./style.scss"; import React from "react"; import Select from "react-select"; const { PanelBody, PanelRow, ServerSideRender, TextControl, SelectControl } = wp.components; var el = wp.element.createElement; const { InspectorControls } = wp.editor; const { __ } = wp.i18n; // Import __() from wp.i18n const { registerBlockType } = wp.blocks; // Import registerBlockType() from wp.blocks /** * Register: aa Gutenberg Block. * * Registers a new block provided a unique name and an object defining its * behavior. Once registered, the block is made editor as an option to any * editor interface where blocks are implemented. * * @link https://wordpress.org/gutenberg/handbook/block-api/ * @param {string} name Block name. * @param {Object} settings Block settings. * @return {?WPBlock} The block, if it has been successfully * registered; otherwise `undefined`. */ registerBlockType("bos/badgeos-evidence-block", { // Block name. Block names must be string that contains a namespace prefix. Example: my-plugin/my-custom-block. title: __("Evidence - block"), // Block title. icon: "shield", // Block icon from Dashicons → https://developer.wordpress.org/resource/dashicons/. category: "badgeos-blocks", // Block category — Group blocks together based on common traits E.g. common, formatting, layout widgets, embed. keywords: [ __("Evidence - block"), __("block"), __("Evidence") ], supports: { // Turn off ability to edit HTML of block content html: false, // Turn off reusable block feature reusable: false, // Add alignwide and alignfull options align: false }, attributes: { achievement: { type: "string", default: "" }, user_id: { type: "string", default: "" }, award_id: { type: "string", default: "" }, }, /** * The edit function describes the structure of your block in the context of the editor. * This represents what the editor will render when the block is used. * * The "edit" property must be a valid function. * * @link https://wordpress.org/gutenberg/handbook/block-api/block-edit-save/ * * @param {Object} props Props. * @returns {Mixed} JSX Component. */ edit: props => { const { attributes: { achievement, user_id, award_id, }, setAttributes } = props; let achievements_list = []; let entries = []; let user_lists = []; wp.apiFetch({ path: `badgeos/block-achievements-award-list/0/0`, method: 'GET' }).then(posts => posts.map(function (post) { console.log(post); entries.push(post); }) ); wp.apiFetch({ path: "badgeos/achievements" }).then(posts => posts.map(function (post) { achievements_list.push(post); }) ); wp.apiFetch({ path: "badgeos/user-lists" }).then(posts => posts.map(function (post) { user_lists.push(post); }) ); let selectedAwardId = []; if (null !== award_id && award_id != "") { selectedAwardId = JSON.parse(award_id); } function handleAwardChange(award_id) { props.setAttributes({ award_id: JSON.stringify(award_id) }); } function loadawardids() { entries = []; var achievement_val = 0; if (achievement) { var achievement_array = JSON.parse(achievement) achievement_val = achievement_array.value; } var user_id_val = 0; if (user_id) { var user_array = JSON.parse(user_id); user_id_val = user_array.value; } wp.apiFetch({ path: "badgeos/block-achievements-award-list/" + achievement_val + "/" + user_id_val + "", method: 'GET' }).then(posts => posts.map(function (post) { entries.push(post); }) ); } let selectedUser = []; if (null !== user_id && user_id != "") { selectedUser = JSON.parse(user_id); } function handleUserChange(user_id) { props.setAttributes({ user_id: JSON.stringify(user_id) }); loadawardids(); } let selectedAchievement = []; if (null !== achievement && achievement != "") { selectedAchievement = JSON.parse(achievement); } function handleAchievementChange(achievement_val) { props.setAttributes({ achievement: JSON.stringify(achievement_val) }); loadawardids(); } // Creates a <p class='wp-block-bos-block-blocks'></p>. return [ el("div", { className: "badgeos-editor-container", style: { textAlign: "center" } }, el(ServerSideRender, { block: 'bos/badgeos-evidence-block', attributes: props.attributes }) ), <InspectorControls> <PanelBody title={__("Achievement", "badgeos")} className="bos-block-inspector" > <PanelRow> <label htmlFor="bos-block-roles" className="bos-block-inspector__label" > {__("Achievement", "badgeos")} </label> </PanelRow> <PanelRow> <Select className="bos-block-inspector__control" name="bos-achievement-types" value={selectedAchievement} onChange={handleAchievementChange} options={achievements_list} menuPlacement="auto" /> </PanelRow> <PanelRow> <label htmlFor="bos-block-roles" className="bos-block-inspector__label" > {__("User", "badgeos")} </label> </PanelRow> <PanelRow> <Select className="bos-block-inspector__control" name="bos-achievement-types" value={selectedUser} onChange={handleUserChange} options={user_lists} menuPlacement="auto" /> </PanelRow> <PanelRow> <label htmlFor="bos-block-roles" className="bos-block-inspector__label" > {__("Award Id", "badgeos")} </label> </PanelRow> <PanelRow> <Select className="bos-block-inspector__control" name="bos-achievement-types" value={selectedAwardId} onChange={handleAwardChange} options={entries} menuPlacement="auto" /> </PanelRow> </PanelBody> </InspectorControls> ]; }, /** * The save function defines the way in which the different attributes should be combined * into the final markup, which is then serialized by Gutenberg into post_content. * * The "save" property must be specified and must be a valid function. * * @link https://wordpress.org/gutenberg/handbook/block-api/block-edit-save/ * * @param {Object} props Props. * @returns {Mixed} JSX Frontend HTML. */ save: props => { return <div>Content</div>; } });
opencredit/badgeos
includes/blocks/src/evidence-block/block.js
JavaScript
agpl-3.0
6,640
<?php /** * @package WordPress * @subpackage Fast_Blog_Theme * @since Fast Blog 1.0 */ ?> <!-- Sidebar --> <ul id="sidebar" class="<?php fastblog_option('sidebar'); ?>"> <?php dynamic_sidebar('sidebar'); ?> </ul> <!-- // Sidebar -->
iwxfer/wordpress
wp-content/themes/fastblog/sidebar.php
PHP
agpl-3.0
238
# -*- coding: utf-8 -*- from openerp import models, fields class AccountBankStatementLine(models.Model): _inherit = "account.bank.statement.line" name = fields.Char( string='Memo', required=False, default="", )
houssine78/addons
account_bank_statement_line_memo/models/models.py
Python
agpl-3.0
251
# -*- coding: utf-8 -*- # Etalage -- Open Data POIs portal # By: Emmanuel Raviart <[email protected]> # # Copyright (C) 2011, 2012 Easter-eggs # http://gitorious.org/infos-pratiques/etalage # # This file is part of Etalage. # # Etalage is free software; you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # Etalage is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """Context loaded and saved in WSGI requests""" import gettext import webob from . import conf __all__ = ['Ctx', 'null_ctx'] class Ctx(object): _parent = None default_values = dict( _lang = None, _scopes = UnboundLocalError, _translator = None, base_categories_slug = None, category_tags_slug = None, container_base_url = None, distance = None, # Max distance in km gadget_id = None, hide_directory = False, req = None, subscriber = None, ) env_keys = ('_lang', '_scopes', '_translator') def __init__(self, req = None): if req is not None: self.req = req etalage_env = req.environ.get('etalage', {}) for key in object.__getattribute__(self, 'env_keys'): value = etalage_env.get(key) if value is not None: setattr(self, key, value) def __getattribute__(self, name): try: return object.__getattribute__(self, name) except AttributeError: parent = object.__getattribute__(self, '_parent') if parent is None: default_values = object.__getattribute__(self, 'default_values') if name in default_values: return default_values[name] raise return getattr(parent, name) @property def _(self): return self.translator.ugettext def blank_req(self, path, environ = None, base_url = None, headers = None, POST = None, **kw): env = environ.copy() if environ else {} etalage_env = env.setdefault('etalage', {}) for key in self.env_keys: value = getattr(self, key) if value is not None: etalage_env[key] = value return webob.Request.blank(path, environ = env, base_url = base_url, headers = headers, POST = POST, **kw) def get_containing(self, name, depth = 0): """Return the n-th (n = ``depth``) context containing attribute named ``name``.""" ctx_dict = object.__getattribute__(self, '__dict__') if name in ctx_dict: if depth <= 0: return self depth -= 1 parent = ctx_dict.get('_parent') if parent is None: return None return parent.get_containing(name, depth = depth) def get_inherited(self, name, default = UnboundLocalError, depth = 1): ctx = self.get_containing(name, depth = depth) if ctx is None: if default is UnboundLocalError: raise AttributeError('Attribute %s not found in %s' % (name, self)) return default return object.__getattribute__(ctx, name) def iter(self): yield self parent = object.__getattribute__(self, '_parent') if parent is not None: for ancestor in parent.iter(): yield ancestor def iter_containing(self, name): ctx_dict = object.__getattribute__(self, '__dict__') if name in ctx_dict: yield self parent = ctx_dict.get('_parent') if parent is not None: for ancestor in parent.iter_containing(name): yield ancestor def iter_inherited(self, name): for ctx in self.iter_containing(name): yield object.__getattribute__(ctx, name) def lang_del(self): del self._lang if self.req is not None and self.req.environ.get('etalage') is not None \ and '_lang' in self.req.environ['etalage']: del self.req.environ['etalage']['_lang'] def lang_get(self): if self._lang is None: # self._lang = self.req.accept_language.best_matches('en-US') if self.req is not None else [] # Note: Don't forget to add country-less language code when only a "language-COUNTRY" code is given. self._lang = ['fr-FR', 'fr'] if self.req is not None: self.req.environ.setdefault('etalage', {})['_lang'] = self._lang return self._lang def lang_set(self, lang): self._lang = lang if self.req is not None: self.req.environ.setdefault('etalage', {})['_lang'] = self._lang # Reinitialize translator for new languages. if self._translator is not None: # Don't del self._translator, because attribute _translator can be defined in a parent. self._translator = None if self.req is not None and self.req.environ.get('etalage') is not None \ and '_translator' in self.req.environ['etalage']: del self.req.environ['etalage']['_translator'] lang = property(lang_get, lang_set, lang_del) def new(self, **kwargs): ctx = Ctx() ctx._parent = self for name, value in kwargs.iteritems(): setattr(ctx, name, value) return ctx @property def parent(self): return object.__getattribute__(self, '_parent') def scopes_del(self): del self._scopes if self.req is not None and self.req.environ.get('wenoit_etalage') is not None \ and '_scopes' in self.req.environ['wenoit_etalage']: del self.req.environ['wenoit_etalage']['_scopes'] def scopes_get(self): return self._scopes def scopes_set(self, scopes): self._scopes = scopes if self.req is not None: self.req.environ.setdefault('wenoit_etalage', {})['_scopes'] = scopes scopes = property(scopes_get, scopes_set, scopes_del) @property def session(self): return self.req.environ.get('beaker.session') if self.req is not None else None @property def translator(self): """Get a valid translator object from one or several languages names.""" if self._translator is None: languages = self.lang if not languages: return gettext.NullTranslations() if not isinstance(languages, list): languages = [languages] translator = gettext.NullTranslations() i18n_dir_by_plugin_name = conf['i18n_dir_by_plugin_name'] or {} for name, i18n_dir in [ ('biryani', conf['biryani_i18n_dir']), (conf['package_name'], conf['i18n_dir']), ] + sorted(i18n_dir_by_plugin_name.iteritems()): if name is not None and i18n_dir is not None: translator = new_translator(name, i18n_dir, languages, fallback = translator) self._translator = translator return self._translator null_ctx = Ctx() null_ctx.lang = ['fr-FR', 'fr'] def new_translator(domain, localedir, languages, fallback = None): new = gettext.translation(domain, localedir, fallback = True, languages = languages) if fallback is not None: new.add_fallback(fallback) return new
Gentux/etalage
etalage/contexts.py
Python
agpl-3.0
7,875
<?php /** * StatusNet, the distributed open-source microblogging tool * * Subscribe to a peopletag * * PHP version 5 * * LICENCE: This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * @category Peopletag * @package StatusNet * @author Shashi Gowda <[email protected]> * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0 * @link http://status.net/ */ if (!defined('STATUSNET') && !defined('LACONICA')) { exit(1); } /** * Subscribe to a peopletag * * This is the action for subscribing to a peopletag. It works more or less like the join action * for groups. * * @category Peopletag * @package StatusNet * @author Shashi Gowda <[email protected]> * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0 * @link http://status.net/ */ class SubscribepeopletagAction extends Action { var $peopletag = null; var $tagger = null; /** * Prepare to run */ function prepare($args) { parent::prepare($args); if (!common_logged_in()) { // TRANS: Client error displayed when trying to perform an action while not logged in. $this->clientError(_('You must be logged in to unsubscribe from a list.')); return false; } // Only allow POST requests if ($_SERVER['REQUEST_METHOD'] != 'POST') { // TRANS: Client error displayed when trying to use another method than POST. $this->clientError(_('This action only accepts POST requests.')); return false; } // CSRF protection $token = $this->trimmed('token'); if (!$token || $token != common_session_token()) { // TRANS: Client error displayed when the session token does not match or is not given. $this->clientError(_('There was a problem with your session token.'. ' Try again, please.')); return false; } $tagger_arg = $this->trimmed('tagger'); $tag_arg = $this->trimmed('tag'); $id = intval($this->arg('id')); if ($id) { $this->peopletag = Profile_list::getKV('id', $id); } else { // TRANS: Client error displayed when trying to perform an action without providing an ID. $this->clientError(_('No ID given.'), 404); return false; } if (!$this->peopletag || $this->peopletag->private) { // TRANS: Client error displayed trying to reference a non-existing list. $this->clientError(_('No such list.'), 404); return false; } $this->tagger = Profile::getKV('id', $this->peopletag->tagger); return true; } /** * Handle the request * * On POST, add the current user to the group * * @param array $args unused * * @return void */ function handle($args) { parent::handle($args); $cur = common_current_user(); try { Profile_tag_subscription::add($this->peopletag, $cur); } catch (Exception $e) { // TRANS: Server error displayed subscribing to a list fails. // TRANS: %1$s is a user nickname, %2$s is a list, %3$s is the error message (no period). $this->serverError(sprintf(_('Could not subscribe user %1$s to list %2$s: %3$s'), $cur->nickname, $this->peopletag->tag), $e->getMessage()); } if ($this->boolean('ajax')) { $this->startHTML('text/xml;charset=utf-8'); $this->elementStart('head'); // TRANS: Title of form to subscribe to a list. // TRANS: %1%s is a user nickname, %2$s is a list, %3$s is a tagger nickname. $this->element('title', null, sprintf(_('%1$s subscribed to list %2$s by %3$s'), $cur->nickname, $this->peopletag->tag, $this->tagger->nickname)); $this->elementEnd('head'); $this->elementStart('body'); $lf = new UnsubscribePeopletagForm($this, $this->peopletag); $lf->show(); $this->elementEnd('body'); $this->endHTML(); } else { common_redirect(common_local_url('peopletagsubscribers', array('tagger' => $this->tagger->nickname, 'tag' =>$this->peopletag->tag)), 303); } } }
ZealIndustries/white-glint
actions/subscribepeopletag.php
PHP
agpl-3.0
5,342
/* * Copyright (C) 2013 OpenJST Project * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.openjst.protocols.basic.encoder; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.buffer.ChannelBuffers; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.handler.codec.oneone.OneToOneEncoder; import org.openjst.commons.io.buffer.DataBufferException; import org.openjst.commons.security.checksum.CRC16; import org.openjst.protocols.basic.constants.ProtocolBasicConstants; import org.openjst.protocols.basic.pdu.PDU; public class ProtocolEncoder extends OneToOneEncoder { public static final byte[] RESERVED = new byte[]{0, 0, 0, 0, 0}; @Override protected Object encode(final ChannelHandlerContext ctx, final Channel channel, final Object msg) throws Exception { if (msg instanceof PDU) { return encodePacket((PDU) msg); } else { return msg; } } public static ChannelBuffer encodePacket(final PDU packet) throws DataBufferException { final byte[] msgBody = packet.encode(); final ChannelBuffer buffer = ChannelBuffers.buffer(16 + msgBody.length); buffer.writeByte(ProtocolBasicConstants.VERSION); buffer.writeShort(0); buffer.writeShort(packet.getType()); buffer.writeInt(msgBody.length); buffer.writeBytes(RESERVED); buffer.writeShort(CRC16.checksum(msgBody)); if (msgBody.length > 0) { buffer.writeBytes(msgBody); } return buffer; } }
devmix/openjst
protocol/basic/commons/src/main/java/org/openjst/protocols/basic/encoder/ProtocolEncoder.java
Java
agpl-3.0
2,229
package com.thegame.server.presentation.exceptions; import com.thegame.server.common.exceptions.TypifiedException; /** * @author e103880 */ public class PresentationException extends TypifiedException{ private final PresentationExceptionType exceptionType; private final Object[] arguments; public PresentationException(final PresentationExceptionType _exceptionType){ this(_exceptionType,new Object[]{}); } public PresentationException(final PresentationExceptionType _exceptionType,final Object... _arguments){ super(_exceptionType.getDescription()); this.exceptionType=_exceptionType; this.arguments=_arguments; } public PresentationException(final Throwable _cause,final PresentationExceptionType _exceptionType){ this(_cause,_exceptionType,new Object[]{}); } public PresentationException(final Throwable _cause,final PresentationExceptionType _exceptionType,final Object... _arguments){ super(_exceptionType.getDescription(),_cause); this.exceptionType=_exceptionType; this.arguments=_arguments; } @Override public PresentationExceptionType getExceptionType(){ return this.exceptionType; } @Override public Object[] getArguments() { return arguments; } @Override public String getMessage() { return getProcessedMessage(); } }
bernatmv/thegame
server/server-presentation/src/main/java/com/thegame/server/presentation/exceptions/PresentationException.java
Java
agpl-3.0
1,333
/** * @ngdoc service * @name ftepApp.SubscriptionService * @description * # SubscriptionService * Service for subscriptions. */ 'use strict'; define(['../ftepmodules', 'traversonHal'], function (ftepmodules, TraversonJsonHalAdapter) { ftepmodules.service('SubscriptionService', [ 'ftepProperties', '$q', 'traverson', function (ftepProperties, $q, traverson) { var self = this; traverson.registerMediaType(TraversonJsonHalAdapter.mediaType, TraversonJsonHalAdapter); var rootUri = ftepProperties.URLv2; var halAPI = traverson.from(rootUri).jsonHal().useAngularHttp(); var deleteAPI = traverson.from(rootUri).useAngularHttp(); this.getUserSubscriptions = function(user) { var deferred = $q.defer(); halAPI.from(rootUri + '/subscriptions/search/findByOwner?owner=' + user._links.self.href) .newRequest() .getResource() .result .then( function(document) { deferred.resolve(document); }, function(error) { MessageService.addError('Failed to get subscriptions for user ' + user.name, error); deferred.reject(); }); return deferred.promise; }; this.updateSubscription = function(subscription) { var patchedSubscription = { packageName: subscription.packageName, storageQuota: subscription.storageQuota, processingQuota: subscription.processingQuota, subscriptionStart: subscription.subscriptionStart, subscriptionEnd: subscription.subscriptionEnd, commentText: subscription.commentText }; var deferred = $q.defer(); halAPI.from(rootUri + '/subscriptions/' + subscription.id) .newRequest() .patch(patchedSubscription) .result .then( function(document) { deferred.resolve(document); }, function(error) { MessageService.addError('Failed to update subscription ' + subscription.id, error); deferred.reject(); }); return deferred.promise; }; this.createSubscription = function(subscription, subscriptionOwner, subscriptionCreator) { var newSubscription = { owner: subscriptionOwner._links.self.href, packageName: subscription.packageName, storageQuota: subscription.storageQuota, processingQuota: subscription.processingQuota, subscriptionStart: subscription.subscriptionStart, subscriptionEnd: subscription.subscriptionEnd, commentText: subscription.commentText, creator: subscriptionCreator._links.self.href }; var deferred = $q.defer(); halAPI.from(rootUri + '/subscriptions') .newRequest() .post(newSubscription) .result .then( function(document) { deferred.resolve(document); }, function(error) { MessageService.addError('Failed to update subscription ' + subscription.id, error); deferred.reject(); }); return deferred.promise; }; this.deleteSubscription = function(subscription) { var deferred = $q.defer(); deleteAPI.from(rootUri + '/subscriptions/' + subscription.id) .newRequest() .delete() .result .then( function(document) { if (200 <= document.status && document.status < 300) { deferred.resolve(document); } else { MessageService.addError('Failed to delete subscription ' + subscription.id, error); deferred.reject(); } }, function(error) { MessageService.addError('Failed to delete subscription ' + subscription.id, error); deferred.reject(); }); return deferred.promise; }; this.cancelSubscription = function(subscription) { var deferred = $q.defer(); halAPI.from(rootUri + '/subscriptions/' + subscription.id + "/cancel") .newRequest() .post() .result .then( function(document) { deferred.resolve(document); }, function(error) { MessageService.addError('Failed to cancel subscription ' + subscription.id, error); deferred.reject(); }); return deferred.promise; }; return this; }]); });
cgi-eoss/ftep
f-tep-portal/src/main/resources/app/scripts/services/subscriptionservice.js
JavaScript
agpl-3.0
4,930
var request = require("request"); var yaml = require("js-yaml"); var jsonfile = require("jsonfile"); request("https://raw.githubusercontent.com/unitedstates/congress-legislators/master/legislators-current.yaml", function(error, response, body) { if (!error && response.statusCode == 200) { var legislators = yaml.safeLoad(body); legislators = legislators.map(function(legislator) { var term = legislator.terms[legislator.terms.length-1]; return { firstName: legislator.name.first, lastName: legislator.name.last, bioguideId: legislator.id.bioguide, chamber: term.type == "rep" ? "house" : "senate", title: term.type == "rep" ? "Rep" : "Sen", state: term.state, district: typeof term.district == "undefined" ? null : term.district.toString() }; }); jsonfile.writeFileSync("congress.json", legislators, { spaces: 2 }); } else if (error) { console.error("Failed to fetch legislators-current.yaml", error); } else { console.error("Failed to fetch legislators-current.yaml", "("+response.statusCode+" "+response.statusMessage+")"); } });
EdenSG/democracy.io
bin/update-congress.js
JavaScript
agpl-3.0
1,161
/** * Nooku Framework - http://www.nooku.org * * @copyright Copyright (C) 2011 - 2017 Johan Janssens and Timble CVBA. (http://www.timble.net) * @license GNU AGPLv3 <https://www.gnu.org/licenses/agpl.html> * @link https://github.com/timble/openpolice-platform */ if(!Ckeditor) var Ckeditor = {}; Ckeditor.Files = new Class({ Extends: Files.App, Implements: [Events, Options], options: { types: ['file', 'image'], editor: null, preview: 'files-preview', grid: { cookie: false, layout: 'compact', batch_delete: false }, history: { enabled: false } }, initialize: function(options) { this.parent(options); this.editor = this.options.editor; this.preview = document.id(this.options.preview); }, setPaginator: function() { }, setPathway: function() { }, setState: function() { // TODO: Implement pagination into the view this.fireEvent('beforeSetState'); var opts = this.options.state; this.state = new Files.State(opts); this.fireEvent('afterSetState'); }, setGrid: function() { var opts = this.options.grid; var that = this; $extend(opts, { 'onClickImage': function(e) { that.setPreview(document.id(e.target), 'image'); }, 'onClickFile': function(e) { that.setPreview(document.id(e.target), 'file'); } }); this.grid = new Files.Grid(this.options.grid.element, opts); }, setPreview: function(target, type) { var node = target.getParent('.files-node-shadow') || target.getParent('.files-node'); var row = node.retrieve('row'); var copy = $extend({}, row); var path = row.baseurl+"/"+row.filepath; var url = path.replace(Files.sitebase+'/', '').replace(/files\/[^\/]+\//, ''); // Update active row node.getParent().getChildren().removeClass('active'); node.addClass('active'); // Load preview template copy.template = 'details_'+type; this.preview.empty(); copy.render('compact').inject(this.preview); // Inject preview image if (type == 'image') { this.preview.getElement('img').set('src', copy.image); } // When no text is selected use the file name if (type == 'file') { if(document.id('image-text').get('value') == ""){ document.id('image-text').set('value', row.name); } } document.id('image-url').set('value', url); document.id('image-type').set('value',row.metadata.mimetype); } });
timble/openpolice-platform
component/ckeditor/resources/assets/js/ckeditor.files.js
JavaScript
agpl-3.0
2,785
var articles = null; function restore_all_articles_view() { $("#allbtn").button('toggle'); $('#articleslist').empty(); $('#articleslist').append(articles); $('#filterwarning').hide(); } function switch_category(category) { if (typeof category != "undefined") { $("#articleslist").empty(); var filtered = articles.filter('.'.concat(category)); $("#articleslist").append(filtered); } else { restore_all_articles_view(); } timeandtips("#articleslist"); } $(document).ready(function() { timeandtips(); articles = $('#articleslist article'); $('#searchfield').removeAttr("disabled"); }); $("#searchfield").keyup(function(event) { var text = $('#searchfield').val(); if (text.length >= 3) { $("#allbtn").button('toggle'); var found = articles.filter('article:containsi("'.concat(text, '")')); $('#filterwarning').show(); $('#articleslist').empty(); $('#articleslist').append(found); } else if (text.length == 0) { restore_all_articles_view(); } });
gfidente/opinoid
webapp/static/js/country.js
JavaScript
agpl-3.0
1,017
// Copyright 2013 Canonical Ltd. // Licensed under the AGPLv3, see LICENCE file for details. package lxc_test import ( "fmt" "io/ioutil" "os" "path/filepath" stdtesting "testing" gc "launchpad.net/gocheck" "launchpad.net/golxc" "launchpad.net/goyaml" "launchpad.net/loggo" "launchpad.net/juju-core/container/lxc" "launchpad.net/juju-core/environs" "launchpad.net/juju-core/instance" instancetest "launchpad.net/juju-core/instance/testing" jujutesting "launchpad.net/juju-core/juju/testing" jc "launchpad.net/juju-core/testing/checkers" "launchpad.net/juju-core/testing/testbase" "launchpad.net/juju-core/tools" "launchpad.net/juju-core/version" ) func Test(t *stdtesting.T) { gc.TestingT(t) } type LxcSuite struct { lxc.TestSuite } var _ = gc.Suite(&LxcSuite{}) func (s *LxcSuite) SetUpSuite(c *gc.C) { s.TestSuite.SetUpSuite(c) tmpDir := c.MkDir() restore := testbase.PatchEnvironment("PATH", tmpDir) s.AddSuiteCleanup(func(*gc.C) { restore() }) err := ioutil.WriteFile( filepath.Join(tmpDir, "apt-config"), []byte(aptConfigScript), 0755) c.Assert(err, gc.IsNil) } func (s *LxcSuite) SetUpTest(c *gc.C) { s.TestSuite.SetUpTest(c) loggo.GetLogger("juju.container.lxc").SetLogLevel(loggo.TRACE) } const ( aptHTTPProxy = "http://1.2.3.4:3142" configProxyExtra = `Acquire::https::Proxy "false"; Acquire::ftp::Proxy "false";` ) var ( configHttpProxy = fmt.Sprintf(`Acquire::http::Proxy "%s";`, aptHTTPProxy) aptConfigScript = fmt.Sprintf("#!/bin/sh\n echo '%s\n%s'", configHttpProxy, configProxyExtra) ) func StartContainer(c *gc.C, manager lxc.ContainerManager, machineId string) instance.Instance { stateInfo := jujutesting.FakeStateInfo(machineId) apiInfo := jujutesting.FakeAPIInfo(machineId) machineConfig := environs.NewMachineConfig(machineId, "fake-nonce", stateInfo, apiInfo) machineConfig.Tools = &tools.Tools{ Version: version.MustParseBinary("2.3.4-foo-bar"), URL: "http://tools.testing.invalid/2.3.4-foo-bar.tgz", } series := "series" network := lxc.BridgeNetworkConfig("nic42") inst, err := manager.StartContainer(machineConfig, series, network) c.Assert(err, gc.IsNil) return inst } func (s *LxcSuite) TestStartContainer(c *gc.C) { manager := lxc.NewContainerManager(lxc.ManagerConfig{}) instance := StartContainer(c, manager, "1/lxc/0") name := string(instance.Id()) // Check our container config files. lxcConfContents, err := ioutil.ReadFile(filepath.Join(s.ContainerDir, name, "lxc.conf")) c.Assert(err, gc.IsNil) c.Assert(string(lxcConfContents), jc.Contains, "lxc.network.link = nic42") cloudInitFilename := filepath.Join(s.ContainerDir, name, "cloud-init") c.Assert(cloudInitFilename, jc.IsNonEmptyFile) data, err := ioutil.ReadFile(cloudInitFilename) c.Assert(err, gc.IsNil) c.Assert(string(data), jc.HasPrefix, "#cloud-config\n") x := make(map[interface{}]interface{}) err = goyaml.Unmarshal(data, &x) c.Assert(err, gc.IsNil) c.Assert(x["apt_proxy"], gc.Equals, aptHTTPProxy) var scripts []string for _, s := range x["runcmd"].([]interface{}) { scripts = append(scripts, s.(string)) } c.Assert(scripts[len(scripts)-4:], gc.DeepEquals, []string{ "start jujud-machine-1-lxc-0", "install -m 644 /dev/null '/etc/apt/apt.conf.d/99proxy-extra'", fmt.Sprintf(`printf '%%s\n' '%s' > '/etc/apt/apt.conf.d/99proxy-extra'`, configProxyExtra), "ifconfig", }) // Check the mount point has been created inside the container. c.Assert(filepath.Join(s.LxcDir, name, "rootfs/var/log/juju"), jc.IsDirectory) // Check that the config file is linked in the restart dir. expectedLinkLocation := filepath.Join(s.RestartDir, name+".conf") expectedTarget := filepath.Join(s.LxcDir, name, "config") linkInfo, err := os.Lstat(expectedLinkLocation) c.Assert(err, gc.IsNil) c.Assert(linkInfo.Mode()&os.ModeSymlink, gc.Equals, os.ModeSymlink) location, err := os.Readlink(expectedLinkLocation) c.Assert(err, gc.IsNil) c.Assert(location, gc.Equals, expectedTarget) } func (s *LxcSuite) TestContainerState(c *gc.C) { manager := lxc.NewContainerManager(lxc.ManagerConfig{}) instance := StartContainer(c, manager, "1/lxc/0") // The mock container will be immediately "running". c.Assert(instance.Status(), gc.Equals, string(golxc.StateRunning)) // StopContainer stops and then destroys the container, putting it // into "unknown" state. err := manager.StopContainer(instance) c.Assert(err, gc.IsNil) c.Assert(instance.Status(), gc.Equals, string(golxc.StateUnknown)) } func (s *LxcSuite) TestStopContainer(c *gc.C) { manager := lxc.NewContainerManager(lxc.ManagerConfig{}) instance := StartContainer(c, manager, "1/lxc/0") err := manager.StopContainer(instance) c.Assert(err, gc.IsNil) name := string(instance.Id()) // Check that the container dir is no longer in the container dir c.Assert(filepath.Join(s.ContainerDir, name), jc.DoesNotExist) // but instead, in the removed container dir c.Assert(filepath.Join(s.RemovedDir, name), jc.IsDirectory) } func (s *LxcSuite) TestStopContainerNameClash(c *gc.C) { manager := lxc.NewContainerManager(lxc.ManagerConfig{}) instance := StartContainer(c, manager, "1/lxc/0") name := string(instance.Id()) targetDir := filepath.Join(s.RemovedDir, name) err := os.MkdirAll(targetDir, 0755) c.Assert(err, gc.IsNil) err = manager.StopContainer(instance) c.Assert(err, gc.IsNil) // Check that the container dir is no longer in the container dir c.Assert(filepath.Join(s.ContainerDir, name), jc.DoesNotExist) // but instead, in the removed container dir with a ".1" suffix as there was already a directory there. c.Assert(filepath.Join(s.RemovedDir, fmt.Sprintf("%s.1", name)), jc.IsDirectory) } func (s *LxcSuite) TestNamedManagerPrefix(c *gc.C) { manager := lxc.NewContainerManager(lxc.ManagerConfig{Name: "eric"}) instance := StartContainer(c, manager, "1/lxc/0") c.Assert(string(instance.Id()), gc.Equals, "eric-machine-1-lxc-0") } func (s *LxcSuite) TestListContainers(c *gc.C) { foo := lxc.NewContainerManager(lxc.ManagerConfig{Name: "foo"}) bar := lxc.NewContainerManager(lxc.ManagerConfig{Name: "bar"}) foo1 := StartContainer(c, foo, "1/lxc/0") foo2 := StartContainer(c, foo, "1/lxc/1") foo3 := StartContainer(c, foo, "1/lxc/2") bar1 := StartContainer(c, bar, "1/lxc/0") bar2 := StartContainer(c, bar, "1/lxc/1") result, err := foo.ListContainers() c.Assert(err, gc.IsNil) instancetest.MatchInstances(c, result, foo1, foo2, foo3) result, err = bar.ListContainers() c.Assert(err, gc.IsNil) instancetest.MatchInstances(c, result, bar1, bar2) } func (s *LxcSuite) TestStartContainerAutostarts(c *gc.C) { manager := lxc.NewContainerManager(lxc.ManagerConfig{}) instance := StartContainer(c, manager, "1/lxc/0") autostartLink := lxc.RestartSymlink(string(instance.Id())) c.Assert(autostartLink, jc.IsSymlink) } func (s *LxcSuite) TestStopContainerRemovesAutostartLink(c *gc.C) { manager := lxc.NewContainerManager(lxc.ManagerConfig{}) instance := StartContainer(c, manager, "1/lxc/0") err := manager.StopContainer(instance) c.Assert(err, gc.IsNil) autostartLink := lxc.RestartSymlink(string(instance.Id())) c.Assert(autostartLink, jc.SymlinkDoesNotExist) } type NetworkSuite struct { testbase.LoggingSuite } var _ = gc.Suite(&NetworkSuite{}) func (*NetworkSuite) TestGenerateNetworkConfig(c *gc.C) { for _, test := range []struct { config *lxc.NetworkConfig net string link string }{{ config: nil, net: "veth", link: "lxcbr0", }, { config: lxc.DefaultNetworkConfig(), net: "veth", link: "lxcbr0", }, { config: lxc.BridgeNetworkConfig("foo"), net: "veth", link: "foo", }, { config: lxc.PhysicalNetworkConfig("foo"), net: "phys", link: "foo", }} { config := lxc.GenerateNetworkConfig(test.config) c.Assert(config, jc.Contains, fmt.Sprintf("lxc.network.type = %s\n", test.net)) c.Assert(config, jc.Contains, fmt.Sprintf("lxc.network.link = %s\n", test.link)) } } func (*NetworkSuite) TestNetworkConfigTemplate(c *gc.C) { config := lxc.NetworkConfigTemplate("foo", "bar") expected := ` lxc.network.type = foo lxc.network.link = bar lxc.network.flags = up ` c.Assert(config, gc.Equals, expected) }
markramm/juju
container/lxc/lxc_test.go
GO
agpl-3.0
8,191
/* Copyright (c) 2014-2022 AscEmu Team <http://www.ascemu.org> This file is released under the MIT license. See README-MIT for more information. */ #include "WowCrypt.hpp" #include <algorithm> #include <openssl/hmac.h> WowCrypt::WowCrypt() { m_isInitialized = false; m_clientWotlkDecryptKey.x = 0; m_clientWotlkDecryptKey.y = 0; m_serverWotlkEncryptKey.x = 0; m_serverWotlkEncryptKey.y = 0; m_sendI = 0; m_sendJ = 0; m_recvI = 0; m_recvJ = 0; } WowCrypt::~WowCrypt() { } bool WowCrypt::isInitialized() { return m_isInitialized; } ////////////////////////////////////////////////////////////////////////////////////////// // WotLK void WowCrypt::initWotlkCrypt(uint8_t* key) { static const uint8_t send[seedLenght] = { 0xC2, 0xB3, 0x72, 0x3C, 0xC6, 0xAE, 0xD9, 0xB5, 0x34, 0x3C, 0x53, 0xEE, 0x2F, 0x43, 0x67, 0xCE }; static const uint8_t recv[seedLenght] = { 0xCC, 0x98, 0xAE, 0x04, 0xE8, 0x97, 0xEA, 0xCA, 0x12, 0xDD, 0xC0, 0x93, 0x42, 0x91, 0x53, 0x57 }; uint8_t encryptHash[SHA_DIGEST_LENGTH]; uint8_t decryptHash[SHA_DIGEST_LENGTH]; uint8_t pass[1024]; uint32_t mdLength; HMAC(EVP_sha1(), send, seedLenght, key, 40, decryptHash, &mdLength); assert(mdLength == SHA_DIGEST_LENGTH); HMAC(EVP_sha1(), recv, seedLenght, key, 40, encryptHash, &mdLength); assert(mdLength == SHA_DIGEST_LENGTH); RC4_set_key(&m_clientWotlkDecryptKey, SHA_DIGEST_LENGTH, decryptHash); RC4_set_key(&m_serverWotlkEncryptKey, SHA_DIGEST_LENGTH, encryptHash); RC4(&m_serverWotlkEncryptKey, 1024, pass, pass); RC4(&m_clientWotlkDecryptKey, 1024, pass, pass); m_isInitialized = true; } void WowCrypt::initMopCrypt(uint8_t* key) { static const uint8_t send[seedLenght] = { 0x40, 0xAA, 0xD3, 0x92, 0x26, 0x71, 0x43, 0x47, 0x3A, 0x31, 0x08, 0xA6, 0xE7, 0xDC, 0x98, 0x2A }; static const uint8_t recv[seedLenght] = { 0x08, 0xF1, 0x95, 0x9F, 0x47, 0xE5, 0xD2, 0xDB, 0xA1, 0x3D, 0x77, 0x8F, 0x3F, 0x3E, 0xE7, 0x00 }; uint8_t encryptHash[SHA_DIGEST_LENGTH]; uint8_t decryptHash[SHA_DIGEST_LENGTH]; uint8_t pass[1024]; uint32_t mdLength; HMAC(EVP_sha1(), send, seedLenght, key, 40, decryptHash, &mdLength); assert(mdLength == SHA_DIGEST_LENGTH); HMAC(EVP_sha1(), recv, seedLenght, key, 40, encryptHash, &mdLength); assert(mdLength == SHA_DIGEST_LENGTH); RC4_set_key(&m_clientWotlkDecryptKey, SHA_DIGEST_LENGTH, decryptHash); RC4_set_key(&m_serverWotlkEncryptKey, SHA_DIGEST_LENGTH, encryptHash); RC4(&m_serverWotlkEncryptKey, 1024, pass, pass); RC4(&m_clientWotlkDecryptKey, 1024, pass, pass); m_isInitialized = true; } void WowCrypt::decryptWotlkReceive(uint8_t* data, size_t length) { if (!m_isInitialized) return; RC4(&m_clientWotlkDecryptKey, (unsigned long)length, data, data); } void WowCrypt::encryptWotlkSend(uint8_t* data, size_t length) { if (!m_isInitialized) return; RC4(&m_serverWotlkEncryptKey, (unsigned long)length, data, data); } ////////////////////////////////////////////////////////////////////////////////////////// // Legacy void WowCrypt::initLegacyCrypt() { m_isInitialized = true; } void WowCrypt::decryptLegacyReceive(uint8_t* data, size_t length) { if (!m_isInitialized) return; if (length < cryptedReceiveLength) return; uint8_t x; for (size_t t = 0; t < cryptedReceiveLength; ++t) { m_recvI %= crypKeyVector.size(); x = (data[t] - m_recvJ) ^ crypKeyVector[m_recvI]; ++m_recvI; m_recvJ = data[t]; data[t] = x; } } void WowCrypt::encryptLegacySend(uint8_t* data, size_t length) { if (!m_isInitialized) return; if (length < cryptedSendLength) return; for (size_t t = 0; t < cryptedSendLength; ++t) { m_sendI %= crypKeyVector.size(); data[t] = m_sendJ = (data[t] ^ crypKeyVector[m_sendI]) + m_sendJ; ++m_sendI; } } void WowCrypt::setLegacyKey(uint8_t* key, size_t length) { crypKeyVector.resize(length); std::copy(key, key + length, crypKeyVector.begin()); } void WowCrypt::generateTbcKey(uint8_t* key, uint8_t* sessionkey) { uint8_t seedKey[seedLenght] = { 0x38, 0xA7, 0x83, 0x15, 0xF8, 0x92, 0x25, 0x30, 0x71, 0x98, 0x67, 0xB1, 0x8C, 0x4, 0xE2, 0xAA }; uint8_t firstBuffer[64]; uint8_t secondBuffer[64]; memset(firstBuffer, 0x36, 64); memset(secondBuffer, 0x5C, 64); for (uint8_t i = 0; i < seedLenght; ++i) { firstBuffer[i] = (uint8_t)(seedKey[i] ^ firstBuffer[i]); secondBuffer[i] = (uint8_t)(seedKey[i] ^ secondBuffer[i]); } Sha1Hash sha1; sha1.UpdateData(firstBuffer, 64); sha1.UpdateData(sessionkey, 40); sha1.Finalize(); uint8_t* tempDigest = sha1.GetDigest(); Sha1Hash sha2; sha2.UpdateData(secondBuffer, 64); sha2.UpdateData(tempDigest, SHA_DIGEST_LENGTH); sha2.Finalize(); memcpy(key, sha2.GetDigest(), SHA_DIGEST_LENGTH); }
AscEmu/AscEmu
src/shared/Auth/WowCrypt.cpp
C++
agpl-3.0
5,007
<?php /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to [email protected] so we can send you a copy immediately. * * @category Zend * @package Zend_Service * @subpackage Amazon * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id$ */ /** * @see Zend_Service_Amazon_Item */ //$1 'Zend/Service/Amazon/Item.php'; /** * @category Zend * @package Zend_Service * @subpackage Amazon * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class Zend_Service_Amazon_ResultSet implements SeekableIterator { /** * A DOMNodeList of <Item> elements * * @var DOMNodeList */ protected $_results = null; /** * Amazon Web Service Return Document * * @var DOMDocument */ protected $_dom; /** * XPath Object for $this->_dom * * @var DOMXPath */ protected $_xpath; /** * Current index for SeekableIterator * * @var int */ protected $_currentIndex = 0; /** * Create an instance of Zend_Service_Amazon_ResultSet and create the necessary data objects * * @param DOMDocument $dom * @return void */ public function __construct(DOMDocument $dom) { $this->_dom = $dom; $this->_xpath = new DOMXPath($dom); $this->_xpath->registerNamespace('az', 'http://webservices.amazon.com/AWSECommerceService/2005-10-05'); $this->_results = $this->_xpath->query('//az:Item'); } /** * Total Number of results returned * * @return int Total number of results returned */ public function totalResults() { $result = $this->_xpath->query('//az:TotalResults/text()'); return (int) $result->item(0)->data; } /** * Total Number of pages returned * * @return int Total number of pages returned */ public function totalPages() { $result = $this->_xpath->query('//az:TotalPages/text()'); return (int) $result->item(0)->data; } /** * Implement SeekableIterator::current() * * @return Zend_Service_Amazon_Item */ public function current() { return new Zend_Service_Amazon_Item($this->_results->item($this->_currentIndex)); } /** * Implement SeekableIterator::key() * * @return int */ public function key() { return $this->_currentIndex; } /** * Implement SeekableIterator::next() * * @return void */ public function next() { $this->_currentIndex += 1; } /** * Implement SeekableIterator::rewind() * * @return void */ public function rewind() { $this->_currentIndex = 0; } /** * Implement SeekableIterator::seek() * * @param int $index * @throws OutOfBoundsException * @return void */ public function seek($index) { $indexInt = (int) $index; if ($indexInt >= 0 && (null === $this->_results || $indexInt < $this->_results->length)) { $this->_currentIndex = $indexInt; } else { throw new OutOfBoundsException("Illegal index '$index'"); } } /** * Implement SeekableIterator::valid() * * @return boolean */ public function valid() { return null !== $this->_results && $this->_currentIndex < $this->_results->length; } }
Sparfel/iTop-s-Portal
library/Zend/Service/Amazon/ResultSet.php
PHP
agpl-3.0
4,003
DELETE FROM `weenie` WHERE `class_Id` = 28184; INSERT INTO `weenie` (`class_Id`, `class_Name`, `type`, `last_Modified`) VALUES (28184, 'collectoralchemysholow', 10, '2019-02-10 00:00:00') /* Creature */; INSERT INTO `weenie_properties_int` (`object_Id`, `type`, `value`) VALUES (28184, 1, 16) /* ItemType - Creature */ , (28184, 2, 31) /* CreatureType - Human */ , (28184, 6, -1) /* ItemsCapacity */ , (28184, 7, -1) /* ContainersCapacity */ , (28184, 16, 32) /* ItemUseable - Remote */ , (28184, 25, 5) /* Level */ , (28184, 93, 6292504) /* PhysicsState - ReportCollisions, IgnoreCollisions, Gravity, ReportCollisionsAsEnvironment, EdgeSlide */ , (28184, 95, 8) /* RadarBlipColor - Yellow */ , (28184, 113, 2) /* Gender - Female */ , (28184, 133, 4) /* ShowableOnRadar - ShowAlways */ , (28184, 134, 16) /* PlayerKillerStatus - RubberGlue */ , (28184, 188, 3) /* HeritageGroup - Sho */ , (28184, 8007, 0) /* PCAPRecordedAutonomousMovement */; INSERT INTO `weenie_properties_bool` (`object_Id`, `type`, `value`) VALUES (28184, 1, True ) /* Stuck */ , (28184, 19, False) /* Attackable */; INSERT INTO `weenie_properties_float` (`object_Id`, `type`, `value`) VALUES (28184, 54, 3) /* UseRadius */; INSERT INTO `weenie_properties_string` (`object_Id`, `type`, `value`) VALUES (28184, 1, 'Apprentice Alchemist') /* Name */ , (28184, 5, 'Apprentice Alchemist') /* Template */ , (28184, 8006, 'AAA9AAAAAAA=') /* PCAPRecordedCurrentMotionState */; INSERT INTO `weenie_properties_d_i_d` (`object_Id`, `type`, `value`) VALUES (28184, 1, 0x0200004E) /* Setup */ , (28184, 2, 0x09000001) /* MotionTable */ , (28184, 3, 0x20000002) /* SoundTable */ , (28184, 6, 0x0400007E) /* PaletteBase */ , (28184, 8, 0x06000FEF) /* Icon */ , (28184, 9, 0x05001043) /* EyesTexture */ , (28184, 10, 0x05001086) /* NoseTexture */ , (28184, 11, 0x050010A0) /* MouthTexture */ , (28184, 15, 0x04001FC5) /* HairPalette */ , (28184, 16, 0x040004AF) /* EyesPalette */ , (28184, 17, 0x040004AB) /* SkinPalette */ , (28184, 8001, 9437238) /* PCAPRecordedWeenieHeader - ItemsCapacity, ContainersCapacity, Usable, UseRadius, RadarBlipColor, RadarBehavior */ , (28184, 8003, 4) /* PCAPRecordedObjectDesc - Stuck */ , (28184, 8005, 100355) /* PCAPRecordedPhysicsDesc - CSetup, MTable, STable, Position, Movement */; INSERT INTO `weenie_properties_position` (`object_Id`, `position_Type`, `obj_Cell_Id`, `origin_X`, `origin_Y`, `origin_Z`, `angles_W`, `angles_X`, `angles_Y`, `angles_Z`) VALUES (28184, 8040, 0xDB3B010D, 55.4016, 82.3784, 28.005, 0.874849, 0, 0, -0.484396) /* PCAPRecordedLocation */ /* @teleloc 0xDB3B010D [55.401600 82.378400 28.005000] 0.874849 0.000000 0.000000 -0.484396 */; INSERT INTO `weenie_properties_i_i_d` (`object_Id`, `type`, `value`) VALUES (28184, 8000, 0xDBAC4E38) /* PCAPRecordedObjectIID */; INSERT INTO `weenie_properties_attribute` (`object_Id`, `type`, `init_Level`, `level_From_C_P`, `c_P_Spent`) VALUES (28184, 1, 80, 0, 0) /* Strength */ , (28184, 2, 90, 0, 0) /* Endurance */ , (28184, 3, 70, 0, 0) /* Quickness */ , (28184, 4, 70, 0, 0) /* Coordination */ , (28184, 5, 50, 0, 0) /* Focus */ , (28184, 6, 60, 0, 0) /* Self */; INSERT INTO `weenie_properties_attribute_2nd` (`object_Id`, `type`, `init_Level`, `level_From_C_P`, `c_P_Spent`, `current_Level`) VALUES (28184, 1, 80, 0, 0, 125) /* MaxHealth */ , (28184, 3, 110, 0, 0, 200) /* MaxStamina */ , (28184, 5, 40, 0, 0, 100) /* MaxMana */; INSERT INTO `weenie_properties_palette` (`object_Id`, `sub_Palette_Id`, `offset`, `length`) VALUES (28184, 67109969, 92, 4) , (28184, 67110059, 0, 24) , (28184, 67110063, 32, 8) , (28184, 67110349, 64, 8) , (28184, 67110539, 72, 8) , (28184, 67111246, 160, 8) , (28184, 67112919, 40, 24) , (28184, 67116997, 24, 8); INSERT INTO `weenie_properties_texture_map` (`object_Id`, `index`, `old_Id`, `new_Id`) VALUES (28184, 0, 83889072, 83886685) , (28184, 0, 83889342, 83889386) , (28184, 1, 83887064, 83886241) , (28184, 2, 83887066, 83887051) , (28184, 3, 83889344, 83887054) , (28184, 4, 83887068, 83887054) , (28184, 5, 83887064, 83886241) , (28184, 6, 83887066, 83887051) , (28184, 7, 83889344, 83887054) , (28184, 8, 83887068, 83887054) , (28184, 9, 83887070, 83886781) , (28184, 9, 83887062, 83886686) , (28184, 10, 83887069, 83886782) , (28184, 11, 83887067, 83891213) , (28184, 13, 83887069, 83886782) , (28184, 14, 83887067, 83891213) , (28184, 16, 83886232, 83890685) , (28184, 16, 83886668, 83890243) , (28184, 16, 83886837, 83890310) , (28184, 16, 83886684, 83890336); INSERT INTO `weenie_properties_anim_part` (`object_Id`, `index`, `animation_Id`) VALUES (28184, 0, 16778359) , (28184, 1, 16778430) , (28184, 2, 16778436) , (28184, 3, 16778361) , (28184, 4, 16778426) , (28184, 5, 16778438) , (28184, 6, 16778437) , (28184, 7, 16778360) , (28184, 8, 16778428) , (28184, 9, 16778425) , (28184, 10, 16778431) , (28184, 11, 16778429) , (28184, 12, 16778423) , (28184, 13, 16778434) , (28184, 14, 16778424) , (28184, 15, 16778435) , (28184, 16, 16795640);
ACEmulator/ACE-World
Database/3-Core/9 WeenieDefaults/SQL/Creature/Human/28184 Apprentice Alchemist.sql
SQL
agpl-3.0
5,555
from django.contrib.auth.decorators import login_required from django.shortcuts import get_object_or_404 from django.http import HttpResponseRedirect, Http404 from django.db.models import Q from django.contrib import messages from cc.general.util import render import cc.ripple.api as ripple from cc.profile.models import Profile from cc.relate.forms import EndorseForm, AcknowledgementForm from cc.relate.models import Endorsement from cc.feed.models import FeedItem from cc.general.mail import send_notification from django.utils.translation import ugettext as _ MESSAGES = { 'endorsement_saved': _("Endorsement saved."), 'endorsement_deleted': _("Endorsement deleted."), 'acknowledgement_sent': _("Acknowledgement sent."), } @login_required @render() def endorse_user(request, recipient_username): recipient = get_object_or_404(Profile, user__username=recipient_username) if recipient == request.profile: raise Http404() try: endorsement = Endorsement.objects.get( endorser=request.profile, recipient=recipient) except Endorsement.DoesNotExist: endorsement = None if request.method == 'POST': if 'delete' in request.POST and endorsement: endorsement.delete() messages.info(request, MESSAGES['endorsement_deleted']) return HttpResponseRedirect( endorsement.recipient.get_absolute_url()) form = EndorseForm(request.POST, instance=endorsement, endorser=request.profile, recipient=recipient) if form.is_valid(): is_new = endorsement is None endorsement = form.save() if is_new: send_endorsement_notification(endorsement) messages.info(request, MESSAGES['endorsement_saved']) return HttpResponseRedirect(endorsement.get_absolute_url()) else: form = EndorseForm(instance=endorsement, endorser=request.profile, recipient=recipient) profile = recipient # For profile_base.html. return locals() def send_endorsement_notification(endorsement): subject = _("%s has endorsed you on Villages.cc") % endorsement.endorser send_notification(subject, endorsement.endorser, endorsement.recipient, 'endorsement_notification_email.txt', {'endorsement': endorsement}) @login_required @render() def endorsement(request, endorsement_id): endorsement = get_object_or_404(Endorsement, pk=endorsement_id) return locals() @login_required @render() def relationships(request): accounts = ripple.get_user_accounts(request.profile) return locals() @login_required @render() def relationship(request, partner_username): partner = get_object_or_404(Profile, user__username=partner_username) if partner == request.profile: raise Http404 # Can't have relationship with yourself. account = request.profile.account(partner) if account: entries = account.entries balance = account.balance else: entries = [] balance = 0 profile = partner # For profile_base.html. return locals() @login_required @render() def acknowledge_user(request, recipient_username): recipient = get_object_or_404(Profile, user__username=recipient_username) if recipient == request.profile: raise Http404 # TODO: Don't recompute max_amount on form submit? Cache, or put in form # as hidden field? max_amount = ripple.max_payment(request.profile, recipient) if request.method == 'POST': form = AcknowledgementForm(request.POST, max_ripple=max_amount) if form.is_valid(): acknowledgement = form.send_acknowledgement( request.profile, recipient) send_acknowledgement_notification(acknowledgement) messages.info(request, MESSAGES['acknowledgement_sent']) return HttpResponseRedirect(acknowledgement.get_absolute_url()) else: form = AcknowledgementForm(max_ripple=max_amount, initial=request.GET) can_ripple = max_amount > 0 profile = recipient # For profile_base.html. return locals() def send_acknowledgement_notification(acknowledgement): subject = _("%s has acknowledged you on Villages.cc") % ( acknowledgement.payer) send_notification(subject, acknowledgement.payer, acknowledgement.recipient, 'acknowledgement_notification_email.txt', {'acknowledgement': acknowledgement}) @login_required @render() def view_acknowledgement(request, payment_id): try: payment = ripple.get_payment(payment_id) except ripple.RipplePayment.DoesNotExist: raise Http404 entries = payment.entries_for_user(request.profile) if not entries: raise Http404 # Non-participants don't get to see anything. sent_entries = [] received_entries = [] for entry in entries: if entry.amount < 0: sent_entries.append(entry) else: received_entries.append(entry) return locals()
rfugger/villagescc
cc/relate/views.py
Python
agpl-3.0
5,122
<?php if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point'); /********************************************************************************* * The contents of this file are subject to the SugarCRM Master Subscription * Agreement ("License") which can be viewed at * http://www.sugarcrm.com/crm/en/msa/master_subscription_agreement_11_April_2011.pdf * By installing or using this file, You have unconditionally agreed to the * terms and conditions of the License, and You may not use this file except in * compliance with the License. Under the terms of the license, You shall not, * among other things: 1) sublicense, resell, rent, lease, redistribute, assign * or otherwise transfer Your rights to the Software, and 2) use the Software * for timesharing or service bureau purposes such as hosting the Software for * commercial gain and/or for the benefit of a third party. Use of the Software * may be subject to applicable fees and any use of the Software without first * paying applicable fees is strictly prohibited. You do not have the right to * remove SugarCRM copyrights from the source code or user interface. * * All copies of the Covered Code must include on each user interface screen: * (i) the "Powered by SugarCRM" logo and * (ii) the SugarCRM copyright notice * in the same form as they appear in the distribution. See full license for * requirements. * * Your Warranty, Limitations of liability and Indemnity are expressly stated * in the License. Please refer to the License for the specific language * governing these rights and limitations under the License. Portions created * by SugarCRM are Copyright (C) 2004-2011 SugarCRM, Inc.; All Rights Reserved. ********************************************************************************/ $dictionary['linked_documents'] = array ( 'table' => 'linked_documents' , 'fields' => array ( array('name' =>'id', 'type' =>'varchar', 'len'=>'36') , array('name' =>'parent_id', 'type' =>'varchar', 'len'=>'36') , array('name' =>'parent_type', 'type' =>'varchar', 'len'=>'25') , array('name' =>'document_id', 'type' =>'varchar', 'len'=>'36') , array('name' =>'document_revision_id', 'type' =>'varchar', 'len'=>'36') , array('name' =>'date_modified','type' => 'datetime') , array('name' =>'deleted', 'type' =>'bool', 'len'=>'1', 'default'=>'0', 'required'=>false) ) , 'indices' => array ( array('name' =>'linked_documentspk', 'type' =>'primary', 'fields'=>array('id')), array( 'name' => 'idx_parent_document', 'type' => 'alternate_key', 'fields' => array('parent_type','parent_id','document_id'), ), ) , 'relationships' => array ( 'contracts_documents' => array('lhs_module'=> 'Contracts', 'lhs_table'=> 'contracts', 'lhs_key' => 'id', 'rhs_module'=> 'Documents', 'rhs_table'=> 'documents', 'rhs_key' => 'id', 'relationship_type'=>'many-to-many', 'join_table'=> 'linked_documents', 'join_key_lhs'=>'parent_id', 'join_key_rhs'=>'document_id', 'relationship_role_column'=>'parent_type', 'relationship_role_column_value'=>'Contracts'), 'leads_documents' => array('lhs_module'=> 'Leads', 'lhs_table'=> 'leads', 'lhs_key' => 'id', 'rhs_module'=> 'Documents', 'rhs_table'=> 'documents', 'rhs_key' => 'id', 'relationship_type'=>'many-to-many', 'join_table'=> 'linked_documents', 'join_key_lhs'=>'parent_id', 'join_key_rhs'=>'document_id', 'relationship_role_column'=>'parent_type', 'relationship_role_column_value'=>'Leads'), 'contracttype_documents' => array('lhs_module'=> 'ContractTypes', 'lhs_table'=> 'contract_types', 'lhs_key' => 'id', 'rhs_module'=> 'Documents', 'rhs_table'=> 'documents', 'rhs_key' => 'id', 'relationship_type'=>'many-to-many', 'join_table'=> 'linked_documents', 'join_key_lhs'=>'parent_id', 'join_key_rhs'=>'document_id', 'relationship_role_column'=>'parent_type', 'relationship_role_column_value'=>'ContracTemplates'), ), ); ?>
harish-patel/ecrm
metadata/linked_documentsMetaData.php
PHP
agpl-3.0
4,059
/** * Copyright (C) 2013 The Language Archive, Max Planck Institute for * Psycholinguistics * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation; either version 2 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program; if not, write to the Free Software Foundation, Inc., 59 Temple * Place - Suite 330, Boston, MA 02111-1307, USA. */ package nl.mpi.yams.common.data; import java.io.Serializable; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlRootElement; /** * Created on : Aug 28, 2013, 5:24:13 PM * * @author Peter Withers <[email protected]> */ @XmlRootElement(name = "Highlight") public class DataNodeHighlight implements Serializable { private String dataNodeId = null; private String highlightPath = null; public String getDataNodeId() { return dataNodeId; } @XmlAttribute(name = "ID") public void setDataNodeId(String dataNodeId) { this.dataNodeId = dataNodeId; } public String getHighlightPath() { return highlightPath; } @XmlAttribute(name = "Path") public void setHighlightPath(String highlightPath) { this.highlightPath = highlightPath; } }
TheLanguageArchive/YAMS
common/src/main/java/nl/mpi/yams/common/data/DataNodeHighlight.java
Java
agpl-3.0
1,663
DELETE FROM `weenie` WHERE `class_Id` = 3140; INSERT INTO `weenie` (`class_Id`, `class_Name`, `type`, `last_Modified`) VALUES (3140, 'scrollarcaneenlightenmentself4', 34, '2019-02-10 00:00:00') /* Scroll */; INSERT INTO `weenie_properties_int` (`object_Id`, `type`, `value`) VALUES (3140, 1, 8192) /* ItemType - Writable */ , (3140, 5, 30) /* EncumbranceVal */ , (3140, 16, 8) /* ItemUseable - Contained */ , (3140, 19, 100) /* Value */ , (3140, 93, 1044) /* PhysicsState - Ethereal, IgnoreCollisions, Gravity */ , (3140, 8041, 101) /* PCAPRecordedPlacement - Resting */; INSERT INTO `weenie_properties_bool` (`object_Id`, `type`, `value`) VALUES (3140, 22, True ) /* Inscribable */; INSERT INTO `weenie_properties_float` (`object_Id`, `type`, `value`) VALUES (3140, 39, 1.5) /* DefaultScale */; INSERT INTO `weenie_properties_string` (`object_Id`, `type`, `value`) VALUES (3140, 1, 'Scroll of Arcane Enlightenment Self IV') /* Name */ , (3140, 14, 'Use this item to attempt to learn its spell.') /* Use */ , (3140, 16, 'Inscribed spell: Arcane Enlightenment Self IV Increases the caster''s Arcane Lore skill by 25 points.') /* LongDesc */; INSERT INTO `weenie_properties_d_i_d` (`object_Id`, `type`, `value`) VALUES (3140, 1, 33554826) /* Setup */ , (3140, 8, 100676447) /* Icon */ , (3140, 22, 872415275) /* PhysicsEffectTable */ , (3140, 28, 681) /* Spell - ArcaneEnlightenmentSelf4 */ , (3140, 8001, 6307864) /* PCAPRecordedWeenieHeader - Value, Usable, Container, Burden, Spell */ , (3140, 8003, 18) /* PCAPRecordedObjectDesc - Inscribable, Attackable */ , (3140, 8005, 135297) /* PCAPRecordedPhysicsDesc - CSetup, ObjScale, PeTable, AnimationFrame */; INSERT INTO `weenie_properties_i_i_d` (`object_Id`, `type`, `value`) VALUES (3140, 8000, 3694570528) /* PCAPRecordedObjectIID */;
LtRipley36706/ACE-World
Database/3-Core/9 WeenieDefaults/SQL/Scroll/Writable/03140 Scroll of Arcane Enlightenment Self IV.sql
SQL
agpl-3.0
1,952
// regversion.c - Oniguruma (regular expression library) // Copyright (c) 2002-2020 K.Kosako All rights reserved. // #include "regint.h" #pragma hdrstop extern const char * onig_version(void) { static char s[12]; /*xsnprintf*/slsprintf_s(s, sizeof(s), "%d.%d.%d", ONIGURUMA_VERSION_MAJOR, ONIGURUMA_VERSION_MINOR, ONIGURUMA_VERSION_TEENY); return s; } extern const char * onig_copyright(void) { static char s[58]; /*xsnprintf*/slsprintf_s(s, sizeof(s), "Oniguruma %d.%d.%d : Copyright (C) 2002-2018 K.Kosako", ONIGURUMA_VERSION_MAJOR, ONIGURUMA_VERSION_MINOR, ONIGURUMA_VERSION_TEENY); return s; }
papyrussolution/OpenPapyrus
Src/OSF/oniguruma/src/regversion.c
C
agpl-3.0
608
# -*- coding: utf-8 -*- ############################################################################## # # Ingenieria ADHOC - ADHOC SA # https://launchpad.net/~ingenieria-adhoc # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## import waybill import wizard import travel import vehicle import requirement import res_partner import waybill_expense import account_invoice # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
adhoc-dev/odoo-logistic
addons/logistic_x/__init__.py
Python
agpl-3.0
1,161
// Copyright Dan Schatzberg, 2015. This file is part of Genesis. // Genesis is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Genesis is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // You should have received a copy of the GNU Affero General Public License // along with Genesis. If not, see <http://www.gnu.org/licenses/>. #![allow(dead_code)] use super::ioport; const PORT_BASE: u16 = 0x3F8; // when DLAB = 0 const DATA_REG: u16 = 0; const INT_ENABLE: u16 = 1; // when DLAB = 1 const BAUD_DIV_LSB: u16 = 0; const BAUD_DIV_MSB: u16 = 1; const LINE_CTRL_REG: u16 = 3; const LINE_CTRL_REG_CHARLEN8: u8 = 1 | 1 << 1; const LINE_CTRL_REG_DLAB: u8 = 1 << 7; const LINE_STATUS_REG: u16 = 5; const LINE_STATUS_REG_THR_EMPTY: u8 = 1 << 5; /// Initialize the Serial Port pub fn init() { assert_has_not_been_called!("serial::init() function \ must only be called once"); unsafe { ioport::out(PORT_BASE + INT_ENABLE, 0u8); // disable interrupts // enable dlab ioport::out(PORT_BASE + LINE_CTRL_REG, LINE_CTRL_REG_DLAB); // XXX: hard coded 115200 baud ioport::out(PORT_BASE + BAUD_DIV_LSB, 1u8); ioport::out(PORT_BASE + BAUD_DIV_MSB, 0u8); // XXX: hard coded as 8N1 (8 bits, no parity, one stop bit) ioport::out(PORT_BASE + LINE_CTRL_REG, LINE_CTRL_REG_CHARLEN8); } } unsafe fn is_transmit_empty() -> bool { ioport::inb(PORT_BASE + LINE_STATUS_REG) & LINE_STATUS_REG_THR_EMPTY != 0 } unsafe fn putc(c: u8) { while !is_transmit_empty() {} ioport::out(PORT_BASE + DATA_REG, c); } /// Write `str` to the Serial Port pub unsafe fn write_str(s: &str) { for c in s.bytes() { putc(c); } }
dschatzberg/genesis
src/arch/x86/serial.rs
Rust
agpl-3.0
2,110
# gnu-social-translation This repository serves as a mirror of the GNU social [translation project](https://www.transifex.com/projects/p/gnu-social/) on Transifex. The main GNU social code repository is [here](https://gnu.githost.io/gnu-social/social). ### Instructions - how to use the translations: 1. Make sure you have **Git** and **GNU Make** installed. On Ubuntu, or similar linux distribution, use `sudo apt-get install git make` 2. Clone this repository using `git clone https://github.com/digital-dreamer/gnu-social-translation.git`, or if you already cloned it some time ago, update it using `git pull` 3. Copy the 2 folders you see in the cloned repository (`locale` and `plugins`), and paste them into the folder where you installed your GNU social instance. 4. Go to that folder (where GNU social is installed) and run this command: `make translations` If you encounter any problems, please go to the issues section of this repository and open a new issue. ----- [GNU social](http://gnu.io/social/) is a decentralized social network software that you can install on your own server. We give you the freedom to reveal as much, or as little, information about you to other sites as you wish... True to GNU itself, social is licensed under the GNU Affero General Public License.
digital-dreamer/gnu-social-translation
README.md
Markdown
agpl-3.0
1,296
/* * JBILLING CONFIDENTIAL * _____________________ * * [2003] - [2012] Enterprise jBilling Software Ltd. * All Rights Reserved. * * NOTICE: All information contained herein is, and remains * the property of Enterprise jBilling Software. * The intellectual and technical concepts contained * herein are proprietary to Enterprise jBilling Software * and are protected by trade secret or copyright law. * Dissemination of this information or reproduction of this material * is strictly forbidden. */ package com.sapienter.jbilling.server.pluggableTask.admin; import java.util.ArrayList; import java.util.List; import org.apache.commons.collections.iterators.ArrayListIterator; import org.apache.log4j.Logger; import com.sapienter.jbilling.common.SessionInternalError; import com.sapienter.jbilling.server.pluggableTask.PluggableTask; import com.sapienter.jbilling.server.util.Constants; import com.sapienter.jbilling.server.util.Context; import com.sapienter.jbilling.server.util.audit.EventLogger; public class PluggableTaskBL<T> { private static final Logger LOG = Logger.getLogger(PluggableTaskBL.class); private EventLogger eLogger = null; private PluggableTaskDAS das = null; private PluggableTaskParameterDAS dasParameter = null; private PluggableTaskDTO pluggableTask = null; public PluggableTaskBL(Integer pluggableTaskId) { init(); set(pluggableTaskId); } public PluggableTaskBL() { init(); } private void init() { eLogger = EventLogger.getInstance(); das = (PluggableTaskDAS) Context.getBean(Context.Name.PLUGGABLE_TASK_DAS); dasParameter = new PluggableTaskParameterDAS(); } public void set(Integer id) { pluggableTask = das.find(id); } public void set(Integer entityId, Integer typeId) { pluggableTask = das.findByEntityType(entityId, typeId); } public void set(PluggableTaskDTO task) { pluggableTask = task; } public PluggableTaskDTO getDTO() { return pluggableTask; } public int create(Integer executorId, PluggableTaskDTO dto) { validate(dto); LOG.debug("Creating a new pluggable task row " + dto); pluggableTask = das.save(dto); eLogger.audit(executorId, null, Constants.TABLE_PLUGGABLE_TASK, pluggableTask.getId(), EventLogger.MODULE_TASK_MAINTENANCE, EventLogger.ROW_CREATED, null, null, null); return pluggableTask.getId(); } public void createParameter(Integer taskId, PluggableTaskParameterDTO dto) { PluggableTaskDTO task = das.find(taskId); dto.setTask(task); task.getParameters().add(dasParameter.save(dto)); // clear the rules cache (just in case this plug-in was ruled based) PluggableTask.invalidateRuleCache(taskId); } public void update(Integer executorId, PluggableTaskDTO dto) { if (dto == null || dto.getId() == null) { throw new SessionInternalError("task to update can't be null"); } validate(dto); List<PluggableTaskParameterDTO> parameterDTOList = dasParameter.findAllByTask(dto); for (PluggableTaskParameterDTO param: dto.getParameters()) { parameterDTOList.remove(dasParameter.find(param.getId())); param.expandValue(); } for (PluggableTaskParameterDTO param: parameterDTOList){ dasParameter.delete(param); } LOG.debug("updating " + dto); pluggableTask = das.save(dto); eLogger.audit(executorId, null , Constants.TABLE_PLUGGABLE_TASK, dto.getId(), EventLogger.MODULE_TASK_MAINTENANCE, EventLogger.ROW_UPDATED, null, null, null); // clear the rules cache (just in case this plug-in was ruled based) PluggableTask.invalidateRuleCache(dto.getId()); das.invalidateCache(); // 3rd level cache pluggableTask.populateParamValues(); } public void delete(Integer executor) { eLogger.audit(executor, null, Constants.TABLE_PLUGGABLE_TASK, pluggableTask.getId(), EventLogger.MODULE_TASK_MAINTENANCE, EventLogger.ROW_DELETED, null, null, null); das.delete(pluggableTask); // clear the rules cache (just in case this plug-in was ruled based) PluggableTask.invalidateRuleCache(pluggableTask.getId()); } public void deleteParameter(Integer executor, Integer id) { eLogger.audit(executor, null, Constants.TABLE_PLUGGABLE_TASK_PARAMETER, id, EventLogger.MODULE_TASK_MAINTENANCE, EventLogger.ROW_DELETED, null, null, null); PluggableTaskParameterDTO toDelete = dasParameter.find(id); toDelete.getTask().getParameters().remove(toDelete); // clear the rules cache (just in case this plug-in was ruled based) PluggableTask.invalidateRuleCache(toDelete.getTask().getId()); dasParameter.delete(toDelete); } public void updateParameters(PluggableTaskDTO dto) { // update the parameters from the dto for (PluggableTaskParameterDTO parameter: dto.getParameters()) { updateParameter(parameter); } } private void updateParameter(PluggableTaskParameterDTO dto) { dto.expandValue(); dasParameter.save(dto); // clear the rules cache (just in case this plug-in was ruled based) PluggableTask.invalidateRuleCache(dto.getTask().getId()); } public T instantiateTask() throws PluggableTaskException { PluggableTaskDTO localTask = getDTO(); String fqn = localTask.getType().getClassName(); T result; try { Class taskClazz = Class.forName(fqn); //.asSubclass(result.getClass()); result = (T) taskClazz.newInstance(); } catch (ClassCastException e) { throw new PluggableTaskException("Task id: " + pluggableTask.getId() + ": implementation class does not implements PaymentTask:" + fqn, e); } catch (InstantiationException e) { throw new PluggableTaskException("Task id: " + pluggableTask.getId() + ": Can not instantiate : " + fqn, e); } catch (IllegalAccessException e) { throw new PluggableTaskException("Task id: " + pluggableTask.getId() + ": Can not find public constructor for : " + fqn, e); } catch (ClassNotFoundException e) { throw new PluggableTaskException("Task id: " + pluggableTask.getId() + ": Unknown class: " + fqn, e); } if (result instanceof PluggableTask) { PluggableTask pluggable = (PluggableTask) result; pluggable.initializeParamters(localTask); } else { throw new PluggableTaskException("Plug-in has to extend PluggableTask " + pluggableTask.getId()); } return result; } private void validate(PluggableTaskDTO task) { List<ParameterDescription> missingParameters = new ArrayList<ParameterDescription>(); try { // start by getting an instance of this type PluggableTask instance = (PluggableTask) PluggableTaskManager.getInstance( task.getType().getClassName(), task.getType().getCategory().getInterfaceName()); // loop through the descriptions of parameters for (ParameterDescription param: instance.getParameterDescriptions()) { if (param.isRequired()) { if(task.getParameters()== null || task.getParameters().size() == 0) { missingParameters.add(param); } else { boolean found = false; for (PluggableTaskParameterDTO parameter:task.getParameters()) { if (parameter.getName().equals(param.getName()) && parameter.getStrValue() != null && parameter.getStrValue().trim().length() > 0) { found = true; break; } } if (!found) { missingParameters.add(param); } } } } } catch (PluggableTaskException e) { LOG.error("Getting instance of plug-in for validation", e); throw new SessionInternalError("Validating plug-in"); } if (missingParameters.size() > 0) { SessionInternalError exception = new SessionInternalError("Validation of new plug-in"); String messages[] = new String[missingParameters.size()]; int f=0; for (ParameterDescription param: missingParameters) { messages[f] = new String("PluggableTaskWS,parameter,plugins.error.required_parameter," + param.getName()); f++; } exception.setErrorMessages(messages); throw exception; } // now validate that the processing order is not already taken boolean nonUniqueResult= false; try { PluggableTaskDTO samePlugin = das.findByEntityCategoryOrder(task.getEntityId(), task.getType().getCategory().getId(), task.getProcessingOrder()); if (samePlugin != null && !samePlugin.getId().equals(task.getId())) { nonUniqueResult=true; } } catch (Exception e) { nonUniqueResult=true; } if (nonUniqueResult) { SessionInternalError exception = new SessionInternalError("Validation of new plug-in"); exception.setErrorMessages(new String[] { "PluggableTaskWS,processingOrder,plugins.error.same_order," + task.getProcessingOrder()}); throw exception; } } }
rahith/ComtalkA-S
src/java/com/sapienter/jbilling/server/pluggableTask/admin/PluggableTaskBL.java
Java
agpl-3.0
10,431
<?php define('DB_ADAPTER', 'mysql'); define('DB_HOST', 'localhost'); define('DB_USER', 'root'); define('DB_PASS', 'e3i71BFGRqda3'); define('DB_NAME', 'ppdev_mf'); define('DB_PREFIX', 'pp088_'); define('DB_CHARSET', 'utf8'); define('DB_PERSIST', false); return true; ?>
pjsangat/ppdev
config/config_mf.php
PHP
agpl-3.0
295
class CreateDidNotVotes < ActiveRecord::Migration[4.2] def change create_table :did_not_votes do |t| t.references :user t.references :motion t.timestamps end add_index :did_not_votes, :user_id add_index :did_not_votes, :motion_id end end
piratas-ar/loomio
db/migrate/20120501012737_create_did_not_votes.rb
Ruby
agpl-3.0
277
module Isi module FreeChat Isi::db_hello __FILE__, name require 'pathname' ModuleRootDir = Pathname(__FILE__).dirname + name.split('::').last # require all files for this module require ModuleRootDir + 'protocol' # this should include everything else require ModuleRootDir + 'free_chat_u_i' # except for this Isi::db_bye __FILE__, name end end
HistoricalValue/freechat
isi/freechat.rb
Ruby
agpl-3.0
385
# Copyright 2015-2018 Camptocamp SA # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html) from . import mass_reconcile from . import advanced_reconciliation
OCA/bank-statement-reconcile
account_mass_reconcile_ref_deep_search/models/__init__.py
Python
agpl-3.0
171
# == Schema Information # # Table name: terms # # id :integer not null, primary key # sourced_id :string # title :string # start_at :datetime # end_at :datetime # created_at :datetime not null # updated_at :datetime not null # class Term < ApplicationRecord has_many :courses, -> { where('courses.enabled = ?', true) } validates :end_at, presence: true validates :sourced_id, uniqueness: true, allow_nil: true validates :start_at, presence: true validates :title, presence: true validates :title, uniqueness: true validate :end_at_is_after_start_at # ==================================================================== # Public Functions # ==================================================================== def self.sync_roster(rterms) # Create and Update with OneRoster data # Synchronous term condition now = Time.zone.now rterms.select!{|rt| ((Time.zone.parse(rt['startDate']) - 1.month)...Time.zone.parse(rt['endDate'])).cover? now} ids = [] rterms.each do |rt| term = Term.find_or_initialize_by(sourced_id: rt['sourcedId']) if term.update_attributes(title: rt['title'], start_at: rt['startDate'], end_at: rt['endDate']) ids.push({id: term.id, sourced_id: term.sourced_id, status: term.status}) end end ids end def self.creatable?(user_id) # Not permitted when SYSTEM_ROSTER_SYNC is :suspended return false if %i[on off].exclude? SYSTEM_ROSTER_SYNC user = User.find user_id user.system_staff? end def destroyable?(user_id) return false if new_record? return false unless courses.size.zero? updatable? user_id end def updatable?(user_id) return false if SYSTEM_ROSTER_SYNC == :on && sourced_id.blank? return false if SYSTEM_ROSTER_SYNC == :off && sourced_id.present? Term.creatable? user_id end def status now = Time.zone.now if now < start_at 'draft' elsif end_at <= now 'archived' else 'open' end end def to_roster_hash hash = { title: self.title, type: 'term', startDate: self.start_at, endDate: self.end_at, schoolYear: self.end_at.year } end # ==================================================================== # Private Functions # ==================================================================== private def end_at_is_after_start_at # start_at: inclusive start date for the term # end_at: exclusive end date for the term if start_at.present? && end_at.present? errors.add(:end_at) unless end_at > start_at end end end
lepo-project/lepo
app/models/term.rb
Ruby
agpl-3.0
2,652
OC.L10N.register( "templateeditor", { "Could not load template" : "امکان بارگذاری قالب وجود ندارد", "Saved" : "ذخیره شد", "Reset" : "تنظیم مجدد", "An error occurred" : "یک خطا رخ داده است", "Sharing email - public link shares (HTML)" : "ایمیل اشتراک گذاری-لینک عمومی اشتراک گذاری(HTML)", "Sharing email - public link shares (plain text fallback)" : "ایمیل اشتراک گذاری-لینک عمومی اشتراک گذاری(plain text fallback)", "Sharing email (HTML)" : "اشتراک‎گذاری ایمیل (HTML)", "Sharing email (plain text fallback)" : "ایمیل اشتراک گذاری (plain text fallback)", "Lost password mail" : "ایمیل فراموش کردن رمز عبور", "New user email (HTML)" : "ایمیل کاربری جدید (HTML)", "New user email (plain text fallback)" : "ایمیل کاربر جدید (plain text fallback)", "Activity notification mail" : "ایمیل هشدار فعالیت", "Mail Templates" : "قالب‌های ایمیل", "Theme" : "تم", "Template" : "قالب", "Please choose a template" : "لطفا یک قالب انتخاب کنید", "Save" : "ذخیره" }, "nplurals=1; plural=0;");
jacklicn/owncloud
apps/templateeditor/l10n/fa.js
JavaScript
agpl-3.0
1,324
# -*- coding: utf-8 -*- # © 2014 Elico Corp (https://www.elico-corp.com) # Licence AGPL-3.0 or later(http://www.gnu.org/licenses/agpl.html) import invoice
Elico-Corp/openerp-7.0
sale_bom_split_anglo_saxon/__init__.py
Python
agpl-3.0
158
<!doctype html> <html class="no-js" lang=""> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <title>{% block title %}{% endblock %}</title> <meta name="description" content=""> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="{{ request.static_url('cnxpublishing:static/css/normalize.min.css') }}"> <link rel="stylesheet" href="{{ request.static_url('cnxpublishing:static/css/main.css') }}"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <script src="{{ request.static_url('cnxpublishing:static/js/vendor/modernizr-2.8.3.min.js') }}"></script> {% block head %} {% endblock %} </head> <body> <div id='content'> {% block content %} {% endblock %} </div> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script> <script>window.jQuery || document.write('<script src="' + "{{ request.static_url('cnxpublishing:static/js/vendor/jquery-1.11.2.min.js') }}" + '"><\/script>')</script> <script src="{{ request.static_url('cnxpublishing:static/js/plugins.js') }}"></script> <script src="{{ request.static_url('cnxpublishing:static/js/main.js') }}"></script> <script> {% block script %} {% endblock %} </script> </body> </html>
Connexions/cnx-publishing
cnxpublishing/views/templates/base.html
HTML
agpl-3.0
1,416
<?php /* * This file is part of the FOSUserBundle package. * * (c) FriendsOfSymfony <http://friendsofsymfony.github.com/> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace FOS\UserBundle\Model; /** * Interface to be implemented by group managers. This adds an additional level * of abstraction between your application, and the actual repository. * * All changes to groups should happen through this interface. * * @author Christophe Coevoet <[email protected]> */ interface GroupManagerInterface { /** * Returns an empty group instance. * * @param string $name * @return GroupInterface */ function createGroup($name); /** * Deletes a group. * * @param GroupInterface $group * @return void */ function deleteGroup(GroupInterface $group); /** * Finds one group by the given criteria. * * @param array $criteria * @return GroupInterface */ function findGroupBy(array $criteria); /** * Finds a group by name. * * @param string $name * @return GroupInterface */ function findGroupByName($name); /** * Returns a collection with all user instances. * * @return \Traversable */ function findGroups(); /** * Returns the group's fully qualified class name. * * @return string */ function getClass(); /** * Updates a group. * * @param GroupInterface $group */ function updateGroup(GroupInterface $group); }
lolostates/Lap
vendor/bundles/FOS/UserBundle/Model/GroupManagerInterface.php
PHP
agpl-3.0
1,483
/* * StatusBarWidget.java * * Copyright (C) 2009-11 by RStudio, Inc. * * This program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ package org.rstudio.studio.client.workbench.views.source.editors.text.status; import com.google.gwt.core.client.GWT; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.user.client.ui.*; import org.rstudio.core.client.widget.IsWidgetWithHeight; public class StatusBarWidget extends Composite implements StatusBar, IsWidgetWithHeight { private int height_; interface Binder extends UiBinder<HorizontalPanel, StatusBarWidget> { } public StatusBarWidget() { Binder binder = GWT.create(Binder.class); HorizontalPanel hpanel = binder.createAndBindUi(this); hpanel.setVerticalAlignment(HorizontalPanel.ALIGN_TOP); hpanel.setCellWidth(hpanel.getWidget(2), "100%"); initWidget(hpanel); height_ = 16; } public int getHeight() { return height_; } public Widget asWidget() { return this; } public StatusBarElement getPosition() { return position_; } public StatusBarElement getFunction() { return function_; } public StatusBarElement getLanguage() { return language_; } public void setFunctionVisible(boolean visible) { function_.setContentsVisible(visible); funcIcon_.setVisible(visible); } @UiField StatusBarElementWidget position_; @UiField StatusBarElementWidget function_; @UiField StatusBarElementWidget language_; @UiField Image funcIcon_; }
Sage-Bionetworks/rstudio
src/gwt/src/org/rstudio/studio/client/workbench/views/source/editors/text/status/StatusBarWidget.java
Java
agpl-3.0
1,945
# -- # Kernel/Modules/AgentFAQAdd.pm - agent frontend to add faq articles # Copyright (C) 2001-2014 OTRS AG, http://otrs.com/ # -- # This software comes with ABSOLUTELY NO WARRANTY. For details, see # the enclosed file COPYING for license information (AGPL). If you # did not receive this file, see http://www.gnu.org/licenses/agpl.txt. # -- package Kernel::Modules::AgentFAQAdd; use strict; use warnings; use Kernel::System::FAQ; use Kernel::System::Queue; use Kernel::System::Web::UploadCache; use Kernel::System::Valid; sub new { my ( $Type, %Param ) = @_; # allocate new hash for object my $Self = {%Param}; bless( $Self, $Type ); # check all needed objects for my $Object (qw(ParamObject DBObject LayoutObject ConfigObject LogObject)) { if ( !$Self->{$Object} ) { $Self->{LayoutObject}->FatalError( Message => "Got no $Object!" ); } } # create needed objects $Self->{FAQObject} = Kernel::System::FAQ->new(%Param); $Self->{UploadCacheObject} = Kernel::System::Web::UploadCache->new(%Param); $Self->{ValidObject} = Kernel::System::Valid->new(%Param); $Self->{QueueObject} = Kernel::System::Queue->new(%Param); # get config of frontend module $Self->{Config} = $Self->{ConfigObject}->Get("FAQ::Frontend::$Self->{Action}") || ''; # get form id $Self->{FormID} = $Self->{ParamObject}->GetParam( Param => 'FormID' ); # create form id if ( !$Self->{FormID} ) { $Self->{FormID} = $Self->{UploadCacheObject}->FormIDCreate(); } # set default interface settings $Self->{Interface} = $Self->{FAQObject}->StateTypeGet( Name => 'internal', UserID => $Self->{UserID}, ); $Self->{InterfaceStates} = $Self->{FAQObject}->StateTypeList( Types => $Self->{ConfigObject}->Get('FAQ::Agent::StateTypes'), UserID => $Self->{UserID}, ); $Self->{MultiLanguage} = $Self->{ConfigObject}->Get('FAQ::MultiLanguage'); return $Self; } sub Run { my ( $Self, %Param ) = @_; # permission check if ( !$Self->{AccessRw} ) { return $Self->{LayoutObject}->NoPermission( Message => 'You need rw permission!', WithHeader => 'yes', ); } # get parameters my %GetParam; for my $ParamName ( qw(Title CategoryID StateID LanguageID ValidID Keywords Approved Field1 Field2 Field3 Field4 Field5 Field6 ) ) { $GetParam{$ParamName} = $Self->{ParamObject}->GetParam( Param => $ParamName ); } # get categories (with category long names) where user has rights my $UserCategoriesLongNames = $Self->{FAQObject}->GetUserCategoriesLongNames( Type => 'rw', UserID => $Self->{UserID}, ); # check that there are categories available for this user if ( !$UserCategoriesLongNames || ref $UserCategoriesLongNames ne 'HASH' || !%{$UserCategoriesLongNames} ) { return $Self->{LayoutObject}->ErrorScreen( Message => 'No categories found where user has read/write permissions!', Comment => 'Please contact the admin.', ); } # ------------------------------------------------------------ # # show the faq add screen # ------------------------------------------------------------ # if ( !$Self->{Subaction} ) { # header my $Output = $Self->{LayoutObject}->Header(); $Output .= $Self->{LayoutObject}->NavigationBar(); if ( $Self->{ConfigObject}->Get('FAQ::ApprovalRequired') ) { # get Approval queue name my $ApprovalQueue = $Self->{ConfigObject}->Get('FAQ::ApprovalQueue') || ''; # check if Approval queue exists my $ApprovalQueueID = $Self->{QueueObject}->QueueLookup( Queue => $ApprovalQueue ); # show notification if Approval queue does not exists if ( !$ApprovalQueueID ) { $Output .= $Self->{LayoutObject}->Notify( Priority => 'Error', Info => "FAQ Approval is enabled but queue '$ApprovalQueue' does not exists", Link => '$Env{"Baselink"}Action=AdminSysConfig;Subaction=Edit;' . 'SysConfigSubGroup=Core%3A%3AApproval;SysConfigGroup=FAQ', ); } } # html output $Output .= $Self->_MaskNew( FormID => $Self->{FormID}, UserCategoriesLongNames => $UserCategoriesLongNames, # last viewed category from session (written by faq explorer) CategoryID => $Self->{LastViewedCategory}, ); # footer $Output .= $Self->{LayoutObject}->Footer(); return $Output; } # ------------------------------------------------------------ # # save the faq # ------------------------------------------------------------ # elsif ( $Self->{Subaction} eq 'Save' ) { # challenge token check for write action $Self->{LayoutObject}->ChallengeTokenCheck(); # header my $Output = $Self->{LayoutObject}->Header(); $Output .= $Self->{LayoutObject}->NavigationBar(); # check required parameters my %Error; for my $ParamName (qw(Title CategoryID)) { # if required field is not given, add server error class if ( !$GetParam{$ParamName} ) { $Error{ $ParamName . 'ServerError' } = 'ServerError'; } } # check if an attachment must be deleted my @AttachmentIDs = map { my ($ID) = $_ =~ m{ \A AttachmentDelete (\d+) \z }xms; $ID ? $ID : (); } $Self->{ParamObject}->GetParamNames(); COUNT: for my $Count ( reverse sort @AttachmentIDs ) { # check if the delete button was pressed for this attachment my $Delete = $Self->{ParamObject}->GetParam( Param => "AttachmentDelete$Count" ); # check next attachment if it was not pressed next COUNT if !$Delete; # remember that we need to show the page again $Error{Attachment} = 1; # remove the attachment from the upload cache $Self->{UploadCacheObject}->FormIDRemoveFile( FormID => $Self->{FormID}, FileID => $Count, ); } # check if there was an attachment upload if ( $Self->{ParamObject}->GetParam( Param => 'AttachmentUpload' ) ) { # remember that we need to show the page again $Error{Attachment} = 1; # get the uploaded attachment my %UploadStuff = $Self->{ParamObject}->GetUploadAll( Param => 'FileUpload', Source => 'string', ); # add attachment to the upload cache $Self->{UploadCacheObject}->FormIDAddFile( FormID => $Self->{FormID}, %UploadStuff, ); } # send server error if any required parameter is missing # or an attachment was deleted or uploaded if (%Error) { # if there was an attachment delete or upload # we do not want to show validation errors for other fields if ( $Error{Attachment} ) { %Error = (); } # get all attachments meta data my @Attachments = $Self->{UploadCacheObject}->FormIDGetAllFilesMeta( FormID => $Self->{FormID}, ); if ( $Self->{ConfigObject}->Get('FAQ::ApprovalRequired') ) { # get Approval queue name my $ApprovalQueue = $Self->{ConfigObject}->Get('FAQ::ApprovalQueue') || ''; # check if Approval queue exists my $ApprovalQueueID = $Self->{QueueObject}->QueueLookup( Queue => $ApprovalQueue ); # show notification if Approval queue does not exists if ( !$ApprovalQueueID ) { $Output .= $Self->{LayoutObject}->Notify( Priority => 'Error', Info => "FAQ Approval is enabled but queue '$ApprovalQueue' does not exists", Link => '$Env{"Baselink"}Action=AdminSysConfig;Subaction=Edit;' . 'SysConfigSubGroup=Core%3A%3AApproval;SysConfigGroup=FAQ', ); } } # html output $Output .= $Self->_MaskNew( UserCategoriesLongNames => $UserCategoriesLongNames, Attachments => \@Attachments, %GetParam, %Error, FormID => $Self->{FormID}, ); # footer $Output .= $Self->{LayoutObject}->Footer(); return $Output; } # add the new faq article my $FAQID = $Self->{FAQObject}->FAQAdd( %GetParam, UserID => $Self->{UserID}, ); # show error if faq could not be added if ( !$FAQID ) { return $Self->{LayoutObject}->ErrorScreen(); } # get all attachments from upload cache my @Attachments = $Self->{UploadCacheObject}->FormIDGetAllFilesData( FormID => $Self->{FormID}, ); # write attachments ATTACHMENT: for my $Attachment (@Attachments) { # check if attachment is an inline attachment my $Inline = 0; if ( $Attachment->{ContentID} ) { # remember that it is inline $Inline = 1; # remember if this inline attachment is used in any faq article my $ContentIDFound; # check all fields for content id FIELD: for my $Number ( 1 .. 6 ) { # get faq field my $Field = $GetParam{ 'Field' . $Number }; # skip empty fields next FIELD if !$Field; # skip fields that do not contain the content id next FIELD if $Field !~ m{ $Attachment->{ContentID} }xms; # found the content id $ContentIDFound = 1; # we do not need to search further last FIELD; } # we do not want to keep this attachment, # because it was deleted in the richt text editor next ATTACHMENT if !$ContentIDFound; } # add attachment my $FileID = $Self->{FAQObject}->AttachmentAdd( %{$Attachment}, ItemID => $FAQID, Inline => $Inline, UserID => $Self->{UserID}, ); # check error if ( !$FileID ) { return $Self->{LayoutObject}->FatalError(); } next ATTACHMENT if !$Inline; next ATTACHMENT if !$Self->{LayoutObject}->{BrowserRichText}; # rewrite the URLs of the inline images for the uploaded pictures my $Ok = $Self->{FAQObject}->FAQInlineAttachmentURLUpdate( Attachment => $Attachment, FormID => $Self->{FormID}, ItemID => $FAQID, FileID => $FileID, UserID => $Self->{UserID}, ); # check error if ( !$Ok ) { $Self->{LogObject}->Log( Priority => 'error', Message => "Could not update the inline image URLs " . "for FAQ Item# '$FAQID'!", ); } } # delete the upload cache $Self->{UploadCacheObject}->FormIDRemove( FormID => $Self->{FormID} ); # redirect to FAQ zoom return $Self->{LayoutObject}->Redirect( OP => 'Action=AgentFAQZoom;ItemID=' . $FAQID ); } } sub _MaskNew { my ( $Self, %Param ) = @_; # get list type my $TreeView = 0; if ( $Self->{ConfigObject}->Get('Ticket::Frontend::ListType') eq 'tree' ) { $TreeView = 1; } # get valid list my %ValidList = $Self->{ValidObject}->ValidList(); my %ValidListReverse = reverse %ValidList; my %Data; # build valid selection $Data{ValidOption} = $Self->{LayoutObject}->BuildSelection( Data => \%ValidList, Name => 'ValidID', SelectedID => $Param{ValidID} || $ValidListReverse{valid}, ); # set no server error class as default $Param{CategoryIDServerError} ||= ''; # build category selection $Data{CategoryOption} = $Self->{LayoutObject}->BuildSelection( Data => $Param{UserCategoriesLongNames}, Name => 'CategoryID', SelectedID => $Param{CategoryID}, PossibleNone => 1, Class => 'Validate_Required ' . $Param{CategoryIDServerError}, Translation => 0, TreeView => 1, ); # get the language list my %Languages = $Self->{FAQObject}->LanguageList( UserID => $Self->{UserID}, ); # get the selected language my $SelectedLanguage; if ( $Param{LanguageID} && $Languages{ $Param{LanguageID} } ) { # get language from given language id $SelectedLanguage = $Languages{ $Param{LanguageID} }; } else { # use the user language, or if not found 'en' $SelectedLanguage = $Self->{LayoutObject}->{UserLanguage} || 'en'; # get user language ID my $SelectedLanguageID = $Self->{FAQObject}->LanguageLookup( Name => $SelectedLanguage ); # check if LanduageID does not exsits if ( !$SelectedLanguageID ) { # get the lowest language ID my @LanguageIDs = sort keys %Languages; $SelectedLanguageID = $LanguageIDs[0]; # set the language with lowest language ID as selected language $SelectedLanguage = $Languages{$SelectedLanguageID}; } } # build the language selection $Data{LanguageOption} = $Self->{LayoutObject}->BuildSelection( Data => \%Languages, Name => 'LanguageID', SelectedValue => $SelectedLanguage, Translation => 0, ); # get the states list my %States = $Self->{FAQObject}->StateList( UserID => $Self->{UserID}, ); # get the selected state my $SelectedState; if ( $Param{StateID} && $States{ $Param{StateID} } ) { # get state from given state id $SelectedState = $States{ $Param{StateID} }; } else { # get default state $SelectedState = $Self->{ConfigObject}->Get('FAQ::Default::State') || 'internal (agent)'; } # build the state selection $Data{StateOption} = $Self->{LayoutObject}->BuildSelection( Data => \%States, Name => 'StateID', SelectedValue => $SelectedState, Translation => 1, ); # show faq add screen $Self->{LayoutObject}->Block( Name => 'FAQAdd', Data => { %Param, %Data, }, ); # show languages field if ( $Self->{MultiLanguage} ) { $Self->{LayoutObject}->Block( Name => 'Language', Data => { %Param, %Data, }, ); } else { # get default language my $DefaultLanguage = $Self->{ConfigObject}->Get('FAQ::Default::Language') || 'en'; # get default language ID my $LanguageID = $Self->{FAQObject}->LanguageLookup( Name => $DefaultLanguage, ); # create default language if it was deleted or does not exists if ( !$LanguageID ) { my $InsertLanguage = $Self->{FAQObject}->LanguageAdd( Name => $DefaultLanguage, UserID => 1, ); if ( !$InsertLanguage ) { # return with error screen return $Self->{LayoutObject}->ErrorScreen( Message => "No default language found and can't create a new one.", Comment => 'Please contact the admin.', ); } # get default language ID $LanguageID = $Self->{FAQObject}->LanguageLookup( Name => $DefaultLanguage, ); } $Param{LanguageID} = $LanguageID; $Self->{LayoutObject}->Block( Name => 'NoLanguage', Data => { %Param, %Data, }, ); } # show approval field if ( $Self->{ConfigObject}->Get('FAQ::ApprovalRequired') ) { # check permission my %Groups = reverse $Self->{GroupObject}->GroupMemberList( UserID => $Self->{UserID}, Type => 'ro', Result => 'HASH', ); # get the faq approval group from config my $ApprovalGroup = $Self->{ConfigObject}->Get('FAQ::ApprovalGroup') || ''; # build the approval selection if user is in the approval group if ( $Groups{$ApprovalGroup} ) { $Data{ApprovalOption} = $Self->{LayoutObject}->BuildSelection( Name => 'Approved', Data => { 0 => 'No', 1 => 'Yes', }, SelectedID => $Param{Approved} || 0, ); $Self->{LayoutObject}->Block( Name => 'Approval', Data => {%Data}, ); } } # show the attachment upload button $Self->{LayoutObject}->Block( Name => 'AttachmentUpload', Data => {%Param}, ); # show attachments ATTACHMENT: for my $Attachment ( @{ $Param{Attachments} } ) { # do not show inline images as attachments # (they have a content id) if ( $Attachment->{ContentID} && $Self->{LayoutObject}->{BrowserRichText} ) { next ATTACHMENT; } $Self->{LayoutObject}->Block( Name => 'Attachment', Data => $Attachment, ); } # add rich text editor javascript # only if activated and the browser can handle it # otherwise just a textarea is shown if ( $Self->{LayoutObject}->{BrowserRichText} ) { # use height/width defined for this screen $Param{RichTextHeight} = $Self->{Config}->{RichTextHeight} || 0; $Param{RichTextWidth} = $Self->{Config}->{RichTextWidth} || 0; $Self->{LayoutObject}->Block( Name => 'RichText', Data => {%Param}, ); } # show FAQ Content $Self->{LayoutObject}->FAQContentShow( FAQObject => $Self->{FAQObject}, InterfaceStates => $Self->{InterfaceStates}, FAQData => {%Param}, UserID => $Self->{UserID}, ); # generate output return $Self->{LayoutObject}->Output( TemplateFile => 'AgentFAQAdd', Data => \%Param, ); } 1;
NeverMin/wuxiapptec
Kernel/Modules/AgentFAQAdd.pm
Perl
agpl-3.0
19,297
/* Copyright (c) 2003-2020, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license */ CKEDITOR.plugins.setLang( 'specialchar', 'cs', { options: 'Nastavení speciálních znaků', title: 'Výběr speciálního znaku', toolbar: 'Vložit speciální znaky' } );
astrobin/astrobin
astrobin/static/astrobin/ckeditor/plugins/specialchar/lang/cs.js
JavaScript
agpl-3.0
339
<div class="row"> <div class="span9"> <span id="long_description_text_1"></span> </div> </div> <div class="row"> <div class="span9"> <span id="long_description_text_2"></span> </div> </div> <script type="text/javascript" src="/static/js/pybossa/pybossa.js"></script> <script type="text/javascript" src="/cellspotting/static/js/jquery.i18n.min.js"></script> <script type="text/javascript" src="/cellspotting/static/js/cellspotting-internationalization.js"></script> <script type="text/javascript"> $("[rel=tooltip]").tooltip(); </script> <script> var language; var dict; pybossa.setEndpoint("/pybossa"); pybossa.getSettings().done(function(data){ language = data.language; if (language == null) { // Detect browser language var userLang = navigator.language || navigator.userLanguage; if (userLang.indexOf("en") != -1) language = "en"; else if (userLang.indexOf("es") != -1) language = "es"; else if (userLang.indexOf("pt") != -1) language = "pt"; } console.log("1"+language); switch(language){ case "en": dict = en_US_dict; break; case "pt": dict = pt_dict; break; case "es": dict = es_dict; break; default: dict = default_dict; } $.i18n.setDictionary(dict); $('#long_description_text_1').html($.i18n._('long_description_text_1')); $('#long_description_text_2').html($.i18n._('long_description_text_2')); }); </script>
Ibercivis/app-cellspotting
long_description.html
HTML
agpl-3.0
1,674
/* * Copyright 2011 Witoslaw Koczewsi <[email protected]>, Artjom Kochtchi * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero * General Public License as published by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public * License for more details. * * You should have received a copy of the GNU General Public License along with this program. If not, see * <http://www.gnu.org/licenses/>. */ package scrum.client.communication; import ilarkesto.core.logging.Log; import ilarkesto.core.time.Tm; import java.util.LinkedList; import scrum.client.DataTransferObject; import scrum.client.core.ApplicationStartedEvent; import scrum.client.core.ApplicationStartedHandler; import scrum.client.project.Requirement; import scrum.client.workspace.BlockCollapsedEvent; import scrum.client.workspace.BlockCollapsedHandler; import scrum.client.workspace.BlockExpandedEvent; import scrum.client.workspace.BlockExpandedHandler; import com.google.gwt.user.client.Timer; public class Pinger extends GPinger implements ServerDataReceivedHandler, BlockExpandedHandler, BlockCollapsedHandler, ApplicationStartedHandler { private static Log log = Log.get(Pinger.class); public static final int MIN_DELAY = 1000; public static final int MAX_DELAY = 5000; private Timer timer; private int maxDelay = MAX_DELAY; private long lastDataReceiveTime = Tm.getCurrentTimeMillis(); private LinkedList<Long> pingTimes = new LinkedList<Long>(); private boolean disabled; @Override public void onApplicationStarted(ApplicationStartedEvent event) { timer = new Timer() { @Override public void run() { if (!disabled && !serviceCaller.containsServiceCall(PingServiceCall.class)) { final long start = Tm.getCurrentTimeMillis(); new PingServiceCall().execute(new Runnable() { @Override public void run() { long time = Tm.getCurrentTimeMillis() - start; pingTimes.add(time); if (pingTimes.size() > 10) pingTimes.removeFirst(); } }); } reschedule(); } }; reschedule(); } public void setDisabled(boolean disabled) { this.disabled = disabled; } public boolean isDisabled() { return disabled; } public void shutdown() { log.info("Shutting down"); if (timer == null) return; timer.cancel(); timer = null; } @Override public void onServerDataReceived(ServerDataReceivedEvent event) { DataTransferObject data = event.getData(); if (data.containsEntities()) { lastDataReceiveTime = Tm.getCurrentTimeMillis(); reschedule(); } } @Override public void onBlockCollapsed(BlockCollapsedEvent event) { deactivatePowerPolling(); } @Override public void onBlockExpanded(BlockExpandedEvent event) { Object object = event.getObject(); if (object instanceof Requirement) { Requirement requirement = (Requirement) object; if (requirement.isWorkEstimationVotingActive()) activatePowerPolling(); } } public void reschedule() { if (timer == null) return; long idle = Tm.getCurrentTimeMillis() - lastDataReceiveTime; idle = (int) (idle * 0.15); if (idle < MIN_DELAY) idle = MIN_DELAY; if (idle > maxDelay) idle = maxDelay; timer.scheduleRepeating((int) idle); } private void activatePowerPolling() { maxDelay = MIN_DELAY; log.debug("PowerPolling activated"); } private void deactivatePowerPolling() { if (maxDelay == MAX_DELAY) return; maxDelay = MAX_DELAY; lastDataReceiveTime = Tm.getCurrentTimeMillis(); log.debug("PowerPolling deactivated"); } public Long getAvaragePingTime() { if (pingTimes.isEmpty()) return null; long sum = 0; for (Long time : pingTimes) { sum += time; } return sum / pingTimes.size(); } public String getAvaragePingTimeMessage() { Long time = getAvaragePingTime(); if (time == null) return null; return "Current response time: " + time + " ms."; } }
MiguelSMendoza/Kunagi
WEB-INF/classes/scrum/client/communication/Pinger.java
Java
agpl-3.0
4,177
RepoXML =============== [PAGE DESCRIPTION HERE] This class is slightly more complex than the SimpleXML system in PHP5, but simplier than direct DOM manipulation. * Class name: RepoXML * Namespace: * Parent class: [XMLLoader](xmlloader.md) Properties ---------- ### $apiversion public float $apiversion The API version of this repo XML. Usually 1.0 or 2.4 * Visibility: **public** ### $_keys private array $_keys = null * Visibility: **private** ### $_rootname protected string $_rootname The name of the root node. This IS required for loading the xml file, as every file MUST have exactly one root node. * Visibility: **protected** ### $_filename protected string $_filename The filename of the original XML file. This IS required and is used in loading and saving of the data. * Visibility: **protected** ### $_file protected \Core\Filestore\File $_file The file object of this XML Loader. This is an option parameter for advanced usage, (ie: loading an XML file from a remote server). * Visibility: **protected** ### $_DOM protected \DOMDocument $_DOM The original DOM document for this object. * Visibility: **protected** ### $_rootnode private null $_rootnode = null Root node cache, used to make the getRootDOM faster by bypassing the lookup. * Visibility: **private** ### $_schema protected null $_schema = null Set this to a valid URL string to ensure that the document is set that for its root node. * Visibility: **protected** Methods ------- ### __construct mixed RepoXML::__construct($filename) * Visibility: **public** #### Arguments * $filename **mixed** ### clearPackages mixed RepoXML::clearPackages() Clear the list of packages. .. useful for the create_repo script. * Visibility: **public** ### addPackage mixed RepoXML::addPackage(\PackageXML $package) Add a single package to this repo * Visibility: **public** #### Arguments * $package **[PackageXML](packagexml.md)** ### getDescription string RepoXML::getDescription() Get this repo's description. * Visibility: **public** ### setDescription mixed RepoXML::setDescription($desc) Set the description for this repo. * Visibility: **public** #### Arguments * $desc **mixed** ### getKeys array RepoXML::getKeys() Get an array of keys to install automatically with this repo. * Visibility: **public** ### addKey mixed RepoXML::addKey(string $id, string $name, string $email) Add a key to this repo to be downloaded automatically upon installing. * Visibility: **public** #### Arguments * $id **string** - &lt;p&gt;The ID of the key&lt;/p&gt; * $name **string** - &lt;p&gt;The name, used for reference.&lt;/p&gt; * $email **string** - &lt;p&gt;The email, used to confirm against the public data upon installing.&lt;/p&gt; ### validateKeys boolean RepoXML::validateKeys() Check and see if the keys registered herein are available and valid in the public servers. * Visibility: **public** ### write mixed RepoXML::write() * Visibility: **public** ### getPackages mixed RepoXML::getPackages() * Visibility: **public** ### serialize string XMLLoader::serialize() Serialize this object, preserving the underlying DOMDocument, (which otherwise wouldn't be perserved). * Visibility: **public** * This method is defined by [XMLLoader](xmlloader.md) ### unserialize mixed|void XMLLoader::unserialize(string $serialized) Magic method called to convert a serialized object back to a valid XMLLoader object. * Visibility: **public** * This method is defined by [XMLLoader](xmlloader.md) #### Arguments * $serialized **string** ### load boolean XMLLoader::load() Setup the internal DOMDocument for usage. This MUST be called before any operations are applied to this object! * Visibility: **public** * This method is defined by [XMLLoader](xmlloader.md) ### loadFromFile boolean XMLLoader::loadFromFile(\Core\Filestore\File|string $file) Load the document from a valid File object or a filename. * Visibility: **public** * This method is defined by [XMLLoader](xmlloader.md) #### Arguments * $file **[Core\Filestore\File](core_filestore_file.md)|string** ### loadFromNode boolean XMLLoader::loadFromNode(\DOMNode $node) Load from a DOMNode * Visibility: **public** * This method is defined by [XMLLoader](xmlloader.md) #### Arguments * $node **DOMNode** ### loadFromString mixed XMLLoader::loadFromString($string) Load from an XML string * Visibility: **public** * This method is defined by [XMLLoader](xmlloader.md) #### Arguments * $string **mixed** - &lt;p&gt;@return bool&lt;/p&gt; ### setFilename mixed XMLLoader::setFilename(string $file) Set the filename for this XML document * Visibility: **public** * This method is defined by [XMLLoader](xmlloader.md) #### Arguments * $file **string** ### setRootName mixed XMLLoader::setRootName(string $name) Set the root name for this XML document * Visibility: **public** * This method is defined by [XMLLoader](xmlloader.md) #### Arguments * $name **string** ### setSchema mixed XMLLoader::setSchema($url) Method to set the schema externally. This will update the DOM object if it's different. * Visibility: **public** * This method is defined by [XMLLoader](xmlloader.md) #### Arguments * $url **mixed** ### getRootDOM \DOMElement XMLLoader::getRootDOM() Get the DOM root node * Visibility: **public** * This method is defined by [XMLLoader](xmlloader.md) ### getDOM \DOMDocument XMLLoader::getDOM() Get the complete DOM object. * Visibility: **public** * This method is defined by [XMLLoader](xmlloader.md) ### getElementsByTagName \DOMNodeList XMLLoader::getElementsByTagName(string $name) Searches for all elements with given tag name * Visibility: **public** * This method is defined by [XMLLoader](xmlloader.md) #### Arguments * $name **string** ### getElementByTagName \DOMNode XMLLoader::getElementByTagName(string $name) Get the first element with the given tag name. * Visibility: **public** * This method is defined by [XMLLoader](xmlloader.md) #### Arguments * $name **string** ### getElement \DOMElement XMLLoader::getElement(string $path, boolean $autocreate) This behaves just like getElementByTagName, with the exception that you can pass '/' seperated paths of a node you want. In simple, you can send it book/chapter/page and it will find the first book and its first chapter and its first page. In addition, if the node does not exist it will be created automagically. In addition, you can send arbitrary attributes and their values. It will search for those, and again create them if they don't exist. Everything is relative to the root, and /book is the same as book. Examples: <code> // XML: // <book> // <chapter chapter="1"> // <page number="1">...</page> // ... // <page number="25">...</page> // </chapter> // </book> $this->getElement('page'); // Will return page 1 of chapter 1. $this->getElement('chapter[chapter=1]/page[number=25]'); // Will return page 25 of chapter 1. </code> * Visibility: **public** * This method is defined by [XMLLoader](xmlloader.md) #### Arguments * $path **string** * $autocreate **boolean** - &lt;p&gt;Automatically create the element if it does not exist.&lt;/p&gt; ### getElementFrom \DOMElement XMLLoader::getElementFrom(string $path, \DOMNode|boolean $el, boolean $autocreate) Lookup an element using XPath. * Visibility: **public** * This method is defined by [XMLLoader](xmlloader.md) #### Arguments * $path **string** - &lt;p&gt;The path to search for.&lt;/p&gt; * $el **DOMNode|boolean** - &lt;p&gt;The element to search for the path in.&lt;/p&gt; * $autocreate **boolean** - &lt;p&gt;Automatically create the element if it does not exist.&lt;/p&gt; ### _translatePath string XMLLoader::_translatePath(string $path) Ensure a path is a valid one and absolute to the root node or relative. * Visibility: **private** * This method is defined by [XMLLoader](xmlloader.md) #### Arguments * $path **string** ### createElement boolean|\DOMElement|\DOMNode XMLLoader::createElement(string $path, boolean $el, integer $forcecreate) Create an XML node based on the given path. This will by default not create duplicate nodes of the same name, but can be forced to by using the $forcecreate option. * Visibility: **public** * This method is defined by [XMLLoader](xmlloader.md) #### Arguments * $path **string** - &lt;p&gt;Pathname to create, should be absolutely resolved if no $el is provided, otherwise relative is preferred.&lt;/p&gt; * $el **boolean** - &lt;p&gt;Element to create this node as a child of, set to false to just use root node.&lt;/p&gt; * $forcecreate **integer** - &lt;p&gt;Instructions on how to handle duplicate nodes. 0 - do not create any duplicate nodes, ie: unique attributes have to exist to create a different node 1 - create duplicate a node at the final tree level, (useful for nodes with no attributes) 2 - create all duplicate nodes from the root level on up, useful for creating completely different trees&lt;/p&gt; ### getElements \DOMNodeList XMLLoader::getElements($path) * Visibility: **public** * This method is defined by [XMLLoader](xmlloader.md) #### Arguments * $path **mixed** ### getElementsFrom \DOMNodeList XMLLoader::getElementsFrom(string $path, boolean|\DomNode $el) * Visibility: **public** * This method is defined by [XMLLoader](xmlloader.md) #### Arguments * $path **string** - &lt;p&gt;The path to search for.&lt;/p&gt; * $el **boolean|DomNode** - &lt;p&gt;The element to start the search in, defaults to the root node.&lt;/p&gt; ### removeElements boolean XMLLoader::removeElements($path) Remove elements that match the requested path from the XML object. Shortcut of removeElementsFrom * Visibility: **public** * This method is defined by [XMLLoader](xmlloader.md) #### Arguments * $path **mixed** ### removeElementsFrom boolean XMLLoader::removeElementsFrom(string $path, \DOMNode $el) Remove elements that match the requested path from the XML object. * Visibility: **public** * This method is defined by [XMLLoader](xmlloader.md) #### Arguments * $path **string** * $el **DOMNode** ### elementToArray array XMLLoader::elementToArray(\DOMNode $el, boolean $nesting) Converts a given element and its children into an associative array containing all the values, attributes, and optionally children. * Visibility: **public** * This method is defined by [XMLLoader](xmlloader.md) #### Arguments * $el **DOMNode** * $nesting **boolean** ### asXML string XMLLoader::asXML() Get this XML object without ANY string manipulations! This is useful if you have CDATA that needs to be preserved. * Visibility: **public** * This method is defined by [XMLLoader](xmlloader.md) ### asMinifiedXML string XMLLoader::asMinifiedXML() Get this XML object as a minified string NOTE, this DOES NOT PLAY NICELY WITH CDATA!!!! Use asXML() for that! * Visibility: **public** * This method is defined by [XMLLoader](xmlloader.md) ### asPrettyXML string XMLLoader::asPrettyXML(boolean $html_output) Prettifies an XML string into a human-readable and indented work of art NOTE, this DOES NOT PLAY NICELY WITH CDATA!!!! Use asXML() for that! * Visibility: **public** * This method is defined by [XMLLoader](xmlloader.md) #### Arguments * $html_output **boolean** - &lt;p&gt;True if the output should be escaped (for use in HTML)&lt;/p&gt;
nicholasryan/CorePlus
docs/phpdoc/repoxml.md
Markdown
agpl-3.0
11,719
# # Bold - more than just blogging. # Copyright (C) 2015-2016 Jens Krämer <[email protected]> # # This file is part of Bold. # # Bold is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # Bold is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with Bold. If not, see <http://www.gnu.org/licenses/>. # require 'test_helper' class AssetSearchTest < ActiveSupport::TestCase setup do Bold::current_site = @site = create :site @asset = create :asset end test 'empty search should be blank' do assert AssetSearch.new.blank? end test 'should search assets' do IndexAsset.call @asset assert s = AssetSearch.new(query: 'photo') assert !s.blank? assert r = s.search(@site.assets) assert r.where(id: @asset.id).any? assert s = AssetSearch.new(query: 'photos') assert s.search(@site.assets).where(id:@asset.id).any? assert s = AssetSearch.new(query: 'foobar') assert !s.blank? assert s.search(@site.assets).blank? end end
bold-app/bold
test/models/asset_search_test.rb
Ruby
agpl-3.0
1,438
<?php /** * Nooku Framework - http://www.nooku.org * * @copyright Copyright (C) 2007 - 2017 Johan Janssens and Timble CVBA. (http://www.timble.net) * @license GNU AGPLv3 <https://www.gnu.org/licenses/agpl.html> * @link https://github.com/timble/openpolice-platform */ namespace Nooku\Library; /** * Callback Object Mixin * * @author Johan Janssens <https://github.com/johanjanssens> * @package Nooku\Library\Object */ class CommandCallback extends ObjectMixinCallback implements CommandInterface { /** * The command priority * * @var integer */ protected $_priority; /** * Object constructor * * @param ObjectConfig $config Configuration options * @throws \InvalidArgumentException */ public function __construct(ObjectConfig $config) { parent::__construct($config); //Set the command priority $this->_priority = $config->priority; } /** * Initializes the options for the object * * Called from {@link __construct()} as a first step of object instantiation. * * @param ObjectConfig $config Configuration options * @return void */ protected function _initialize(ObjectConfig $config) { $config->append(array( 'priority' => self::PRIORITY_NORMAL, )); parent::_initialize($config); } /** * Command handler * * If params are passed as a associative array or as a KConfig object they will be merged with the context of the * command chain and passed along. If they are passed as an indexed array they will be passed to the callback * directly. * * @param string $name The command name * @param CommandContext $context The command context * @return boolean */ public function execute( $name, CommandContext $context) { $result = true; $callbacks = $this->getCallbacks($name); foreach($callbacks as $key => $callback) { $params = $this->_params[$name][$key]; if(is_array($params) && is_numeric(key($params))) { $result = call_user_func_array($callback, $params); } else { $result = call_user_func($callback, $context->append($params)); } //Call the callback if ( $result === false) { break; } } return $result === false ? false : true; } /** * Get the methods that are available for mixin. * * @param Object $mixer Mixer object * @return array An array of methods */ public function getMixableMethods(ObjectMixable $mixer = null) { $methods = parent::getMixableMethods(); unset($methods['execute']); unset($methods['getPriority']); return $methods; } /** * Get the priority of a behavior * * @return integer The command priority */ public function getPriority() { return $this->_priority; } }
timble/openpolice-platform
library/command/callback.php
PHP
agpl-3.0
3,083
<?php //============================================================+ // File name : tce_page_timer.php // Begin : 2004-04-29 // Last Update : 2010-10-05 // // Description : Display timer (date-time + countdown). // // Author: Nicola Asuni // // (c) Copyright: // Nicola Asuni // Tecnick.com LTD // www.tecnick.com // [email protected] // // License: // Copyright (C) 2004-2010 Nicola Asuni - Tecnick.com LTD // See LICENSE.TXT file for more information. //============================================================+ /** * @file * Display client timer (date-time + countdown). * @package com.tecnick.tcexam.shared * @author Nicola Asuni * @since 2004-04-29 */ if (!isset($_REQUEST['examtime'])) { $examtime = 0; // remaining exam time in seconds $enable_countdown = 'false'; $timeout_logout = 'false'; } else { $examtime = floatval($_REQUEST['examtime']); $enable_countdown = 'true'; if (isset($_REQUEST['timeout_logout']) AND ($_REQUEST['timeout_logout'])) { $timeout_logout = 'true'; } else { $timeout_logout = 'false'; } } echo '<form action="'.$_SERVER['SCRIPT_NAME'].'" id="timerform">'.K_NEWLINE; echo '<div>'.K_NEWLINE; //echo '<label for="timer" class="timerlabel">'.$l['w_time'].':</label>'.K_NEWLINE; echo '<input type="text" name="timer" id="timer" value="" size="29" maxlength="29" title="'.$l['w_clock_timer'].'" readonly="readonly"/>'.K_NEWLINE; echo '&nbsp;</div>'.K_NEWLINE; echo '</form>'.K_NEWLINE; echo '<script src="'.K_PATH_SHARED_JSCRIPTS.'timer.js" type="text/javascript"></script>'.K_NEWLINE; echo '<script type="text/javascript">'.K_NEWLINE; echo '//<![CDATA['.K_NEWLINE; echo 'FJ_start_timer('.$enable_countdown.', '.(time() - $examtime).', \''.addslashes($l['m_exam_end_time']).'\', '.$timeout_logout.', '.(round(microtime(true) * 1000)).');'.K_NEWLINE; echo '//]]>'.K_NEWLINE; echo '</script>'.K_NEWLINE; //============================================================+ // END OF FILE //============================================================+
satheesh586/raudra
shared/code/tce_page_timer.php
PHP
agpl-3.0
2,069
/***************************************************************************** @(#) File: src/drivers/sl_x400p.c ----------------------------------------------------------------------------- Copyright (c) 2008-2015 Monavacon Limited <http://www.monavacon.com/> Copyright (c) 2001-2008 OpenSS7 Corporation <http://www.openss7.com/> Copyright (c) 1997-2001 Brian F. G. Bidulock <[email protected]> All Rights Reserved. This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, version 3 of the license. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>, or write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. ----------------------------------------------------------------------------- U.S. GOVERNMENT RESTRICTED RIGHTS. If you are licensing this Software on behalf of the U.S. Government ("Government"), the following provisions apply to you. If the Software is supplied by the Department of Defense ("DoD"), it is classified as "Commercial Computer Software" under paragraph 252.227-7014 of the DoD Supplement to the Federal Acquisition Regulations ("DFARS") (or any successor regulations) and the Government is acquiring only the license rights granted herein (the license rights customarily provided to non-Government users). If the Software is supplied to any unit or agency of the Government other than DoD, it is classified as "Restricted Computer Software" and the Government's rights in the Software are defined in paragraph 52.227-19 of the Federal Acquisition Regulations ("FAR") (or any successor regulations) or, in the cases of NASA, in paragraph 18.52.227-86 of the NASA Supplement to the FAR (or any successor regulations). ----------------------------------------------------------------------------- Commercial licensing and support of this software is available from OpenSS7 Corporation at a fee. See http://www.openss7.com/ *****************************************************************************/ static char const ident[] = "src/drivers/sl_x400p.c (" PACKAGE_ENVR ") " PACKAGE_DATE; /* * This is an SL (Signalling Link) kernel module which provides all of the * capabilities of the SLI for the E400P-SS7 and T400P-SS7 cards. This is a * complete SS7 MTP Level 2 OpenSS7 implementation. */ //#define _DEBUG 1 #undef _DEBUG #define _MPS_SOURCE 1 #define _SVR4_SOURCE 1 #define _SUN_SOURCE 1 #define _HPUX_SOURCE 1 #define X400P_DOWNLOAD_FIRMWARE 1 #include <sys/os7/compat.h> #ifndef KBUILD_MODNAME #define KBUILD_MODNAME KBUILD_BASENAME #endif #ifdef LINUX #include <linux/ioport.h> #include <asm/io.h> #include <asm/dma.h> #include <linux/pci.h> #include <linux/interrupt.h> #ifndef _MPS_SOURCE #if 0 #include "bufpool.h" #else #include <sys/os7/bufpool.h> #endif #endif /* _MPS_SOURCE */ #endif /* LINUX */ #include <linux/if.h> #include <net/lif.h> #include <net/nit_if.h> #include <net/bpf.h> #undef LMI_DEFAULT #include <ss7/lmi.h> #include <ss7/lmi_ioctl.h> #undef _MPS_SOURCE /* get the right sdl/sdt/sl_timers_t */ #include <ss7/sdli.h> #include <ss7/sdli_ioctl.h> #include <ss7/sdti.h> #include <ss7/sdti_ioctl.h> #include <ss7/sli.h> #include <ss7/sli_ioctl.h> #define _MPS_SOURCE 1 #include <sys/mxi.h> #include <sys/mxi_ioctl2.h> #include <sys/dsx_ioctl.h> #include <sys/dlpi.h> #include <sys/dlpi_ioctl.h> #ifdef X400P_DOWNLOAD_FIRMWARE #include "v401pfw.h" #endif #define SL_X400P_DESCRIP "X400P-SS7: SS7/SL (Signalling Link) STREAMS Driver" #define SL_X400P_EXTRA "Part of the OpenSS7 Stack for Linux Fast-STREAMS" #define SL_X400P_REVISION "OpenSS7 src/drivers/sl_x400p.c (" PACKAGE_ENVR ") " PACKAGE_DATE #define SL_X400P_COPYRIGHT "Copyright (c) 2008-2015 Monavacon Limited. All Rights Reserved." #define SL_X400P_DEVICE "Supports the V40XP E1/T1/J1 (Tormenta II/III) PCI boards." #define SL_X400P_CONTACT "Brian Bidulock <[email protected]>" #define SL_X400P_LICENSE "GPL" #define SL_X400P_BANNER SL_X400P_DESCRIP "\n" \ SL_X400P_EXTRA "\n" \ SL_X400P_REVISION "\n" \ SL_X400P_COPYRIGHT "\n" \ SL_X400P_DEVICE "\n" \ SL_X400P_CONTACT #define SL_X400P_SPLASH SL_X400P_DESCRIP " - " \ SL_X400P_REVISION #ifdef LINUX MODULE_AUTHOR(SL_X400P_CONTACT); MODULE_DESCRIPTION(SL_X400P_DESCRIP); MODULE_SUPPORTED_DEVICE(SL_X400P_DEVICE); #ifdef MODULE_LICENSE MODULE_LICENSE(SL_X400P_LICENSE); #endif /* MODULE_LICENSE */ #if defined MODULE_ALIAS MODULE_ALIAS("streams-sl_x400p"); #endif #if defined MODULE_VERSION MODULE_VERSION(PACKAGE_ENVR); #endif #endif /* LINUX */ #ifndef CONFIG_STREAMS_SL_X400P_NAME #define CONFIG_STREAMS_SL_X400P_NAME "x400p-sl" #endif #ifndef CONFIG_STREAMS_SL_X400P_MODID #define CONFIG_STREAMS_SL_X400P_MODID 2083 #endif #ifndef CONFIG_STREAMS_SL_X400P_NMINORS #define CONFIG_STREAMS_SL_X400P_NMINORS 1 #endif #ifndef CONFIG_STREAMS_SL_X400P_NMAJORS #define CONFIG_STREAMS_SL_X400P_NMAJORS 1 #endif #ifndef CONFIG_STREAMS_SL_X400P_MAJOR #define CONFIG_STREAMS_SL_X400P_MAJOR 2083 #endif #ifndef CONFIG_STREAMS_SL_X400P_MAJOR_0 #define CONFIG_STREAMS_SL_X400P_MAJOR_0 2083 #endif #ifndef CONFIG_STREAMS_SL_X400P_MODULE #define CONFIG_STREAMS_SL_X400P_MODULE 1 #endif #define SL_X400P_DRV_ID CONFIG_STREAMS_SL_X400P_MODID #define SL_X400P_DRV_NAME CONFIG_STREAMS_SL_X400P_NAME #define SL_X400P_CMAJORS CONFIG_STREAMS_SL_X400P_NMAJORS #define SL_X400P_CMAJOR_0 CONFIG_STREAMS_SL_X400P_MAJOR #define SL_X400P_UNITS CONFIG_STREAMS_SL_X400P_NMINORS #ifdef LINUX #ifdef MODULE_ALIAS MODULE_ALIAS("streams-modid-" __stringify(CONFIG_STREAMS_SL_X400P_MODID)); MODULE_ALIAS("streams-driver-sl-x400p"); MODULE_ALIAS("streams-major-" __stringify(CONFIG_STREAMS_SL_X400P_MAJOR)); MODULE_ALIAS("/dev/streams/x400p-sl"); MODULE_ALIAS("/dev/streams/x400p-sl/*"); MODULE_ALIAS("/dev/streams/clone/x400p-sl"); MODULE_ALIAS("char-major-" __stringify(CONFIG_STREAMS_CLONE_MAJOR) "-" __stringify(SL_X400P_CMAJOR_0)); MODULE_ALIAS("/dev/x400p-sl"); //MODULE_ALIAS("devname:x400p-sl"); #endif /* MODULE_ALIAS */ #endif /* LINUX */ #ifdef _OPTIMIZE_SPEED #define X400LOG(sid, level, flags, fmt, ...) \ do { } while (0) #else #define X400LOG(sid, level, flags, fmt, ...) \ strlog(SL_X400P_DRV_ID, sid, level, flags, fmt, ##__VA_ARGS__) #endif #define STRLOGERR 0 /* log X400 error information */ #define STRLOGNO 0 /* log X400 notice information */ #define STRLOGST 1 /* log X400 state transitions */ #define STRLOGTO 2 /* log X400 timeouts */ #define STRLOGRX 3 /* log X400 primitives received */ #define STRLOGTX 4 /* log X400 primitives issued */ #define STRLOGTE 5 /* log X400 timer events */ #define STRLOGIO 6 /* log X400 additional data */ #define STRLOGDA 7 /* log X400 data */ #define LOGERR(sid, fmt, ...) X400LOG(sid, STRLOGERR, SL_TRACE | SL_ERROR | SL_CONSOLE, fmt, ##__VA_ARGS__) #define LOGNO(sid, fmt, ...) X400LOG(sid, STRLOGNO, SL_TRACE, fmt, ##__VA_ARGS__) #define LOGST(sid, fmt, ...) X400LOG(sid, STRLOGNO, SL_TRACE, fmt, ##__VA_ARGS__) #define LOGTO(sid, fmt, ...) X400LOG(sid, STRLOGNO, SL_TRACE, fmt, ##__VA_ARGS__) #define LOGRX(sid, fmt, ...) X400LOG(sid, STRLOGNO, SL_TRACE, fmt, ##__VA_ARGS__) #define LOGTX(sid, fmt, ...) X400LOG(sid, STRLOGNO, SL_TRACE, fmt, ##__VA_ARGS__) #define LOGTE(sid, fmt, ...) X400LOG(sid, STRLOGNO, SL_TRACE, fmt, ##__VA_ARGS__) #define LOGIO(sid, fmt, ...) X400LOG(sid, STRLOGNO, SL_TRACE, fmt, ##__VA_ARGS__) #define LOGDA(sid, fmt, ...) X400LOG(sid, STRLOGNO, SL_TRACE, fmt, ##__VA_ARGS__) #define ch2sid(ch) (ch->ppa + (1<<12)) #define xp2sid(xp) (xp->cminor) /* * ======================================================================= * * STREAMS Definitions * * ======================================================================= */ #define DRV_ID SL_X400P_DRV_ID #define DRV_NAME SL_X400P_DRV_NAME #define CMAJORS SL_X400P_CMAJORS #define CMAJOR_0 SL_X400P_CMAJOR_0 #define UNITS SL_X400P_UNITS #ifdef MODULE #define DRV_BANNER SL_X400P_BANNER #else /* MODULE */ #define DRV_BANNER SL_X400P_SPLASH #endif /* MODULE */ STATIC struct module_info xp_minfo = { .mi_idnum = DRV_ID, /* Module ID number */ .mi_idname = DRV_NAME, /* Module name */ .mi_minpsz = 1, /* Min packet size accepted */ .mi_maxpsz = INFPSZ, /* Max packet size accepted */ .mi_hiwat = 1024, /* Hi water mark */ .mi_lowat = 0, /* Lo water mark */ }; STATIC struct module_stat xp_rstat __attribute__ ((aligned(SMP_CACHE_BYTES))); STATIC struct module_stat xp_wstat __attribute__ ((aligned(SMP_CACHE_BYTES))); STATIC streamscall int xp_qopen(queue_t *, dev_t *, int, int, cred_t *); STATIC streamscall int xp_qclose(queue_t *, int, cred_t *); STATIC streamscall int xp_rput(queue_t *, mblk_t *); STATIC streamscall int xp_rsrv(queue_t *); STATIC struct qinit xp_rinit = { .qi_putp = xp_rput, /* Read put (message from below) */ .qi_srvp = xp_rsrv, /* Read queue service */ .qi_qopen = xp_qopen, /* Each open */ .qi_qclose = xp_qclose, /* Last close */ .qi_minfo = &xp_minfo, /* Information */ .qi_mstat = &xp_rstat, /* Statistics */ }; STATIC streamscall int xp_wput(queue_t *, mblk_t *); STATIC streamscall int xp_wsrv(queue_t *); STATIC struct qinit xp_winit = { .qi_putp = xp_wput, /* Write put (message from above) */ .qi_srvp = xp_wsrv, /* Write queue service */ .qi_minfo = &xp_minfo, /* Information */ .qi_mstat = &xp_wstat, /* Statistics */ }; STATIC struct streamtab sl_x400pinfo = { .st_rdinit = &xp_rinit, /* Upper read queue */ .st_wrinit = &xp_winit, /* Upper write queue */ }; /* * ======================================================================== * * Private structure * * ======================================================================== */ struct xp; struct ch; struct sp; struct cd; typedef struct xp_path { uint residue; /* residue bits */ uint rbits; /* number of residue bits */ ushort bcc; /* crc for message */ uint state; /* state */ uint mode; /* path mode */ uint type; /* path frame type */ uint bytes; /* number of whole bytes */ mblk_t *msg; /* message */ mblk_t *nxt; /* message chain block */ mblk_t *cmp; /* compression/repeat message */ uint repeat; /* compression/repeat count */ uint octets; /* octets counted */ } xp_path_t; typedef struct xp { queue_t *rq; /* read queue */ queue_t *wq; /* write queue */ uint i_state; /* interface state */ uint i_flags; /* interface flags */ uint i_style; /* interface style */ uint i_version; /* interface version */ uint i_oldstate; /* interface saved state */ major_t cmajor; /* major device number */ minor_t cminor; /* minor device number */ minor_t bminor; /* opened minor number */ struct ch *ch; /* channel for this interface */ uint ppa; /* attached ppa */ int card, span, chan; /* attached card span chan */ int monitor; /* monitoring point */ #define XP_MONITOR_NONE 0 #define XP_MONITOR_GLOB 1 #define XP_MONITOR_CARD 2 #define XP_MONITOR_SPAN 3 #define XP_MONITOR_CHAN 4 int level; /* connection level */ #define XP_LEVEL_MON_SDT 0 #define XP_LEVEL_MON_SL 1 #define XP_LEVEL_MON_SDL 2 #define XP_LEVEL_ACT_SDT 3 #define XP_LEVEL_ACT_SL 4 #define XP_LEVEL_ACT_SDL 5 struct { struct xp **prev; /* prev next pointer in xray list */ struct xp *next; /* next in xray list */ uint flags; /* xray flags */ atomic_t drops; /* xray drops */ struct { uint flags; /* NIT options flags */ #ifndef NI_TIMESTAMP #define NI_PROMISC (1<<0) #define NI_TIMESTAMP (1<<1) #define NI_LEN (1<<2) #define NI_DROPS (1<<3) #define NI_USERBITS (NI_PROMISC|NI_TIMESTAMP|NI_LEN|NI_DROPS) #endif uint snap; /* snapshot length */ } nit; struct { uint flags; /* BPF options flags */ #define BPF_PROMISC (1<<0) #define BPF_SEESENT (1<<1) #define BPF_HDRCMPLT (1<<2) #define BPF_FEEDBACK (1<<3) uint dlt; /* data link type */ uint direction; /* direction */ struct bpf_stat stats; /* stats - part bpfmod */ } bpf; } xray; } xp_t; #define XP_PRIV(__q) ((struct xp *)(__q)->q_ptr) #define XP_XRAY_SL_RX_GLOB (1<< 4) /* a global xray rx stream exists */ #define XP_XRAY_SL_RX_CARD (1<< 5) /* a card xray rx stream exists */ #define XP_XRAY_SL_RX_SPAN (1<< 6) /* a span xray rx stream exists */ #define XP_XRAY_SL_RX_CHAN (1<< 7) /* a chan xray rx stream exists */ #define XP_XRAY_SL_TX_GLOB (1<< 8) /* a global xray tx stream exists */ #define XP_XRAY_SL_TX_CARD (1<< 9) /* a card xray tx stream exists */ #define XP_XRAY_SL_TX_SPAN (1<<10) /* a span xray tx stream exists */ #define XP_XRAY_SL_TX_CHAN (1<<11) /* a chan xray tx stream exists */ #define XP_XRAY_SDT_RX_GLOB (1<<12) /* a global xray rx stream exists */ #define XP_XRAY_SDT_RX_CARD (1<<13) /* a card xray rx stream exists */ #define XP_XRAY_SDT_RX_SPAN (1<<14) /* a span xray rx stream exists */ #define XP_XRAY_SDT_RX_CHAN (1<<15) /* a chan xray rx stream exists */ #define XP_XRAY_SDT_TX_GLOB (1<<16) /* a global xray tx stream exists */ #define XP_XRAY_SDT_TX_CARD (1<<17) /* a card xray tx stream exists */ #define XP_XRAY_SDT_TX_SPAN (1<<18) /* a span xray tx stream exists */ #define XP_XRAY_SDT_TX_CHAN (1<<19) /* a chan xray tx stream exists */ #define XP_XRAY_SDL_RX_GLOB (1<<20) /* a global xray rx stream exists */ #define XP_XRAY_SDL_RX_CARD (1<<21) /* a card xray rx stream exists */ #define XP_XRAY_SDL_RX_SPAN (1<<22) /* a span xray rx stream exists */ #define XP_XRAY_SDL_RX_CHAN (1<<23) /* a chan xray rx stream exists */ #define XP_XRAY_SDL_TX_GLOB (1<<24) /* a global xray tx stream exists */ #define XP_XRAY_SDL_TX_CARD (1<<25) /* a card xray tx stream exists */ #define XP_XRAY_SDL_TX_SPAN (1<<26) /* a span xray tx stream exists */ #define XP_XRAY_SDL_TX_CHAN (1<<27) /* a chan xray tx stream exists */ #define XP_XRAY_SL_GLOB (XP_XRAY_SL_RX_GLOB|XP_XRAY_SL_TX_GLOB) #define XP_XRAY_SL_CARD (XP_XRAY_SL_RX_CARD|XP_XRAY_SL_TX_CARD) #define XP_XRAY_SL_SPAN (XP_XRAY_SL_RX_SPAN|XP_XRAY_SL_TX_SPAN) #define XP_XRAY_SL_CHAN (XP_XRAY_SL_RX_CHAN|XP_XRAY_SL_TX_CHAN) #define XP_XRAY_SDT_GLOB (XP_XRAY_SDT_RX_GLOB|XP_XRAY_SDT_TX_GLOB) #define XP_XRAY_SDT_CARD (XP_XRAY_SDT_RX_CARD|XP_XRAY_SDT_TX_CARD) #define XP_XRAY_SDT_SPAN (XP_XRAY_SDT_RX_SPAN|XP_XRAY_SDT_TX_SPAN) #define XP_XRAY_SDT_CHAN (XP_XRAY_SDT_RX_CHAN|XP_XRAY_SDT_TX_CHAN) #define XP_XRAY_SDL_GLOB (XP_XRAY_SDL_RX_GLOB|XP_XRAY_SDL_TX_GLOB) #define XP_XRAY_SDL_CARD (XP_XRAY_SDL_RX_CARD|XP_XRAY_SDL_TX_CARD) #define XP_XRAY_SDL_SPAN (XP_XRAY_SDL_RX_SPAN|XP_XRAY_SDL_TX_SPAN) #define XP_XRAY_SDL_CHAN (XP_XRAY_SDL_RX_CHAN|XP_XRAY_SDL_TX_CHAN) #define XP_XRAY_GLOB (XP_XRAY_SL_GLOB|XP_XRAY_SDT_GLOB|XP_XRAY_SDL_GLOB) #define XP_XRAY_CARD (XP_XRAY_SL_CARD|XP_XRAY_SDT_CARD|XP_XRAY_SDL_CARD) #define XP_XRAY_SPAN (XP_XRAY_SL_SPAN|XP_XRAY_SDT_SPAN|XP_XRAY_SDL_SPAN) #define XP_XRAY_CHAN (XP_XRAY_SL_CHAN|XP_XRAY_SDT_CHAN|XP_XRAY_SDL_CHAN) #define XP_XRAY_SL_RX (XP_XRAY_SL_RX_GLOB|XP_XRAY_SL_RX_CARD|XP_XRAY_SL_RX_SPAN|XP_XRAY_SL_RX_CHAN) #define XP_XRAY_SL_TX (XP_XRAY_SL_TX_GLOB|XP_XRAY_SL_TX_CARD|XP_XRAY_SL_TX_SPAN|XP_XRAY_SL_TX_CHAN) #define XP_XRAY_SDT_RX (XP_XRAY_SDT_RX_GLOB|XP_XRAY_SDT_RX_CARD|XP_XRAY_SDT_RX_SPAN|XP_XRAY_SDT_RX_CHAN) #define XP_XRAY_SDT_TX (XP_XRAY_SDT_TX_GLOB|XP_XRAY_SDT_TX_CARD|XP_XRAY_SDT_TX_SPAN|XP_XRAY_SDT_TX_CHAN) #define XP_XRAY_SDL_RX (XP_XRAY_SDL_RX_GLOB|XP_XRAY_SDL_RX_CARD|XP_XRAY_SDL_RX_SPAN|XP_XRAY_SDL_RX_CHAN) #define XP_XRAY_SDL_TX (XP_XRAY_SDL_TX_GLOB|XP_XRAY_SDL_TX_CARD|XP_XRAY_SDL_TX_SPAN|XP_XRAY_SDL_TX_CHAN) #define XP_XRAY_RX (XP_XRAY_SL_RX|XP_XRAY_SDT_RX|XP_XRAY_SDL_RX) #define XP_XRAY_TX (XP_XRAY_SL_TX|XP_XRAY_SDT_TX|XP_XRAY_SDL_TX) /* * This structure gets rid of a problem that we used to have that the channel configuration would be * lost when a stream on the driver was closed. * * This also opens the possibilty to leave signalling links running while there is no Stream * associated with them. Processor outage can be used to bridge the gap between the upper layer * reopening or otherwise resetting the stream. The processor outage condition can be set on stream * closure. This would involve separating the receive buffer from the read queue and making timers * run without a queue (i.e. use simple timeout(9) and put(9)). */ typedef struct ch { atomic_t refcnt; /* reference count */ spinlock_t lock; /* structure lock */ struct sp *sp; /* span for this channel */ uint ppa; /* really only 16 bits */ int chan; /* index (chan) */ xp_path_t tx; /* transmit path variables */ xp_path_t rx; /* receive path variables */ struct xp *xp; /* active stream for this channel */ struct { struct xp *list; /* xraying streams for this channel */ uint flags; /* xray flags for speed */ } xray; lmi_option_t option; /* LMI protocol and variant options */ struct { bufq_t rb; /* received buffer */ bufq_t tb; /* transmission buffer */ bufq_t rtb; /* retransmission buffer */ sl_timers_t timers; /* SL protocol timers */ sl_config_t config; /* SL configuration */ sl_statem_t statem; /* SL state machine */ sl_notify_t notify; /* SL notification options */ sl_stats_t stats; /* SL statistics */ sl_stats_t stamp; /* SL statistics timestamps */ sl_stats_t statsp; /* SL statistics periods */ } sl; struct { bufq_t tb; /* transmission buffer */ sdt_timers_t timers; /* SDT protocol timers */ sdt_config_t config; /* SDT configuration */ sdt_statem_t statem; /* SDT state machine */ sdt_notify_t notify; /* SDT notification options */ sdt_stats_t stats; /* SDT statistics */ sdt_stats_t stamp; /* SDT statistics timestamps */ sdt_stats_t statsp; /* SDT statistics periods */ } sdt; struct { bufq_t tb; /* transmission buffer */ sdl_timers_t timers; /* SDL protocol timers */ sdl_config_t config; /* SDL configuration */ sdl_statem_t statem; /* SDL state machine variables */ sdl_notify_t notify; /* SDL notification options */ sdl_stats_t stats; /* SDL statistics */ sdl_stats_t stamp; /* SDL statistics timestamps */ sdl_stats_t statsp; /* SDL statistics periods */ } sdl; } ch_t; STATIC void xp_init_ch(struct sp *, struct ch *, uint8_t); STATIC struct ch *xp_alloc_ch(struct sp *, uint8_t); STATIC void xp_free_ch(struct ch *); STATIC struct ch *ch_get(struct ch *); STATIC void ch_put(struct ch *); STATIC struct ch *ch_find(uint); typedef struct st { uint32_t SECs; /* elapsed [seconds] */ uint32_t ESs; /* errored [seconds] */ uint32_t SESs; /* severely errored [seconds] */ uint32_t SEFSs; /* severly errored framing [seconds] */ uint32_t UASs; /* unavailable [seconds] */ uint32_t CSSs; /* controlled slip [seconds] */ uint32_t PCVs; /* path coding [violations] */ uint32_t LESs; /* line errored [seconds] */ uint32_t BESs; /* bursty errored [seconds] */ uint32_t DMs; /* degraded [minutes] */ uint32_t LCVs; /* line coding [violations] */ uint32_t FASEs; /* frame alignment [errors] */ uint32_t FABEs; /* error bit [errors] */ uint32_t FEBEs; /* far end block errors [errors] */ uint32_t ValidData; /* valid data */ } st_t; typedef struct sp { atomic_t refcnt; /* reference count */ spinlock_t lock; /* structure lock */ struct cd *cd; /* card for this span */ struct ch *chans[32]; /* channels for this span */ struct xp *xray; /* xraying streams for this span */ ulong interval; ulong recovertime; /* alarm recover time */ ulong iobase; /* span iobase */ int span; /* index (span) */ volatile ulong loopcnt; /* loop command count */ sdl_config_t config; /* span configuration */ struct { uint count; uint state; /* autoconfig state number */ uint flags; /* state flags */ #define XP_STATE_TOCD (1<< 0) /* tx open circuit */ #define XP_STATE_TSCD (1<< 1) /* tx short circuit */ #define XP_STATE_LOLITC (1<< 2) /* tx i/f loss of tx clock */ #define XP_STATE_LOTC (1<< 3) /* tx loss of tx clock */ #define XP_STATE_LRCL (1<< 8) /* rx line i/f carrier loss */ #define XP_STATE_ILUT (1<< 9) /* rx input level under thresh */ #define XP_STATE_RLOS (1<<10) /* rx loss of sync */ #define XP_STATE_FRCL (1<<11) /* rx framer carrier loss */ #define XP_STATE_RUA1 (1<<12) /* rx unframed all ones */ #define XP_STATE_RYEL (1<<13) /* rx yellow alarm */ #define XP_STATE_RRA (1<<14) /* rx remote alarm */ #define XP_STATE_LORC (1<<15) /* rx loss of rx clock */ #define XP_STATE_LUP (1<<16) /* rx loop up code */ #define XP_STATE_LDN (1<<17) /* rx loop down code */ #define XP_STATE_SPARE (1<<18) /* rx spare code */ #define XP_STATE_RDMA (1<<19) /* rx dist MF alarm */ #define XP_STATE_RSAZ (1<<20) /* rx sign all zeros */ #define XP_STATE_RSAO (1<<21) /* rx sign all ones */ #define XP_STATE_RAIS (1<<22) /* rx AIS-CI */ #define XP_STATE_B8ZS (1<<23) /* rx B8ZS codeword */ #define XP_STATE_16ZD (1<<24) /* rx 16-zeros */ #define XP_STATE_8ZD (1<<25) /* rx 8-zeros */ #define XP_STATE_JALT (1<<26) /* rx JA limit trip */ #define XP_STATE_LIRST (1<<27) /* line interface reset */ #define XP_STATE_CRC (1<<28) #define XP_STATE_CAS (1<<29) #define XP_STATE_FAS (1<<30) #define XP_DEF_AIS (XP_EVENT_RPDV) #define XP_DEF_OOF (XP_XXX_SEFE|XP_XXX_COFA) #define XP_FAIL_AIS (XP_STATE_RUA1) #define XP_FAIL_FEA (XP_STATE_RYEL|XP_STATE_RRA) #define XP_FAIL_FELOM (XP_STATE_RDMA) #define XP_FAIL_LPF (XP_STATE_LUP|XP_STATE_LDN|XP_STATE_SPARE) #define XP_FAIL_LOF #define XP_FAIL_LOM #define XP_FAIL_LOS #define XP_FAIL_T16AIS uint errors; /* error conditions */ #define XP_ERR_SES (1<< 0) /* severe error */ #define XP_ERR_SEFS (1<< 1) /* severely errored frame */ #define XP_ERR_UAS (1<< 2) /* unavailable */ #define XP_ERR_CSS (1<< 3) /* controlled slip */ #define XP_ERR_PCV (1<< 4) /* path code violation */ #define XP_ERR_LES (1<< 5) /* line error */ #define XP_ERR_BES (1<< 6) /* bursty error */ #define XP_ERR_DM (1<< 7) /* degraded */ #define XP_ERR_LCV (1<< 8) /* line code violation */ #define XP_ERR_OOF (1<< 9) /* out of frame */ #define XP_ERR_FASE (1<<10) /* frame alignment signal */ #define XP_ERR_FABE (1<<11) /* e-bit error */ #define XP_ERR_B8ZS (1<<12) /* B8ZS code violation */ #define XP_ERR_PDV (1<<13) /* pulse density violation */ #define XP_ERR_ES (1<<14) /* errored second */ #define XP_ERR_FEBE (1<<15) uint jalts; /* consecutive jitter atten. limit trips */ uint sess; /* consecutive severely errored seconds */ uint nses; /* consecutive non-severely errored seconds */ uint config; } status; /* state structure */ uint curr; /* current history index */ struct st stats[3]; /* current statistics, 1 sec, 1 min. 15 min. */ struct st hist[96]; /* historical statistics */ } sp_t; STATIC void xp_init_sp(struct cd *, struct sp *, uint8_t); STATIC struct sp *xp_alloc_sp(struct cd *, uint8_t); STATIC void xp_free_sp(struct sp *); STATIC struct sp *sp_get(struct sp *); STATIC void sp_put(struct sp *); STATIC struct sp *sp_find(uint); typedef struct sg { atomic_t refcnt; /* reference count */ spinlock_t lock; /* structure lock */ uint group; /* synchronization group number */ uint members; /* number of members */ uint ifgtype; /* type of current sync source */ struct cd *master; /* current group master */ struct cd *cd; /* list of cards in this group */ } sg_t; STATIC struct sg *xp_alloc_sg(void); STATIC void xp_free_sg(struct sg *); STATIC struct sg *sg_get(struct sg *); STATIC void sg_put(struct sg *); STATIC struct sg *sg_find(uint); typedef struct cd { atomic_t refcnt; /* reference count */ spinlock_t lock; /* structure lock */ ulong xll_region; /* Xilinx 32-bit memory region */ ulong xll_length; /* Xilinx 32-bit memory length */ volatile uint32_t *xll; /* Xilinx 32-bit memory map */ ulong xlb_region; /* Xilinx 8-bit memory region */ ulong xlb_length; /* Xilinx 8-bit memory lenght */ volatile uint8_t *xlb; /* Xilinx 8-bit memory map */ ulong plx_region; /* PLX 9030 memory region */ ulong plx_length; /* PLX 9030 memory length */ volatile uint16_t *plx; /* PLX 9030 memory map */ volatile uint8_t synreg; /* local copy of synreg contents */ volatile uint8_t ctlreg; /* local copy of ctlreg contents (static bits) */ volatile uint8_t ledreg; /* local copy of ledreg contents */ volatile uint8_t tstreg; /* local copy of tstreg contents */ volatile uint8_t clkreg; /* local copy of need for E1DIV for local clock */ uint frame; /* frame number */ struct sp *spans[4]; /* structures for spans */ struct xp *xray; /* xraying streams for this span */ uint32_t *wbuf; /* wr buffer */ uint32_t *rbuf; /* rd buffer */ volatile int uebno; /* upper elastic buffer number */ volatile int lebno; /* lower elastic buffer number */ volatile int eval_syncsrc; /* need to reevaluate sync src */ volatile int leds; /* leds on the card */ int card; /* index (card) */ int board; /* board hardware index */ int device; /* device hardware index */ int devrev; /* device hardware revision */ int hw_flags; /* board and device hardware flags */ int ports; /* number of ports populated on the board */ struct { struct cd *next; /* next card in this sync group */ struct cd **prev; /* prev card in this sync group */ uint index; /* index of this card in this sync group */ struct sg *sg; /* the synchronization group structure */ } sg; ulong irq; /* card irq */ ulong bus; /* card pci bus number */ ulong slot; /* card pci slot number */ ulong iobase; /* card iobase */ struct tasklet_struct tasklet; /* card tasklet */ #ifdef HAVE_KTYPE_IRQ_HANDLER_T irq_handler_t isr; /* interrupt service routine */ #else irqreturn_t(*isr) (int, void *, struct pt_regs *); /* interrupt service routine */ #endif sdl_config_t config; /* card configuration */ } cd_t; STATIC struct cd *xp_alloc_cd(void); STATIC void xp_free_cd(struct cd *); STATIC struct cd *cd_get(struct cd *); STATIC void cd_put(struct cd *); STATIC struct cd *cd_find(uint); #ifdef _MPS_SOURCE #define ss7_fast_allocb(__bufpoolp, __size, __priority) allocb(__size, __priority) #define ss7_fast_freemsg(__bufpoolp, __mp) freemsg(__mp) #define ss7_bufpool_reserve(__bufpoolp, __numb) do { } while (0) #define ss7_bufpool_release(__bufpoolp, __numb) do { } while (0) #define ss7_bufpool_init(__bufpoolp) do { } while (0) #define ss7_bufpool_term(__bufpoolp) do { } while (0) #else /* _MPS_SOURCE */ STATIC struct ss7_bufpool xp_bufpool = { 0, }; #endif /* _MPS_SOURCE */ #ifndef _OPTIMIZE_SPEED noinline fastcall const char * lmi_statename(lmi_long state) { switch (state) { case LMI_UNATTACHED: return ("LMI_UNATTACHED"); case LMI_ATTACH_PENDING: return ("LMI_ATTACH_PENDING"); case LMI_UNUSABLE: return ("LMI_UNUSABLE"); case LMI_DISABLED: return ("LMI_DISABLED"); case LMI_ENABLE_PENDING: return ("LMI_ENABLE_PENDING"); case LMI_ENABLED: return ("LMI_ENABLED"); case LMI_DISABLE_PENDING: return ("LMI_DISABLE_PENDING"); case LMI_DETACH_PENDING: return ("LMI_DETACH_PENDING"); default: return ("(uknown)"); } } #endif /** xp_set_state: - set LMI state of private structure * @xp: private structure (locked) for which to set state * @state: the state to set */ static inline fastcall __hot void xp_set_state(struct xp *xp, lmi_ulong state) { if (likely(xp->i_state != state)) { LOGST(xp2sid(xp), "%s <- %s", lmi_statename(state), lmi_statename(xp->i_state)); xp->i_state = state; } } /** xp_get_state: - get LMI state of private structure * @xp: private structure (locked) for which to get state * @state: the state to get */ static inline fastcall __hot lmi_ulong xp_get_state(struct xp *xp) { return (xp->i_state); } static inline fastcall __hot void xp_save_state(struct xp *xp) { xp->i_oldstate = xp->i_state; } static inline fastcall __hot void xp_restore_state(struct xp *xp) { xp_set_state(xp, xp->i_oldstate); } #define dl_get_state(xp) xp_get_state(xp) #ifndef _OPTIMIZE_SPEED noinline fastcall const char * dl_statename(dl_ulong state) { switch (state) { case DL_UNATTACHED: return ("DL_UNATTACHED"); case DL_ATTACH_PENDING: return ("DL_ATTACH_PENDING"); case DL_DETACH_PENDING: return ("DL_DETACH_PENDING"); case DL_UNBOUND: return ("DL_UNBOUND"); case DL_BIND_PENDING: return ("DL_BIND_PENDING"); case DL_UNBIND_PENDING: return ("DL_UNBIND_PENDING"); case DL_IDLE: return ("DL_IDLE"); case DL_UDQOS_PENDING: return ("DL_UDQOS_PENDING"); case DL_OUTCON_PENDING: return ("DL_OUTCON_PENDING"); case DL_INCON_PENDING: return ("DL_INCON_PENDING"); case DL_CONN_RES_PENDING: return ("DL_CONN_RES_PENDING"); case DL_DATAXFER: return ("DL_DATAXFER"); case DL_USER_RESET_PENDING: return ("DL_USER_RESET_PENDING"); case DL_PROV_RESET_PENDING: return ("DL_PROV_RESET_PENDING"); case DL_RESET_RES_PENDING: return ("DL_RESET_RES_PENDING"); case DL_DISCON8_PENDING: return ("DL_DISCON8_PENDING"); case DL_DISCON9_PENDING: return ("DL_DISCON9_PENDING"); case DL_DISCON11_PENDING: return ("DL_DISCON11_PENDING"); case DL_DISCON12_PENDING: return ("DL_DISCON12_PENDING"); case DL_DISCON13_PENDING: return ("DL_DISCON13_PENDING"); case DL_SUBS_BIND_PND: return ("DL_SUBS_BIND_PND"); case DL_SUBS_UNBIND_PND: return ("DL_SUBS_UNBIND_PND"); default: return ("(unknown)"); } } #endif /** dl_set_state: - set DLPI state of private structure * @xp: private structure (locked) for which to set state * @state: the state to set */ static inline fastcall __hot void dl_set_state(struct xp *xp, dl_ulong state) { if (likely(xp->i_state != state)) { LOGST(xp2sid(xp), "%s <- %s", dl_statename(state), dl_statename(xp->i_state)); xp->i_state = state; } } #if defined DEFINE_RWLOCK static DEFINE_RWLOCK(xp_core_lock); static DEFINE_RWLOCK(xp_list_lock); #elif defined __RW_LOCK_UNLOCKED static rwlock_t xp_core_lock = __RW_LOCK_UNLOCKED(xp_core_lock); /* protects ch->sp linkage */ static rwlock_t xp_list_lock = __RW_LOCK_UNLOCKED(xp_list_lock); /* protects open list */ #elif defined RW_LOCK_UNLOCKED static rwlock_t xp_core_lock = RW_LOCK_UNLOCKED; /* protect cd,sp,ch linkage */ static rwlock_t xp_list_lock = RW_LOCK_UNLOCKED; /* protect open list */ #else #error cannot initialize read-write locks #endif /* * ------------------------------------------------------------------------ * * Card Structures and Macros * * ------------------------------------------------------------------------ */ #ifdef X400P_DOWNLOAD_FIRMWARE #define GPIOC (0x54 >> 1) /* GPIO control register */ #define GPIO_WRITE 0x4000 /* GPIO4 data */ #define GPIO_PROGRAM 0x20000 /* GPIO5 data */ #define GPIO_INIT 0x100000 /* GPIO6 data */ #define GPIO_DONE 0x800000 /* GPIO7 data */ #endif #define INTCSR (0x4c >> 1) #define PLX_INTENA 0x43 #define STAREG 0x400 #define INTENABLED (1<<0) /* STAREG.0: interrupt enabled */ #define INTACTIVE (1<<1) /* STAREG.1: interrupt active */ #define DINTACT (1<<2) /* STAREG.2: dallas interrupt active */ #define SYNREG 0x400 #define SYNCSELF 0 /* SYNREG: 0x00 = sync to local clock (free run) */ #define SYNC1 1 /* SYNREG: 0x01 = sync source span 1 */ #define SYNC2 2 /* SYNREG: 0x02 = sync source span 2 */ #define SYNC3 3 /* SYNREG: 0x03 = sync source span 3 */ #define SYNC4 4 /* SYNREG: 0x04 = sync source span 4 */ #define SYNCEXTERN 5 /* SYNREG: 0x05 = sync to timing bus */ #define SYNCAUTO 6 /* SYNREG: 0x06 = sync to local clock (free run) */ #define CTLREG 0x401 #define INTENA (1<<0) /* CTLREG.0: interrupt enable */ #define OUTBIT (1<<1) /* CTLREG.1: drives "TEST1" signal ("Interrupt" outbit) */ #define DINTENA (1<<2) /* CTLREG.2: dallas interrupt enable (allows DINT signal to drive INT) */ #define MASTER (1<<3) /* CTLREG.3: external syncrhonization enable (MASTER signal). */ #define E1DIV (1<<4) /* CTLREG.4: select E1 divisor mode (0 to T1, 1 for E1). */ #define RSERLB (1<<5) /* CTLREG.5: remote serial loopback (TSER from RSER). */ #define LSERLB (1<<6) /* CTLREG.6: local serial loopback (Rx buffers from Tx buffers). */ #define INTACK (1<<7) /* CTLREG.7: interrupt acknowledge (set to 1 to acknowledge interrupt) */ #define LEDREG 0x402 /* LEDREG.0: span 1 green */ /* LEDREG.1: span 1 red */ #define LEDBLK 0 /* LEDREG.2: span 2 green */ /* LEDREG.3: span 2 red */ #define LEDGRN 1 /* LEDREG.4: span 3 green */ /* LEDREG.5: span 3 red */ #define LEDRED 2 /* LEDREG.6: span 4 green */ /* LEDREG.7: span 1 red */ #define LEDYEL 3 #define TSTREG 0x403 #define TEST2 (1<<0) /* TSTREG.0: drives TEST2 pin */ #define CTLREG1 0x404 #define NONREVA (1<<0) /* CTLREG1.0: non-REV.A mode (set this bit for Dallas chips later than Rev. A) */ #define X400_ABIT 8 #define X400_BBIT 4 #define X400_CARDS 16 /* 16 cards per system */ #define X400_SYNCS 16 /* 16 sync groups per system */ #define X400_SPANS 4 /* 4 spans per card */ /* allow alarms to settle for 5 seconds */ #define X400P_SDL_ALARM_SETTLE_SECONDS 5 #define X400P_SDL_ALARM_SETTLE_E1 80 #define X400P_SDL_ALARM_SETTLE_T1 120 #define X400P_SDL_ALARM_SETTLE_TIME 5000 enum xp_board { PLX9030 = 0, PLXDEVBRD, X400P, E400P, T400P, X400PSS7, E400PSS7, T400PSS7, V400P, V400PE, V400PT, V401PE, V401PT, AE400P, AT400P, A400P, A400PE, A400PT, CP100, CP100P, CP100E, CP200, CP200P, CP200E, CP400, CP400P, CP400E }; /* indexed by xp_board above */ #ifndef __devinitdata #define __devinitdata __initdata #endif #ifndef __devinit #define __devinit __init #endif #ifndef __devexit #define __devexit __exit #endif #ifndef __devexit_p #define __devexit_p __exit_p #endif /* *INDENT-OFF* */ static struct { char *name; uint32_t hw_flags; uint32_t idle_word; int ports; } xp_board_info[] __devinitdata = { { "PLX 9030", 0, 0x00000000, 4 }, { "PLX Development Board", 0, 0x00000000, 4 }, { "X400P", 1, 0xffffffff, 4 }, { "E400P", 1, 0xffffffff, 4 }, { "T400P", 1, 0xfefefefe, 4 }, { "X400P-SS7", 1, 0xffffffff, 4 }, { "E400P-SS7", 1, 0xffffffff, 4 }, { "T400P-SS7", 1, 0xfefefefe, 4 }, { "V400P", 1, 0xffffffff, 4 }, { "V400PE", 1, 0xffffffff, 4 }, { "V400PT", 1, 0xfefefefe, 4 }, { "V401PE", 1, 0xffffffff, 4 }, { "V401PT", 1, 0xfefefefe, 4 }, { "AE400P", 1, 0xffffffff, 4 }, { "AT400P", 1, 0xfefefefe, 4 }, { "A400P", 1, 0xffffffff, 4 }, { "A400PE", 1, 0xffffffff, 4 }, { "A400PT", 1, 0xfefefefe, 4 }, { "CP100", 1, 0xffffffff, 1 }, { "CP100P", 1, 0xffffffff, 1 }, { "CP100E", 1, 0xffffffff, 1 }, { "CP200", 1, 0xffffffff, 2 }, { "CP200P", 1, 0xffffffff, 2 }, { "CP200E", 1, 0xffffffff, 2 }, { "CP400", 1, 0xffffffff, 4 }, { "CP400P", 1, 0xffffffff, 4 }, { "CP400E", 1, 0xffffffff, 4 } }; #define XPF_SUPPORTED (1<<0) #define XP_DEV_IDMASK 0xf0 #define XP_DEV_SHIFT 4 #define XP_DEV_REVMASK 0x0f #define XP_DEV_DS2152 0x00 /* '0000XXXX'B DS2152 */ #define XP_DEV_DS21352 0x01 /* '0001XXXX'B DS21352 */ #define XP_DEV_DS21552 0x02 /* '0010XXXX'B DS21552 */ #define XP_DEV_DS21458 0x08 /* '1000XXXX'B DS21458 */ #define XP_DEV_DS21354 0x09 /* '1001XXXX'B DS21354 */ #define XP_DEV_DS21554 0x0a /* '1010XXXX'B DS21554 */ #define XP_DEV_DS2155 0x0b /* '1011XXXX'B DS2155 */ #define XP_DEV_DS21455 0x0c /* '1100XXXX'B DS21455 */ #define XP_DEV_DS2153 0x10 /* '00000000'B DS2153 */ /* make this 0x10: it really conflicts with 0x00 */ #define XP_DEV_DS2156 0x1c /* '1010XXXX'B DS2156 */ /* make this 0x1c: it really conflicts with 0x0c */ #define XP_DEV_DS2154 0x18 /* '1000XXXX'B DS2154 */ /* make this 0x18: it really conflicts with 0x08 */ STATIC struct { char *name; uint32_t hw_flags; } xp_device_info[] __devinitdata = { { "DS2152 (T1)", 0 }, /* { "DS2153 (E1)", 0 }, */ { "DS21352 (T1)", 1 }, { "DS21552 (T1)", 1 }, { "Unknown ID 0011", 0 }, { "Unknown ID 0100", 0 }, { "Unknown ID 0101", 0 }, { "Unknown ID 0110", 0 }, { "Unknown ID 0111", 0 }, { "DS21458 (E1/T1/J1)", 1 }, /* { "DS2154 (E1)", 0 }, */ { "DS21354 (E1)", 1 }, { "DS21554 (E1)", 1 }, { "DS2155 (E1/T1/J1)", 1 }, { "DS21455 (E1/T1/J1)", 1 }, /* { "DS2156 (E1/T1/J1)", 1 }, */ { "Unknown ID 1101", 0 }, { "Unknown ID 1110", 0 }, { "Unknown ID 1111", 0 } }; STATIC struct pci_device_id xp_pci_tbl[] __devinitdata = { {PCI_VENDOR_ID_PLX, 0x9030, PCI_ANY_ID, PCI_ANY_ID, PCI_CLASS_BRIDGE_OTHER << 8, 0xffff00, PLX9030}, {PCI_VENDOR_ID_PLX, 0x3001, PCI_ANY_ID, PCI_ANY_ID, PCI_CLASS_BRIDGE_OTHER << 8, 0xffff00, PLXDEVBRD}, {PCI_VENDOR_ID_PLX, 0xD00D, PCI_ANY_ID, PCI_ANY_ID, PCI_CLASS_BRIDGE_OTHER << 8, 0xffff00, X400P}, {PCI_VENDOR_ID_PLX, 0x0557, PCI_ANY_ID, PCI_ANY_ID, PCI_CLASS_BRIDGE_OTHER << 8, 0xffff00, X400PSS7}, {PCI_VENDOR_ID_PLX, 0xD44D, PCI_ANY_ID, 0x17F6, PCI_CLASS_BRIDGE_OTHER << 8, 0xffff00, CP100}, {PCI_VENDOR_ID_PLX, 0xD44D, PCI_ANY_ID, 0x17F8, PCI_CLASS_BRIDGE_OTHER << 8, 0xffff00, CP200}, {PCI_VENDOR_ID_PLX, 0xD44D, PCI_ANY_ID, 0x17F7, PCI_CLASS_BRIDGE_OTHER << 8, 0xffff00, CP400}, {PCI_VENDOR_ID_PLX, 0x4000, PCI_ANY_ID, PCI_ANY_ID, PCI_CLASS_BRIDGE_OTHER << 8, 0xffff00, V400P}, {PCI_VENDOR_ID_PLX, 0xD33D, PCI_ANY_ID, PCI_ANY_ID, PCI_CLASS_BRIDGE_OTHER << 8, 0xffff00, V401PT}, {PCI_VENDOR_ID_PLX, 0xD44D, PCI_ANY_ID, PCI_ANY_ID, PCI_CLASS_BRIDGE_OTHER << 8, 0xffff00, V401PE}, {PCI_VENDOR_ID_PLX, 0x1000, PCI_ANY_ID, PCI_ANY_ID, PCI_CLASS_BRIDGE_OTHER << 8, 0xffff00, AT400P}, {PCI_VENDOR_ID_PLX, 0x2000, PCI_ANY_ID, PCI_ANY_ID, PCI_CLASS_BRIDGE_OTHER << 8, 0xffff00, AE400P}, {PCI_VENDOR_ID_PLX, 0x4001, PCI_ANY_ID, PCI_ANY_ID, PCI_CLASS_BRIDGE_OTHER << 8, 0xffff00, A400PE}, {PCI_VENDOR_ID_PLX, 0x4002, PCI_ANY_ID, PCI_ANY_ID, PCI_CLASS_BRIDGE_OTHER << 8, 0xffff00, A400PT}, {0,} }; /* *INDENT-ON* */ #ifdef MODULE_DEVICE_TABLE MODULE_DEVICE_TABLE(pci, xp_pci_tbl); #ifdef MODULE_ALIAS MODULE_ALIAS("pci:v000010B5d00009030sv*sd*bc06sc80i*"); MODULE_ALIAS("pci:v000010B5d00003001sv*sd*bc06sc80i*"); MODULE_ALIAS("pci:v000010B5d0000D00Dsv*sd*bc06sc80i*"); MODULE_ALIAS("pci:v000010B5d00000557sv*sd*bc06sc80i*"); MODULE_ALIAS("pci:v000010B5d00004000sv*sd*bc06sc80i*"); MODULE_ALIAS("pci:v000010B5d0000D33Dsv*sd*bc06sc80i*"); MODULE_ALIAS("pci:v000010B5d0000D44Dsv*sd*bc06sc80i*"); MODULE_ALIAS("pci:v000010B5d00001000sv*sd*bc06sc80i*"); MODULE_ALIAS("pci:v000010B5d00002000sv*sd*bc06sc80i*"); MODULE_ALIAS("pci:v000010B5d00004001sv*sd*bc06sc80i*"); MODULE_ALIAS("pci:v000010B5d00004002sv*sd*bc06sc80i*"); MODULE_ALIAS("pci:v000010B5d0000D44Dsv*sd000017F6bc06sc80i*"); MODULE_ALIAS("pci:v000010B5d0000D44Dsv*sd000017F8bc06sc80i*"); MODULE_ALIAS("pci:v000010B5d0000D44Dsv*sd000017F7bc06sc80i*"); #endif /* MODULE_ALIAS */ #endif /* MODULE_DEVICE_TABLE */ unsigned short ansi = 0; unsigned short etsi = 0; unsigned short japan = 0; #ifndef module_param MODULE_PARM(ansi, "h"); MODULE_PARM(etsi, "h"); MODULE_PARM(japan, "h"); #else module_param(ansi, ushort, 0444); module_param(etsi, ushort, 0444); module_param(japan, ushort, 0444); #endif MODULE_PARM_DESC(japan, "Configure any T1/J1 or E1/T1/J1 devices for J1 (only) operation (overrides ansi=1)."); MODULE_PARM_DESC(ansi, "Configure any T1/J1 or E1/T1/J1 devices for T1 (only) operation."); MODULE_PARM_DESC(etsi, "Configure all E1 or E1/T1/J1 devices for E1 (only) operation (overrides ansi=1)."); /* Map from T1 channel number to Tormenta backpane time slot offset. */ STATIC int xp_t1_chan_map[] = { 0, 1, 2, 3, 5, 6, 7, 9, 10, 11, 13, 14, 15, 17, 18, 19, 21, 22, 23, 25, 26, 27, 29, 30, 31 }; /* Map from E1 channel number to Tormenta backplane time slot offset. */ STATIC int xp_e1_chan_map[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31 }; #define XP_T1_TS_VALID_MASK 0x00ffffff /* Mask of valid T1 time slots. */ #define XP_E1_TS_VALID_MASK 0x7fffffff /* Mask of valid E1 time slots. */ #define XP_T1_CHAN_VALID_MASK 0xeeeeeeee /* Mask of valid T1 Tormenta channels. */ #define XP_E1_CHAN_VALID_MASK 0xfffffffe /* Mask of valid E1 Tormenta channels. */ #ifdef __LITTLE_ENDIAN #define span_to_byte(__span) (3-(__span)) #else #ifdef __BIG_ENDIAN #define span_to_byte(__span) (__span) #else #error "Must know the endianess of processor\n" #endif #endif STATIC int x400p_boards = 0; STATIC struct cd *x400p_cards[X400_CARDS] = { NULL, }; /* master card list */ STATIC int x400p_groups = 0; STATIC struct sg *x400p_syncs[X400_SYNCS] = { NULL, }; /* master sync list */ #if defined DEFINE_RWLOCK STATIC DEFINE_RWLOCK(x400p_lock); #elif defined __RW_LOCK_UNLOCKED STATIC rwlock_t x400p_lock = __RW_LOCK_UNLOCKED(x400p_lock); #elif defined RW_LOCK_UNLOCKED STATIC rwlock_t x400p_lock = RW_LOCK_UNLOCKED; #else #error cannot initialize read-write locks #endif STATIC struct xp *x400p_xrays; /* xraying streams for this driver */ #define X400P_EBUFNO (1<<7) /* 128k elastic buffers */ /* * ======================================================================== * * PRIMITIVES Sent Upstream * * ======================================================================== */ static inline fastcall __hot void snapmsg(mblk_t *mp, ssize_t len) { register mblk_t *b; register ssize_t remain = len; for (b = mp; b; b = b->b_cont) { register ssize_t blen = b->b_rptr - b->b_wptr; if (blen <= 0) continue; if (unlikely(remain == 0)) { b->b_wptr = b->b_rptr; } else if (likely(blen <= remain)) { remain -= blen; } else { b->b_wptr = b->b_rptr + remain; remain = 0; } } } noinline fastcall __hot void xp_dup_to_xray(struct xp *xp, mblk_t *mp, uint mask, size_t hlen, struct timeval *tv, size_t mlen) { for (; xp; xp = xp->xray.next) { mblk_t *dp; uint hlen = 0; uint flags = xp->xray.nit.flags; if (!(flags & mask)) continue; if (unlikely(!canputnext(xp->rq))) goto dropped; if (unlikely((dp = dupmsg(mp)) == NULL)) goto dropped; if (unlikely(flags & NI_TIMESTAMP)) hlen += sizeof(*tv); if (unlikely(flags & NI_DROPS)) hlen += sizeof(ulong); if (unlikely(flags & NI_LEN)) hlen += sizeof(ulong); if (unlikely(xp->xray.nit.snap > 0)) snapmsg(dp, xp->xray.nit.snap + hlen); if (unlikely(hlen != 0)) { mblk_t *bp = allocb(hlen, BPRI_MED); /* nit(4) says theses must be in their own M_PROTO */ DB_TYPE(bp) = M_PROTO; if (unlikely(bp == NULL)) { freemsg(dp); goto dropped; } bp->b_wptr = bp->b_rptr + hlen; bp->b_cont = dp; if (likely(flags & NI_LEN)) { bp->b_wptr -= sizeof(ulong); *(ulong *) bp->b_wptr = mlen; } if (likely(flags & NI_DROPS)) { bp->b_wptr -= sizeof(ulong); *(ulong *) bp->b_wptr = atomic_read(&xp->xray.drops); atomic_set(&xp->xray.drops, 0); } if (likely(flags & NI_TIMESTAMP)) { bp->b_wptr -= sizeof(*tv); *(typeof(tv)) bp->b_wptr = *tv; } bp->b_wptr = bp->b_rptr + hlen; dp = bp; } putnext(xp->rq, dp); continue; dropped: atomic_inc(&xp->xray.drops); } } noinline fastcall __hot void xp_xray_data(struct ch *ch, mblk_t *mp, uint flags, size_t hlen) { struct sp *sp = ch->sp; struct timeval tv = { 0, 0 }; size_t mlen = 0; prefetch(sp); if (unlikely(flags & NI_TIMESTAMP)) /* some xray stream wants a timestamp */ do_gettimeofday(&tv); if (unlikely(flags & NI_LEN)) /* some xray stream wants message length */ mlen = msgsize(mp); if (unlikely(flags & XP_XRAY_CHAN)) xp_dup_to_xray(ch->xray.list, mp, flags, hlen, &tv, mlen); { struct cd *cd = sp->cd; prefetch(cd); if (unlikely(flags & XP_XRAY_SPAN)) xp_dup_to_xray(sp->xray, mp, flags, hlen, &tv, mlen); prefetch(x400p_xrays); if (unlikely(flags & XP_XRAY_CARD)) xp_dup_to_xray(cd->xray, mp, flags, hlen, &tv, mlen); } if (unlikely(flags & XP_XRAY_GLOB)) xp_dup_to_xray(x400p_xrays, mp, flags, hlen, &tv, mlen); } /* The Old SNIT headers are struct nit_iftime (2 ulongs) if NI_TIMESTAMP set, struct nit_ifdrops (1 * ulong) if NI_DROPS set, struct nit_iflen (1 ulong) if NI_LEN set. This is up to 4 ulongs (or as * many as 32 bytes). */ /* SL data is DLT_MTP3, mp must be M_DATA */ static inline fastcall __hot void sl_xray_data_rx(struct ch *ch, mblk_t *mp) { if (unlikely(ch->xray.flags & XP_XRAY_SL_RX)) xp_xray_data(ch, mp, ch->xray.flags & (XP_XRAY_SL_RX | NI_USERBITS), 0); } /* SL data is DLT_MTP3, mp must be M_DATA */ static inline fastcall __hot void sl_xray_data_tx(struct ch *ch, mblk_t *mp) { if (unlikely(ch->xray.flags & XP_XRAY_SL_TX)) xp_xray_data(ch, mp, ch->xray.flags & (XP_XRAY_SL_TX | NI_USERBITS), 0); } /** sdt_xray_data: - generate SDT-level monitoring data * @ch: channel structure (locked) * @mp: the M_DATA buffer containing the data * @flags: xray flags * @dir: the direction of the data * * pseudo header is 1 byte for sent or received, true when sent, 1 byte for Annex A used, true when * used, and 2 bytes for the link number. We used the ppa for the link number. For RX data, we * can fix the lower layer to leave 4 bytes room on the head of its buffers so that we do not have * to allocate a message block. Note that the upper layers do not add headers so even though the * message blocks are shared, the pseudo header will not later be overwritten. * * Note that SS7_POPT_XSN is tested instead of SS7_POPT_HSL. HSL is just for high-speed links (full * span). XSN is for extended sequence numbers, the only thing PCAP worries about. */ noinline fastcall __hot void sdt_xray_data(struct ch *ch, mblk_t *mp, uint flags, uint dir) { mblk_t *dp = mp; if (likely(DB_LIM(mp) + 4 < mp->b_rptr)) { dp->b_rptr -= 4; } else { if (unlikely((dp = allocb(4, BPRI_MED)) == NULL)) return; dp->b_wptr = dp->b_rptr + 4; dp->b_cont = mp; } dp->b_rptr[0] = dir; dp->b_rptr[1] = (ch->option.popt & SS7_POPT_XSN) ? 1 : 0; *(uint16_t *) &dp->b_rptr[2] = ch->ppa; xp_xray_data(ch, dp, ch->xray.flags & (flags | NI_USERBITS), 4); if (dp == mp) dp->b_rptr += 4; else freeb(dp); } /* SDT data is DLT_MTP2_WITH_PHDR, mp must be M_DATA */ static inline fastcall __hot void sdt_xray_data_rx(struct ch *ch, mblk_t *mp) { if (unlikely(ch->xray.flags & XP_XRAY_SDT_RX)) sdt_xray_data(ch, mp, XP_XRAY_SDT_RX, 0); } /* SDT data is DLT_MTP2_WITH_PHDR, mp must be M_DATA */ static inline fastcall __hot void sdt_xray_data_tx(struct ch *ch, mblk_t *mp) { if (unlikely(ch->xray.flags & XP_XRAY_SDT_TX)) sdt_xray_data(ch, mp, XP_XRAY_SDT_TX, 1); } /* PCAP can't capture raw bit streams */ static inline __hot void sdl_xray_data_rx(struct ch *ch, mblk_t *mp) { if (unlikely(ch->xray.flags & XP_XRAY_SDL_RX)) xp_xray_data(ch, mp, ch->xray.flags & XP_XRAY_SDL_RX, 0); } static inline __hot void sdl_xray_data_tx(struct ch *ch, mblk_t *mp) { if (unlikely(ch->xray.flags & XP_XRAY_SDL_TX)) xp_xray_data(ch, mp, ch->xray.flags & XP_XRAY_SDL_TX, 0); } /* * ======================================================================= * * PRIMITIVES * * ======================================================================= */ #if !defined _OPTIMIZE_SPEED /** lmi_primname: - name LMI, SL, SDT or SDL primitives. * @prim: the primitive to name * Returns the name of the primitive or "(unknown)". */ static const char * sl_primname(lmi_long prim) { switch (prim) { case SL_PDU_REQ: return ("SL_PDU_REQ"); case SL_EMERGENCY_REQ: return ("SL_EMERGENCY_REQ"); case SL_EMERGENCY_CEASES_REQ: return ("SL_EMERGENCY_CEASES_REQ"); case SL_START_REQ: return ("SL_START_REQ"); case SL_STOP_REQ: return ("SL_STOP_REQ"); case SL_RETRIEVE_BSNT_REQ: return ("SL_RETRIEVE_BSNT_REQ"); case SL_RETRIEVAL_REQUEST_AND_FSNC_REQ: return ("SL_RETRIEVAL_REQUEST_AND_FSNC_REQ"); case SL_CLEAR_BUFFERS_REQ: return ("SL_CLEAR_BUFFERS_REQ"); case SL_CLEAR_RTB_REQ: return ("SL_CLEAR_RTB_REQ"); case SL_CONTINUE_REQ: return ("SL_CONTINUE_REQ"); case SL_LOCAL_PROCESSOR_OUTAGE_REQ: return ("SL_LOCAL_PROCESSOR_OUTAGE_REQ"); case SL_RESUME_REQ: return ("SL_RESUME_REQ"); case SL_CONGESTION_DISCARD_REQ: return ("SL_CONGESTION_DISCARD_REQ"); case SL_CONGESTION_ACCEPT_REQ: return ("SL_CONGESTION_ACCEPT_REQ"); case SL_NO_CONGESTION_REQ: return ("SL_NO_CONGESTION_REQ"); case SL_POWER_ON_REQ: return ("SL_POWER_ON_REQ"); case SL_OPTMGMT_REQ: return ("SL_OPTMGMT_REQ"); case SL_NOTIFY_REQ: return ("SL_NOTIFY_REQ"); case SL_PDU_IND: return ("SL_PDU_IND"); case SL_LINK_CONGESTED_IND: return ("SL_LINK_CONGESTED_IND"); case SL_LINK_CONGESTION_CEASED_IND: return ("SL_LINK_CONGESTION_CEASED_IND"); case SL_RETRIEVED_MESSAGE_IND: return ("SL_RETRIEVED_MESSAGE_IND"); case SL_RETRIEVAL_COMPLETE_IND: return ("SL_RETRIEVAL_COMPLETE_IND"); case SL_RB_CLEARED_IND: return ("SL_RB_CLEARED_IND"); case SL_BSNT_IND: return ("SL_BSNT_IND"); case SL_IN_SERVICE_IND: return ("SL_IN_SERVICE_IND"); case SL_OUT_OF_SERVICE_IND: return ("SL_OUT_OF_SERVICE_IND"); case SL_REMOTE_PROCESSOR_OUTAGE_IND: return ("SL_REMOTE_PROCESSOR_OUTAGE_IND"); case SL_REMOTE_PROCESSOR_RECOVERED_IND: return ("SL_REMOTE_PROCESSOR_RECOVERED_IND"); case SL_RTB_CLEARED_IND: return ("SL_RTB_CLEARED_IND"); case SL_RETRIEVAL_NOT_POSSIBLE_IND: return ("SL_RETRIEVAL_NOT_POSSIBLE_IND"); case SL_BSNT_NOT_RETRIEVABLE_IND: return ("SL_BSNT_NOT_RETRIEVABLE_IND"); case SL_OPTMGMT_ACK: return ("SL_OPTMGMT_ACK"); case SL_NOTIFY_IND: return ("SL_NOTIFY_IND"); case SL_LOCAL_PROCESSOR_OUTAGE_IND: return ("SL_LOCAL_PROCESSOR_OUTAGE_IND"); case SL_LOCAL_PROCESSOR_RECOVERED_IND: return ("SL_LOCAL_PROCESSOR_RECOVERED_IND"); default: return ("(unknown)"); } } static const char * sdt_primname(const lmi_long prim) { switch (prim) { case SDT_DAEDT_TRANSMISSION_REQ: return ("SDT_DAEDT_TRANSMISSION_REQ"); case SDT_DAEDT_START_REQ: return ("SDT_DAEDT_START_REQ"); case SDT_DAEDR_START_REQ: return ("SDT_DAEDR_START_REQ"); case SDT_AERM_START_REQ: return ("SDT_AERM_START_REQ"); case SDT_AERM_STOP_REQ: return ("SDT_AERM_STOP_REQ"); case SDT_AERM_SET_TI_TO_TIN_REQ: return ("SDT_AERM_SET_TI_TO_TIN_REQ"); case SDT_AERM_SET_TI_TO_TIE_REQ: return ("SDT_AERM_SET_TI_TO_TIE_REQ"); case SDT_SUERM_START_REQ: return ("SDT_SUERM_START_REQ"); case SDT_SUERM_STOP_REQ: return ("SDT_SUERM_STOP_REQ"); case SDT_RC_SIGNAL_UNIT_IND: return ("SDT_RC_SIGNAL_UNIT_IND"); case SDT_RC_CONGESTION_ACCEPT_IND: return ("SDT_RC_CONGESTION_ACCEPT_IND"); case SDT_RC_CONGESTION_DISCARD_IND: return ("SDT_RC_CONGESTION_DISCARD_IND"); case SDT_RC_NO_CONGESTION_IND: return ("SDT_RC_NO_CONGESTION_IND"); case SDT_IAC_CORRECT_SU_IND: return ("SDT_IAC_CORRECT_SU_IND"); case SDT_IAC_ABORT_PROVING_IND: return ("SDT_IAC_ABORT_PROVING_IND"); case SDT_LSC_LINK_FAILURE_IND: return ("SDT_LSC_LINK_FAILURE_IND"); case SDT_TXC_TRANSMISSION_REQUEST_IND: return ("SDT_TXC_TRANSMISSION_REQUEST_IND"); default: return ("(unknown)"); } } static const char * sdl_primname(lmi_long prim) { switch (prim) { case SDL_BITS_FOR_TRANSMISSION_REQ: return ("SDL_BITS_FOR_TRANSMISSION_REQ"); case SDL_CONNECT_REQ: return ("SDL_CONNECT_REQ"); case SDL_DISCONNECT_REQ: return ("SDL_DISCONNECT_REQ"); case SDL_RECEIVED_BITS_IND: return ("SDL_RECEIVED_BITS_IND"); case SDL_DISCONNECT_IND: return ("SDL_DISCONNECT_IND"); default: return ("(unknown)"); } } static const char * lmi_primname(lmi_long prim) { switch (prim) { case LMI_INFO_REQ: return ("LMI_INFO_REQ"); case LMI_ATTACH_REQ: return ("LMI_ATTACH_REQ"); case LMI_DETACH_REQ: return ("LMI_DETACH_REQ"); case LMI_ENABLE_REQ: return ("LMI_ENABLE_REQ"); case LMI_DISABLE_REQ: return ("LMI_DISABLE_REQ"); case LMI_OPTMGMT_REQ: return ("LMI_OPTMGMT_REQ"); case LMI_INFO_ACK: return ("LMI_INFO_ACK"); case LMI_OK_ACK: return ("LMI_OK_ACK"); case LMI_ERROR_ACK: return ("LMI_ERROR_ACK"); case LMI_ENABLE_CON: return ("LMI_ENABLE_CON"); case LMI_DISABLE_CON: return ("LMI_DISABLE_CON"); case LMI_OPTMGMT_ACK: return ("LMI_OPTMGMT_ACK"); case LMI_ERROR_IND: return ("LMI_ERROR_IND"); case LMI_STATS_IND: return ("LMI_STATS_IND"); case LMI_EVENT_IND: return ("LMI_EVENT_IND"); default: return ("(unknown)"); } } static const char * dlpi_primname(dl_ulong prim) { switch (prim) { case DL_INFO_REQ: return ("DL_INFO_REQ"); case DL_INFO_ACK: return ("DL_INFO_ACK"); case DL_ATTACH_REQ: return ("DL_ATTACH_REQ"); case DL_DETACH_REQ: return ("DL_DETACH_REQ"); case DL_BIND_REQ: return ("DL_BIND_REQ"); case DL_BIND_ACK: return ("DL_BIND_ACK"); case DL_UNBIND_REQ: return ("DL_UNBIND_REQ"); case DL_OK_ACK: return ("DL_OK_ACK"); case DL_ERROR_ACK: return ("DL_ERROR_ACK"); case DL_SUBS_BIND_REQ: return ("DL_SUBS_BIND_REQ"); case DL_SUBS_BIND_ACK: return ("DL_SUBS_BIND_ACK"); case DL_SUBS_UNBIND_REQ: return ("DL_SUBS_UNBIND_REQ"); case DL_ENABMULTI_REQ: return ("DL_ENABMULTI_REQ"); case DL_DISABMULTI_REQ: return ("DL_DISABMULTI_REQ"); case DL_PROMISCON_REQ: return ("DL_PROMISCON_REQ"); case DL_PROMISCOFF_REQ: return ("DL_PROMISCOFF_REQ"); case DL_UNITDATA_REQ: return ("DL_UNITDATA_REQ"); case DL_UNITDATA_IND: return ("DL_UNITDATA_IND"); case DL_UDERROR_IND: return ("DL_UDERROR_IND"); case DL_UDQOS_REQ: return ("DL_UDQOS_REQ"); case DL_CONNECT_REQ: return ("DL_CONNECT_REQ"); case DL_CONNECT_IND: return ("DL_CONNECT_IND"); case DL_CONNECT_RES: return ("DL_CONNECT_RES"); case DL_CONNECT_CON: return ("DL_CONNECT_CON"); case DL_TOKEN_REQ: return ("DL_TOKEN_REQ"); case DL_TOKEN_ACK: return ("DL_TOKEN_ACK"); case DL_DISCONNECT_REQ: return ("DL_DISCONNECT_REQ"); case DL_DISCONNECT_IND: return ("DL_DISCONNECT_IND"); case DL_RESET_REQ: return ("DL_RESET_REQ"); case DL_RESET_IND: return ("DL_RESET_IND"); case DL_RESET_RES: return ("DL_RESET_RES"); case DL_RESET_CON: return ("DL_RESET_CON"); case DL_DATA_ACK_REQ: return ("DL_DATA_ACK_REQ"); case DL_DATA_ACK_IND: return ("DL_DATA_ACK_IND"); case DL_DATA_ACK_STATUS_IND: return ("DL_DATA_ACK_STATUS_IND"); case DL_REPLY_REQ: return ("DL_REPLY_REQ"); case DL_REPLY_IND: return ("DL_REPLY_IND"); case DL_REPLY_STATUS_IND: return ("DL_REPLY_STATUS_IND"); case DL_REPLY_UPDATE_REQ: return ("DL_REPLY_UPDATE_REQ"); case DL_REPLY_UPDATE_STATUS_IND: return ("DL_REPLY_UPDATE_STATUS_IND 0x28"); case DL_XID_REQ: return ("DL_XID_REQ"); case DL_XID_IND: return ("DL_XID_IND"); case DL_XID_RES: return ("DL_XID_RES"); case DL_XID_CON: return ("DL_XID_CON"); case DL_TEST_REQ: return ("DL_TEST_REQ"); case DL_TEST_IND: return ("DL_TEST_IND"); case DL_TEST_RES: return ("DL_TEST_RES"); case DL_TEST_CON: return ("DL_TEST_CON"); case DL_PHYS_ADDR_REQ: return ("DL_PHYS_ADDR_REQ"); case DL_PHYS_ADDR_ACK: return ("DL_PHYS_ADDR_ACK"); case DL_SET_PHYS_ADDR_REQ: return ("DL_SET_PHYS_ADDR_REQ"); case DL_GET_STATISTICS_REQ: return ("DL_GET_STATISTICS_REQ"); case DL_GET_STATISTICS_ACK: return ("DL_GET_STATISTICS_ACK"); case DL_MONITOR_LINK_LAYER: return ("DL_MONITOR_LINK_LAYER"); #ifdef _SUN_SOURCE case DL_NOTIFY_REQ: return ("DL_NOTIFY_REQ"); case DL_NOTIFY_ACK: return ("DL_NOTIFY_ACK"); case DL_NOTIFY_IND: return ("DL_NOTIFY_IND"); case DL_AGGR_REQ: return ("DL_AGGR_REQ"); case DL_AGGR_IND: return ("DL_AGGR_IND"); case DL_UNAGGR_REQ: return ("DL_UNAGGR_REQ"); case DL_CAPABILITY_REQ: return ("DL_CAPABILITY_REQ"); case DL_CAPABILITY_ACK: return ("DL_CAPABILITY_ACK"); case DL_CONTROL_REQ: return ("DL_CONTROL_REQ"); case DL_CONTROL_ACK: return ("DL_CONTROL_ACK"); case DL_PASSIVE_REQ: return ("DL_PASSIVE_REQ"); case DL_INTR_MODE_REQ: return ("DL_INTR_MODE_REQ"); #endif /* _SUN_SOURCE */ #ifdef _HPUX_SOURCE case DL_HP_PPA_REQ: return ("DL_HP_PPA_REQ"); case DL_HP_PPA_ACK: return ("DL_HP_PPA_ACK"); case DL_HP_MULTICAST_LIST_REQ: return ("DL_HP_MULTICAST_LIST_REQ"); case DL_HP_MULTICAST_LIST_ACK: return ("DL_HP_MULTICAST_LIST_ACK"); case DL_HP_RAWDATA_REQ: return ("DL_HP_RAWDATA_REQ"); case DL_HP_RAWDATA_IND: return ("DL_HP_RAWDATA_IND"); case DL_HP_HW_RESET_REQ: return ("DL_HP_HW_RESET_REQ"); case DL_HP_INFO_REQ: return ("DL_HP_INFO_REQ"); case DL_HP_INFO_ACK: return ("DL_HP_INFO_ACK"); case DL_HP_SET_ACK_TO_REQ: return ("DL_HP_SET_ACK_TO_REQ"); case DL_HP_SET_P_TO_REQ: return ("DL_HP_SET_P_TO_REQ"); case DL_HP_SET_REJ_TO_REQ: return ("DL_HP_SET_REJ_TO_REQ"); case DL_HP_SET_BUSY_TO_REQ: return ("DL_HP_SET_BUSY_TO_REQ"); case DL_HP_SET_SEND_ACK_TO_REQ: return ("DL_HP_SET_SEND_ACK_TO_REQ"); case DL_HP_SET_MAX_RETRIES_REQ: return ("DL_HP_SET_MAX_RETRIES_REQ"); case DL_HP_SET_ACK_THRESHOLD_REQ: return ("DL_HP_SET_ACK_THRESHOLD_REQ"); case DL_HP_SET_LOCAL_WIN_REQ: return ("DL_HP_SET_LOCAL_WIN_REQ"); case DL_HP_SET_REMOTE_WIN_REQ: return ("DL_HP_SET_REMOTE_WIN_REQ"); case DL_HP_CLEAR_STATS_REQ: return ("DL_HP_CLEAR_STATS_REQ"); case DL_HP_SET_LOCAL_BUSY_REQ: return ("DL_HP_SET_LOCAL_BUSY_REQ"); case DL_HP_CLEAR_LOCAL_BUSY_REQ: return ("DL_HP_CLEAR_LOCAL_BUSY_REQ"); #endif /* _HPUX_SOURCE */ default: return ("(unknown)"); } } #endif /* !defined _OPTIMIZE_SPEED */ /* * STREAMS MESSAGES ISSUED UPSTREAM * ------------------------------------------------------------------------- */ /** m_error: issue M_ERROR message * @xp: private structure (locked) * @q: active queue (write queue) * @mp: message to reuse * @err: +'ve or -'ve error to return * * Note that this is only ever called in response to a message on the write queue. The passed in * message is always consumed. */ noinline __unlikely int m_error(struct xp *xp, queue_t *q, mblk_t *mp, int err) { if (mp || (mp = mi_allocb(q, 2, BPRI_MED))) { if (mp->b_cont) freemsg(XCHG(&mp->b_cont, NULL)); /* I don't know that the above was necessary, the Stream head will not look beyond the M_ERROR message block. */ mp->b_band = 0; DB_TYPE(mp) = M_ERROR; mp->b_wptr = mp->b_rptr + 2; mp->b_rptr[0] = err < 0 ? -err : err; mp->b_rptr[1] = err < 0 ? -err : err; LOGTX(xp2sid(xp), "<- M_ERROR"); qreply(q, mp); return (0); } rare(); return (-ENOBUFS); } /* * SLI PRIMITIVES ISSUED UPSTREAM * ------------------------------------------------------------------------- */ /** sl_flush_wq: - flush write queue of active stream * @ch: channel structure (locked) * * This function is called from the state machine (but only under the context of the write queue * put or service routine). The function should remove M_DATA and SL_PDU_REQ messages only instead * of flushing all M_PROTO, M_PCPROTO, M_DATA and M_DELAY messages. */ static inline fastcall __unlikely void sl_flush_wq(struct ch *ch) { struct xp *xp; if (likely((xp = ch->xp) != NULL)) flushq(xp->wq, FLUSHDATA); } /** sl_flush_rq: - flush read queue of active stream * @ch: channel structure (locked) * * This function is called from the state machine (but only under the context of the write queue * put or service routine). The function should remove M_DATA and SL_PDU_REQ messages only instead * of flushing all M_PROTO, M_PCPROTO, M_DATA and M_DELAY messages. */ static inline fastcall __unlikely void sl_flush_rq(struct ch *ch) { struct xp *xp; if (likely((xp = ch->xp) != NULL)) flushq(xp->rq, FLUSHDATA); } /** sl_enable_rq: - flush read queue of active stream * @ch: channel structure (locked) */ static inline fastcall __unlikely void sl_enable_rq(struct ch *ch) { struct xp *xp; if (likely((xp = ch->xp) != NULL)) qenable(xp->rq); } /** sl_count_rq: - count read queue of active stream * @ch: channel structure (locked) */ static inline fastcall __hot_write uint sl_count_rq(struct ch *ch) { struct xp *xp; if (likely((xp = ch->xp) != NULL)) return xp->rq->q_count; else return (0); } /** sl_data_ind: issue M_DATA message upstream * @ch: channel structure (locked) * @mp: the M_DATA message */ static inline fastcall __hot_read int sl_data_ind(struct ch *ch, mblk_t *mp) { struct xp *xp; if (likely((xp = ch->xp) != NULL)) { put(xp->rq, mp); return (0); } else { freemsg(mp); return (-ENXIO); } } /** sl_pdu_ind: issue SL_PDU_IND message upstream * @ch: channel structure (locked) * @dp: data portion of message * * We don't actually use SL_PDU_INDs, we pass along M_DATA messages. This function is never * called. */ static inline fastcall __hot_read int sl_pdu_ind(struct ch *ch, mblk_t *dp) { struct xp *xp; /* FIXME: this is where we do SL monitoring */ if (likely((xp = ch->xp) != NULL)) { #if 0 sl_pdu_ind_t *p; mblk_t *mp; if ((mp = allocb(sizeof(*p), BPRI_MED))) { DB_TYPE(mp) = M_PROTO; p = (typeof(p)) mp->b_wptr; mp->b_wptr += sizeof(*p); p->sl_primitive = SL_PDU_IND; mp->b_cont = dp; LOGTX(xp2sid(xp), "<- SL_PDU_IND"); put(xp->rq, mp); return (0); } else { return (-ENOBUFS); } #else put(xp->rq, dp); ch->sl.stats.sl_recv_msus++; return (0); #endif } else { return (-ENXIO); } } /** sl_link_congested_ind: - issue SL_LINK_CONGESTED_IND primitive * @ch: channel structure (locked) * @q: active queue (write queue) or NULL * @mp: message to reuse or NULL * * There are two ways that SL_LINK_CONGESTED_IND can be issued: (1) in response adding a message * for transmision (SL_PDU_REQ or M_DATA); (2) in response to an autonomous event within the state * machine. In the first case, @q and @mp will be non-null and the xp structure will be locked * because we are called from the context of the write queue put or service procedure. In the * later case, @q and @mp are NULL, xp is unlocked (and might not exist), and we are being called * from the tasklet. */ noinline fastcall __unlikely int sl_link_congested_ind(struct ch *ch, queue_t *q, mblk_t *mp) { struct xp *xp; if (likely((xp = ch->xp) != NULL)) { sl_link_cong_ind_t *p; if (mp || (mp = mi_allocb(q ? : xp->rq, sizeof(*p), BPRI_MED))) { mp->b_band = 0; DB_TYPE(mp) = M_PROTO; p = (typeof(p)) mp->b_rptr; mp->b_wptr = mp->b_rptr + sizeof(*p); p->sl_primitive = SL_LINK_CONGESTED_IND; p->sl_cong_status = ch->sl.statem.cong_status; p->sl_disc_status = ch->sl.statem.disc_status; /* FIXME: clear bit indicating that SL_LINK_CONGESTED_IND is required. */ LOGTX(xp2sid(xp), "<- SL_LINK_CONGESTED_IND"); put(q ? RD(q) : xp->rq, mp); return (0); } /* FIXME: set bit indicating that SL_LINK_CONGESTED_IND is required. */ rare(); return (-ENOBUFS); } freemsg(mp); return (0); } /** sl_link_congestion_ceased_ind: - issue SL_LINK_CONGESTION_CEASED_IND * @ch: channel structure (locked) * @q: active queue (write queue) or NULL * @mp: message to reuse or NULL */ noinline fastcall __unlikely int sl_link_congestion_ceased_ind(struct ch *ch, queue_t *q, mblk_t *mp) { struct xp *xp; if (likely((xp = ch->xp) != NULL)) { sl_link_cong_ceased_ind_t *p; if (mp || (mp = mi_allocb(q ? : xp->rq, sizeof(*p), BPRI_MED))) { mp->b_band = 0; DB_TYPE(mp) = M_PROTO; p = (typeof(p)) mp->b_rptr; mp->b_wptr = mp->b_rptr + sizeof(*p); p->sl_primitive = SL_LINK_CONGESTION_CEASED_IND; p->sl_timestamp = jiffies; p->sl_cong_status = ch->sl.statem.cong_status; p->sl_disc_status = ch->sl.statem.disc_status; /* FIXME: clear bit indicating that SL_LINK_CONGESTION_CEASED_IND is required. */ LOGTX(xp2sid(xp), "<- SL_LINK_CONGESTION_CEASED_IND"); put(q ? RD(q) : xp->rq, mp); return (0); } /* FIXME: set bit indicating that SL_LINK_CONGESTION_CEASED_IND is required. */ rare(); return (-ENOBUFS); } freemsg(mp); return (0); } /** sl_retrieved_message_ind: - issue SL_RETRIEVED_MESSAGE_IND primitive * @ch: channel structure (locked) * @q: active queue (write queue) * @dp: data portion of message * * This is called in response to SL_RETRIEVAL_REQUEST_AND_FSNC_REQ received on write queue from * within the write put or service procedure. The xp structure is locked. */ noinline fastcall __unlikely int sl_retrieved_message_ind(struct ch *ch, queue_t *q, mblk_t *dp) { struct xp *xp = XP_PRIV(q); sl_retrieved_msg_ind_t *p; mblk_t *mp; if ((mp = mi_allocb(q, sizeof(*p), BPRI_MED))) { DB_TYPE(mp) = M_PROTO; p = (typeof(p)) mp->b_wptr; mp->b_wptr += sizeof(*p); p->sl_primitive = SL_RETRIEVED_MESSAGE_IND; mp->b_cont = dp; LOGTX(xp2sid(xp), "<- SL_RETRIEVED_MESSGAGE_IND"); putq(xp->rq, mp); return (0); } rare(); return (-ENOBUFS); } /** sl_retrieval_complete_ind: - issue SL_RETRIEVAL_COMPLETE_IND primitive * @ch: channel structure (locked) * @q: active queue (write queue) * @mp: SL_RETRIEVAL_REQUEST_AND_FSNC_REQ primitive * * This is called in response to SL_RETRIEVAL_REQUEST_AND_FSNC_REQ received on write queue from * within the write put or service procedure. The xp structure is locked. */ noinline fastcall __unlikely void sl_retrieval_complete_ind(struct ch *ch, queue_t *q, mblk_t *mp) { struct xp *xp = XP_PRIV(q); sl_retrieval_comp_ind_t *p; mp->b_band = 0; DB_TYPE(mp) = M_PROTO; p = (typeof(p)) mp->b_rptr; mp->b_wptr = mp->b_rptr + sizeof(*p); p->sl_primitive = SL_RETRIEVAL_COMPLETE_IND; LOGTX(xp2sid(xp), "<- SL_RETIREVAL_COMPLETE_IND"); putq(xp->rq, mp); } /** sl_rb_cleared_ind: - issue SL_RB_CLEARED_IND primitive * @ch: channel structure (locked) * @q: active queue (write queue) * @mp: message to reuse * * This is called in response to SL_CLEAR_BUFFERS_REQ received on write queue from within the write * put or service procedure. The xp structure is locked. */ noinline fastcall __unlikely void sl_rb_cleared_ind(struct ch *ch, queue_t *q, mblk_t *mp) { struct xp *xp = XP_PRIV(q); sl_rb_cleared_ind_t *p; mp->b_band = 0; DB_TYPE(mp) = M_PROTO; p = (typeof(p)) mp->b_rptr; mp->b_wptr = mp->b_rptr + sizeof(*p); p->sl_primitive = SL_RB_CLEARED_IND; LOGTX(xp2sid(xp), "<- SL_RB_CLEARED_IND"); putq(xp->rq, mp); } /** sl_bsnt_ind: - issue SL_BSNT_IND primitive * @ch: channel structure (locked) * @q: active queue (write queue) * @mp: SL_RETRIEVE_BSNT_REQ primitive * * This is called in response to SL_RETRIEVE_BSNT_REQ received on write queue, from within the * write put or service procedure. The xp structure is locked. */ noinline fastcall __unlikely void sl_bsnt_ind(struct ch *ch, queue_t *q, mblk_t *mp) { struct xp *xp = XP_PRIV(q); sl_bsnt_ind_t *p; mp->b_band = 0; DB_TYPE(mp) = M_PROTO; p = (typeof(p)) mp->b_rptr; mp->b_wptr = mp->b_rptr + sizeof(*p); p->sl_primitive = SL_BSNT_IND; p->sl_bsnt = ch->sl.statem.rx.T.bsn; LOGTX(xp2sid(xp), "<- SL_BSNT_IND"); putq(xp->rq, mp); } /** sl_in_service_ind: - issue an SL_IN_SERVICE_IND primitive * @ch: channel structure (locked) * * This primitive is only issued from the bottom-half tasklet as a result of receiving the * appropriate message sequence for initial alignement. */ noinline fastcall void sl_in_service_ind(struct ch *ch) { if (ch->sl.statem.failure_reason == 0) { struct xp *xp; if (likely((xp = ch->xp) != NULL)) { sl_in_service_ind_t *p; mblk_t *mp; if ((mp = mi_allocb(xp->rq, sizeof(*p), BPRI_MED))) { DB_TYPE(mp) = M_PROTO; p = (typeof(p)) mp->b_wptr; mp->b_wptr += sizeof(*p); p->sl_primitive = SL_IN_SERVICE_IND; /* FIXME: clear bit indicating that we need SL_IN_SERVICE_IND. */ LOGTX(xp2sid(xp), "<- SL_IN_SERVICE_IND"); put(xp->rq, mp); } else { /* FIXME: set bit indicating that we need SL_IN_SERVICE_IND. */ rare(); } } } } /** sl_out_of_service_ind: - issue SL_OUT_OF_SERVICE_IND primitive * @ch: channel structure (locked) * * This primitive is issued from two contexts: either the primitive is issued as a result of a * timeout; otherwise, it is issued as a result of autonomous events within the signalling link * state machine. For the timeout, the execution context is the timer callback procedure. For the * autonomous event, the execution context is the bottom-half tasklet. Both are technically * running at bottom half and bottom half suppression is sufficient for ch->lock from process * context. * * The only reason that timeout processing would ever fail in the SL state machine is because this * function returns non-zero (fails to allocate a buffer). Therefore, when we have an active * stream associated with the signalling link state machine, we use mi_allocb(9) to allocate the * message block and schedule the read queue for enabling on the bufcall(9) callback. This way, * the read service procedure will run when a buffer is available. A wakeup flag is set indicating * that a link out of service condition has occurred so that the wakeup routine of the read service * procedure can attempt to issue the indication at that time. This is a better approach than * attempting to defer timeouts. Care should be taken that the read service wakeup procedure is * run *before* the queue is processed for messages, otherwise, a message order reversal could * occur. */ noinline fastcall void sl_out_of_service_ind(struct ch *ch) { if (ch->sl.statem.failure_reason) { struct xp *xp; if (likely((xp = ch->xp) != NULL)) { sl_out_of_service_ind_t *p; mblk_t *mp; if ((mp = mi_allocb(xp->rq, sizeof(*p), BPRI_MED))) { DB_TYPE(mp) = M_PROTO; p = (typeof(p)) mp->b_wptr; mp->b_wptr += sizeof(*p); p->sl_primitive = SL_OUT_OF_SERVICE_IND; p->sl_timestamp = jiffies; p->sl_reason = ch->sl.statem.failure_reason; /* FIXME: clear bit indicating that we need SL_OUT_OF_SERVICE_IND. */ LOGTX(xp2sid(xp), "<- SL_OUT_OF_SERVICE_IND"); put(xp->rq, mp); } else { /* FIXME: set bit indicating that we need SL_OUT_OF_SERVICE_IND. */ rare(); } } } } /** sl_remote_processor_outage_ind: - issue SL_REMOTE_PROCESSOR_OUTAGE_IND * @ch: channel structure (locked) * @q: active queue (write queue) or NULL * * This primitive is issued from two contexts: either the primitive is issued as a result of a * SL_RESUME_REQ being received on the write queue, in which case @q will be non-NULL; otherwise, * it is issued as a result of autonomous events (receiving SIPO) within the signalling link state * machine. For the SL_RESUME_REQ, the execution context is the write queue put or service * procedure. For the autonomous event, the execution context is the bottom-half tasklet. */ noinline fastcall __unlikely int sl_remote_processor_outage_ind(struct ch *ch, queue_t *q, mblk_t *mp) { if (ch->sl.statem.remote_processor_outage || ch->sl.statem.poc_state == SL_STATE_REMOTE_PROCESSOR_OUTAGE || ch->sl.statem.poc_state == SL_STATE_BOTH_PROCESSORS_OUT) { struct xp *xp; if (likely((xp = ch->xp) != NULL)) { sl_rem_proc_out_ind_t *p; if (mp || (mp = mi_allocb(q ? : xp->rq, sizeof(*p), BPRI_MED))) { mp->b_band = 0; DB_TYPE(mp) = M_PROTO; p = (typeof(p)) mp->b_rptr; mp->b_wptr = mp->b_rptr + sizeof(*p); p->sl_primitive = SL_REMOTE_PROCESSOR_OUTAGE_IND; p->sl_timestamp = jiffies; /* FIXME: clear bit indicating that we need SL_OUT_OF_SERVICE */ LOGTX(xp2sid(xp), "<- SL_REMOTE_PROCESSOR_OUTAGE_IND"); put(q ? RD(q) : xp->rq, mp); return (0); } /* FIXME: set bit indicating that we need SL_OUT_OF_SERVICE */ rare(); return (-ENOBUFS); } } freemsg(mp); return (0); } /** sl_remote_processor_recovered_ind: - issue SL_REMOTE_PROCESSOR_RECOVERED_IND * @ch: channel structure (locked) * * This primitive is only issued from the bottom-half tasklet. */ noinline fastcall __unlikely void sl_remote_processor_recovered_ind(struct ch *ch) { if (ch->sl.statem.remote_processor_outage == 0 && ch->sl.statem.poc_state != SL_STATE_REMOTE_PROCESSOR_OUTAGE && ch->sl.statem.poc_state != SL_STATE_BOTH_PROCESSORS_OUT) { struct xp *xp; if (likely((xp = ch->xp) != NULL)) { sl_rem_proc_recovered_ind_t *p; mblk_t *mp; if ((mp = mi_allocb(xp->rq, sizeof(*p), BPRI_MED))) { DB_TYPE(mp) = M_PROTO; p = (typeof(p)) mp->b_wptr; mp->b_wptr += sizeof(*p); p->sl_primitive = SL_REMOTE_PROCESSOR_RECOVERED_IND; p->sl_timestamp = jiffies; /* FIXME: clear bit indicating that we need SL_REMOTE_PROCESSOR_RECOVERED_IND. */ LOGTX(xp2sid(xp), "<- SL_REMOTE_PROCESSOR_RECOVERED_IND"); put(xp->rq, mp); } else { /* FIXME: set bit indicating that we need SL_REMOTE_PROCESSOR_RECOVERED_IND. */ rare(); } } } } /** sl_rtb_cleared_ind: - issue SL_RTB_CLEARED_IND primitive * @ch: channel structure (locked) * @q: active queue (write queue) or NULL * @mp: message to reuse or NULL * * This is called in response to */ noinline fastcall __unlikely int sl_rtb_cleared_ind(struct ch *ch, queue_t *q, mblk_t *mp) { struct xp *xp; /* FIXME: verify that condition still exists */ if (likely((xp = ch->xp) != NULL)) { sl_rtb_cleared_ind_t *p; if (mp || (mp = mi_allocb(q ? : xp->rq, sizeof(*p), BPRI_MED))) { mp->b_band = 0; DB_TYPE(mp) = M_PROTO; p = (typeof(p)) mp->b_rptr; mp->b_wptr = mp->b_rptr + sizeof(*p); p->sl_primitive = SL_RTB_CLEARED_IND; /* FIXME: clear bit indicating that we need SL_RTB_CLEARED_IND. */ LOGTX(xp2sid(xp), "<- SL_RTB_CLEARED_IND"); put(q ? RD(q) : xp->rq, mp); return (0); } /* FIXME: set bit indicating that we need SL_RTB_CLEARED_IND. */ rare(); return (-ENOBUFS); } freemsg(mp); return (0); } #if 1 /** sl_retrieval_not_possible_ind: - issue SL_RETREIVAL_NOT_POSSIBLE_IND primitive * @ch: channel structure (locked) * @q: active queue (write queue) or NULL * @mp: message to reuse or NULL * * This message is never issued because in the integrated driver retrieval is always possible. */ static inline fastcall __unlikely int sl_retrieval_not_possible_ind(struct ch *ch, queue_t *q, mblk_t *mp) { struct xp *xp; if (likely((xp = ch->xp) != NULL)) { sl_retrieval_not_poss_ind_t *p; if (mp || (mp = mi_allocb(q, sizeof(*p), BPRI_MED))) { mp->b_band = 0; DB_TYPE(mp) = M_PROTO; p = (typeof(p)) mp->b_rptr; mp->b_wptr = mp->b_rptr + sizeof(*p); p->sl_primitive = SL_RETRIEVAL_NOT_POSSIBLE_IND; LOGTX(xp2sid(xp), "<- SL_RETRIEVAL_NOT_POSSIBLE_IND"); putq(RD(q), mp); return (0); } rare(); return (-ENOBUFS); } freemsg(mp); return (0); } /** sl_bsnt_not_retrievable_ind: - issue SL_BSNT_NOT_RETRIEVABLE_IND primitive * @ch: channel structure (locked) * @q: active queue (write queue) or NULL * @mp: message to reuse or NULL * * This message is never issued because in the integrated driver BSNT retrieval is always possible. */ static inline fastcall __unlikely int sl_bsnt_not_retrievable_ind(struct ch *ch, queue_t *q, mblk_t *mp, sl_ulong bsnt) { struct xp *xp; if (likely((xp = ch->xp) != NULL)) { sl_bsnt_not_retr_ind_t *p; if (mp || (mp = mi_allocb(q, sizeof(*p), BPRI_MED))) { mp->b_band = 0; DB_TYPE(mp) = M_PROTO; p = (typeof(p)) mp->b_rptr; mp->b_wptr = mp->b_rptr + sizeof(*p); p->sl_primitive = SL_BSNT_NOT_RETRIEVABLE_IND; p->sl_bsnt = bsnt; LOGTX(xp2sid(xp), "<- SL_BSNT_NOT_RETRIEVABLE_IND"); putq(RD(q), mp); return (0); } rare(); return (-ENOBUFS); } freemsg(mp); return (0); } #endif #if 0 /* * SL_OPTMGMT_ACK * ----------------------------------- */ static inline fastcall __unlikely int sl_optmgmt_ack(struct xp *xp, queue_t *q, mblk_t *rp, caddr_t opt_ptr, size_t opt_len, sl_ulong flags) { mblk_t *mp; sl_optmgmt_ack_t *p; if ((mp = mi_allocb(q, sizeof(*p) + opt_len, BPRI_MED))) { DB_TYPE(mp) = M_PROTO; p = (typeof(p)) mp->b_wptr; mp->b_wptr += sizeof(*p); p->sl_primitive = SL_OPTMGMT_ACK; p->opt_length = opt_len; p->opt_offset = opt_len ? sizeof(*p) : 0; p->mgmt_flags = flags; bcopy(opt_ptr, mp->b_wptr, opt_len); mp->b_wptr += opt_len; freemsg(rp); LOGTX(xp2sid(xp), "<- SL_OPTMGMT_ACK"); putnext(RD(q), mp); return (0); } rare(); return (-ENOBUFS); } /** sl_notify_ind: - issue SL_NOTIFY_IND primitive * @xp: private structure (locked) * @q: active queue (or NULL) * @oid: object identifier * @level: severity level * * Currently this primitive is never issued. * * TODO: We should use this primitive (or LMI_EVENT_IND) to deliver notification of first-and-delta * events and other SS7 management events. */ static inline fastcall __unlikely int sl_notify_ind(struct xp *xp, queue_t *q, sl_ulong oid, sl_ulong level) { static const int nb = 2; if (likely(bcanput(xp->rq, nb))) { lmi_event_ind_t *p; mblk_t *mp; if ((mp = mi_allocb(q, sizeof(*p), BPRI_MED))) { DB_TYPE(mp) = M_PROTO; mp->b_band = nb; /* band it up */ p = (typeof(p)) mp->b_wptr; mp->b_wptr += sizeof(*p); p->lmi_primitive = SL_NOTIFY_IND; p->lmi_objectid = oid; p->lmi_timestamp = jiffies; p->lmi_severity = level; LOGTX(xp2sid(xp), "<- SL_NOTIFY_IND"); put(xp->rq, mp); return (0); } rare(); return (-ENOBUFS); } rare(); return (-EBUSY); } #endif /* * SDTI PRIMITIVES ISSUED UPSTREAM * ------------------------------------------------------------------------- */ /** sdt_rc_signal_unit_ind: - issue SDT_RC_SIGNAL_UNIT_IND primitive * @ch: channel structure (locked) * @dp: the M_DATA portion of the message * @count: the number of repetitions of a FISU or LSSU * * We prefer to send M_DATA blocks. When the count is 1, we simply send M_DATA. When the count is * greater than one, we send an SDT_RC_SIGNAL_UNIT_IND which also includes the count. This is so * that upper layer modules can collect SU statistics. * * Can't use buffer service. * * Note: this is the wrong place to do buffer duping: this is executed within a tasklet and needs * to return fast to keep soft-HDLC caches hot. The proper place to perform the duping is in the * read side service procedure. */ static inline fastcall __hot_in int sdt_rc_signal_unit_ind(struct ch *ch, mblk_t *dp, sl_ulong count) { struct xp *xp; /* FIXME: here is where we do monitoring of SDT messages */ if (likely((xp = ch->xp) != NULL)) { if (likely(count)) { if (likely(canput(xp->rq))) { sdt_rc_signal_unit_ind_t *p; mblk_t *mp; if (likely((mp = allocb(sizeof(*p), BPRI_MED)) != NULL)) { DB_TYPE(mp) = M_PROTO; p = (typeof(p)) mp->b_wptr; mp->b_wptr += sizeof(*p); p->sdt_primitive = SDT_RC_SIGNAL_UNIT_IND; p->sdt_count = count; mp->b_cont = dp; LOGDA(xp2sid(xp), "<- SDT_RC_SIGNAL_UNIT_IND"); put(xp->rq, mp); /* FIXME: NEED to dup to the XRAY chain */ return (0); } rare(); return (-ENOBUFS); } rare(); return (-EBUSY); } swerr(); return (-EFAULT); } return (-ENXIO); } /* Note: none of the following SDT primitives are actually issued. They are signals that are * delivered to the signalling link level internally when required. Implementing them requires * splitting the signalling terminal state machine from the signalling link state machine. */ #if 1 /** sdt_rc_congestion_accept_ind: - issue SDT_RC_CONGESTION_ACCEPT_IND primitive * @ch: channel structure (locked) * * This primitive is never issued. TODO: generate this primitive when operating in SDT-only mode. */ noinline fastcall __unlikely int sdt_rc_congestion_accept_ind(struct ch *ch) { struct xp *xp; if (likely((xp = ch->xp) != NULL)) { sdt_rc_congestion_accept_ind_t *p; mblk_t *mp; if ((mp = allocb(sizeof(*p), BPRI_MED))) { DB_TYPE(mp) = M_PROTO; p = (typeof(p)) mp->b_wptr; mp->b_wptr += sizeof(*p); p->sdt_primitive = SDT_RC_CONGESTION_ACCEPT_IND; LOGTX(xp2sid(xp), "<- SDT_RC_CONGESTION_ACCEPT_IND"); put(xp->rq, mp); return (0); } rare(); return (-ENOBUFS); } return (-ENXIO); } /** sdt_rc_congestion_discard_ind: - issue SDT_RC_CONGESTION_DISCARD_IND primitive * @ch: channel structure (locked) * * This primitive is never issued. TODO: generate this primitive when operating in SDT-only mode. */ noinline fastcall __unlikely int sdt_rc_congestion_discard_ind(struct ch *ch) { struct xp *xp; if (likely((xp = ch->xp) != NULL)) { sdt_rc_congestion_discard_ind_t *p; mblk_t *mp; if ((mp = allocb(sizeof(*p), BPRI_MED))) { DB_TYPE(mp) = M_PROTO; p = (typeof(p)) mp->b_wptr; mp->b_wptr += sizeof(*p); p->sdt_primitive = SDT_RC_CONGESTION_DISCARD_IND; LOGTX(xp2sid(xp), "<- SDT_RC_CONGESTION_DISCARD_IND"); put(xp->rq, mp); return (0); } rare(); return (-ENOBUFS); } return (-ENXIO); } /** sdt_rc_no_congestion_ind: - issue SDT_RC_NO_CONGESTION_IND primitive * @ch: channel structure (locked) * * This primitive is never issued. TODO: generate this primitive when operating in SDT-only mode. */ noinline fastcall __unlikely int sdt_rc_no_congestion_ind(struct ch *ch) { struct xp *xp; if (likely((xp = ch->xp) != NULL)) { sdt_rc_no_congestion_ind_t *p; mblk_t *mp; if ((mp = allocb(sizeof(*p), BPRI_MED))) { DB_TYPE(mp) = M_PROTO; p = (typeof(p)) mp->b_wptr; mp->b_wptr += sizeof(*p); p->sdt_primitive = SDT_RC_NO_CONGESTION_IND; LOGTX(xp2sid(xp), "<- SDT_RC_NO_CONGESTION_IND"); put(xp->rq, mp); return (0); } rare(); return (-ENOBUFS); } return (-ENXIO); } /** sdt_iac_correct_su_ind: - issue SDT_IAC_CORRECT_SU_IND primitive * @ch: channel structure (locked) * * This primitive is never issued. TODO: generate this primitive when operating in SDT-only mode. */ static inline fastcall __hot_read int sdt_iac_correct_su_ind(struct ch *ch) { struct xp *xp; if (likely((xp = ch->xp) != NULL)) { if (canputnext(xp->rq)) { sdt_iac_correct_su_ind_t *p; mblk_t *mp; if ((mp = allocb(sizeof(*p), BPRI_MED))) { DB_TYPE(mp) = M_PROTO; p = (typeof(p)) mp->b_wptr; mp->b_wptr += sizeof(*p); p->sdt_primitive = SDT_IAC_CORRECT_SU_IND; LOGTX(xp2sid(xp), "<- SDT_IAC_CORRECT_SU_IND"); put(xp->rq, mp); return (0); } rare(); return (-ENOBUFS); } rare(); return (-EBUSY); } return (-ENXIO); } /** sdt_iac_abort_proving_ind: - issue SDT_IAC_ABORT_PROVING_IND primitive * @ch: channel structure (locked) * * This primitive is never issued. TODO: generate this primitive when operating in SDT-only mode. */ noinline fastcall int sdt_iac_abort_proving_ind(struct ch *ch) { struct xp *xp; if (likely((xp = ch->xp) != NULL)) { sdt_iac_abort_proving_ind_t *p; mblk_t *mp; if ((mp = allocb(sizeof(*p), BPRI_MED))) { DB_TYPE(mp) = M_PROTO; p = (typeof(p)) mp->b_wptr; mp->b_wptr += sizeof(*p); p->sdt_primitive = SDT_IAC_ABORT_PROVING_IND; LOGTX(xp2sid(xp), "<- SDT_IAC_ABORT_PROVING_IND"); put(xp->rq, mp); return (0); } rare(); return (-ENOBUFS); } return (-ENXIO); } /** sdt_lsc_link_failure_ind: - issue SDT_LSC_LINK_FAILURE_IND primitive * @ch: channel structure (locked) * * This primitive is never issued. TODO: generate this primitive when operating in SDT-only mode. */ noinline fastcall __unlikely int sdt_lsc_link_failure_ind(struct ch *ch, queue_t *q) { struct xp *xp; if (likely((xp = ch->xp) != NULL)) { sdt_lsc_link_failure_ind_t *p; mblk_t *mp; if ((mp = allocb(sizeof(*p), BPRI_MED))) { DB_TYPE(mp) = M_PROTO; p = (typeof(p)) mp->b_wptr; mp->b_wptr += sizeof(*p); p->sdt_primitive = SDT_LSC_LINK_FAILURE_IND; LOGTX(xp2sid(xp), "<- SDT_LSC_LINK_FAILURE_IND"); put(xp->rq, mp); return (0); } rare(); return (-ENOBUFS); } return (-ENXIO); } /** sdt_txc_transmission_request_ind: - issue SDT_TXC_TRANSMISSION_REQUEST_IND primitive * @ch: channel structure (locked) * * This primitive is never issued. TODO: generate this primitive when operating in SDT-only mode. */ static inline fastcall __hot_out int sdt_txc_transmission_request_ind(struct ch *ch) { struct xp *xp; if (likely((xp = ch->xp) != NULL)) { sdt_txc_transmission_request_ind_t *p; mblk_t *mp; if ((mp = allocb(sizeof(*p), BPRI_MED))) { DB_TYPE(mp) = M_PROTO; p = (typeof(p)) mp->b_wptr; mp->b_wptr += sizeof(*p); p->sdt_primitive = SDT_TXC_TRANSMISSION_REQUEST_IND; LOGDA(xp2sid(xp), "<- SDT_TXC_TRANSMISSION_REQUEST_IND"); putnext(xp->rq, mp); return (0); } rare(); return (-ENOBUFS); } return (-ENXIO); } #endif /* * SDLI PRIMITIVES ISSUED UPSTREAM * ------------------------------------------------------------------------- */ /** sdl_received_bits_ind: - issue SDL_RECEIVED_BITS_IND primitive * @ch: channel structure (locked) * @dp: M_DATA portion of message */ static inline fastcall __hot_in int sdl_received_bits_ind(struct ch *ch, mblk_t *dp) { struct xp *xp; if (likely((xp = ch->xp) != NULL)) { if (canput(xp->rq)) { LOGDA(xp2sid(xp), "<- SDL_RECEIVED_BITS_IND"); put(xp->rq, dp); return (0); } rare(); dp->b_wptr = dp->b_rptr; /* discard contents */ return (-EBUSY); } dp->b_wptr = dp->b_rptr; /* discard contents */ return (-ENXIO); } /* Note: none of the following SDL primitives are actually issued. We do not provide disconnect * indications because SS7 does not examine "leads". */ #if 1 /** sdl_disconnect_ind: - issue SDL_DISCONNECT_IND primitive * @ch: channel structure (locked) * * This primitive is never issued. TODO: generate this primitive when operating in SDL-only mode. */ static inline fastcall __unlikely int sdl_disconnect_ind(struct ch *ch) { struct xp *xp; if (likely((xp = ch->xp) != NULL)) { sdl_disconnect_ind_t *p; mblk_t *mp; if ((mp = allocb(sizeof(*p), BPRI_MED))) { DB_TYPE(mp) = M_PROTO; p = (typeof(p)) mp->b_wptr; mp->b_wptr += sizeof(*p); p->sdl_primitive = SDL_DISCONNECT_IND; LOGTX(xp2sid(xp), "<- SDL_DISCONNECT_IND"); put(xp->rq, mp); return (0); } rare(); return (-ENOBUFS); } return (-ENXIO); } #endif /* * LMI PRIMITIVES ISSUED UPSTREAM * ------------------------------------------------------------------------- */ /** lmi_ok_ack: - issue LMI_OK_ACK primitive * @xp: private structure (locked) * @q: active queue (write queue) * @mp: the correct primitive * @state: the new state to set * @prim: the primitive type of the correct primitive */ noinline fastcall __unlikely void lmi_ok_ack(struct xp *xp, queue_t *q, mblk_t *mp, sl_ulong state, sl_long prim) { lmi_ok_ack_t *p; mp->b_band = 0; DB_TYPE(mp) = M_PCPROTO; p = (typeof(p)) mp->b_rptr; mp->b_wptr = mp->b_rptr + sizeof(*p); p->lmi_primitive = LMI_OK_ACK; p->lmi_correct_primitive = prim; p->lmi_state = state; xp_set_state(xp, state); LOGTX(xp2sid(xp), "<- LMI_OK_ACK"); qreply(q, mp); } /** lmi_error_ack: - issue LMI_ERROR_ACK primitive * @xp: private structure (locked) * @q: active queue (write queue) * @mp: primitive in error * @state: the new state to set * @prim: the primitive type of the primitive in error * @errno: the UNIX error number * @reason: the DLPI error number */ noinline fastcall __unlikely void lmi_error_ack(struct xp *xp, queue_t *q, mblk_t *mp, sl_ulong state, sl_long prim, sl_ulong errno, sl_ulong reason) { lmi_error_ack_t *p; mp->b_band = 0; DB_TYPE(mp) = M_PCPROTO; p = (typeof(p)) mp->b_rptr; mp->b_wptr = mp->b_rptr + sizeof(*p); p->lmi_primitive = LMI_ERROR_ACK; p->lmi_errno = errno; p->lmi_reason = reason; p->lmi_error_primitive = prim; p->lmi_state = state; xp_set_state(xp, state); LOGTX(xp2sid(xp), "<- LMI_ERROR_ACK"); qreply(q, mp); } /** lmi_info_ack: - issue LMI_INFO_ACK primitive * @xp: private structure (locked) * @q: active queue (write queue) * @rp: message to reuse * @ppa_ptr: pointer to ppa (or NULL) * @ppa_len: length of ppa (or zero) */ static inline fastcall __unlikely int lmi_info_ack(struct xp *xp, queue_t *q, mblk_t *rp, caddr_t ppa_ptr, size_t ppa_len) { struct ch *ch; lmi_info_ack_t *p; mblk_t *mp = NULL; if (MBLKSIZE(rp) >= sizeof(*p) + ppa_len) { mp = rp; rp = NULL; mp->b_band = 0; mp->b_rptr = mp->b_wptr = DB_BASE(mp); } if (mp || (mp = mi_allocb(q, sizeof(*p) + ppa_len, BPRI_MED))) { DB_TYPE(mp) = M_PCPROTO; p = (typeof(p)) mp->b_wptr; mp->b_wptr += sizeof(*p); p->lmi_primitive = LMI_INFO_ACK; p->lmi_version = LMI_CURRENT_VERSION; p->lmi_state = xp_get_state(xp); if ((ch = xp->ch)) { if (ch->option.popt & SS7_POPT_XSN) { p->lmi_max_sdu = ch->sdt.config.m + 1 + 6; p->lmi_min_sdu = 6; } else { p->lmi_max_sdu = ch->sdt.config.m + 1 + 3; p->lmi_min_sdu = 3; } } else { if (xp->chan == 0) { p->lmi_max_sdu = 272 + 1 + 6; p->lmi_min_sdu = 6; } else { p->lmi_max_sdu = 272 + 1 + 3; p->lmi_min_sdu = 3; } } p->lmi_header_len = 0; p->lmi_ppa_style = LMI_STYLE2; p->lmi_ppa_length = ppa_len; p->lmi_ppa_offset = sizeof(*p); p->lmi_prov_flags = xp->i_flags; p->lmi_prov_state = xp->i_state; fixme(("%s: maintain provider flags", __FUNCTION__)); bcopy(ppa_ptr, mp->b_wptr, ppa_len); mp->b_wptr += ppa_len; freemsg(rp); LOGTX(xp2sid(xp), "<- LMI_INFO_ACK"); putnext(RD(q), mp); return (0); } rare(); return (-ENOBUFS); } /** lmi_enable_con: - issue LMI_ENABLE_CON primitive * @xp: private structure (locked) * @q: active queue (write queue) * @mp: the LMI_ENABLE_REQ primitive */ static inline fastcall __unlikely void lmi_enable_con(struct xp *xp, queue_t *q, mblk_t *mp) { lmi_enable_con_t *p; mp->b_band = 0; DB_TYPE(mp) = M_PROTO; p = (typeof(p)) mp->b_rptr; mp->b_wptr = mp->b_rptr + sizeof(*p); p->lmi_primitive = LMI_ENABLE_CON; p->lmi_state = LMI_ENABLED; xp_set_state(xp, LMI_ENABLED); LOGTX(xp2sid(xp), "<- LMI_ENABLE_CON"); qreply(q, mp); } /** lmi_disable_con: - issue LMI_DISABLE_CON primitive * @xp: private structure (locked) * @q: active queue (write queue) * @mp: the LMI_DISABLE_REQ primitive */ static inline fastcall __unlikely void lmi_disable_con(struct xp *xp, queue_t *q, mblk_t *mp) { lmi_disable_con_t *p; putctl2(RD(q), M_FLUSH, FLUSHRW, 0); mp->b_band = 0; DB_TYPE(mp) = M_PROTO; p = (typeof(p)) mp->b_rptr; mp->b_wptr = mp->b_rptr + sizeof(*p); p->lmi_primitive = LMI_DISABLE_CON; p->lmi_state = LMI_DISABLED; xp_set_state(xp, LMI_DISABLED); LOGTX(xp2sid(xp), "<- LMI_DISABLE_CON"); qreply(q, mp); } #if 1 /** lmi_optmgmt_ack: - issue LMI_OPTMGMT_ACK primitive * @xp: private structure (locked) * @q: active queue (write queue) * @rp: the LMI_OPTMGMT_REQ primitive * @flags: management flags * @opt_ptr: options pointer (or NULL) * @opt_len: options length (or zero) * * Currently this primitive is never issued. */ static inline fastcall __unlikely int lmi_optmgmt_ack(struct xp *xp, queue_t *q, mblk_t *rp, sl_ulong flags, caddr_t opt_ptr, size_t opt_len) { mblk_t *mp = NULL; lmi_optmgmt_ack_t *p; if (MBLKSIZE(rp) >= sizeof(*p) + opt_len) { mp = rp; rp = NULL; mp->b_wptr = mp->b_rptr = DB_BASE(mp); mp->b_band = 0; } if (mp || (mp = mi_allocb(q, sizeof(*p) + opt_len, BPRI_MED))) { DB_TYPE(mp) = M_PCPROTO; p = (typeof(p)) mp->b_wptr; mp->b_wptr += sizeof(*p); p->lmi_primitive = LMI_OPTMGMT_ACK; p->lmi_opt_length = opt_len; p->lmi_opt_offset = sizeof(*p); p->lmi_mgmt_flags = flags; if (opt_len) { bcopy(opt_ptr, mp->b_wptr, opt_len); mp->b_wptr += opt_len; } freemsg(rp); LOGTX(xp2sid(xp), "<- LMI_OPTMGMT_ACK"); qreply(q, mp); return (0); } rare(); return (-ENOBUFS); } /** lmi_error_ind: - issue LMI_ERROR_IND primitive * @xp: private structure (locked) * @q: active queue * @rp: message to reuse (or NULL) * @errno: UNIX error number * @reason: LMI error number * * Currently this primitive is never issued. */ static inline fastcall __unlikely int lmi_error_ind(struct xp *xp, queue_t *q, mblk_t *rp, sl_ulong errno, sl_ulong reason) { mblk_t *mp = NULL; lmi_error_ind_t *p; if (MBLKSIZE(rp) >= sizeof(*p)) { mp = rp; rp = NULL; mp->b_wptr = mp->b_rptr = DB_BASE(mp); mp->b_band = 0; } if (mp || (mp = mi_allocb(q, sizeof(*p), BPRI_MED))) { DB_TYPE(mp) = M_PROTO; p = (typeof(p)) mp->b_wptr; mp->b_wptr += sizeof(*p); p->lmi_primitive = LMI_ERROR_IND; p->lmi_errno = errno; p->lmi_reason = reason; p->lmi_state = xp_get_state(xp); LOGTX(xp2sid(xp), "<- LMI_ERROR_IND"); put(xp->rq, mp); return (0); } rare(); return (-ENOBUFS); } /** lmi_stats_ind: - issue LMI_STATS_IND primitive * @xp: private structure (locked) * @q: active queue * @interval: statistics interval number * @sta_ptr: pointer to specific statistics structure * @sta_len: length of specific statistics structure * * Currently this primitive is never issued. * * TODO: We should use this primitive to deliver 5-minute statistics at the end of every 5-minute * interval. */ static inline fastcall __unlikely int lmi_stats_ind(struct xp *xp, queue_t *q, sl_ulong interval, caddr_t sta_ptr, size_t sta_len) { if (likely(canput(xp->rq))) { lmi_stats_ind_t *p; mblk_t *mp; if ((mp = mi_allocb(q, sizeof(*p) + sta_len, BPRI_MED))) { DB_TYPE(mp) = M_PROTO; p = (typeof(p)) mp->b_wptr; mp->b_wptr += sizeof(*p); p->lmi_primitive = LMI_STATS_IND; p->lmi_interval = interval; p->lmi_timestamp = jiffies; if (sta_len) { bcopy(sta_ptr, mp->b_wptr, sta_len); mp->b_wptr += sta_len; } LOGTX(xp2sid(xp), "<- LMI_STATS_IND"); put(xp->rq, mp); return (0); } rare(); return (-ENOBUFS); } rare(); return (-EBUSY); } /** lmi_event_ind: - issue LMI_EVENT_IND primitive * @xp: private structure (locked) * @q: active queue (or NULL) * @oid: object identifier * @level: severity level * * Currently this primitive is never issued. * * TODO: We should use this primitive (or SL_NOTIFY_IND) to deliver notification of first-and-delta * events and other SS7 management events. */ static inline fastcall __unlikely int lmi_event_ind(struct xp *xp, queue_t *q, sl_ulong oid, sl_ulong level) { static const int nb = 2; if (likely(bcanput(xp->rq, nb))) { lmi_event_ind_t *p; mblk_t *mp; if ((mp = mi_allocb(q, sizeof(*p), BPRI_MED))) { DB_TYPE(mp) = M_PROTO; mp->b_band = nb; /* band it up */ p = (typeof(p)) mp->b_wptr; mp->b_wptr += sizeof(*p); p->lmi_primitive = LMI_EVENT_IND; p->lmi_objectid = oid; p->lmi_timestamp = jiffies; p->lmi_severity = level; LOGTX(xp2sid(xp), "<- LMI_EVENT_IND"); put(xp->rq, mp); return (0); } rare(); return (-ENOBUFS); } rare(); return (-EBUSY); } #endif /* * DLPI PRIMITIVES ISSUED UPSTREAM * ------------------------------------------------------------------------- */ /** dl_error_ack: - issue DL_ERROR_ACK primitive * @xp: private structure (locked) * @q: active queue (write queue) * @mp: primitive in error * @prim: primitive type of primtiive in error * @errno: UNIX error number * @errno: DLPI error number */ static inline fastcall __unlikely void dl_error_ack(struct xp *xp, queue_t *q, mblk_t *mp, int prim, int errno, uint reason) { dl_error_ack_t *p; mp->b_band = 0; mp->b_flag = 0; mp->b_rptr = mp->b_wptr = DB_BASE(mp); DB_TYPE(mp) = M_PCPROTO; p = (typeof(p)) mp->b_rptr; mp->b_wptr = mp->b_rptr + sizeof(*p); p->dl_primitive = DL_ERROR_ACK; p->dl_error_primitive = prim; p->dl_errno = reason; p->dl_unix_errno = errno < 0 ? -errno : errno; LOGTX(xp2sid(xp), "<- DL_ERROR_ACK"); qreply(q, mp); return; } /** dl_ok_ack: - issue DL_OK_ACK primitive * @xp: private structure (locked) * @q: active queue (write queue) * @mp: the correct primitive * @state: the new state to set * @prim: the primitive type of the correct primitive */ static inline fastcall __hot_in void dl_ok_ack(struct xp *xp, queue_t *q, mblk_t *mp, dl_ulong state, dl_long prim) { dl_ok_ack_t *p; mp->b_band = 0; mp->b_flag = 0; mp->b_rptr = mp->b_wptr = DB_BASE(mp); DB_TYPE(mp) = M_PCPROTO; p = (typeof(p)) mp->b_rptr; mp->b_wptr = mp->b_rptr + sizeof(*p); p->dl_primitive = DL_OK_ACK; p->dl_correct_primitive = prim; dl_set_state(xp, state); LOGTX(xp2sid(xp), "<- DL_OK_ACK"); qreply(q, mp); return; } /** dl_bind_ack: - issue DL_BIND_ACK primitive * @xp: private structure (locked) * @q: active queue (write queue) * @mp: the DL_BIND_REQ primitive * @dl_sap: the SAP that was set * @dl_max_conind: the maximum number of connection indications */ static inline fastcall __unlikely void dl_bind_ack(struct xp *xp, queue_t *q, mblk_t *mp, dl_ulong dl_sap, dl_ulong dl_max_conind) { dl_bind_ack_t *p; mp->b_band = 0; mp->b_flag = 0; mp->b_rptr = mp->b_wptr = DB_BASE(mp); DB_TYPE(mp) = M_PCPROTO; p = (typeof(p)) mp->b_rptr; mp->b_wptr = mp->b_rptr + sizeof(*p); p->dl_primitive = DL_BIND_ACK; p->dl_sap = dl_sap; p->dl_addr_length = 0; p->dl_addr_offset = 0; p->dl_max_conind = dl_max_conind; p->dl_xidtest_flg = 0; LOGTX(xp2sid(xp), "<- DL_BIND_ACK"); qreply(q, mp); return; } /** dl_token_ack: - issue DL_TOKEN_ACK primitive * @xp: private structure (locked) * @q: active queue (write queue) * @mp: the DL_TOKEN_REQ primitive */ static inline fastcall __unlikely void dl_token_ack(struct xp *xp, queue_t *q, mblk_t *mp) { dl_token_ack_t *p; mp->b_band = 0; mp->b_flag = 0; mp->b_rptr = mp->b_wptr = DB_BASE(mp); DB_TYPE(mp) = M_PCPROTO; p = (typeof(p)) mp->b_rptr; mp->b_wptr = mp->b_rptr + sizeof(*p); p->dl_primitive = DL_TOKEN_ACK; p->dl_token = (dl_ulong) (ulong) xp; LOGTX(xp2sid(xp), "<- DL_TOKEN_ACK"); qreply(q, mp); return; } /** dl_info_ack: - issue DL_INFO_ACK primitive * @xp: private structure (locked) * @q: active queue (write queue) * @rp: the DL_INFO_REQ primitive * * The DL_INFO_REQ primitive message block will be reused for the DL_INFO_ACK if it is of * sufficient size. It is, however, likely on 32-bit architectures that the FASTBUF size (used by * the DL_INFO_REQ) is too small to contain the DL_INFO_ACK. */ static inline fastcall __unlikely int dl_info_ack(struct xp *xp, queue_t *q, mblk_t *rp) { struct ch *ch; dl_info_ack_t *p; mblk_t *mp = NULL; if (MBLKSIZE(rp) >= sizeof(*p)) { mp = rp; rp = NULL; mp->b_band = 0; mp->b_flag = 0; mp->b_rptr = mp->b_wptr = DB_BASE(mp); } if (!mp && !(mp = mi_allocb(q, sizeof(*p), BPRI_MED))) { rare(); return (-ENOBUFS); } DB_TYPE(mp) = M_PCPROTO; p = (typeof(p)) mp->b_rptr; mp->b_wptr = mp->b_rptr + sizeof(*p); p->dl_primitive = DL_INFO_ACK; if ((ch = xp->ch)) { if (ch->option.popt & SS7_POPT_XSN) { p->dl_max_sdu = ch->sdt.config.m + 1 + 6; p->dl_min_sdu = 6; } else { p->dl_max_sdu = ch->sdt.config.m + 1 + 3; p->dl_min_sdu = 3; } } else { if (xp->chan == 0) { p->dl_max_sdu = 272 + 1 + 6; p->dl_min_sdu = 6; } else { p->dl_max_sdu = 272 + 1 + 6; p->dl_min_sdu = 3; } } p->dl_addr_length = 0; p->dl_mac_type = DL_OTHER; p->dl_reserved = 0; p->dl_current_state = dl_get_state(xp); if (xp->monitor) { p->dl_sap_length = 4; #ifdef DL_HP_RAWDLS p->dl_service_mode = DL_HP_RAWDLS; #else p->dl_service_mode = DL_CLDLS; #endif } else { p->dl_sap_length = 0; p->dl_service_mode = DL_CODLS; } p->dl_qos_length = 0; p->dl_qos_offset = 0; p->dl_qos_range_length = 0; p->dl_qos_range_offset = 0; p->dl_provider_style = DL_STYLE2; p->dl_addr_offset = 0; p->dl_version = DL_CURRENT_VERSION; p->dl_brdcst_addr_length = 0; p->dl_brdcst_addr_offset = 0; p->dl_growth = 0; LOGTX(xp2sid(xp), "<- DL_INFO_ACK"); freemsg(rp); qreply(q, mp); return (0); } /* * ========================================================================= * * PROTOCOL STATE MACHINE FUNCTIONS * * ========================================================================= */ /* * ------------------------------------------------------------------------ * * Default Configuration * * ------------------------------------------------------------------------ */ STATIC lmi_option_t lmi_default_e1_chan = { .pvar = SS7_PVAR_ITUT_00, .popt = 0, }; STATIC lmi_option_t lmi_default_t1_chan = { .pvar = SS7_PVAR_ANSI_00, .popt = SS7_POPT_MPLEV, }; STATIC lmi_option_t lmi_default_j1_chan = { .pvar = SS7_PVAR_JTTC_94, .popt = SS7_POPT_MPLEV, }; STATIC lmi_option_t lmi_default_e1_span = { .pvar = SS7_PVAR_ITUT_00, .popt = SS7_POPT_HSL | SS7_POPT_XSN, }; STATIC lmi_option_t lmi_default_t1_span = { .pvar = SS7_PVAR_ANSI_00, .popt = SS7_POPT_MPLEV | SS7_POPT_HSL | SS7_POPT_XSN, }; STATIC lmi_option_t lmi_default_j1_span = { .pvar = SS7_PVAR_JTTC_94, .popt = SS7_POPT_MPLEV | SS7_POPT_HSL | SS7_POPT_XSN, }; #if 1 #define UPS HZ #else #define UPS 1000 #endif STATIC sl_config_t sl_default_e1_chan = { .t1 = 45 * UPS, .t2 = 5 * UPS, .t2l = 20 * UPS, .t2h = 100 * UPS, .t3 = 1 * UPS, .t4n = 8 * UPS, .t4e = UPS / 2, .t5 = UPS / 10, .t6 = 4 * UPS, .t7 = 1 * UPS, .rb_abate = 3, .rb_accept = 6, .rb_discard = 9, .tb_abate_1 = 128 * 272, .tb_onset_1 = 256 * 272, .tb_discd_1 = 384 * 272, .tb_abate_2 = 512 * 272, .tb_onset_2 = 640 * 272, .tb_discd_2 = 768 * 272, .tb_abate_3 = 896 * 272, .tb_onset_3 = 1024 * 272, .tb_discd_3 = 1152 * 272, .N1 = 127, .N2 = 8192, .M = 5, }; STATIC sl_config_t sl_default_e1_span = { .t1 = 45 * UPS, .t2 = 5 * UPS, .t2l = 20 * UPS, .t2h = 100 * UPS, .t3 = 1 * UPS, .t4n = 8 * UPS, .t4e = UPS / 2, .t5 = UPS / 10, .t6 = 4 * UPS, .t7 = 1 * UPS, .rb_abate = 3, .rb_accept = 6, .rb_discard = 9, .tb_abate_1 = 128 * 272, .tb_onset_1 = 256 * 272, .tb_discd_1 = 384 * 272, .tb_abate_2 = 512 * 272, .tb_onset_2 = 640 * 272, .tb_discd_2 = 768 * 272, .tb_abate_3 = 896 * 272, .tb_onset_3 = 1024 * 272, .tb_discd_3 = 1152 * 272, .N1 = 127, .N2 = 8192, .M = 5, }; STATIC sl_config_t sl_default_t1_chan = { .t1 = 45 * UPS, .t2 = 5 * UPS, .t2l = 20 * UPS, .t2h = 100 * UPS, .t3 = 1 * UPS, .t4n = 8 * UPS, .t4e = UPS / 2, .t5 = UPS / 10, .t6 = 4 * UPS, .t7 = 1 * UPS, .rb_abate = 3, .rb_accept = 6, .rb_discard = 9, .tb_abate_1 = 128 * 272, .tb_onset_1 = 256 * 272, .tb_discd_1 = 384 * 272, .tb_abate_2 = 512 * 272, .tb_onset_2 = 640 * 272, .tb_discd_2 = 768 * 272, .tb_abate_3 = 896 * 272, .tb_onset_3 = 1024 * 272, .tb_discd_3 = 1152 * 272, .N1 = 127, .N2 = 8192, .M = 5, }; STATIC sl_config_t sl_default_t1_span = { .t1 = 45 * UPS, .t2 = 5 * UPS, .t2l = 20 * UPS, .t2h = 100 * UPS, .t3 = 1 * UPS, .t4n = 8 * UPS, .t4e = UPS / 2, .t5 = UPS / 10, .t6 = 4 * UPS, .t7 = 1 * UPS, .rb_abate = 3, .rb_accept = 6, .rb_discard = 9, .tb_abate_1 = 128 * 272, .tb_onset_1 = 256 * 272, .tb_discd_1 = 384 * 272, .tb_abate_2 = 512 * 272, .tb_onset_2 = 640 * 272, .tb_discd_2 = 768 * 272, .tb_abate_3 = 896 * 272, .tb_onset_3 = 1024 * 272, .tb_discd_3 = 1152 * 272, .N1 = 127, .N2 = 8192, .M = 5, }; STATIC sl_config_t sl_default_j1_chan = { .t1 = 45 * UPS, .t2 = 5 * UPS, .t2l = 20 * UPS, .t2h = 100 * UPS, .t3 = 1 * UPS, .t4n = 8 * UPS, .t4e = UPS / 2, .t5 = UPS / 10, .t6 = 4 * UPS, .t7 = 1 * UPS, .rb_abate = 3, .rb_accept = 6, .rb_discard = 9, .tb_abate_1 = 128 * 272, .tb_onset_1 = 256 * 272, .tb_discd_1 = 384 * 272, .tb_abate_2 = 512 * 272, .tb_onset_2 = 640 * 272, .tb_discd_2 = 768 * 272, .tb_abate_3 = 896 * 272, .tb_onset_3 = 1024 * 272, .tb_discd_3 = 1152 * 272, .N1 = 127, .N2 = 8192, .M = 5, }; STATIC sl_config_t sl_default_j1_span = { .t1 = 45 * UPS, .t2 = 5 * UPS, .t2l = 20 * UPS, .t2h = 100 * UPS, .t3 = 1 * UPS, .t4n = 8 * UPS, .t4e = UPS / 2, .t5 = UPS / 10, .t6 = 4 * UPS, .t7 = 1 * UPS, .rb_abate = 3, .rb_accept = 6, .rb_discard = 9, .tb_abate_1 = 128 * 272, .tb_onset_1 = 256 * 272, .tb_discd_1 = 384 * 272, .tb_abate_2 = 512 * 272, .tb_onset_2 = 640 * 272, .tb_discd_2 = 768 * 272, .tb_abate_3 = 896 * 272, .tb_onset_3 = 1024 * 272, .tb_discd_3 = 1152 * 272, .N1 = 127, .N2 = 8192, .M = 5, }; STATIC sdt_config_t sdt_default_e1_span = { .Tin = 4, .Tie = 1, .T = 64, .D = 256, .t8 = UPS / 10, .Te = 793544, .De = 11328, .Ue = 198384, .N = 16, .m = 272, .b = 8, .f = SDT_FLAGS_ONE, }; STATIC sdt_config_t sdt_default_t1_span = { .Tin = 4, .Tie = 1, .T = 64, .D = 256, .t8 = UPS / 10, .Te = 577169, .De = 9308, .Ue = 144292, .N = 16, .m = 272, .b = 8, .f = SDT_FLAGS_ONE, }; STATIC sdt_config_t sdt_default_j1_span = { .Tin = 4, .Tie = 1, .T = 64, .D = 256, .t8 = UPS / 10, .Te = 577169, .De = 9308, .Ue = 144292, .N = 16, .m = 272, .b = 8, .f = SDT_FLAGS_ONE, }; STATIC sdt_config_t sdt_default_e1_chan = { .Tin = 4, .Tie = 1, .T = 64, .D = 256, .t8 = UPS / 10, .Te = 793544, .De = 11328, .Ue = 198384, .N = 16, .m = 272, .b = 8, .f = SDT_FLAGS_ONE, }; STATIC sdt_config_t sdt_default_t1_chan = { .Tin = 4, .Tie = 1, .T = 64, .D = 256, .t8 = UPS / 10, .Te = 577169, .De = 9308, .Ue = 144292, .N = 16, .m = 272, .b = 8, .f = SDT_FLAGS_ONE, }; STATIC sdt_config_t sdt_default_j1_chan = { .Tin = 4, .Tie = 1, .T = 64, .D = 256, .t8 = UPS / 10, .Te = 577169, .De = 9308, .Ue = 144292, .N = 16, .m = 272, .b = 8, .f = SDT_FLAGS_ONE, }; STATIC sdl_config_t sdl_default_e1_chan = { .ifname = NULL, .ifflags = 0, .iftype = SDL_TYPE_DS0, .ifrate = 64000, .ifgtype = SDL_GTYPE_E1, .ifgrate = 2048000, .ifmode = SDL_MODE_IDLE, .ifgmode = SDL_GMODE_NONE, .ifgcrc = SDL_GCRC_CRC4, .ifclock = SDL_CLOCK_SLAVE, .ifcoding = SDL_CODING_HDB3, .ifframing = SDL_FRAMING_CCS, .ifblksize = 8, .ifleads = 0, .ifbpv = 0, .ifalarms = 0, .ifrxlevel = 0, .iftxlevel = 1, .ifsync = 0, .ifsyncsrc = {0, 0, 0, 0} }; STATIC sdl_config_t sdl_default_t1_chan = { .ifname = NULL, .ifflags = 0, .iftype = SDL_TYPE_DS0, .ifrate = 64000, .ifgtype = SDL_GTYPE_T1, .ifgrate = 1544000, .ifmode = SDL_MODE_IDLE, .ifgmode = SDL_GMODE_NONE, .ifgcrc = SDL_GCRC_CRC6, .ifclock = SDL_CLOCK_LOOP, .ifcoding = SDL_CODING_B8ZS, .ifframing = SDL_FRAMING_ESF, .ifblksize = 8, .ifleads = 0, .ifbpv = 0, .ifalarms = 0, .ifrxlevel = 0, .iftxlevel = 0, .ifsync = 0, .ifsyncsrc = {0, 0, 0, 0} }; STATIC sdl_config_t sdl_default_j1_chan = { .ifname = NULL, .ifflags = 0, .iftype = SDL_TYPE_DS0A, .ifrate = 64000, .ifgtype = SDL_GTYPE_J1, .ifgrate = 1544000, .ifmode = SDL_MODE_IDLE, .ifgmode = SDL_GMODE_NONE, .ifgcrc = SDL_GCRC_CRC6J, .ifclock = SDL_CLOCK_LOOP, .ifcoding = SDL_CODING_B8ZS, .ifframing = SDL_FRAMING_ESF, .ifblksize = 8, .ifleads = 0, .ifbpv = 0, .ifalarms = 0, .ifrxlevel = 0, .iftxlevel = 0, .ifsync = 0, .ifsyncsrc = {0, 0, 0, 0} }; STATIC sdl_config_t sdl_default_e1_span = { .ifname = NULL, .ifflags = 0, .iftype = SDL_TYPE_E1, .ifrate = 2048000, .ifgtype = SDL_GTYPE_E1, .ifgrate = 2048000, .ifmode = SDL_MODE_PEER, .ifgmode = SDL_GMODE_NONE, .ifgcrc = SDL_GCRC_CRC4, .ifclock = SDL_CLOCK_SLAVE, .ifcoding = SDL_CODING_HDB3, .ifframing = SDL_FRAMING_CCS, .ifblksize = 64, .ifleads = 0, .ifbpv = 0, .ifalarms = 0, .ifrxlevel = 0, .iftxlevel = 1, .ifsync = 0, .ifsyncsrc = {0, 0, 0, 0} }; STATIC sdl_config_t sdl_default_t1_span = { .ifname = NULL, .ifflags = 0, .iftype = SDL_TYPE_T1, .ifrate = 1544000, .ifgtype = SDL_GTYPE_T1, .ifgrate = 1544000, .ifmode = SDL_MODE_PEER, .ifgmode = SDL_GMODE_NONE, .ifgcrc = SDL_GCRC_CRC6, .ifclock = SDL_CLOCK_LOOP, .ifcoding = SDL_CODING_B8ZS, .ifframing = SDL_FRAMING_ESF, .ifblksize = 64, .ifleads = 0, .ifbpv = 0, .ifalarms = 0, .ifrxlevel = 0, .iftxlevel = 0, .ifsync = 0, .ifsyncsrc = {0, 0, 0, 0} }; STATIC sdl_config_t sdl_default_j1_span = { .ifname = NULL, .ifflags = 0, .iftype = SDL_TYPE_J1, .ifrate = 1544000, .ifgtype = SDL_GTYPE_J1, .ifgrate = 1544000, .ifmode = SDL_MODE_PEER, .ifgmode = SDL_GMODE_NONE, .ifgcrc = SDL_GCRC_CRC6J, .ifclock = SDL_CLOCK_LOOP, .ifcoding = SDL_CODING_B8ZS, .ifframing = SDL_FRAMING_ESF, .ifblksize = 64, .ifleads = 0, .ifbpv = 0, .ifalarms = 0, .ifrxlevel = 0, .iftxlevel = 0, .ifsync = 0, .ifsyncsrc = {0, 0, 0, 0} }; /** xp_allocate_chans: - allocate or reinitialize channel structures for a span * @sp: span structure pointer * * Allocates (on initial config or T1/J1 to E1 change-up) or reinitializes (on T1/J1 E1 change) the * channel structures for a given span. Once channels have been allocated, this function cannot * fail. Note that 31 channel structures are allocated regardless of span type. */ noinline __unlikely int xp_allocate_chans(struct sp *sp) { int chan; for (chan = 0; chan < 32; chan++) { struct ch *ch; if (!(ch = sp->chans[chan])) { if (!(ch = xp_alloc_ch(sp, chan))) return (-ENOMEM); } else { if (ch->sdl.config.ifgtype != sp->config.ifgtype) xp_init_ch(sp, ch, chan); } } return (0); } noinline __unlikely int xp_t1_span_config(struct sp *sp, bool timeouts); noinline __unlikely int xp_e1_span_config(struct sp *sp, bool timeouts); noinline __unlikely int xp_x1_span_config(struct sp *sp, bool timeouts); /** xp_span_config: - perform initial configuration on a span * @sp: span structure pointer * @timeouts: perform initial boot timeouts */ noinline __unlikely int xp_span_config(struct sp *sp, bool timeouts) { int err; switch (sp->cd->device) { case XP_DEV_DS21352: case XP_DEV_DS21552: err = xp_t1_span_config(sp, timeouts); break; case XP_DEV_DS21354: case XP_DEV_DS21554: err = xp_e1_span_config(sp, timeouts); break; case XP_DEV_DS2155: case XP_DEV_DS21455: case XP_DEV_DS21458: err = xp_x1_span_config(sp, timeouts); break; default: swerr(); err = -EFAULT; break; } return (err); } noinline __unlikely void xp_t1_chan_config(struct sp *sp, struct ch *ch, volatile uint8_t *xlb); noinline __unlikely int xp_t1_span_config(struct sp *sp, bool timeouts) { volatile unsigned char *xlb = (typeof(xlb)) sp->iobase; u_char tcr1 = 0, ccr2 = 0, ccr3 = 0, ccr5 = 0, ccr6 = 0, licr = 0, test2 = 0; int offset; int err; if ((err = xp_allocate_chans(sp)) != 0) return (err); /* set the idle code */ xlb[0x3f] = 0x7f; /* TIDR */ for (offset = 0; offset < 8; offset++) { xlb[0x50 + offset] = 0x7f; /* TC1 to TC8 */ } for (offset = 0; offset < 16; offset++) { xlb[0x40 + offset] = 0x7f; /* TC9 to TC24 */ xlb[0x80 + offset] = 0x7f; /* RC1 to RC16 */ } for (offset = 0; offset < 8; offset++) { xlb[0x58 + offset] = 0x7f; /* RC17 to RC24 */ } switch (sp->config.ifclock) { default: sp->config.ifclock = SDL_CLOCK_LOOP; case SDL_CLOCK_LOOP: /* Use the signal present at RCLK as the transmit clock. The TCLK pin is ignored. */ ccr3 |= (1 << 6); /* CCR3.6: TCLKSRC: Transmit Clock Source Select. 0 = TCR1.7; 1 = RCLK. */ tcr1 &= ~(1 << 7); /* TCR1.7: LOTCMC: Loss of Transmit Clock Mux Control. 0 = TCLK; 1 = RCLK if TCLK stops. */ /* default for T1 in tor3 driver, and here */ break; case SDL_CLOCK_INT: /* The TCLK pin is always the source of transmit clock. */ ccr3 &= ~(1 << 6); /* CCR3.6: TCLKSRC: Transmit Clock Source Select. 0 = TCR1.7; 1 = RCLK. */ tcr1 &= ~(1 << 7); /* TCR1.7: LOTCMC: Loss of Transmit Clock Mux Control. 0 = TCLK; 1 = RCLK if TCLK stops. */ break; case SDL_CLOCK_MASTER: /* Use the scaled signal present at MCLK as the transmit clock. The TCLK pin is ignored. */ ccr3 &= ~(1 << 6); /* CCR3.6: TCLKSRC: Transmit Clock Source Select. 0 = TCR1.7; 1 = RCLK. */ tcr1 &= ~(1 << 7); /* TCR1.7: LOTCMC: Loss of Transmit Clock Mux Control. 0 = TCLK; 1 = RCLK if TCLK stops. */ break; case SDL_CLOCK_EXT: /* Use the scaled signal present at TSYSCLK as the transmit clock. The TCLK pin is ignored. */ ccr3 &= ~(1 << 6); /* CCR3.6: TCLKSRC: Transmit Clock Source Select. 0 = TCR1.7; 1 = RCLK. */ tcr1 &= ~(1 << 7); /* TCR1.7: LOTCMC: Loss of Transmit Clock Mux Control. 0 = TCLK; 1 = RCLK if TCLK stops. */ break; case SDL_CLOCK_SLAVE: /* Switch to the clock present at RCLK when the signal at the TCLK pin fails to transition after 1 channel time. */ ccr3 &= ~(1 << 6); /* CCR3.6: TCLKSRC: Transmit Clock Source Select. 0 = TCR1.7; 1 = RCLK. */ tcr1 |= (1 << 7); /* TCR1.7: LOTCMC: Loss of Transmit Clock Mux Control. 0 = TCLK; 1 = RCLK if TCLK stops. */ /* default for E1 in tor3 driver, and here */ break; } switch (sp->config.ifframing) { default: sp->config.ifframing = SDL_FRAMING_ESF; /* fall through */ case SDL_FRAMING_ESF: /* CCR2.7: TFM: Transmit Frame Mode Select. 0 = D4; 1 = ESF. */ ccr2 |= (1 << 7); /* CCR2.3: RFM: Receive Frame Mode Select. 0 = D4; 1 = ESF. */ ccr2 |= (1 << 3); break; case SDL_FRAMING_SF: /* CCR2.5: TSLC96: Transmit SLC-96/Fs-Bit Insertion. 0 = disabled; 1 = enabled. */ ccr2 |= (1 << 5); break; } switch (sp->config.ifcoding) { default: sp->config.ifcoding = SDL_CODING_B8ZS; /* fall through */ case SDL_CODING_B8ZS: /* CCR2.6: TB7ZS: Transmit B8ZS Enable. 0 = disabled; 1 = enabled. */ ccr2 |= (1 << 6); /* CCR2.2: RB8ZS: Receive B8ZS Enable. 0 = disabled; 1 = enabled. */ ccr2 |= (1 << 2); break; case SDL_CODING_AMI: xlb[0x7e] = 0x1c; /* Set FDL register to 0x1c */ break; } switch (sp->config.ifgcrc) { default: switch (sp->config.ifgtype) { default: sp->config.ifgtype = SDL_GTYPE_T1; /* fall through */ case SDL_GTYPE_T1: sp->config.ifgcrc = SDL_GCRC_CRC6; goto gcrc_crc6; case SDL_TYPE_J1: sp->config.ifgcrc = SDL_GCRC_CRC6J; goto gcrc_crc6j; } break; case SDL_GCRC_CRC6: gcrc_crc6: /* CCR5.7: TJC: 0 = ANSI CRC6 Tx, 1 = JT-G704 CRC6 Tx */ ccr5 &= ~(1 << 7); /* CRC6.7: RJC: 0 = ANSI CRC6 Rx, 1 = JT-G704 CRC6 Rx */ ccr6 &= ~(1 << 7); break; case SDL_GCRC_CRC6J: gcrc_crc6j: /* CCR5.7: TJC: 0 = ANSI CRC6 Tx, 1 = JT-G704 CRC6 Tx */ ccr5 |= (1 << 7); /* CRC6.7: RJC: 0 = ANSI CRC6 Rx, 1 = JT-G704 CRC6 Rx */ ccr6 |= (1 << 7); break; } if (sp->config.iftxlevel < 8) { /* not monitoring mode */ licr &= ~(1 << 0); /* 0dB CSU, transmitters on */ licr |= ((sp->config.iftxlevel & 0x7) << 5); /* LBO */ } else { /* monitoring mode */ licr |= (1 << 0); /* 0dB CSU, transmitters off */ switch (sp->config.iftxlevel & 0x3) { case 1: test2 |= 0x72; /* TEST2 12dB gain */ /* 150 Ohm Lo-Z tap */ break; case 2: case 3: test2 |= 0x70; /* TEST2 20db gain */ /* single 432 OHm Hi-Z tap */ break; } } xlb[0x2b] = 0x08; /* Full-on sync required (RCR1) */ /* RCR1.7: LCVCRF: Line Code Violation Count Register Function Select. 0 = do not count excessive zeros; 1 = count excessive zeros. */ /* RCR1.6: ARC: Auto Resync Criteria. 0 = resync on OOF or RCL; 1 = resync on OOF only */ /* RCR1.5: OOF1: Out of Frame Select 1. 0 = 2/4 fram bits in error; 1 = 2/5 frame bits in error. */ /* RCR1.4: OOF2: Out of Frame Select 2. 0 = follor RCR1.5; 1 = 2/6 frame bits in error */ /* RCR1.3: SYNCC: Sync Criteria. D4 0 = search Ft then Fs; 1 = cross couple Ft and Fs. ESF 0 = search for FPS only; 1 = search for FPS and verify with CRC6 */ /* RCR1.2: SYNCT: Sync Time. 0 = qualify 10 bits; 1 = qualify 24 bits. */ /* RCR1.1: SYNCE: Sync Enable. 0 = auto resync enabled; 1 = auto resync disabled. */ /* RCR1.0: RESYNC: Resync. Toggle to request a resync. */ xlb[0x2c] = (1 << 3) | (1 << 7); /* RSYNC is an input (RCR2) */ /* RCR2.7: RCS: Receive Code Select. 0 = idle code (0x7f); 1 = milliwatt. */ /* RCR2.6: RZBTSI: Rx ZBTSI support. 0 = disabled; 1 = enabled. */ /* RCR2.5: RSDW: RSYNC double-wide. 0 = single wide; 1 = double wide. */ /* RCR2.4: RSM: RSYNC Mode Select. 0 = frame mode; 1 = multiframe mode. */ /* RCR2.3: RSIO: RSYNC I/O Select. 0 = ouput; 1 = input. */ /* RCR2.2: RD4YM: Receive Side D4 Yellow Alarm Select. 0 = zeros in bit 2; 1 = one in S-bit frame 12. */ /* RCR2.1: FSBE: PCVCR Rs-Bit Error Report Enable. 0 = no report Fs-bit errors; 1 = report Fs-bit errors. */ /* RCR2.0: MOSCRF: Multiframe out-of-sync Count Register Function Select. 0 = framing bits; 1 = number of multiframes. */ xlb[0x35] = tcr1 | (1 << 4); /* RBS enable (TCR1) */ /* TCR1.7=X: LOTCMC: Loss of Transmit Clock Mux Control. 0 = TCLK; 1 = RCLK if TCLK stops. */ /* TCR1.6=0: TFPT: Transmit F-bit pass through. 0 = F bits source internal; 1 = sampled at TSER. */ /* TCR1.5=0: TCPT: Transmit CRC pass through. 0 = CRC source internal; 1 = sampled at TSER. */ /* TCR1.4=1: TSSE: Transmit Software Signalling Enable. 0 = no signalling; 1 = from TSx/TTRx */ /* TCR1.3=0: GB7S: Global Bit 7 Stuffing. 0 = by TTR regs; 1 = forced */ /* TCR1.2=0: TFDLS: TFDL Register Select. 0 = FDL or Fs source internal; 1 = from HDLC/BOC or TLINK pin. */ /* TCR1.1=0: TBL: Transmit Blue Alarm. 0 = normal; 1 = tx unframed all ones. */ /* TCR1.0=0: TYEL: Transmit Yellow Alarm. 0 = no alarm; 1 = yellow alarm. */ xlb[0x36] = 0x04; /* TSYNC to be output (TCR2) */ /* TCR2.7: TEST1: Test mode. 0 = normal operation. */ /* TCR2.6: TEST0: Test mode. 0 = normal operation. */ /* TCR2.5: TZBTSI: Tx ZBTSI Support. 0 = disabled; 1 = enabled. */ /* TCR2.4: TSDDW: TSYN double-wide. 0 = single wide; 1 = double wide. */ /* TCR2.3: TSM: TSYN Mode Select. 0 = frame mode; 1 = multiframe mode. */ /* TCR2.2: TSIO: TSYNC I/O Select. 0 = input; 1 = output. */ /* TCR2.1: TD4YM: Tx D4 Yellow Alarm Select. 0 = bit2 all chan; 1 = S-bit frame 12. */ /* TCR2.0: TB7ZS: Tx Bit 7 Zero Suppression. 0 = no stuffing; 1 = force bit 7. */ xlb[0x37] = 0x9c; /* Tx & Rx Elastic stor, sysclk(s) = 2.048 mhz, loopback controls (CCR1) */ /* CCR1.7: TESE: Transmit Elastic Store Enable. 0 = bypassed; 1 = enabled. */ /* CCR1.6: ODF: Output Data Format. 0 = bipolar; 1 = NRZ. */ /* CCR1.5: RSAO: Receive Signalling All Ones. 0 = sign at RSER; 1 = forced to one. */ /* CCR1.4: TSCLKM: TSYSCLK Mode Select. 0 = 1.544 MHz; 1 = 2.048 or IBO. */ /* CCR1.3: RSCLKM: RSYSCLK Mode Select. 0 = 1.544 MHz; 1 = 2.048 or IBO. */ /* CCR1.2: RESE: Receive Elastic Store Enable. 0 = bypassed; 1 = enabled. */ /* CCR1.1: PLB: Payload Loopback. 0 = disabled; 1 = enabled. */ /* CCR1.0: FLB: Framer Loopback. 0 = disabled; 1 = enabled. */ xlb[0x38] = ccr2; /* CCR2.7: TFM: Transmit Frame Mode Select. 0 = D4; 1 = ESF. */ /* CCR2.6: TB7ZS: Transmit B8ZS Enable. 0 = disabled; 1 = enabled. */ /* CCR2.5: TSLC96: Transmit SLC-96/Fs-Bit Insertion. 0 = disabled; 1 = enabled. */ /* CCR2.4: TFDL: Transmit FDL Zero Stuffer Enable. 0 = diabled; 1 = enabled. */ /* CCR2.3: RFM: Receive Frame Mode Select. 0 = D4; 1 = ESF. */ /* CCR2.2: RB8ZS: Receive B8ZS Enable. 0 = disabled; 1 = enabled. */ /* CCR2.1: RSLC96: Receive SLC-96 Enable. 0 = disabled; 1 = enabled. */ /* CCR2.0: RZSE: Receive FDL Zero Destuffer Enable. 0 = disabled; 1 = enabled. */ xlb[0x30] = ccr3 | (1 << 2); /* CCR3.7: RESMDM: Rx Elastic Store Min Delay. 0 = full; 1 = 32-bits. */ /* CCR3.6: TCLKSRC: Transmit Clock Source Select. 0 = TCR1.7; 1 = RCLK. */ /* CCR3.5: RLOSF: RLOS/LOTC output. 0 = RLOS; 1 = LOTC. */ /* CCR3.4: RSMS: RSYNC MF Skip. 0 = each; 1 = every other. */ /* CCR3.3: PDE: Pulse Density Enforcer Enable. 0 = disable; 1 = enable. */ /* CCR3.2: ECUS: Error Counter Update. 0 = one second; 1 = 42 ms (333 frames). */ /* CCR3.1: TLOOP: Transmit Loop Code Enable. 0 = normal data; 1 = TCD data. */ /* CCR3.0: TESMDM: Tx Elastic Store Min Delay. 0 = full; 1 = 32-bits. */ xlb[0x11] = (1 << 0); /* CCR4.7: RSRE: Rx Sign. Reinsertion. 0 = disabled; 1 = reinsert. */ /* CCR4.6: RPCSI: Rx Perchannel Sign Insert. 0 = disabled; 1 = enabled. */ /* CCR4.5: RFSA1: Receive Force Sign. All Ones. 0 = normal; 1 = forced to 1. */ /* CCR4.4: RFE: Receive Freeze Enable. 0 = no freeze; 1 = allow freeze. */ /* CCR4.3: RFF: Receive Force Freeze. 0 = no freeze; 1 = freeze. */ /* CCR4.2: THSE: Tx Hw Sign Insertion. 0 = no insert; 1 = insert. */ /* CCR4.1: TPCSI: Tx Perchannel Sign Insert. 0 = disabled; 1 = enabled. */ /* CCR4.0: TIRFS: Tx Idle Registers Function. 0 = idle code; 1 = loopback. */ xlb[0x19] = ccr5; /* CCR5.7: TJC: Transmit Japanese CRC6 Enable. 0 = ANSI; 1 = JT-G704. */ /* CCR5.6: LLB: Local Loopback. 0 = disabled; 1 = enabled. */ /* CCR5.5: LIAIS: Lin Interface ASI Generation Enable. 0 = normal; 1 = unframed all ones. */ /* CCR5.4-0: TCM4-TCM0: Transmit Monitor channel. */ xlb[0x1e] = ccr6; /* CCR6.7: RJC: Receive Japanese CRC6 Enable. 0 = ANSI; 1 = JT-G704. */ /* CCR6.6: RESA: Receive Elastic Store Align. toggle to align. */ /* CCR6.5: TESA: Transmit Elastic Store Align. toggle to align. */ /* CCR6.4-0: RSM4-RSM0: Receive Monitor channel. */ xlb[0x0a] = 0x00; /* CCR7.7: LIRST: Line Interface Reset. Toggle and wait 40ms to reset. */ /* CCR7.6: RLB: Remote Loopback. 0 = disabled; 1 = enabled. */ /* CCR7.5: RESR: Receive Elastic Store Reset. toggle to reset. */ /* CCR7.4: TESR: Transmit Elastic Store Reset. toggle to reset. */ /* CCR7.3: -: Reserved. Set to zero. */ /* CCR7.2: LIUSI: Line Interface Sync Interface Enable. 0 = T1 signal; 1 = Sync signal. */ /* CCR7.1: CDIG: Customer Disconnect Indication Generator. 0 = normal; 1 = CDI. */ /* CCR7.0: LIUODO: Line Interface Open Drain Option. 0 = normal; 1 = open drain. */ xlb[0x7f] = 0xff; /* IMR1.7: LUP: Loop Up Code Detect. */ /* IMR1.6: LDN: Loop Down Code Detect. */ /* IMR1.5: LOTC: Loss of Transmit Clock. */ /* IMR1.4: SLIP: Elastic Store Slip Occurrence. */ /* IMR1.3: RBL: Receive Blue Alarm. */ /* IMR1.2: RYEL: Receive Yelllow Alarm. */ /* IMR1.1: LRCL: Line Interface Receive Carrier Loss. */ /* IMR1.0: RLOS: Receive Loss of Sync. */ xlb[0x6f] = 0x20; /* IMR2.7: RMF: Receive Multiframe. */ /* IMR2.6: TMF: Transmit Multiframe. */ /* IMR2.5: SEC: One Second Timer. */ /* IMR2.4: RFDL: Receive FDL Buffer Full. */ /* IMR2.3: TFDL: Transmit FDL Buffer Empty. */ /* IMR2.2: RMTCH: Receive FDL Match Occurrence. */ /* IMR2.1: RAF: Receive FDL Abort. */ /* IMR2.0: RSC: Receive Signaling Change. */ xlb[0x12] = 0x22; /* IBCC 5-bit loop up, 3-bit loop down code */ xlb[0x13] = 0x80; /* TCD - 10000 */ xlb[0x14] = 0x80; /* RUPCD - 10000 */ xlb[0x15] = 0x80; /* RDNCD - 100 */ xlb[0x09] = test2; /* TEST2 */ xlb[0x7c] = licr; /* LICR.7-5: L2-L0: Line Build Out Select. */ /* LICR.4: EGL: Receive Equalizer Gain Limit. 0 = -36dB, 1 = -30dB. */ /* LICR.3: JAS: Jitter Attenuator Select. 0 = receive; 1 = transmit. */ /* LICR.2: JABDS: Jitter Attenuator Buffer Depth Select. 0 = 128 bits; 1 = 32 bits. */ /* LICR.1: DJA: Disable Jitter Attenuator. 0 = enabled; 1 = disabled. */ /* LICR.0: TPD: Transmit Power Down. 0 = normal; 1 = power-down. */ /* CONFIGURE ALL TIMESLOTS. */ { struct ch *ch; int chan; for (chan = 1; chan < 25; chan++) { if ((ch = sp->chans[chan]) != NULL) { xp_t1_chan_config(sp, ch, xlb); continue; } swerr(); } } /* SET UP INTERRUPT MASK REGISTERS */ xlb[0x7f] = 0xff; /* IMR1.7: LUP: Loop Up Code Detected. */ /* IMR1.6: LDN: Loop Down Code Detected. */ /* IMR1.5: LOTC: Loss of Transmit Clock. */ /* IMR1.4: SLIP: Elastic Store Slip Occurrence. */ /* IMR1.3: RBL: Receive Blue Alarm. */ /* IMR1.2: RYEL: Receive Yellow Alarm. */ /* IMR1.1: LRCL: Line Interface Receive Carrier Loss. */ /* IMR1.0: RLOS: Receive Loss of Sync. */ xlb[0x6f] = (1 << 5); /* IMR2.7: RMF: Receive Multiframe. */ /* IMR2.6: TMF: Transmit Multiframe. */ /* IMR2.5: SEC: One Second Timer. */ /* IMR2.4: RFDL: Receive FDL Buffer Full. */ /* IMR2.3: TFDL: Transmit FDL Buffer Empty. */ /* IMR2.2: RMTCH: Receive FDL Match Occurrence. */ /* IMR2.1: RAF: Receive FDL Abort. */ /* IMR2.0: RSC: Receive Signaling Change. */ if (timeouts) { unsigned long timeout; /* line interface reset */ xlb[0x0a] |= (1 << 7); xlb[0x0a] &= ~(1 << 7); /* wait for 40 ms */ timeout = (volatile unsigned long) jiffies + 100 * HZ / 1000; while ((volatile unsigned long) jiffies < timeout) ; /* elastic store reset */ /* CCR7.4 and CCR7.5 are TESR and RESR (resp) */ xlb[0x0a] |= ((1 << 4) | (1 << 5)); /* CCR7: TESR and RESR */ xlb[0x0a] &= ~((1 << 4) | (1 << 5)); /* CCR7: */ /* elastic store align */ /* CCR6.5 and CCR6.6 are TESA and RESA (resp) */ xlb[0x1e] |= ((1 << 5) | (1 << 6)); /* CCR6: TESA and RESA */ xlb[0x1e] &= ~((1 << 5) | (1 << 6)); /* CCR6: */ } return (0); } /** xp_t1_chan_config: - configure a T1/J1 channel * @sp: span structure pointer * @ch: chan structure pointer */ noinline __unlikely void xp_t1_chan_config(struct sp *sp, struct ch *ch, volatile uint8_t *xlb) { if (ch->chan == 0) { swerr(); return; } if (ch->sdl.config.iftype != SDL_TYPE_DS0A) /* DS0 needs to be set for clear-channel operation. */ xlb[0x39 + ((ch->chan - 1) >> 3)] |= (1 << ((ch->chan - 1) % 8)); else /* DS0A does not need to be set for clear-channel operation. */ xlb[0x39 + ((ch->chan - 1) >> 3)] &= ~(1 << ((ch->chan - 1) % 8)); /* Per-channel quiet code. */ if (ch->sdl.config.ifmode == SDL_MODE_IDLE) { xlb[0x16 + ((ch->chan - 1) >> 3)] |= (1 << ((ch->chan - 1) % 8)); xlb[0x1b + ((ch->chan - 1) >> 3)] |= (1 << ((ch->chan - 1) % 8)); } else { xlb[0x16 + ((ch->chan - 1) >> 3)] &= ~(1 << ((ch->chan - 1) % 8)); xlb[0x1b + ((ch->chan - 1) >> 3)] &= ~(1 << ((ch->chan - 1) % 8)); } /* Per-channel milliwatt. */ /* RCR2.7 must be 1 for this to work. */ if (ch->sdl.config.ifmode == SDL_MODE_MW) { xlb[0x16 + ((ch->chan - 1) >> 3)] |= (1 << ((ch->chan - 1) % 8)); xlb[0x2d + ((ch->chan - 1) >> 3)] |= (1 << ((ch->chan - 1) % 8)); } else xlb[0x2d + ((ch->chan - 1) >> 3)] &= ~(1 << ((ch->chan - 1) % 8)); /* Per-channel remote payload loopback. */ /* CCR4.0 must be 1 for this to work. */ if (ch->sdl.config.ifmode == SDL_MODE_REM_LB) xlb[0x3c + ((ch->chan - 1) >> 3)] |= (1 << ((ch->chan - 1) % 8)); else xlb[0x3c + ((ch->chan - 1) >> 3)] &= ~(1 << ((ch->chan - 1) % 8)); } noinline __unlikely void xp_e1_chan_config(struct sp *sp, struct ch *ch, volatile uint8_t *xlb); noinline __unlikely int xp_e1_span_config(struct sp *sp, bool timeouts) { volatile unsigned char *xlb = (typeof(xlb)) sp->iobase; uint8_t ccr1 = 0, tcr1 = 0, tcr2 = 0, licr = 0, test3 = 0, ccr6 = 0, ccr2 = 0; int offset; int err; if ((err = xp_allocate_chans(sp)) != 0) return (err); /* The 2.048 MHz clock attached at the MCLK pin is internally multiplied by 16 via an internal PLL circuit to form a 16-times over-sampler, which is used to recover the clock and data. Normally the clock that is output at the RCLKO pin is the recovered clock from the E1 AMI/HDB3 waveform presented at the RTIP and RRING inputs. When no AMI signal is present at RTIP and RRING, a receive carrier loss (RCL) condition occurs, and the RCLKO is sourced from the clock applied at the MCLK pin. If the jitter attenuator is either placed in the transmit path or disabled, the RCLKO output can exhibit slightly shorter high cycles of the clock, which is due to the highly oversampled digital clock recovery circuitry. if the jitter attenuator is placed in the receive path (as is the case in most applications), the jitter attenuator restores the RCLK to being close to 50% duty cycle. */ switch (sp->config.ifclock) { default: sp->config.ifclock = SDL_CLOCK_LOOP; case SDL_CLOCK_LOOP: /* Use the signal present at RCLK as the transmit clock. The TCLK pin is ignored. */ ccr6 |= (1 << 2); /* CCR6.2: 1 = Force transmitter to internally switch to RCLK as source of transmit clock. Signal at TCLK pin is ignored. */ ccr2 &= ~(1 << 2); /* CCR2.2: 0 = do not switch to RCLKO if TCLK stops */ break; case SDL_CLOCK_INT: /* The TCLK pin is always the source of the transmit clock. */ ccr6 &= ~(1 << 2); /* CCR6.2: 0 = source to transmit clock determined by CCR2.2 (LOTCMC). */ ccr2 &= ~(1 << 2); /* CCR2.2: 0 = do not switch to RCLKO if TCLK stops */ break; case SDL_CLOCK_MASTER: /* Use the scaled signal present at MCLK as the transmit clock. The TCLK pin is ignored. */ ccr6 &= ~(1 << 2); /* CCR6.2: 0 = source to transmit clock determined by CCR2.2 (LOTCMC). */ ccr2 &= ~(1 << 2); /* CCR2.2: 0 = do not switch to RCLKO if TCLK stops */ break; case SDL_CLOCK_EXT: /* Use the scaled signal present at the TSYSCLK as the transmit clock. The TCLK pin is ignored. */ ccr6 &= ~(1 << 2); /* CCR6.2: 0 = source to transmit clock determined by CCR2.2 (LOTCMC). */ ccr2 &= ~(1 << 2); /* CCR2.2: 0 = do not switch to RCLKO if TCLK stops */ break; case SDL_CLOCK_SLAVE: /* Switch to the clock present at RCLK when the signal at the TCLK pin fails to transition after 1 channel time. */ ccr6 &= ~(1 << 2); /* CCR6.2: 0 = source to transmit clock determined by CCR2.2 (LOTCMC). */ ccr2 |= (1 << 2); /* CCR2.2: 1 = switch to RCLKO if TCLK stops */ break; } switch (sp->config.ifframing) { default: sp->config.ifframing = SDL_FRAMING_CCS; case SDL_FRAMING_CCS: ccr1 |= (1 << 3); /* CCR1.3: 1 = Rx CCS signaling mode */ tcr1 &= ~(1 << 5); /* TCR1.5: 0 = sample time slot 16 at TSER pin */ break; case SDL_FRAMING_CAS: ccr1 &= ~(1 << 3); /* CCR1.3: 0 = Rx CAS signaling mode */ tcr1 |= (1 << 5); /* TCR1.5: 1 = source time slot 16 from TS1 to TS15 registers */ break; } switch (sp->config.ifcoding) { default: sp->config.ifcoding = SDL_CODING_HDB3; case SDL_CODING_HDB3: ccr1 |= (1 << 6); /* CCR1.6: 1 = Tx HDB3 enabled */ ccr1 |= (1 << 2); /* CCR1.2: 1 = Rx HDB3 enabled */ ccr2 |= (1 << 6); /* CCR2.6: 1 = count CVs */ break; case SDL_CODING_AMI: ccr1 &= ~(1 << 6); /* CCR1.6: 0 = Tx HDB3 disabled */ ccr1 &= ~(1 << 2); /* CCR1.2: 0 = Rx HDB3 disabled */ ccr2 &= ~(1 << 6); /* CCR2.6: 0 = count BPVs */ break; } switch (sp->config.ifgcrc) { default: sp->config.ifgcrc = SDL_GCRC_CRC4; case SDL_GCRC_CRC4: ccr1 |= (1 << 4); /* CRC1.4: 1 = Tx CRC4 enabled */ ccr1 |= (1 << 0); /* CRC1.0: 1 = Rx CRC4 enalled */ tcr2 |= (1 << 1); /* TCR2.1: 1 = E-bits automatically set */ #if 0 if (sp->config.ifframing == SDL_FRAMING_CAS) tcr1 |= (1 << 1); /* TCR1.1: 1 = CAS and CRC4 multiframe mode */ #endif break; case SDL_GCRC_CRC5: ccr1 &= ~(1 << 4); /* CRC1.4: 0 = Tx CRC4 disabled */ ccr1 &= ~(1 << 0); /* CRC1.0: 0 = Rx CRC4 disabled */ break; } licr = 0x00; /* LICR.7-5: 0x0 = 75 Ohm w/o protection resistors */ /* LICR.4: 0 = -12dB Rx EGL */ /* LICR.3: 0 = JA on receive side */ /* LICR.2: 0 = JA buffer depth 128 bits */ /* LICR.1: 0 = JA enabled */ /* LICR.0: X = transmitters on/off */ licr = 0x10; /* LICR.7-5: 0x0 = 75 Ohm w/o protection resistors */ /* LICR.4: 1 = -43dB Rx EGL */ /* LICR.3: 0 = JA on receive side */ /* LICR.2: 0 = JA buffer depth 128 bits */ /* LICR.1: 0 = JA enabled */ /* LICR.0: X = transmitters on/off */ /* LICR.7-5: DS21354: '000' 75(1:2) Ohm normal. */ /* LICR.7-5: DS21354: '001' 120(1:2) Ohm normal. */ /* LICR.7-5: DS21354: '010' 75(1:2) Ohm w/ Rt */ /* LICR.7-5: DS21354: '011' 120(1:2) Ohm w/ Rt */ /* LICR.7-5: DS21354: '100' 75(1:2) Ohm HRL */ /* LICR.7-5: DS21354: '101' 120(1:2) Ohm HRL */ /* LICR.7-5: DS21554: '000' 75(1:1.15) Ohm normal */ /* LICR.7-5: DS21554: '001' 120(1:1.15) Ohm normal */ /* LICR.7-5: DS21554: '010' 75(1:1.15) Ohm w/ Rt */ /* LICR.7-5: DS21554: '011' 120(1:1.15) Ohm w/ Rt */ /* LICR.7-5: DS21554: '100' 75(1:1.15)/120(1:1.36) Ohm HLR */ /* LICR.7-5: DS21554: '101' invalid */ /* LICR.7-5: DS21554: '110' 75(1.1.36) Ohm HRL */ /* LICR.7-5: DS21554: '111' invalid */ /* Responsibility of IOCTLs to ensure that the iftxlevel has one of the valid values. Given the t2 and t3 circuitry, the only valid value is LICR.7-5='001' and for the DS21354 only because the transformer ratios are 1:2, there are 2x60.9=120 Ohm resistors on the cards and there are no transmit termination resistors (Rt) in the Tormenta design. */ /* Theoretically, one could install 2x36 Ohm resistors instead of 2x60.9 Ohm resistors for a 75 Ohm balanced termination. */ test3 = 0x00; /* TEST3: 0x00 = no Rx gain */ if (sp->config.iftxlevel < 8) { /* not monitoring mode */ test3 = 0x00; /* TEST3: 0x00 = no Rx gain */ licr = 0x00; /* 75 Ohm, Normal, -12dB Rx EGL, transmitter on */ licr |= ((sp->config.iftxlevel & 0x7) << 5); /* LBO */ } else { /* monitoring mode */ test3 = 0x00; /* TEST3: 0x00 = no Rx gain */ // licr = 0x01; /* LICR.0: 1 = transmitter off */ // licr |= 0x10; /* LICR.4: 1 = -43dB Rx EGL */ licr = 0x21; /* 120 Ohm, Normal, -12dB Rx EGL, transmitter off */ switch (sp->config.iftxlevel & 0x3) { case 0: break; case 1: test3 |= 0x72; /* TEST3: 0x72 = 12dB Rx gain */ /* 180 Ohm Lo-Z tap */ break; case 2: case 3: test3 |= 0x70; /* TEST3: 0x70 = 30dB Rx gain */ /* 1800 Ohm Hi-Z tap */ break; } } tcr1 = (1 << 3) | (1 << 0); xlb[0x12] = tcr1; /* TCR1 */ /* TCR1.7: 0 = bipolar data at TPOS0 and TNEG0 */ /* TCR1.6: 0 = FAS bits/Sa bits/RAI sources from TAF and TNAF registers */ /* TCR1.5: X = sample TS 16 at TSER pin/source TS 16 from TS0 to TS15 */ /* TCR1.4: 0 = transmit data normally */ /* TCR1.3: 1 = source Si bits from TAF and TNAF regsiters (TCR1.6 must be zero) */ /* TCR1.2: 0 = transmit data normally */ /* TCR1.1: X = frame mode/CAS and CRC4 multiframe mode */ /* TCR1.0: 1 = TSYNC is an output */ xlb[0x13] = tcr2; /* TCR2 */ /* TCR2.7: 0 = do not source Sa8 bit from TLINK pin */ /* TCR2.6: 0 = do not source Sa7 bit from TLINK pin */ /* TCR2.5: 0 = do not source Sa6 bit from TLINK pin */ /* TCR2.4: 0 = do not source Sa5 bit from TLINK pin */ /* TCR2.3: 0 = do not source Sa4 bit from TLINK pin */ /* TCR2.2: 0 = TPOSO/TNEGO full clock period */ /* TCR2.1: X = E-bits not automatically/automatically set */ /* TCR2.0: 0 = RLOS/LOTC pin is RLOS */ xlb[0x10] = (1 << 5); /* RCR1 */ /* RCR1.7: 0 = CAS/CRC4 multiframe */ /* RCR1.6: 0 = frame mode */ /* RCR1.5: 1 = RSYNC is an input */ /* RCR1.4: 0 = unassigned */ /* RCR1.3: 0 = unassigned */ /* RCR1.2: 0 = resync if FAS received in error 3 consecutive times */ /* RCR1.1: 0 = auto resync enabled */ /* RCR1.0: 0 = no immediate resync */ xlb[0x11] = (1 << 2) | (1 << 1); /* RCR2 */ /* RCR2.7: 0 = RLCLK low during Sa8 bit */ /* RCR2.6: 0 = RLCLK low during Sa7 bit */ /* RCR2.5: 0 = RLCLK low during Sa6 bit */ /* RCR2.4: 0 = RLCLK low during Sa5 bit */ /* RCR2.3: 0 = RLCLK low during Sa4 bit */ /* RCR2.2: 1 = RSYSCLK is 2.048/4.096/8.192 MHz */ /* RCR2.1: 1 = elastic store (receive) enabled */ /* RCR2.0: 0 = unassigned */ xlb[0x14] = ccr1; /* CCR1 */ /* CCR1.7: 0 = framer loopback disabled */ /* CCR1.6: X = Tx HDB3 disabled/enabled */ /* CCR1.5: 0 = Tx G.802 disabled */ /* CCR1.4: X = Tx CRC4 disabled */ /* CCR1.3: X = signalling mode CAS/CCS */ /* CCR1.2: X = Rx HDB3 disabled/enabled */ /* CCR1.1: 0 = Rx G.802 disabled */ /* CCR1.0: X = Rx CRC4 disabled */ ccr2 |= (1 << 4) | (1 << 5) | (1 << 7); xlb[0x1a] = ccr2; /* CCR2 */ /* CCR2.7: 1 = update error counters once each 62.5ms */ /* CCR2.6: X = count CVs/count BPVs */ /* CCR2.5: 1 = automatic transmit AIS generation enabled */ /* CCR2.4: 1 = automatic transmit RAI generation enabled */ /* CCR2.3: 0 = RSER as received under all conditions */ /* CCR2.2: X = do not/do switch to RCLKO if TCLK stops */ /* CCR2.1: 0 = do not force a freeze event */ /* CCR2.0: 0 = no freezing of receive signalling data */ xlb[0x1b] = (1 << 7) | (1 << 5) | (1 << 1); /* CCR3 */ /* CCR3.7: 1 = Tx elastic store is enabled */ /* CCR3.6: 0 = define operation of TCHBLK output pin */ /* CCR3.5: 1 = TIRs define channels to loopback */ /* CCR3.4: 0 = unassigned (elastic store reset DS2154) */ /* CCR3.3: 0 = do not reinsert signalling bits at RSER (LIRST on DS2153) */ /* CCR3.2: 0 = do not insert signalling from TSIG pin */ /* CCR3.1: 1 = TSYSCLK is 2.048/4.096/8.192 MHz */ /* CCR3.0: 0 = RCL declared upon 255 consecutive zeros */ xlb[0xa8] = 0x00; /* CCR4 */ /* CCR4.7: 0 = remote loopback disabled */ /* CCR4.6: 0 = local loopback disabled */ /* CCR4.5: 0 = transmit normal data */ /* CCR4.4: 0 = TCM bit 4 (unused) */ /* CCR4.3: 0 = TCM bit 3 (unused) */ /* CCR4.2: 0 = TCM bit 2 (unused) */ /* CCR4.1: 0 = TCM bit 1 (unused) */ /* CCR4.0: 0 = TCM bit 0 (unused) */ xlb[0xaa] = 0x00; /* CCR5 */ /* CCR5.7: 0 = no immediate LIRST */ /* CCR5.6: 0 = no RES align (not assigned DS2154) */ /* CCR5.5: 0 = no TES align (not assigned DS2154) */ /* CCR5.4: 0 = RCM bit 4 (unused) */ /* CCR5.3: 0 = RCM bit 3 (unused) */ /* CCR5.2: 0 = RCM bit 2 (unused) */ /* CCR5.1: 0 = RCM bit 1 (unused) */ /* CCR5.0: 0 = RCM bit 0 (unused) */ xlb[0x1d] = ccr6; /* CRC6 */ /* CCR6.7: 0 = TTIP and TRING normal */ /* CCR6.6: 0 = normal data */ /* CCR6.5: 0 = E1 signal */ /* CCR6.4: 0 = unassigned */ /* CCR6.3: 0 = unassigned */ /* CCR6.2: X = Tx clock determined by CRC2.2 (LOTCMC)/Tx clock is RCLK */ /* CCR6.1: 0 = no RES reset */ /* CCR6.0: 0 = no TES reset */ xlb[0xac] = test3; /* TEST3: 0x00 = no Rx gain */ /* TEST3: 0x70 = 30dB Rx gain */ /* TEST3: 0x72 = 12dB Rx gain */ xlb[0x18] = licr; /* LICR.7: X = LBO bit 2 */ /* LICR.6: X = LBO bit 1 */ /* LICR.5: X = LBO bit 0 */ /* LICR.4: X = -12dB/-43dB Rx EGL */ /* LICR.3: 0 = JA on receive side */ /* LICR.2: 0 = JA buffer depth 128 bits */ /* LICR.1: 0 = JA enabled */ /* LICR.0: X = transmitters on/off */ xlb[0x20] = 0x1b; /* TAFR: Note:The TAF register must be programmed with the 7-bit FAS word (0x1b). The DS21354/DS21554 do not automatically set these bits. */ /* TAF.7: 0 = Si bit */ /* TAF.6: 0 = frame alignment signal bit */ /* TAF.5: 0 = frame alignment signal bit */ /* TAF.4: 1 = frame alignment signal bit */ /* TAF.3: 1 = frame alignment signal bit */ /* TAF.2: 0 = frame alignment signal bit */ /* TAF.1: 1 = frame alignment signal bit */ /* TAF.0: 1 = frame alignment signal bit */ xlb[0x21] = 0x5f; /* TNAFR: Note: bit 6 of the TNAF register must be programmed to one. The DS21354/DS21554 does not automaticallly set this bit. G.704/2.3.2: Bits Sa4 to Sa8 (where these are not used) should be set to 1 on links crossing an international border. This also conveys a synchronization status message of "do not use for synchronization" regardless of sychronization status bit assignment. */ /* TNAF.7 0 = Si bit */ /* TNAF.6 1 = FNA signal bit */ /* TNAF.5 0 = remote alarm */ /* TNAF.4 1 = additional bit 4 */ /* TNAF.3 1 = additional bit 5 */ /* TNAF.2 1 = additional bit 6 */ /* TNAF.1 1 = additional bit 7 */ /* TNAF.0 1 = additional bit 8 */ /* CONFIGURE ALL TIMESLOTS. */ /* set the idle code */ xlb[0x2a] = 0xff; for (offset = 0; offset < 32; offset++) { xlb[0x60 + offset] = 0xff; /* tx idle code */ xlb[0x80 + offset] = 0xff; /* rx idle code */ } /* Note that setting up these registers has no effect unless the line framing is set to CAS instead of CCS. */ xlb[0x40] = 0x0b; /* TS1: X = 1, Y = 0: CAS alignment word */ /* TS1.0=1: X: 1 = spare bit */ /* TS1.1=1: X: 1 = spare bit */ /* TS1.2=0: Y: 0 = no remote alarm */ /* TS1.3=1: X: 1 = spare bit */ /* TS1.4=0: 0: 0 = must be zero */ /* TS1.5=0: 0: 0 = must be zero */ /* TS1.6=0: 0: 0 = must be zero */ /* TS1.7=0: 0: 0 = must be zero */ for (offset = 0; offset < 4; offset++) { /* Note: If CCR3.6 == 1, then a zero in the TCBRs implies that signaling data is to be sourced from TSER (or TSIG if CCR3.2 == 1), and a one implies that signaling data for that channel is to be sourced from the Transmit Signaling (TS) registers. In this mode, the voice-channel number scheme (CH1 to CH30) is used. */ xlb[0x22 + offset] = 0xff; /* TCB1 to TCB4 = all ones */ } { struct ch *ch; int chan; for (chan = 1; chan < 32; chan++) { if ((ch = sp->chans[chan]) != NULL) { xp_e1_chan_config(sp, ch, xlb); continue; } swerr(); } } /* SET UP INTERRUPT MASK REGISTERS */ xlb[0x16] = (1 << 0) | (1 << 1) | (1 << 2) | (1 << 3) | (1 << 4); /* IMR1.7=0: RSA1: Receive Signaling All Ones/Signaling Change. */ /* IMR1.6=0: RDMA: Receive Distant MF Alarm. */ /* IMR1.5=0: RSA0: Receive Signaling All Zeros/Signaling Change. */ /* IMR1.4=1: RSLIP: Receive Elastic Store Slip Occurrence. */ /* IMR1.3=1: RUA1: Receive Unframed All Ones. */ /* IMR1.2=1: RRA: Receive Remote Alarm. */ /* IMR1.1=1: RCL: Receive Carrier Loss. */ /* IMR1.0=1: RLOS: Receive Loss of Sync. */ xlb[0x17] = (1 << 0) | (1 << 2) | (1 << 4); /* IMR2.7=0: RMF: Receive CAS Multiframe. */ /* IMR2.6=0: RAF: Receive Align Frame. */ /* IMR2.5=0: TMF: Transmit Multiframe. */ /* IMR2.4=1: SEC: One Second Timer. */ /* IMR2.3=0: TAF: Transmit Align Frame. */ /* IMR2.2=1: LOTC: Loss of Transmit Clock. */ /* IMR2.1=0: RCMF: Receive CRC4 Multiframe. */ /* IMR2.0=1: TSLIP: Transmit-Side Eleastic Store Slip Occurrence. */ #if 1 if (timeouts) { unsigned long timeout; /* line interface reset */ xlb[0xaa] |= (1 << 7); /* CCR5 line interface reset (LIRST) */ timeout = (volatile unsigned long) jiffies + 100 * HZ / 1000; while ((volatile unsigned long) jiffies < timeout) ; xlb[0xaa] &= ~(1 << 7); /* CCR5 */ /* This must always be done after LIRST. */ /* reset and realign elastic stores */ xlb[0x1d] |= ((1 << 1) | (1 << 0)); /* CRC6: reset elastic stores */ xlb[0x1d] &= ~((1 << 1) | (1 << 0)); /* CRC6 */ /* CCR6.7: 0 = TTIP and TRING normal */ /* CCR6.6: 0 = normal data */ /* CCR6.5: 0 = E1 signal */ /* CCR6.4: 0 = unassigned */ /* CCR6.3: 0 = unassigned */ /* CCR6.2: X = Tx clock determined by CRC2.2 (LOTCMC)/Tx clock is RCLK */ /* CCR6.1: X = no RES reset */ /* CCR6.0: X = no TES reset */ xlb[0xaa] |= ((1 << 6) | (1 << 5)); /* CCR5 realign elastic stores */ xlb[0xaa] &= ~((1 << 6) | (1 << 5)); /* CCR5 */ } #endif return (0); } noinline __unlikely void xp_e1_chan_config(struct sp *sp, struct ch *ch, volatile uint8_t *xlb) { if (ch->chan == 0) { swerr(); return; } /* Per-channel signalling from signalling registers. */ /* TS2 thru TS16. Set b and d bits transmit signalling each channel. (ITU-T specifications recommend that ABCD signalling not be set to all zero because they will emulate a CAS multiframe alignment word. */ /* Note that this has no effect unless the framing is set to CAS instead of CCS. */ if (ch->chan < 16) /* chan 1 through chan 15 is upper nibble of 0x41 through 0x4f */ xlb[0x40 + (ch->chan % 16)] = (xlb[0x40 + (ch->chan % 16)] & ~0xf0) | 0x50; if (ch->chan > 16) /* chan 17 through chan 31 is lower nibble of 0x41 through 0x4f */ xlb[0x40 + (ch->chan % 16)] = (xlb[0x40 + (ch->chan % 16)] & ~0x0f) | 0x05; /* When CAS signalling is used we cannot apply the same logic to channel 16 as we normally do. */ if (ch->chan == 16) { if (sp->config.ifframing == SDL_FRAMING_CAS) ch->sdl.config.ifmode = SDL_MODE_SIG; else if (ch->sdl.config.ifmode == SDL_MODE_SIG) ch->sdl.config.ifmode = SDL_MODE_PEER; } /* Per-channel quiet code. */ if (ch->sdl.config.ifmode == SDL_MODE_IDLE) { xlb[0xa0 + (sp->span >> 3)] |= (1 << (ch->chan % 8)); xlb[0xa4 + (sp->span >> 3)] |= (1 << (ch->chan % 8)); } else { xlb[0xa0 + (sp->span >> 3)] &= ~(1 << (ch->chan % 8)); xlb[0xa4 + (sp->span >> 3)] &= ~(1 << (ch->chan % 8)); } /* Per-channel remote payload loopback. */ if (ch->sdl.config.ifmode == SDL_MODE_REM_LB) xlb[0x26 + (sp->span >> 3)] |= (1 << (ch->chan % 8)); else xlb[0x26 + (sp->span >> 3)] &= ~(1 << (ch->chan % 8)); } noinline __unlikely void xp_x1_chan_config(struct sp *sp, struct ch *ch, volatile uint8_t *xlb); noinline __unlikely int xp_x1_span_config(struct sp *sp, bool timeouts) { volatile unsigned char *xlb = (typeof(xlb)) sp->iobase; u_char t1rcr2, t1tcr1, t1tcr2, t1ccr1, e1rcr1, e1tcr1, sigcr, ercnt, ccr1, lic1, lic2, lic3, lic4; int err; if ((err = xp_allocate_chans(sp)) != 0) return (err); /* MSTRREG.0: SFTRST: Software issued reset. */ /* MSTRREG.1: T1/E1: Operating Mode. */ /* MSTRREG.2: TEST0: 0 = operate normally */ /* MSTRREG.3: TEST1: 0 = operate normally */ switch (sp->config.ifgtype) { default: case SDL_GTYPE_NONE: sp->config.ifgtype = SDL_GTYPE_E1; case SDL_GTYPE_E1: /* MSTRREG.1=1: E1 Operating Mode. */ xlb[0x00] = (1 << 1); break; case SDL_GTYPE_T1: case SDL_GTYPE_J1: /* MSTRREG.1=0: T1/J1 Operating Mode. */ xlb[0x00] = (0 << 1); break; } /* IOCR1.7=0 (E1 MR) CAS multiframe boundaries */ /* IOCR1.6=0 N/A when TSYNC is an input */ /* IOCR1.5=0 RSYNC pin is frame mode */ /* IOCR1.4=1 RSYNC is an input (not an output) */ /* IOCR1.3=0 N/A when TSYNC is an ouput */ /* IOCR1.2=0 TSYNC pin is frame mode */ /* IOCR1.1=1 TSYNC is an output (not an input) */ /* IOCR1.0=0 bibolar (not NRZ) data at TPOSO and TNEGO */ /* IOCR1.4=1 RSYNC is an input (elastic store). */ /* IOCR1.1=1 TSYNC is an output, */ /* IOCR1.0=0 Output data format is bipolar, */ xlb[0x01] = (1 << 4) | (1 << 1); /* RSIO + 1 is from O12.0 */ /* IOCR2.7=0 RCLK no inversion */ /* IOCR2.6=0 TCLK no inversion */ /* IOCR2.5=0 RSYNC no inversion */ /* IOCR2.4=0 TSYNC no inversion */ /* IOCR2.3=0 TSSYNC no inversion */ /* IOCR2.2=0 H.100 SYNC mode normal */ /* IOCR2.1=1 TSYSCLK is 2.048/4.096/8.192MHz or IBO enabled */ /* IOCR2.0=1 RSYSCLK is 2.048MHz or IBO enabled */ xlb[0x02] = (1 << 1) | (1 << 0); /* RSYSCLK/TSYSCLK 8.192MHz IBO */ /* IBOC.6=0: IBS1: 01 - four devices; 11 - reserved. */ /* IBOC.5=1: IBS0: 00 - two devices; 10 - Eight devices; */ /* IBOC.4=0: IBOSEL: IBO Select (0-channel,1-frame) interleave */ /* IBOC.3=1: IBOEN: Interleave Bus Operation Enable. */ /* IBOC.2-0=n: DA2-DA0: Position on bus. */ xlb[0xc5] = (1 << 5) | (1 << 3) | sp->span; /* ESCR.7=0 !TESALIGN no align. */ /* ESCR.6=0 !TESR no reset. */ /* ESCR.5=0 !TESMDM full two frame depth. */ /* ESCR.4=1 TESE transmit eleastic store enabled. */ /* ESCR.3=0 !RESALGN no align. */ /* ESCR.2=0 !RESR no reset. */ /* ESCR.1=0 !RESMDM full two frame depth. */ /* ESCR.0=1 RESE receive eleastic store enabled. */ xlb[0x4f] = (1 << 4) | (1 << 0); /* RES/TES (elastic store) enabled */ #if 1 /* NOTE: this should be done after LIRST */ /* We should really reset the elastic store after reset like so: */ /* ESCR.2=1 RESR reset. */ /* ESCR.6=1 TESR reset. */ xlb[0x4f] &= ~((1 << 6) | (1 << 2)); /* Clear enabled elastic stores. */ xlb[0x4f] |= ((1 << 6) | (1 << 2)); /* Reset enabled elastic stores. */ xlb[0x4f] &= ~((1 << 6) | (1 << 2)); /* Clear enabled elastic stores. */ #endif #if 1 /* NOTE: this should be done after LIRST */ /* And even align it like so: */ /* ESCR.3=1 RESALGN align. */ /* ESCR.7=1 TESALIGN align. */ xlb[0x4f] &= ~((1 << 7) | (1 << 3)); /* Clear enabled elastic stores. */ xlb[0x4f] |= ((1 << 7) | (1 << 3)); /* Align enabled elastic stores. */ xlb[0x4f] &= ~((1 << 7) | (1 << 3)); /* Clear enabled elastic stores. */ #endif /* CCR1.0=0 RLOS/LOTC ouput is RLOS */ /* CCR1.3=0 Unused, must set to zero. */ /* CCR1.4=0 pulses at TPOSO and TNEGO are one full TCLKO period wide */ /* CCR1.5=0 signalling changes reported on any change. */ /* CCR1.6=0 transmit CRC-4 generation and insertion normal */ switch (sp->config.ifclock) { default: sp->config.ifclock = SDL_CLOCK_LOOP; case SDL_CLOCK_LOOP: /* Use the signal present at RCLK as the transmit clock. The TCLK pin is ignored. */ /* CCR1.1-2 = '11'B Use the signal present at RCLK as the transmit clock. The TCLK pin is ignored. */ /* CRC1.7=0 MCLK sourced from the MCLK pin. */ /* default for T1 in tor3 driver, and here */ ccr1 = (0 << 7) | (0x3 << 1); break; case SDL_CLOCK_INT: /* The TCLK pin is always the source of transmit clock. */ /* CCR1.1-2 = '00'B The TCLK pin is always the source of transmit clock. */ /* CRC1.7=0 MCLK sourced from the MCLK pin. */ ccr1 = (0 << 7) | (0x0 << 1);; break; case SDL_CLOCK_MASTER: /* Use the scaled signal present at MCLK as the transmit clock. The TCLK pin is ignored. */ /* CCR1.1-2 = '10'B Use the scaled signal present at MCLK as the transmit clock. The TCLK pin is ignored. */ /* CRC1.7=0 MCLK sourced from the MCLK pin. */ ccr1 = (0 << 7) | (0x2 << 1); break; case SDL_CLOCK_EXT: /* Use the scaled signal present at TSYSCLK as the transmit clock. The TCLK pin is ignored. */ /* CCR1.1-2 = '10'B Use the scaled signal present at MCLK as the transmit clock. The TCLK pin is ignored. */ /* CRC1.7=1 MCLK sourced from the TSYSCLK pin. */ ccr1 = (1 << 7) | (0x2 << 1); break; case SDL_CLOCK_SLAVE: /* Switch to the clock present at RCLK when the signal at the TCLK pin fails to transition after 1 channel time. */ /* CCR1.1-2 = '01'B Switch to the clock present at RCLK when the signal at the TCLK pin fails to transition. */ /* CRC1.7=0 MCLK sourced from the MCLK pin. */ /* default for E1 in tor3 driver, and here */ ccr1 = (0 << 7) | (0x1 << 1); break; } xlb[0x70] = ccr1; /* initial signalling register */ sigcr = 0x00; /* initial error counter regsiter */ ercnt = 0x00; /* initial E1 registers */ e1rcr1 = 0x00; e1tcr1 = 0x00; /* initial T1 registers */ t1rcr2 = 0x00; t1tcr1 = 0x00; t1tcr2 = 0x00; t1ccr1 = 0x00; switch (sp->config.ifframing) { default: switch (sp->config.ifgtype) { default: case SDL_GTYPE_NONE: case SDL_GTYPE_E1: sp->config.ifframing = SDL_FRAMING_CCS; goto framing_ccs; case SDL_GTYPE_T1: case SDL_GTYPE_J1: sp->config.ifframing = SDL_FRAMING_ESF; goto framing_esf; } break; case SDL_FRAMING_CCS: framing_ccs: sigcr |= (1 << 2); /* SIGCR.2: RCCS: 1, CCS. */ sigcr |= (1 << 1); /* SIGCR.1: TCCS: 1, CCS. */ e1rcr1 |= (1 << 6); /* E1RCR1.6: RSIGM: 1, CCS. */ break; case SDL_FRAMING_CAS: /* We should really bork on this for all by the MX driver. Note that when SDL_FRAMING_CAS is set, channel 16 is unusable on E1. */ break; case SDL_FRAMING_ESF: framing_esf: t1rcr2 |= (1 << 6); /* T1RCR2.6: RFM: 1, Rx ESF. */ t1ccr1 |= (1 << 2); /* T1CCR1.2: TFM: 1, Tx ESF. */ break; case SDL_FRAMING_SF: /* D4 */ break; } switch (sp->config.ifcoding) { default: switch (sp->config.ifgtype) { default: case SDL_GTYPE_NONE: case SDL_GTYPE_E1: sp->config.ifcoding = SDL_CODING_HDB3; goto coding_hdb3; case SDL_GTYPE_T1: case SDL_GTYPE_J1: sp->config.ifcoding = SDL_CODING_B8ZS; goto coding_b8zs; } break; case SDL_CODING_HDB3: coding_hdb3: e1rcr1 |= (1 << 5); /* E1RCR1.5: RHDB3: 1, Rx HDB3. */ e1tcr1 |= (1 << 2); /* E1TCR1.2: THDB3: 1, Tx HDB3. */ ercnt |= (1 << 3); /* ERCNT.3: VCRFS: 1, count CVs. */ break; case SDL_CODING_AMI: break; case SDL_CODING_B8ZS: coding_b8zs: t1rcr2 |= (1 << 5); /* T1RCR2.5: RB8ZS: 1, Rx B8ZS */ t1tcr2 |= (1 << 7); /* T1TCR2.7: TB8ZS: 1, Tx B8ZS. */ break; } switch (sp->config.ifgcrc) { default: switch (sp->config.ifgtype) { default: case SDL_GTYPE_E1: sp->config.ifgcrc = SDL_GCRC_CRC4; goto gcrc_crc4; case SDL_GTYPE_T1: sp->config.ifgcrc = SDL_GCRC_CRC6; goto gcrc_crc6; case SDL_GTYPE_J1: sp->config.ifgcrc = SDL_GCRC_CRC6J; goto gcrc_crc6j; } break; case SDL_GCRC_CRC5: break; case SDL_GCRC_CRC4: gcrc_crc4: e1rcr1 |= (1 << 3); /* E1RCR1.3: RCRC4: 1, Rx CRC-4. */ e1tcr1 |= (1 << 0); /* E1TCR1.0: TCRC4: 1, Tx CRC-4. */ break; case SDL_GCRC_CRC6: gcrc_crc6: break; case SDL_GCRC_CRC6J: gcrc_crc6j: t1tcr1 |= (1 << 7); /* T1TCR1.7: TJC: 1, Tx Japan CRC6J. */ t1rcr2 |= (1 << 1); /* T1RCR2.1: RJC: 1, Tx Japan CRC6J. */ if (sp->config.ifframing == SDL_FRAMING_D4) { t1rcr2 |= (1 << 0); /* T1RCR2.0: RD4YM: 1, Rx Japanese Yellow. */ t1tcr2 |= (1 << 2); /* T1TCR2.2: TD4YM: 1, Tx Japanese Yellow. */ } break; } /* 0x40 is a signalling control register */ xlb[0x40] = sigcr; /* RCCS, TCCS (set to zero for T1) */ /* SIGCR.7: GRSRE: Global Receive Signalling Reinsertion Enabled. 0, no; 1, yes. */ /* SIGCR.6: -: Unused, must be set to zero. */ /* SIGCR.5: -: Unused, must be set to zero. */ /* SIGCR.4: RFE: Receive Freeze Enable. 0, no freezing; 1, allow freezing. */ /* SIGCR.3: RFF: Receive Force Freeze. 0, no force freeze; 1, force freeze. */ /* SIGCR.2: RCCS: Receie Time Slot Control for CAS signalling. 0, CAS; 1, CCS. */ /* SIGCR.1: TCCS: Transmit Time Slot Control for CAS Signalling. 0, CAS; 1, CCS. */ /* SIGCR.0: FRSAO: Force Receive Signalling All Ones. 0, normal; 1, force to one. */ xlb[0x41] = ercnt; /* ERCNT.7: -: Unused, must be set to zero. */ /* ERCNT.6: MECU: Manual Error Counter Update. Toggle to read counters. */ /* ERCNT.5: ECUS: Error Counter Update Select. 0, second; 1, 42ms(T1)/62ms(E1). */ /* ERCNT.4: EAMS: Error Accumulation Mode Select. 0, automatic; 1, manual. */ /* ERCNT.3: VCRFS: Line Code Violation Count Regiser Function Select. 0, BPVs; 1, CVs. */ /* ERCNT.2: FSBE: PCVCR Fs-Bit Error Report Enable. 0, Ft-bit only; 1, Fs-bit too. */ /* ERCNT.1: MOSCRF: Multiframe OOS Count Reg Func Sel. 0, F-bit errors; 1, mfs oos. */ /* ERCNT.0: LCVCRF: LCV Count Reg Func Sel. 0, no EXZ; 1, count EXZ. */ if (sp->config.ifgtype == SDL_GTYPE_E1) { /* 0x33 to 0x36 are E1 Tx and Rx control registers */ xlb[0x33] = e1rcr1; /* RCR4, RHDB3, RSM, SYNCE */ /* E1RCR1.7: RSERC: RSER Control. 0, rx data; 1, force to 1 under RLOS. */ /* E1RCR1.6: RSIGM: Receive Signaling Mode Select. 0, CAS; 1, CCS. */ /* E1RCR1.5: RHDB3: Receive HDB3 Enable. 0, AMI; 1, HDB3. */ /* E1RCR1.4: RG802: Receive G.802 Enable. 0, disabled; 1, enabled. */ /* E1RCR1.3: RCRC4: Receve CRC-4 Enable. 0, non-CRC-4; 1, CRC-4. */ /* E1RCR1.2: FRC: Frame Resync Criteria. 0, 3 FAS error; 1, or bit 2 of non-FAS. */ /* E1RCR1.1: SYNCE: Sync Enable. 0, auto resync enabled; 1, disabled. */ /* E1RCR1.0: RESYNC: Resync. Toggle to 1 for resync. */ xlb[0x34] = (1 << 0); /* RCL (1ms) */ /* E1RCR2.7: Sa8S: Sa8-bit select. 0, RLCLK low during bit position; 1, high. */ /* E1RCR2.6: Sa7S: Sa7-bit select. 0, RLCLK low during bit position; 1, high. */ /* E1RCR2.5: Sa6S: Sa6-bit select. 0, RLCLK low during bit position; 1, high. */ /* E1RCR2.4: Sa5S: Sa5-bit select. 0, RLCLK low during bit position; 1, high. */ /* E1RCR2.3: Sa4S: Sa4-bit select. 0, RLCLK low during bit position; 1, high. */ /* E1RCR2.2: -: Unused, must be set to zero. */ /* E1RCR2.1: -: Unused, must be set to zero. */ /* E1RCR2.0: RCLA: RCL Alternate Criteria. 0, 255 zeros (125us); 1, 2048 zeros (1ms). */ /* We could be setting automatic report alarm generation (0x01) (T1) or automatic AIS generation (0x02) (E1). */ xlb[0x35] = e1tcr1 | (1 << 4); /* TSiS, TCRC4 (from 014.4), THDB3 (from O14.6) */ /* E1TCR1.7: TFPT: Transmit Time Slot 0 Pass Through. 0, TAF/TNAF; 1, TSER. */ /* E1TCR1.6: T16S: Transmit Time Slot 16 Data Select. 0, SSIE; 1, TS1-16. */ /* E1TCR1.5: TUA1: Transmit Unframed All Ones. 0, normal; 1, tua1. */ /* E1TCR1.4: TSiS: Transmit International Bit Select. 0, TSER; 1, TAF/TNAF. */ /* E1TCR1.3: TSA1: Transmit Signaling All Ones. 0, normal; 1, all 1's. */ /* E1TCR1.2: THDB3: Transmit HDB3 Enable. 0, AMI; 1, HDB3. */ /* E1TCR1.1: TG802: Transmit G.802 Enable. 0, disabled; 1, enabled. */ /* E1TCR1.0: TCRC4: Transmit CRC-4 Enable. 0, non-CRC-4; 1, CRC-4. */ xlb[0x36] = (1 << 2) | (1 << 1) | (1 << 0); /* AEBE=1, AAIS=1, ARAI=1 */ /* E1TCR2.7: Sa8S: Sa8-bit select. 0 do not source from TLINK pin. */ /* E1TCR2.6: Sa7S: Sa7-bit select. 0 do not source from TLINK pin. */ /* E1TCR2.5: Sa6S: Sa6-bit select. 0 do not source from TLINK pin. */ /* E1TCR2.4: Sa5S: Sa5-bit select. 0 do not source from TLINK pin. */ /* E1TCR2.3: Sa4S: Sa4-bit select. 0 do not source from TLINK pin. */ /* E1TCR2.2: AEBE: Automatic E-bit Enable. 1 = E-bits auto set in tx * direction */ /* E1TCR2.1: AAIS: Automatic AIS generation. 0 = disabled; 1 = enabled. */ /* E1TCR2.0: ARA: Automatic Remote Alarm Generation. 0 = disabled; 1 = enabled. */ #if 0 xlb[0x33] = e1rcr1 | (1 << 0); /* RCR4, RHDB3, RSM, SYNCE, RESYNC */ xlb[0x33] = e1rcr1 | 0x00; /* RCR4, RHDB3, RSM, SYNCE */ #endif /* 0xd0 and 0xd1 are Tx Sa bits for E1 operation */ /* This is a little peculiar: the host should be using Method 3 in section 22.3 of the DS2155 manual instead of this method that only permits 250us to read or write the bits. */ xlb[0xd0] = 0x1b; /* TAF.0-7='00011011'B (default) */ /* TAF.7: 0 = Si bit */ /* TAF.6: 0 = frame alignment signal bit */ /* TAF.5: 0 = frame alignment signal bit */ /* TAF.4: 1 = frame alignment signal bit */ /* TAF.3: 1 = frame alignment signal bit */ /* TAF.2: 0 = frame alignment signal bit */ /* TAF.1: 1 = frame alignment signal bit */ /* TAF.0: 1 = frame alignment signal bit */ /* Note: bit 6 of the TNAF register must be programmed to one. The DS21354/DS21554 does not automaticallly set this bit. G.704/2.3.2: Bits Sa4 to Sa8 (where these are not used) should be set to 1 on links crossing an international border. This also conveys a synchronization status message of "do not use for synchronization" regardless of sychronization status bit assignment. */ xlb[0xd1] = 0x5f; /* TNAF.0-7='01011111'B (Sa all ones) XXX */ /* TNAF.7 0 = Si bit */ /* TNAF.6 1 = FNA signal bit */ /* TNAF.5 0 = remote alarm */ /* TNAF.4 1 = additional bit 4 */ /* TNAF.3 1 = additional bit 5 */ /* TNAF.2 1 = additional bit 6 */ /* TNAF.1 1 = additional bit 7 */ /* TNAF.0 1 = additional bit 8 */ /* 0x03 to 0x07 are T1 Tx and Rx control registers */ xlb[0x03] = 0x00; xlb[0x04] = t1rcr2; /* '00000000'B for E1 */ xlb[0x05] = t1tcr1; /* '00000000'B for E1 */ xlb[0x06] = t1tcr2; /* '00000000'B for E1 */ xlb[0x07] = t1ccr1; /* '00000000'B for E1 */ /* 0xb6 to 0xbf are programmable in-band loop code generatiion and detection that are only applicable to T1. */ xlb[0xb6] = 0x00; xlb[0xb7] = 0x00; xlb[0xb8] = 0x00; xlb[0xb9] = 0x00; xlb[0xba] = 0x00; xlb[0xbb] = 0x00; xlb[0xbc] = 0x00; xlb[0xbd] = 0x00; xlb[0xbe] = 0x00; xlb[0xbf] = 0x00; } else { /* T1TCR1.4=1: TSSE: Tx Soft. Sign. Enable (0, not from regs; 1, from regs) */ t1tcr1 |= (1 << 4); /* TSSE */ { int byte, c; unsigned short mask = 0; /* establish which channels are clear channel for T1 */ for (c = 0; c < 24; c++) { byte = c >> 3; if (sp->chans[c + 1] && sp->chans[c + 1]->sdl.config.iftype == SDL_TYPE_DS0A) mask |= 1 << (c % 8); if ((c % 8) == 7) { xlb[0x08 + byte] = mask; mask = 0; } } } /* 0x03 to 0x07 are T1 Tx and Rx control registers */ #if 0 xlb[0x03] = 0x08 | 0x00; /* SYNCC/SYNCE */ xlb[0x03] = 0x08 | 0x01; /* SYNCC/SYNCE, RESYNC */ xlb[0x03] = 0x08 | 0x00; /* SYNCC/SYNCE */ #else xlb[0x03] = 0x00; #endif /* T1RCR1.7 NA: must set to 0 */ /* T1RCR1.6: ARC: resync criteria (0, OOF or RCL; 1, OOF only) */ /* T1RCR1.4,5: OOF2,OOF1: (00, 2/4; 10, 2/6; 01, 2/5; 11, 2/6) */ /* T1RCR1.3: SYNCC: sync criteria (0, simple; 1, complex) */ /* T1RCR1.2: SYNCT: sync time (0, 10-bits; 1, 24-bits) */ /* T1RCR1.1: SYNCE: auto resync (0, enabled; 1, disabled) */ /* T1RCR1.0: RESYNC: toggle 0 to 1 to resync rx framer */ xlb[0x04] = t1rcr2; /* RESF RB8ZS RCRC6J */ /* T1RCR2.7: NA: must be set to 0 */ /* T1RCR2.6: RFM: framing mode (0, D4; 1, ESF) */ /* T1RCR2.5: RB8ZS: receive B8ZS (0, disabled; 1, enabled) */ /* T1RCR2.4: RSLC96: Rx SLC-96 (0, disabled; 1, enabled) */ /* T1RCR2.3: RZSE: 0 = zero destuffer disabled */ /* T1RCR2.2: RZBTSI: ZBTSI on RLINK pin (0, disabled; 1, enabled) */ /* T1RCR2.1: RJC: Japan CRC6 (0, ANSI CRC6; JT-G704 CRC6J ) */ /* T1RCR2.0: RD4YM: D4 Yellow Alarm (0, 0's in bit 2; 1, 1 in S-bit frame 12) */ xlb[0x05] = t1tcr1; /* TSSE TCRC6J */ /* T1TCR1.7: TJC: Japan CRC6 (0, ANSI CRC6; JT-G704 CRC6J) */ /* T1TCR1.6: TFPT: F-Bit passthru (0, internal; 1, at TSER) */ /* T1TCR1.5: TCPT: CRC passthru (0, internal; 1, at TSER) */ /* T1TCR1.4: TSSE: Tx Soft. Sign. Enable (0, not from regs; 1, from regs) */ /* T1TCR1.3: GB7S: Global Bit 7 stuffing (0, from regs; 1, from bit 7) */ /* T1TCR1.2: TFDLS: TFDL select (0, legacy; 1, HDLC or TLINK pin) */ /* T1TCR1.1: TBL: Transmit blue alarm (0, data; 1, unframed all ones) */ /* T1TCR1.0 TYEL: Yellow alarm (0, don't tx; 1, do tx) */ xlb[0x06] = t1tcr2; /* TB8ZS */ /* T1TCR2.7: TB8ZS: trans B8ZS (0, disabled; 1, enabled) */ /* T1TCR2.6: TSLC96: SLC-96 enable (0, disabled; 1, enabled) */ /* T1TCR2.5: TZSE: FDL zero-stuff (0, HDLC; 1, legacy) */ /* T1TCR2.4: FBCT2: F-bit corruption 2 (0, disabled; 1, enabled) */ /* T1TCR2.3: FBCT1: F-bit corruption 1 (0, disabled; 1, enabled) */ /* T1TCR2.2: TD4YM: D4 Yellow Alarm (0, 0's in bit 2; 1, 1 in S-bit fr 12) */ /* T1TCR2.1: TZBTSI: ZBTSI support (0, disabled; 1, enabled) */ /* T1TCR2.0: TB7ZS: Bit 7 stuffing (0, no; 1, stuffing) */ xlb[0x07] = t1ccr1; /* TESF */ /* T1CCR1.7: NA: must set to 0 */ /* T1CCR1.6: NA: must set to 0 */ /* T1CCR1.5: NA: must set to 0 */ /* T1CCR1.4: TRAI-CI: RAI-CI enable (0, no tx; 1, RAI-CI code) ESF */ /* T1CCR1.3: TAIS-CI: AIS-CI enable (0, no tx; 1, AIS-CI code) TCRC1.1=1 */ /* T1CCR1.2: TFM: Frame mode (0, D4; 1, ESF) */ /* T1CCR1.1: PDE: pulse density enforcer (0, disable; 1, enable) */ /* T1CCR1.0: TLOOP: tx loop-code (0, no; 1, loop per TCD1 and TCD2) */ /* 0x33 to 0x36 are E1 Tx and Rx control registers */ xlb[0x33] = 0x00; /* E1RCR1.0-7='00000000'B */ xlb[0x34] = 0x00; /* E1RCR2.0-7='00000000'B */ xlb[0x35] = 0x00; /* E1TCR1.0-7='00000000'B */ xlb[0x36] = 0x00; /* E1TCR2.0-7='00000000'B */ /* 0xd0 and 0xd1 are Tx Sa bits for E1 operation */ xlb[0xd0] = 0x1b; /* TAF.0-7='00011011'B (default) */ xlb[0xd1] = 0x40; /* TNAF.0-7='01000000'B (default) */ /* 0xb6 to 0xbf are programmable in-band loop code generatiion and detection that are only applicable to T1. */ xlb[0xb6] = 0x22; /* IBCC 5-bit loop up, 3-bit loop down code */ xlb[0xb7] = 0x80; /* TCD1 - 10000 loop up code (for now) */ xlb[0xb8] = 0x00; /* TCD2 don't care */ xlb[0xb9] = 0x80; /* RUPCD1 - 10000 receive loop up code */ xlb[0xba] = 0x00; /* RUPCD2 don't care */ xlb[0xbb] = 0x80; /* RDNCD1 - 100 receive loop down code */ xlb[0xbc] = 0x00; /* RDNCD2 don't card */ xlb[0xbd] = 0x00; xlb[0xbe] = 0x00; xlb[0xbf] = 0x00; } if (sp->config.ifgtype == SDL_GTYPE_E1) { /* LIC1.4=1 EGL E1 -43dB (long haul) */ /* LIC1.5-7=001 E1 120 Ohmm normal */ lic1 = (0x01 << 5) | (1 << 4); /* LIC2.3=1 JAMUX Jitter Atten. MUX (0, MCLK 2.048 or 1.544; 1, PLL 2.048 at MCLK */ /* LIC2.7=1 ETS E1/T1 select (0, T1; 1, E1) */ lic2 = (1 << 3) | (1 << 7); /* JACLK on for E1 */ /* LIC4.0-1=11 RT0-RT1 120 Ohm termination enabled */ /* LIC4.2-3=11 TT0-TT1 120 Ohm termination enabled */ /* LIC4.4-5=00 MPS0-MPS1 E1 LIC2.3=0 1.544MHz ??? */ /* LIC4.6=0 CMI normal */ /* LIC4.7=0 CMI disabled */ lic4 = (0x00 << 4) | (0x03 << 2) | (0x03 << 0); /* 120 Ohm term, MCLK 2.048 MHz */ } else { /* LIC1.4=0 EGL T1 -36db (long haul) */ /* LIC1.5-7=000 T1 0dB CSU */ lic1 = (0x00 << 5) | (0 << 4); /* LIC2.3=1 JAMUX Jitter Atten. MUX (0, MCLK 2.048 or 1.544; 1, PLL 2.048 at MCLK */ /* LIC2.7=0 ETS E1/T1 select (0, T1; 1, E1) */ lic2 = (1 << 3); /* JACLK on for T1 */ /* LIC4.0-1=10 RT0-RT1 100 Ohm termination enabled */ /* LIC4.2-3=10 TT0-TT1 100 Ohm termination enabled */ /* LIC4.4-5=00 MPS0-MPS1 T1 LIC2.3=0 1.544MHz, LIC2.3=1 2.048MHz */ /* LIC4.6=0 CMI normal */ /* LIC4.7=0 CMI disabled */ lic4 = (0x00 << 4) | (0x02 << 2) | (0x02 << 0); /* 100 Ohm term, MCLK 2.048 MHz */ } lic3 = 0x00; /* no gain */ if (sp->config.iftxlevel < 8) { lic1 |= (1 << 0); /* LIC1.0=1 TBD transmitter on */ if (sp->config.ifgtype != SDL_GTYPE_E1) lic1 |= ((sp->config.iftxlevel & 0x7) << 5); /* LBO */ } else { /* monitoring mode */ lic1 &= ~(1 << 0); /* LIC1.0=0 TBD transmitter off */ lic3 |= ((sp->config.iftxlevel & 0x3) << 3); /* Linear gain */ /* 00 - 0dB linear gain */ /* 01 - 20dB linear gain (single 432/470 Ohm tap) */ /* 10 - 26dB linear gain (double 432/470 Ohm tap) */ /* 11 - 30dB linear gain (triple 432/470 Ohm tap) */ } xlb[0x78] = lic1 & ~(1 << 0); /* don't power up transmitter yet */ /* LIC1.0=? TBD Transmit Power-Down (0, power-down; 1, normal) */ /* LIC1.1=0 DJA Disable Jitter Attenuator (0, enabled; 1, disabled) */ /* LIC1.2=0 JABDS JA Buffer Depth (0, 128bits; 1, 32bits) */ /* LIC1.3=0 JAS JA select (0, on Rx side; 1, on Tx side) */ /* LIC1.4=? EGL Receive Equal. Gain Limit */ /* T1: 0, -36dB (long haul); 1, -15dB (short haul) */ /* E1: 0, -12dB (short haul); 1, -43dB (long haul) */ /* LIC1.5-7=??? LBO */ xlb[0x79] = lic2; /* LIC2.0 CLDS Custom Line Driver Select (0, normal) */ /* LIC2.1 SCLD Short Circuit Limit Disable (0, enable; 1, disable) */ /* LIC2.2 Unused, zero for proper operation */ /* LIC2.3 JAMUX Jitter Atten. MUX (0, MCLK 2.048 or 1.544; 1, PLL 2.048 at MCLK */ /* LIC2.4 TUA1 Transmit Unframed All Ones (0, all ones; 1, normal data) */ /* LIC2.5 IBPF Insert BPV (0=>1 insert BPV) */ /* LIC2.6 LISRT Line Interface Reset (0=>1, reset) */ /* LIC2.7 ETS E1/T1 select (0, T1; 1, E1) */ xlb[0x7a] = lic3; /* LIC3.7: -: Unused. must be set to zero. */ /* LIC3.6: TCES: TCLKI Edge Select. 0 = rising; 1 = falling. */ /* LIC3.5: RCES: RCLKO Edge Select. 0 = rising; 1 = falling. */ /* LIC3.4-3: MM1-MM0: 00, no gain; 01, 20dB; 10, 26dB; 11, 32dB. */ /* LIC3.2: RSCLKE: Tx Sync G.703 Clock Span. 0 = disable; 1 = enable. */ /* LIC3.1: TSCLKE: Rx Sync G.703 Clock Span. 0 = disable; 1 = enable. */ /* LIC3.0: TAOZ: Tx Alternal Ones and Zeros (CDI). 0, disable; 1, enable. */ xlb[0x7b] = lic4; /* LIC4.0-1 RT0-RT1 Internal Receive Termination. */ /* 00 - internal termination disabled */ /* 01 - 75 Ohm termination enabled */ /* 10 - 100 Ohm termination enabled */ /* 11 - 120 Ohm termination enabled */ /* LIC4.2-3 TT0-TT1 Internal Transmit Termination. */ /* 00 - internal termination disabled */ /* 01 - 75 Ohm termination enabled */ /* 10 - 100 Ohm termination enabled */ /* 11 - 120 Ohm termination enabled */ /* LIC4.4-5 MPS0-1 MBLK Prescaler */ /* T1 00 LIC2.3=0 1.544 MHz */ /* T1 01 LIC2.3=0 3.088 MHz */ /* T1 10 LIC2.3=0 6.176 MHz */ /* T1 11 LIC2.3=0 12.352 MHz */ /* T1 00 LIC2.3=1 2.048 MHz */ /* T1 01 LIC2.3=1 4.096 MHz */ /* T1 10 LIC2.3=1 8.192 MHz */ /* T1 11 LIC2.3=1 16.384 MHz */ /* E1 00 LIC2.3=0 1.544 MHz */ /* E1 01 LIC2.3=0 3.088 MHz */ /* E1 10 LIC2.3=0 6.176 MHz */ /* E1 11 LIC2.3=0 12.352 MHz */ /* LIC4.6 CMII CMI Invert (0, normal; 1, invert) */ /* LIC4.7 CMIE CMI Enable (0, disable; 1, enable) */ xlb[0x7d] = 0x00; /* Automatic gain control */ xlb[0x78] = lic1 | (1 << 0); /* power up transmitter if not monitoring */ /* CONFIGURE ALL TIMESLOTS. */ xlb[0x7e] = (1 << 7) | (1 << 6); /* IAAR.6 (GRIC), IAAR.7 (GTIC) */ switch (sp->config.ifgtype) { case SDL_GTYPE_E1: xlb[0x7f] = 0xff; /* PCICR, set idle code to 0xff. */ break; case SDL_GTYPE_T1: case SDL_GTYPE_J1: xlb[0x7f] = 0x7f; /* PCICR, set idle code to 0x7f. */ break; } { struct ch *ch; int chan; if (sp->config.ifgtype == SDL_GTYPE_E1) { /* Note that setting CAS registers has no effect unless the line framing is set to CAS instead of CSS. */ xlb[0x50] = (1 << 3) | (1 << 1) | (1 << 0); /* TS1: X = 1, Y = 0: CAS alignment word. */ /* TS1.0=1: X: 1 = spare bit */ /* TS1.1=1: X: 1 = spare bit */ /* TS1.2=0: Y: 0 = no remote alarm */ /* TS1.3=1: X: 1 = spare bit */ /* TS1.4=0: 0: 0 = must be zero */ /* TS1.5=0: 0: 0 = must be zero */ /* TS1.6=0: 0: 0 = must be zero */ /* TS1.7=0: 0: 0 = must be zero */ for (chan = 1; chan < 32; chan++) { if ((ch = sp->chans[chan]) != NULL) { xp_x1_chan_config(sp, ch, xlb); continue; } swerr(); } } else { for (chan = 1; chan < 24; chan++) { if ((ch = sp->chans[chan]) != NULL) { xp_x1_chan_config(sp, ch, xlb); continue; } swerr(); } } } /* SET UP INTERRUPT MASK REGISTERS */ xlb[0x17] = (1 << 7) | (1 << 6) | (1 << 4) | (1 << 3) | (1 << 2) | (1 << 1) | (1 << 0); /* IMR1.7=1: ILUT: Input Level Under Threshold. */ /* IMR1.6=1: TIMER: Timer Event. */ /* IMR1.5=0: RSCOS: Receive Signaling Change-of-State Event. */ /* IMR1.4=1: JALT: Jitter Attenuator Limit Trip Event (JALT). */ /* IMR1.3=1: LRCL: Line Interface Receive Carrier Loss Condition. */ /* IMR1.2=1: TCLE: Transmit Current Limit Exceeded. */ /* IMR1.1=1: TOCD: Transmit Open Circuit Detect Condition. */ /* IMR1.0=1: LOLITC: Loss of Transmit Clock Condition. */ xlb[0x19] = (1 << 6) | (1 << 5) | (1 << 4) | (1 << 2) | (1 << 1) | (1 << 0); /* IMR2.7=0: RYELC: Receive Yellow Alarm Clear Event. */ /* IMR2.6=1: RUA1C: Receive Unframed All Ones Condition Clear Event. */ /* IMR2.5=1: FRCLC: Receive Carrier Loss Condition Clear. */ /* IMR2.4=1: RLOSC: Receive Loss of Sync Clear Event. */ /* IMR2.3=0: RYEL: Receive Yellow Alarm Condition. */ /* IMR2.2=1: RUA1: Receive Unframed All Ones (Blue Alarm) Condition. */ /* IMR2.1=1: FRCL: Framer Receive Carrier Loss Condition. */ /* IMR2.0=1: RLOS: Receive Loss of Sync Condition. */ if (sp->config.ifgtype != SDL_GTYPE_E1) /* IMR2.7=1: RYELC: Receive Yellow Alarm Clear Event. */ /* IMR2.3=1: RYEL: Receive Yellow Alarm Condition. */ xlb[0x19] |= (1 << 7) | (1 << 3); xlb[0x1b] = (1 << 3) | (1 << 4); /* 'XXX11XXX' */ /* IMR3.7=0: LSPARE: Spare Code Detected Condition. */ /* IMR3.6=0: LDN: Loop-Down Code Detected Condition. */ /* IMR3.5=0: LUP: Loop-Up Code Detected Condition. */ /* IMR3.4=1: LOTC: Loss of Transmit Clock Condition. */ /* IMR3.3=1: LORC: Loss of Receive Clock Condition. */ /* IMR3.2=0: V52LNK: V5.2 Link Detected Condition. */ /* IMR3.1=0: RDMA: Receive Distant MF Alarm Condition. */ /* IMR3.0=0: RRA: Receive Remote Alarm Condition. */ if (sp->config.ifgtype == SDL_GTYPE_E1) /* IMR3.2=1: V52LNK: V5.2 Link Detected Condition. */ /* IMR3.1=1: RDMA: Receive Distant MF Alarm Condition. */ /* IMR3.0=1: RRA: Receive Remote Alarm Condition. */ xlb[0x1b] |= (1 << 2) | (1 << 1) | (1 << 0); /* 'XXXXX111' */ else /* IMR3.7=1: LSPARE: Spare Code Detected Condition. */ /* IMR3.6=1: LDN: Loop-Down Code Detected Condition. */ /* IMR3.5=1: LUP: Loop-Up Code Detected Condition. */ xlb[0x1b] |= (1 << 7) | (1 << 6) | (1 << 5); /* '111XXXXX' */ xlb[0x1d] = (0 << 4) | (0 << 2); /* 'tee0e0ee' */ /* IMR4.7=0: RAIS-CI: Receive AIS-CI Event. */ /* IMR4.6=0: RSA1: Receive Signalling All-Ones Event. */ /* IMR4.5=0: RSA0: Receive Signalling All-Zeros Event. */ /* IMR4.4=0: TMF: Transmit Multiframe Event. */ /* IMR4.3=0: TAF: Transmit Align Frame. */ /* IMR4.2=0: RMF: Receive Multiframe Event. */ /* IMR4.1=0: RCMF: Receive CRC-4 Multiframe Event. */ /* IMR4.0=0: RAF: Receive Align Frame. */ if (sp->config.ifgtype == SDL_GTYPE_E1) /* IMR4.6=1: RSA1: Receive Signalling All-Ones Event. */ /* IMR4.5=1: RSA0: Receive Signalling All-Zeros Event. */ xlb[0x1d] |= (1 << 6) | (1 << 5); else /* IMR4.7=1: RAIS-CI: Receive AIS-CI Event. */ xlb[0x1d] |= (1 << 7); xlb[0x1f] = (1 << 5) | (1 << 4) | (1 << 3) | (1 << 2) | (1 << 1) | (1 << 0); /* IRM5.7=0: -: */ /* IMR5.6=0: -: */ /* IMR5.5=1: TESF: Transmit Elastic Store Full Event. */ /* IMR5.4=1: TESEM: Transmit Elastic Store Empty Event. */ /* IMR5.3=1: TSLIP: Transmit Elastic Store Slip Occurrence Event. */ /* IMR5.2=1: RESF: Receive Elastic Store Full Event. */ /* IMR5.1=1: RESEM: Receive Elastic Store Empty Event. */ /* IMR5.0=1: RSPLIP: Receive Elastic Store Slip Occurrence Event. */ xlb[0x21] = 0x00; /* IMR6 */ xlb[0x23] = 0x00; /* IMR7 */ xlb[0x25] = 0x00; /* IMR8 */ xlb[0x27] = 0x00; /* IMR9 */ #if 0 if (timeouts) { unsigned long timeout; xlb[0x79] = lic2 | 0x40; /* LIRST on */ timeout = (volatile unsigned long) jiffies + 100 * HZ / 1000; while ((volatile unsigned long) jiffies < timeout) ; xlb[0x79] = lic2; /* LIRST off */ } #endif return (0); } noinline __unlikely void xp_x1_chan_config(struct sp *sp, struct ch *ch, volatile uint8_t *xlb) { if (ch->chan == 0) { swerr(); return; } switch (ch->sdl.config.ifgtype) { case SDL_GTYPE_E1: if (ch->chan < 16) { int m = 1, c = ch->chan - m; /* chan 1 through chan 15 is lower then upper nibble of 0x51(TS2) through 0x58(TS9) ending on lower nibble */ if (c & 0x01) { /* upper-nibble */ xlb[0x50 + m + (c >> 1)] = (xlb[0x50 + m + (c >> 1)] & 0xf0) | 0x50; } else { /* lower-nibble */ xlb[0x50 + m + (c >> 1)] = (xlb[0x50 + m + (c >> 1)] & 0x0f) | 0x05; } } if (ch->chan > 16) { int m = 0, c = ch->chan - m; /* chan 17 through chan 31 is upper, lower then upper nibble of 0x58(TS9) through 0x5f(TS16). */ if (c & 0x01) { /* upper-nibble */ xlb[0x50 + m + (c >> 1)] = (xlb[0x50 + m + (c >> 1)] & 0xf0) | 0x50; } else { /* lower-nibble */ xlb[0x50 + m + (c >> 1)] = (xlb[0x50 + m + (c >> 1)] & 0x0f) | 0x05; } } if (ch->chan != 16) { if (sp->config.ifframing == SDL_FRAMING_CAS) xlb[0x08 + (ch->chan >> 3)] |= (1 << (ch->chan % 8)); else xlb[0x08 + (ch->chan >> 3)] &= ~(1 << (ch->chan % 8)); } else { /* When CAS signalling is used we cannot apply the same logic to channel 16 as we normally do. */ if (sp->config.ifframing == SDL_FRAMING_CAS) ch->sdl.config.ifmode = SDL_MODE_SIG; else if (ch->sdl.config.ifmode == SDL_MODE_SIG) ch->sdl.config.ifmode = SDL_MODE_PEER; } break; case SDL_GTYPE_T1: case SDL_GTYPE_J1: /* Note that setting the TS1 through TS12 registers has no effect unless the channel is marked for robbed-bit signalling. */ if (ch->chan <= 24) { int c = ch->chan - 1; /* chan 1 through chan 24 is TS1 through TS12, lower then upper nibble */ if (c & 0x01) { /* upper nibble */ xlb[0x50 + (c >> 1)] = (xlb[0x50 + (c >> 1)] & 0xf0) | 0x50; } else { /* lower nibble */ xlb[0x50 + (c >> 1)] = (xlb[0x50 + (c >> 1)] & 0x0f) | 0x05; } } if (ch->sdl.config.iftype == SDL_TYPE_DS0A) /* DS0A does not need to be set for clear-channel operation. */ xlb[0x08 + ((ch->chan - 1) >> 3)] |= (1 << ((ch->chan - 1) % 8)); else /* DS0 needs to be set for clear-channel operation. */ xlb[0x08 + ((ch->chan - 1) >> 3)] &= ~(1 << ((ch->chan - 1) % 8)); break; default: swerr(); return; } /* Per-channel quiet code. */ if (ch->sdl.config.ifmode == SDL_MODE_IDLE) { xlb[0x80 + ((ch->chan - 1) >> 3)] |= (1 << ((ch->chan - 1) % 8)); xlb[0x84 + ((ch->chan - 1) >> 3)] |= (1 << ((ch->chan - 1) % 8)); } else { xlb[0x80 + ((ch->chan - 1) >> 3)] &= ~(1 << ((ch->chan - 1) % 8)); xlb[0x84 + ((ch->chan - 1) >> 3)] &= ~(1 << ((ch->chan - 1) % 8)); } /* Per-channel milliwatt. */ if (ch->sdl.config.ifgtype != SDL_GTYPE_E1) { if (ch->sdl.config.ifmode == SDL_MODE_MW) { xlb[0x80 + ((ch->chan - 1) >> 3)] |= (1 << ((ch->chan - 1) % 8)); xlb[0x0c + ((ch->chan - 1) >> 3)] |= (1 << ((ch->chan - 1) % 8)); } else xlb[0x0c + ((ch->chan - 1) >> 3)] &= ~(1 << ((ch->chan - 1) % 8)); } /* Per-channel remote payload loopback. */ if (ch->sdl.config.ifmode == SDL_MODE_REM_LB) xlb[0x4b + ((ch->chan - 1) >> 3)] |= (1 << ((ch->chan - 1) % 8)); else xlb[0x4b + ((ch->chan - 1) >> 3)] &= ~(1 << ((ch->chan - 1) % 8)); } noinline __unlikely int xp_t1_card_config(struct cd *cd); noinline __unlikely int xp_e1_card_config(struct cd *cd); noinline __unlikely int xp_x1_card_config(struct cd *cd); /** * xp_card_config: - perform initial configure of a card * @cd: card structure */ noinline __unlikely int xp_card_config(struct cd *cd) { int err; switch (cd->device) { case XP_DEV_DS21352: case XP_DEV_DS21552: err = xp_t1_card_config(cd); break; case XP_DEV_DS21354: case XP_DEV_DS21554: err = xp_e1_card_config(cd); break; case XP_DEV_DS2155: case XP_DEV_DS21455: case XP_DEV_DS21458: err = xp_x1_card_config(cd); break; default: swerr(); err = -EFAULT; } return (err); } /** xp_t1_card_config: - configure a card with a T1 device * @cd: card structure pointer */ noinline __unlikely int xp_t1_card_config(struct cd *cd) { int span, offset; unsigned long timeout; cd->xlb[CTLREG] = cd->ctlreg = cd->clkreg = 0; /* 1.544 MHz Crystal */ cd->xlb[SYNREG] = cd->synreg = SYNCSELF; /* Sync to crystal */ cd->xlb[LEDREG] = cd->ledreg = 0; cd->xlb[TSTREG] = cd->tstreg = 0; /* do not drive TEST2 pin */ if (cd->devrev > 3) { cd->xlb[CTLREG1] = NONREVA; /* non Rev. A mode */ cmn_err(CE_NOTE, "%s: setting non-Rev.A mode", DRV_NAME); } else { cd->xlb[CTLREG1] = 0; /* Rev. A mode */ cmn_err(CE_NOTE, "%s: setting Rev.A mode", DRV_NAME); } if (japan) { /* setup J1 card defaults */ cd->config = sdl_default_j1_chan; } else { /* setup T1 card defaults */ cd->config = sdl_default_t1_chan; } /* Idle out all channels. The idle byte depends on whether the span is configured for E1 operation or T1 or J1 operation. This sets the registers as well as setting the driver's elastic buffers. */ { int word; uint idle_word = 0x7f7f7f7f; /* idle out all channels */ for (word = 0; word < 256; word++) { int ebuf; cd->xll[word] = idle_word; for (ebuf = 0; ebuf < X400P_EBUFNO; ebuf++) cd->wbuf[(ebuf << 8) + word] = idle_word; } } /* On power-up, after supplies are stable the DS21352/552 should be configured for operation by writing all of the internal registers (this includes setting test registers to 00h) since the contents of the internal registers cannot be predicted on power-up. The LIRST (CCR7.7) should be toggled from zero to one to reset the line interface circuitry (it will take the DS21352/552 about 40ms to recover from the LIRST bit being toggled). Finally, after the TSYSCLK and RSYSCLK inputs are stable, the ESR bit should be toggled from zero to a one (this step can be skipped if the elastic stores are disabLed). */ /* Zero all span registers, note that the DS21352/552 only have 160 defined registers. */ for (span = 0; span < X400_SPANS; span++) for (offset = 0; offset < 160; offset++) cd->xlb[(span << 8) + offset] = 0x00; /* The interleaved PCM bus option (IBO) supports two bus speeds. The 4.096 MHz bus speed allows two SCTs to share a common bus. The 8.192 MHz bus speed allows 4 SCTs to share a common bus. Each SCT that shares a common bus must be configured through software and requires the use of one or two device pins. The elastic stores of each SCT must be enabled and configured for 2.048 MHz operation. For all bus configuration, one SCTP will be configured as the master device and the remaining SCTs will be configured as slave devices. */ /* IBO.0: MSEL1: '00' slave; '10' master, 1 slave. */ /* IBO.1: MSEL0: '01' master 3 slaves; '11' reserved. */ /* IBO.2: INTSEL: Interleave type (0, byte; 1, frame) */ /* IBO.3: IBOEN: Interleave enable (0, disabled; 1, enabled) */ /* IBO.4-7: NA: should be set to zero. */ /* set up for interleaved serial bus operation, byte mode */ cd->xlb[0x094] = 0x09; /* IBOEN, '01' master, 3 slaves */ cd->xlb[0x194] = 0x08; /* IBOEN, '00' slave */ cd->xlb[0x294] = 0x08; /* IBOEN, '00' slave */ cd->xlb[0x394] = 0x08; /* IBOEN, '00' slave */ cd->config.ifflags = (SDL_IF_UP | SDL_IF_TX_RUNNING | SDL_IF_RX_RUNNING); /* Allocate span structures and write all of the registers of interest. */ for (span = 0; span < cd->ports; span++) { struct sp *sp; int err; if (!(sp = cd->spans[span])) { if (!(sp = xp_alloc_sp(cd, span))) return (-ENOMEM); } else xp_init_sp(cd, sp, span); if ((err = xp_t1_span_config(sp, 0)) != 0) return (err); } /* CCR7.7: LIRST: Line Interface Reset */ /* CCR7.6: RLB: Remote loopback (0, disabled; 1, enabled) */ /* CCR7.5: RESR: Receive elastic store reset. */ /* CCR7.4: TESR: Transmit elastic store reset. */ /* CCR7.3: NA: set to zero */ /* CCR7.2: LIUSI: LI sync interface (0, normal; 1, sync signal only) */ /* CCR7.1: CDIG: Customer disconnect indication (0, normal; 1, unframed ..1010.. */ /* CCR7.0: LIUODO: LI open drain (0, normal; 1, TTIP/TRING open drain) */ /* line interface reset */ /* CCR7.7=1 (LIRST) */ cd->xlb[0x00a] |= (1 << 7); cd->xlb[0x10a] |= (1 << 7); cd->xlb[0x20a] |= (1 << 7); cd->xlb[0x30a] |= (1 << 7); /* Wait 40 milliseconds. */ timeout = (volatile unsigned long) jiffies + 100 * HZ / 1000; while ((volatile unsigned long) jiffies < timeout) ; /* release LIRST bit */ /* CCR7.7=0 (~LIRST) */ cd->xlb[0x00a] &= ~(1 << 7); cd->xlb[0x10a] &= ~(1 << 7); cd->xlb[0x20a] &= ~(1 << 7); cd->xlb[0x30a] &= ~(1 << 7); /* At this point we are ready to detect the line connection. This determination is more difficult on the DS21[35]52 because there is no transmitter open-circuit detection. */ /* reset elastic stores */ /* CCR7.4=1 (TESR), CCR7.5=1 (RESR) */ cd->xlb[0x00a] |= ((1 << 4) | (1 << 5)); cd->xlb[0x10a] |= ((1 << 4) | (1 << 5)); cd->xlb[0x20a] |= ((1 << 4) | (1 << 5)); cd->xlb[0x30a] |= ((1 << 4) | (1 << 5)); /* CCR7.4=0 (~TESR), CCR7.5=0 (~RESR) */ cd->xlb[0x00a] &= ~((1 << 4) | (1 << 5)); cd->xlb[0x10a] &= ~((1 << 4) | (1 << 5)); cd->xlb[0x20a] &= ~((1 << 4) | (1 << 5)); cd->xlb[0x30a] &= ~((1 << 4) | (1 << 5)); /* align elastic stores */ /* CCR6.5=1 (TESA), CCR6.6=1 (RESA) */ cd->xlb[0x01e] |= ((1 << 5) | (1 << 6)); cd->xlb[0x11e] |= ((1 << 5) | (1 << 6)); cd->xlb[0x21e] |= ((1 << 5) | (1 << 6)); cd->xlb[0x31e] |= ((1 << 5) | (1 << 6)); /* CCR6.5=0 (~TESA), CCR6.6=0 (~RESA) */ cd->xlb[0x01e] &= ~((1 << 5) | (1 << 6)); cd->xlb[0x11e] &= ~((1 << 5) | (1 << 6)); cd->xlb[0x21e] &= ~((1 << 5) | (1 << 6)); cd->xlb[0x31e] &= ~((1 << 5) | (1 << 6)); return (0); } /** xp_e1_card_config: - configure a card with an E1 device * @cd: card structure pointer */ noinline __unlikely int xp_e1_card_config(struct cd *cd) { int span, offset; unsigned long timeout; /* 2.048 MHz Crytal on-board. */ cd->xlb[CTLREG] = cd->ctlreg = cd->clkreg = E1DIV; cd->xlb[SYNREG] = cd->synreg = SYNCSELF; /* Sync to crystal. */ cd->xlb[LEDREG] = cd->ledreg = 0; cd->xlb[TSTREG] = cd->tstreg = 0; /* don't drive TEST2 pin */ if (cd->devrev > 3) { cd->xlb[CTLREG1] = NONREVA; /* non Rev. A mode */ cmn_err(CE_NOTE, "%s: setting non-Rev.A mode", DRV_NAME); } else { cd->xlb[CTLREG1] = 0; /* Rev. A mode */ cmn_err(CE_NOTE, "%s: setting Rev.A mode", DRV_NAME); } /* setup E1 card defaults */ cd->config = sdl_default_e1_chan; /* Idle out all channels. The idle byte depends on whether the span is configured for E1 operation or T1 or J1 operation. This sets the registers as well as setting the driver's elastic buffers. */ { int word; uint idle_word = 0xffffffff; /* idle out all channels */ for (word = 0; word < 256; word++) { int ebuf; cd->xll[word] = idle_word; for (ebuf = 0; ebuf < X400P_EBUFNO; ebuf++) cd->wbuf[(ebuf << 8) + word] = idle_word; } } /* On power-up, after the supplies are stable, the DS21345/DS21554 should be configured for operation by writing to all the internal registers (this includes setting test registers to 00h) since the contents of the internal registers cannot be predicted on power-up. The LIRST (CCR5.7) should be toggled from zero to one to reset the line interface circuitry (it will take the device about 40ms to recover from the LIRST bit being toggled). Finally, after TSYSCLK and RSYSCLK inputs are stable, the ESR bits (CCR6.0 and CCR6.1) should be toggled from a zero to a one (this step can be skipped if the elastic stores are disabled). */ /* Zero all span registers. Note that these devices have a full 256 register locations. */ for (span = 0; span < X400_SPANS; span++) for (offset = 0; offset < 256; offset++) cd->xlb[(span << 8) + offset] = 0x00; /* The interleaved PCM bus option (IBO) supports two bus speeds. The 4.096 MHz bus speed allows to share a common bus. The 8.192 MHz bus speed allows four SCTs to share a common bus. Each SCT that shares a common bus must be configured through software and requires the use of one or two device pints. The elastic stores of each SCT must be enabled and configured for 2.048 MHz operation. For all bus configurations, one SCT will be configured as the master device and the remaining SCTs will be configured as slave devices. In the 8.192 MHz bus configuration there is one master and three slaves. */ /* set up for interleaved serial bus operation, byte mode */ /* IBO.7: NA: should be set to 0 */ /* IBO.6: NA: should be set to 0 */ /* IBO.5: NA: should be set to 0 */ /* IBO.4: NA: should be set to 0 */ /* IBO.3: IBOEN: IBO enable (0, disabled; 1, enabled) */ /* IBO.2: INTSEL: Interleave type (0, byte; 1, frame) */ /* IBO.1: MSEL0: '00' slave; '10' master with 1 slave */ /* IBO.0: MSEL1: '01' master with 3 slaves; '11' reserved */ cd->xlb[0x0b5] = 0x09; /* IBOEN, master w/ 3 slaves, 8.192 MHz bus */ cd->xlb[0x1b5] = 0x08; /* IBOEN, slave */ cd->xlb[0x2b5] = 0x08; /* IBOEN, slave */ cd->xlb[0x3b5] = 0x08; /* IBOEN, slave */ cd->config.ifflags = (SDL_IF_UP | SDL_IF_TX_RUNNING | SDL_IF_RX_RUNNING); /* Allocate span structures and write all of the registers of interest. */ for (span = 0; span < cd->ports; span++) { struct sp *sp; int err; if (!(sp = cd->spans[span])) { if (!(sp = xp_alloc_sp(cd, span))) return (-ENOMEM); } else xp_init_sp(cd, sp, span); if ((err = xp_e1_span_config(sp, 0)) != 0) return (err); } /* line interface reset */ /* CCR5.7=1 (LIRST) */ cd->xlb[0x0aa] |= (1 << 7); cd->xlb[0x1aa] |= (1 << 7); cd->xlb[0x2aa] |= (1 << 7); cd->xlb[0x3aa] |= (1 << 7); /* Wait 40 milliseconds. */ timeout = (volatile unsigned long) jiffies + 100 * HZ / 1000; while ((volatile unsigned long) jiffies < timeout) ; /* release LIRST bit */ /* CCR5.7=0 (~LIRST) */ cd->xlb[0x0aa] &= ~(1 << 7); cd->xlb[0x1aa] &= ~(1 << 7); cd->xlb[0x2aa] &= ~(1 << 7); cd->xlb[0x3aa] &= ~(1 << 7); /* At this point we are ready to detect the line connection. We initially configure sending a blue alarm (AIS) unframed all ones, with the transmitters enabled. This is because these chips cannot detect open circuit. What we are trying to figure out is whether the receivers and/or transmitters are connected. If we are live on a functional span, the receivers will be reporting no alarm (other than AIS), and the receivers will be synced. The receivers will be reporting AIS or remote AIS. Receivers: LORC: loss of receive carrier: RX not connected or monitoring. LOS: loss of sync: Rx connected, perhaps wrong framing or wrong E1/T1 setting. RAIS: Rx connected, Tx connected. RAI: Tx not connected, or alarm settling. */ /* reset elastic store */ /* CCR6.0=1 (RESR), CCR6.1=1 (TESR) */ cd->xlb[0x01d] |= ((1 << 0) | (1 << 1)); cd->xlb[0x11d] |= ((1 << 0) | (1 << 1)); cd->xlb[0x21d] |= ((1 << 0) | (1 << 1)); cd->xlb[0x31d] |= ((1 << 0) | (1 << 1)); /* CCR6.0=0 (~RESR), CCR6.1=0 (~TESR) */ cd->xlb[0x01d] &= ~((1 << 0) | (1 << 1)); cd->xlb[0x11d] &= ~((1 << 0) | (1 << 1)); cd->xlb[0x21d] &= ~((1 << 0) | (1 << 1)); cd->xlb[0x31d] &= ~((1 << 0) | (1 << 1)); /* align elastic store */ /* CCR5.5=1 (RESA), CCR5.6=1 (TESA) */ cd->xlb[0x0aa] |= ((1 << 5) | (1 << 6)); cd->xlb[0x1aa] |= ((1 << 5) | (1 << 6)); cd->xlb[0x2aa] |= ((1 << 5) | (1 << 6)); cd->xlb[0x3aa] |= ((1 << 5) | (1 << 6)); /* CCR5.5=0 (~RESA), CCR5.6=0 (~TESA) */ cd->xlb[0x0aa] &= ~((1 << 5) | (1 << 6)); cd->xlb[0x1aa] &= ~((1 << 5) | (1 << 6)); cd->xlb[0x2aa] &= ~((1 << 5) | (1 << 6)); cd->xlb[0x3aa] &= ~((1 << 5) | (1 << 6)); return (0); } /** xp_x1_card_config: - configure a card with an E1/T1 device * @cd: card structure pointer */ noinline __unlikely int xp_x1_card_config(struct cd *cd) { int span; unsigned long timeout; int err; switch (cd->board) { case V400PE: case A400PE: case AE400P: /* 2.048 MHz Crystal on board. */ cd->xlb[CTLREG] = cd->ctlreg = cd->clkreg = E1DIV; break; case V400PT: case A400PT: case AT400P: /* 1.544 MHz Crystal on board. */ cd->xlb[CTLREG] = cd->ctlreg = cd->clkreg = 0; break; case A400P: case V400P: /* Should only get here for A400P as V400P has DS21Q352 or DS21Q354 chip instead of E1/T1 chip. */ /* 2.048 MHz Crystal on board. */ cd->xlb[CTLREG] = cd->ctlreg = cd->clkreg = E1DIV; break; case CP100: case CP100P: case CP100E: case CP200: case CP200P: case CP200E: case CP400: case CP400P: case CP400E: /* 2.048 MHz Crystal on board. */ cd->xlb[CTLREG] = cd->ctlreg = cd->clkreg = E1DIV; break; } cd->xlb[SYNREG] = cd->synreg = SYNCSELF; /* Sync to crystal for now. */ cd->xlb[LEDREG] = cd->ledreg = 0; cd->xlb[TSTREG] = cd->tstreg = 0; /* do not drive TEST2 pin */ if (cd->devrev > 3) { cd->xlb[CTLREG1] = NONREVA; /* non Rev. A mode */ cmn_err(CE_NOTE, "%s: setting non-Rev.A mode", DRV_NAME); } else { cd->xlb[CTLREG1] = 0; /* Rev. A mode */ cmn_err(CE_NOTE, "%s: setting Rev.A mode", DRV_NAME); } if (japan) { /* setup J1 card defaults */ cd->config = sdl_default_j1_chan; } else if (etsi) { /* setup E1 card defaults */ cd->config = sdl_default_e1_chan; } else if (ansi) { /* setup T1 card defaults */ cd->config = sdl_default_t1_chan; } else { switch (cd->board) { case V401PE: case A400PE: /* setup E1 card defaults */ cd->config = sdl_default_e1_chan; break; case V401PT: case A400PT: /* setup T1 card defaults */ cd->config = sdl_default_t1_chan; break; case V400P: case A400P: case CP100: case CP100P: case CP100E: case CP200: case CP200P: case CP200E: case CP400: case CP400P: case CP400E: default: /* setup T1/E1/J1 card defaults */ cd->config = sdl_default_t1_chan; break; } } /* Allocate span structures and idle out all channels. The idle byte depends on whether the span is configured for E1 operation or T1 or J1 operation. This sets the registers as well as setting the driver's elastic buffers. */ { int word, idle_word; switch (__builtin_expect(cd->config.ifgtype, SDL_GTYPE_E1)) { default: case SDL_GTYPE_E1: idle_word = 0xffffffff; break; case SDL_GTYPE_T1: case SDL_GTYPE_J1: idle_word = 0x7f7f7f7f; break; } /* idle out all channels */ for (word = 0; word < 256; word++) { int ebuf; cd->xll[word] = idle_word; for (ebuf = 0; ebuf < X400P_EBUFNO; ebuf++) cd->wbuf[(ebuf << 8) + word] = idle_word; } } /* The DS2155/DS21455/DS21458 contains an on-chip power-up reset function that automatically clears the writeable register space immediately after power is supplied to the device. The user can issue a chip reset at any time. Issuing a reset disrupts traffic flowing until the device is reprogrammed. The reset can be issued through hardware using the TSTRST pin or through software using the SFTRST function in the master mode register. The LIRST (LIC2.6) should be toggled from zero to one to reset the line interface circuitry. (It takes the DS2155 about 40ms to recover from the LIRST bit being toggled.) Finally, after the TSYSCLK and RSYSCLK inputs are stable, the receive and transmit elastic stores should be reset (this step can be skipped if the elastic stores are disabled.) */ /* No need to zero all registers. Note that TAF and TNAF do not initialize to zero anyway and would be disrupted by writing zeros everywhere. */ /* Interleaved PCM Bus Operation: The interleaved PCM bus option (IBO) supports three bus speeds. The 4.096 MHz bus speed allows two PCM data streams to share a common bus. The 8.192 MHZ bus speed allows four PCM data streams to share a common bus. The 16.384 MHz bus speed allows eight PCM data streams to share a common bus. THE RECEIVE ELASTIC STORES OF EACH TRANSCEIVER MUST BE ENABLED. Via the IBO register, the user can configure each transceiver for a specific bus position. For all IBO bus configurations each transceiver is assigned an exclusive position in the high-speed PCM bus. The 8kHz frame sync can be generated from the system backplane or from the first device on the bus. ALL OTHER DEVICES ON THE BUS MUST HAVE THEIR FRAME SYNCS CONFIGURED AS INPUTS. Relative to this common frame sync, the devices will await their turn to drive or sample the bus according to the setting of the DA0, DA1, and DA2 bits of the IBOC register. In channel interleave mode, data is output to the PCM data-out bus one channel at a time from each of the connected devices until all channels of frame n from each device has been placed on the bus. This mode can be used even when the DS21455/DS21458s are operating asyncrhonous to each other. The elastic stores will manage slip conditions. In frame interleave mode, data is output to the PCM data-out bus one frame at a time from each of the devices. This mode is used when all connected devices are operating in syncrhonous fashion (all inbound T1 or E1 lines are syncrhonous) and are synchronous with the system clock (system clock derived from T1 or E1 line). In this mode slip conditions are not allowed. */ /* set up for interleaved serial bus operation, byte mode */ /* IBOC.7: -: Unused. set to zero. */ /* IBOC.6: IBS1: 01 - four devices; 11 - reserved. */ /* IBOC.5: IBS0: 00 - two devices; 10 - Eight devices; */ /* IBOC.4: IBOSEL: IBO Select (0-channel,1-frame) interleave */ /* IBOC.3: IBOEN: Interleave Bus Operation Enable. */ /* IBOC.2-0: DA2-DA0: Position on bus. */ cd->xlb[0x0c5] = 0x28 + 0; /* IBO, channel, 4 devices, 1st device. */ cd->xlb[0x1c5] = 0x28 + 1; /* IBO, channel, 4 devices, 2nd device. */ cd->xlb[0x2c5] = 0x28 + 2; /* IBO, channel, 4 devices, 3rd device. */ cd->xlb[0x3c5] = 0x28 + 3; /* IBO, channel, 4 devices, 4th device. */ cd->config.ifflags = (SDL_IF_UP | SDL_IF_TX_RUNNING | SDL_IF_RX_RUNNING); /* Allocate span structures and Write all registers of interest. The reason that we do not do LIRST in the span configuration is because we want to start them all and then wait 40ms once for all instead of waiting 40ms once for each (which would be 160ms). */ for (span = 0; span < cd->ports; span++) { struct sp *sp; int err; if (!(sp = cd->spans[span])) { if (!(sp = xp_alloc_sp(cd, span))) return (-ENOMEM); } else xp_init_sp(cd, sp, span); if ((err = xp_x1_span_config(sp, 0)) != 0) return (err); } /* LIC2.3: JAMUX-PLL: by setting this bit, we take the jitter attenuator input from the Phase Locked Loop instead of from MCLK. This allows running a T1 or J1 Span when the E1 divider for the board is set to E1DIV. This might be adjusted later on a span by span basis. We can run T1 or J1 spans on a card set for E1, but not visa versa. This is why we set the V400P and A400P to E1 mode. */ switch (cd->board) { } /* line interface reset */ /* LIC2.6=1 (LIRST) */ cd->xlb[0x079] |= (1 << 6); cd->xlb[0x179] |= (1 << 6); cd->xlb[0x279] |= (1 << 6); cd->xlb[0x379] |= (1 << 6); /* Wait 40 milliseconds. */ timeout = (volatile unsigned long) jiffies + 100 * HZ / 1000; while ((volatile unsigned long) jiffies < timeout) ; /* release LIRST bit */ /* LIC2.6=0 (~LIRST) */ cd->xlb[0x079] &= ~(1 << 6); cd->xlb[0x179] &= ~(1 << 6); cd->xlb[0x279] &= ~(1 << 6); cd->xlb[0x379] &= ~(1 << 6); /* reset elastic stores */ /* ESCR.2=1 (RESR), ESCR.6=1 (TESR) */ cd->xlb[0x04f] |= ((1 << 2) | (1 << 6)); cd->xlb[0x14f] |= ((1 << 2) | (1 << 6)); cd->xlb[0x24f] |= ((1 << 2) | (1 << 6)); cd->xlb[0x34f] |= ((1 << 2) | (1 << 6)); /* ESCR.2=0 (~RESR), ESCR.6=0 (~TESR) */ cd->xlb[0x04f] &= ~((1 << 2) | (1 << 6)); cd->xlb[0x14f] &= ~((1 << 2) | (1 << 6)); cd->xlb[0x24f] &= ~((1 << 2) | (1 << 6)); cd->xlb[0x34f] &= ~((1 << 2) | (1 << 6)); /* align elastic stores */ /* ESCR.3=1 (RESALGN), ESCR.7=1 (TESALGN) */ cd->xlb[0x04f] |= ((1 << 2) | (1 << 6)); cd->xlb[0x14f] |= ((1 << 2) | (1 << 6)); cd->xlb[0x24f] |= ((1 << 2) | (1 << 6)); cd->xlb[0x34f] |= ((1 << 2) | (1 << 6)); /* ESCR.3=0 (~RESALGN), ESCR.7=0 (~TESALGN) */ cd->xlb[0x04f] &= ~((1 << 2) | (1 << 6)); cd->xlb[0x14f] &= ~((1 << 2) | (1 << 6)); cd->xlb[0x24f] &= ~((1 << 2) | (1 << 6)); cd->xlb[0x34f] &= ~((1 << 2) | (1 << 6)); /* align elastic store */ /* At this point we are ready to detect the line connection for each span. This determination is easier on the DS2155 series because they have transmitter open-circuit detection. When the transmitters are open-circuited, there are several possibilities: either the span is disconnected altogether, or it is connected to a low impedance monitoring jack, or it is connected to a high impedance monitoring jack. When the receiver detects a carrier, it could be connected to a low impedance monitoring jack. If the receiver is also recovering clock and is synchronized, then the framing is correct and we can just mark monitoring mode. When the receive does not detect a carrier, we can try applying a linear gain to the receiver and see if we can detect a carrier. Experience shows that +30-32dB is required to get the receivers working on a high-impedance port. We will probably have to wait another number of milliseconds to get things to work. When the receiver does not detect a carrier, even with linear gain applied, then the span is completely disconnected. When the transmitters are not open-circuited, the receivers should be detecting a carrier. Otherwise, the span is faulty and should be disabled. When detecting a carrier, the receiver should be recovering clock and may or may not be synced. When the receiver is synced and reporting AIS or RAIS, everything is correct and we can mark the span up. Otherwise, the E1/T1/J1 setting or framing might be incorrect. When we are set for T1 on a J1 link, we should be getting errors associated with CRC6/CRC6J mismatches. In that case, we can set J1 and try again. When we are set for T1 ESF and we are not receiving RAIS, it is likely because D4 framing is being used, so we can set D4 and perhaps SLC-96. When we are set for E1 the CAS/CCS CRC4/CRC5 HDB3/AMI settings might be off. When we are set for T1 the DS0/DS0a CRC6/CRC6J ESF/D4 B8ZS/AMI settings might be off. We can use the real-time INFO registers for checking all of this stuff. When we change something, it might require waiting an additional step. */ /* INFO1.0: FBE: Frame bit error event. Set when a Ft (D4) or FPS (ESF) framing bit is received in error. This might indicate that the ESF/D4 setting is incorrect. */ /* INFO1.1: B8ZS: B8ZS Codeword detect event. Set when a B8ZS codeword is detected a RPOS and RNEG independent of whether the B8ZS mode is selected or not via T1TRC2.7. This can indicate that B8ZS setting is correct, or misset to AMI. */ /* INFO1.2: SEFE: Severely errored framing event. Set when two out of six framing bits (Ft or FPS) are received in error. This can indicate that the ESF/D4 setting is incorrect. */ /* INFO1.3: 16ZD: Sixteen zero detect event. Set when a string of at least 16 consecutive zeros (regardless of the length of the string) has been received at RPOSI or RNEGI. */ /* INFO1.4: 8ZD: Eight zero detect event. Set when a string of eight consecutive zeros (regardless of the length of the string) have been received at RPOSI and RNEGI. */ /* INFO1.5: COFA: Change of frame alignment event. Set when the last resync resulted in a change of frame or multiframe alignment. */ /* INFO1.6: TPDV: Transmit pulse density violation. Set when the transmit data stream does not meet the ANSI T1.403 requirements for pulse density. */ /* INFO1.7: RPDV: Receive pulse density violation. Set when the receive data does not meet the ANSI T1.403 requiremenst for pulse density. This can mean that the line coding is AMI instead of B8ZS. */ /* INFO2.0-3: RL0-RL3: Receive level. Indicates the receive level in -2.5dB increments down less than -37.5dB. Note that the DS2155 only indicates the signal range as specified by the EGL bit in LIC1. */ /* INFO2.4: TOCD: Tranmit open-circuit detect. A real-time bit set when the device detects that the TTIP and TRING outputs are open-circuited. */ /* INFO2.5: TCLE: Transmit current limit exceeded. A real-time bit set when the 50mA (RMS) current limiter is activated, whether the curren limiter is enabled or not. This can indicate a short-circuit condition on the transmitter. */ /* INFO2.6: BD: BOC detected. A real-time bit that is set high when the BOC detector is presently seeing a valid sequence and set low when no BOC is currently being detected. */ /* INFO2.7: BERT: BERT real-time synchronization status. */ /* INFO3.0: CASRC: CAS resync criteria met event. Set when two consecutive CAS MF alignment words are received in error. Note: During a CRC resync, the FAS syncrhonizer is brought online to verify FAS alignment. If during this process a FAS emulator exists, the FAS synchronizer may temporarily align to the emulator. The FASRC will go active indicating a search for a valid FAS has been activated. */ /* INFO3.1: FASRC: FAS resync criteria met. Set when three consecutive FAS words are received in error. */ /* INFO3.2: CRCRC: CRC resync criteria met. Set when 915/1000 codewords are received in error. */ /* INFO7.0: CRC4SA: CRC-4 MF sync active. Set when the syncrhonizer is searching for the CRC-4 MF alignment word. */ /* INFO7.1: CASSA: CAS MF sync active. Set while the syncrhonizer is searching for the CAS MF alignment word. */ /* INFO7.2: FASSA: FAS sync active. Set while the syncrhonizer is searching for alignment at the FAS level. */ /* INFO7.3-7: CSC0,CSC2-CSC4: CRC-4 Sync counter bits. */ /* SR1.0: LOLITC: Loss of line interface transmit clock condition. Set when TCLKI has not transitioned for one channel time. */ /* SR1.1: TOCD: Transmit open-circuit detect condition. Set when the device detects that the TTIP and TRING output are open-circuited. */ /* SR1.2: TCLE: Transmit current limit exceeded. Set when the 50mA (RMS) current limiter is activated, whether the current limiter is enabled or not. */ /* SR1.3: LRCL: Line interface receive carrier-loss condition. Set when the carrier signal is lost. */ /* SR1.4: JALT: Jitter attenuator limit trip event. Set when the jitter attenuator FIFO reaches to within 4 bits of its useful limit. This bit is cleared when read. */ /* SR1.5: RSCOS: Receive signalling change of state event. Set when any channel selected by the receive signalling change-of-state interrupt-enable registers (RSCSE1 through RSCSE4) change signalling state. */ /* SR1.6: TIMER: Timer event. */ /* SR1.7: ILUT: Input level under threshold. This bit is set whenever the input level at RTIP and RRING falls below the threshold set by the valud in CCR4.4 through CCR4.7. The level must remain below the programmed threshold for approximately 50ms for this bit to be set. */ /* SR2.0: RLOS: Receive loss-of-sync condition. Set when the DS2155 is not syncrhonized to the received data stream. */ /* SR2.1: FRCL: Framer receive carrier-loss condition. Set when 255 (or 2048 if E1RCRC2.0 = 1) E1 mode or 192 T1 mode consecutive 0s have been detected at RPOSI and RNEGI. */ /* SR2.2: RUA1: Receive unframed all-ones condition. Set when an unframed all 1s code is received at RPOS1 and RNEG1. */ /* SR2.3: RYEL: Receive yellow alarm condition. Set when a yellow alarm is received at RPOSI and RNEGI. */ /* SR2.4: RLOSC: Receive loss-of-sync clear event. Set when the carrier loss condition at RPOSI and RNEGI is no longer detected. */ /* SR2.5: FRCLC: Framer receive carrier-lost clear event. Set when the carrier loss condition at RPOSI and RNEGI is no longer detected. */ /* SR2.6: RUA1C: Receive unframed all-ones clear event. Set when the unframed all ones condition is no longer detected. */ /* SR2.7: RYELC: Receive yellow alarm clear event. Set when the receive Yellow Alarm condition is no longer detected. */ /* SR3.0: RRA: Receive remote alarm condition. Set when a remote alarm is received at RPOSI and RNEGI. */ /* SR3.1: RDMA: Receive distant MF alarm condition. Set when bit 6 of time slot 16 in frame 0 has been set for two consecutive multiframes. This alarm is not disabled in the CCS signaling mode. */ /* SR3.2: V52LINK:V5.2 link detected condition. Set on detection of a V5.2 link identification signal (G.965). */ /* SR3.3: LORC: Loss of receive clock condition. Set when the RCLKI pin has not transitioned for one channel time. */ /* SR3.4: LOTC: Loss of transmit clock condition. Set when the TCLK pin has not transitioned for one channel time. */ /* SR3.5: LUP: Loop-up code detected condition. Set when the loop-up code as defined in the RUPCD1/2 register is being received. */ /* SR3.6: LDN: Loop-down code detected condition. Set when the loop-down code as defined in the RDNCD1/2 register is being received. */ /* SR3.7: LSPARE: Spare code detected condition. Set when the spare code as defined in the RSCD1/2 registers is being received. */ /* SR4.0: RAF: Receive align frame event. Set every 250us at the beginning of align frames. Used to alert the host that Si and Sa bits are available in the RAF and RNAF registers. */ /* SR4.1: RCMF: Receive CRC multiframe event. Set on CRC4 multiframe boundaries; continues to set every 2ms on an arbitrary boundary if CRC4 is disabled. */ /* SR4.2: RMF: Receive multiframe event. E1: Set every 2ms (regardless if CAS signaling is enabled or not) on receive multiframe boundaries. Used to alert the host that signaling data is available. T1: Set every 1.5ms on D4 MF boundaries or every 3ms on ESF MF boundaries. */ /* SR4.3: TAF: Transmit align frame event. Set every 250us at the beginning of align frames. Used to alert the host that the TAF and TNAF registers need to be updated. */ /* SR4.4: TMF: Transmit multiframe event. E1: Set every 2ms (regardless if CRC4 is enabled) on transmit multiframe boundaries. Used to alert the host that signalling data needs to be updated. */ /* SR4.5: RSAZ: Receive signalling all-zeros event. Set when over a full MF, time slot 16 contains all zeros. */ /* SR4.6: RSAO: Receive signalling all-ones event. Set when the contents of time slot 16 contains few than three 0s over 16 consecutive frames. This alarm is not disabled in the CCS signaling mode. */ /* SR4.7: RAIS-CI:Set when the receiver detects the AIS-CI pattern as defined in ANSI T1.403. */ for (span = 0; span < cd->ports; span++) { struct sp *sp; volatile uint8_t *xlb = &cd->xlb[span << 8]; uint8_t status, info; int tod = 0, tcle = 0, lrcl = 0, jalt = 0, ilut = 0; int retry = 0; if ((sp = cd->spans[span]) == NULL) continue; retry: /* SR1.1: TOCD: Transmit open-circuit detect condition. Set when the device detects that the TTIP and TRING output are open-circuited. */ /* SR1.2: TCLE: Transmit current limit exceeded. Set when the 50mA (RMS) current limiter is activated, whether the current limiter is enabled or not. */ /* SR1.3: LRCL: Line interface receive carrier-loss condition. Set when the carrier signal is lost. */ /* SR1.4: JALT: Jitter attenuator limit trip event. Set when the jitter attenuator FIFO reaches to within 4 bits of its useful limit. This bit is cleared when read. */ /* SR1.7: ILUT: Input level under threshold. This bit is set whenever the input level at RTIP and RRING falls below the threshold set by the valud in CCR4.4 through CCR4.7. The level must remain below the programmed threshold for approximately 50ms for this bit to be set. */ xlb[0x16] = 0x9e; status = xlb[0x16] & 0x0e; /* check transmitter open-circuit */ if (status & 0x02) { /* transmitters were open-circuited, read real-time */ xlb[0x11] = 0x10; info = xlb[0x11] & 0x10; if (info) { /* transmitters currently open-circuited */ tod = 1; } } /* check transmitter short-circuit */ if (status & 0x04) { /* transmitter current limit was exceeded, read real-time */ xlb[0x11] = 0x20; info = xlb[0x11] & 0x20; if (info) { /* tranmitter current limit currently exceeded */ tcle = 1; } } /* check line inteface receive carrier loss */ if (status & 0x08) { lrcl = 1; } /* check the jitter attenuator trip limit */ if (status & 0x10) { jalt = 1; } /* check input level under threshold */ if (status & 0x80) { ilut = 1; } if (tcle) { /* The transmitter is short circuited. Shut down the transmitter to protect it and mark the transmitter down. */ /* Welllll, we might want to leave the transmitter up because it cannot detect short circuit recovery when it is tri-stated. */ xlb[0x78] &= ~0x01; /* shut down transmitter */ sp->config.ifflags &= ~SDL_IF_TX_RUNNING; } if (tod) { /* The transmitter is open-circuited. Shut down the transmitter and mark it down. */ /* Welllll, we might want to leave the transmitter up because it cannot detect open circuit recovery when it is tri-stated. */ xlb[0x78] &= ~0x01; /* shut down transmitter */ sp->config.ifflags &= ~SDL_IF_TX_RUNNING; } if (!tod && !tcle) { /* The transmitter is connected and operating normally. Mark the transmitter up. */ sp->config.ifflags |= SDL_IF_TX_RUNNING; } if (lrcl) { /* The receivers are disconnected or there is a gain problem. */ } else { /* The receivers are connected and receiving carrier, mark the receivers up. */ sp->config.ifflags |= SDL_IF_RX_RUNNING; if (jalt) { /* A jitter attenuator trip limit being exceeded this fast might indicate that the line rate is rather different than what we set. */ switch (sp->config.ifgtype) { default: case SDL_GTYPE_NONE: case SDL_GTYPE_E1: /* We have E1 set, if the user did not explicitly request etsi when the driver was loaded, try switching to T1 and LIRST again. */ if (!etsi && !retry) { sp->config = sdl_default_t1_chan; if ((err = xp_x1_span_config(sp, 1)) != 0) return (err); retry = 1; goto retry; } break; case SDL_GTYPE_T1: /* We have T1 set, if the user did not explicitly request ansi when the driver was loaded, try switching it to E1 and LIRST again. */ if (!ansi && !retry) { sp->config = sdl_default_e1_chan; if ((err = xp_x1_span_config(sp, 1)) != 0) return (err); retry = 1; goto retry; } break; case SDL_GTYPE_J1: /* We have J1 set, if the user did not explicitly request japan when the driver was loaded, try switching it to E1 and LIRST again. */ if (!japan && !retry) { sp->config = sdl_default_e1_chan; if ((err = xp_x1_span_config(sp, 1)) != 0) return (err); retry = 1; goto retry; } break; } } else { /* The jitter attenuator is within limits meaning that the rate is likely set correctly. Now check some things about whether the settings are also correct. */ switch (sp->config.ifgtype) { default: case SDL_GTYPE_E1: break; case SDL_GTYPE_T1: break; case SDL_GTYPE_J1: break; } } } } return (0); } /** * xp_span_reconfig: perform reconfiguration of a running span * @cd: card structure owning span * @span: span number */ noinline __unlikely int xp_span_reconfig(struct sp *sp) { int err; switch (sp->cd->device) { case XP_DEV_DS21352: case XP_DEV_DS21552: err = xp_t1_span_config(sp, 1); break; case XP_DEV_DS21354: case XP_DEV_DS21554: err = xp_e1_span_config(sp, 1); break; case XP_DEV_DS2155: case XP_DEV_DS21455: case XP_DEV_DS21458: err = xp_x1_span_config(sp, 1); break; default: swerr(); err = -EFAULT; break; } return (err); } noinline __unlikely void xp_t1_card_reconfig(struct cd *cd); noinline __unlikely void xp_e1_card_reconfig(struct cd *cd); noinline __unlikely void xp_x1_card_reconfig(struct cd *cd); /** * xp_card_reconfig: - perform reconfiguration of a running card * @cd: card structure */ noinline __unlikely void xp_card_reconfig(struct cd *cd, int restart) { uint8_t ctlreg = 0, synreg; uint8_t span; /* do not disrupt loopback bits */ ctlreg &= ~LSERLB; if (cd->config.ifgmode & SDL_GMODE_LOC_LB) ctlreg |= LSERLB; ctlreg &= ~RSERLB; if (cd->config.ifgmode & SDL_GMODE_REM_LB) ctlreg |= RSERLB; /* do not disrupt master bit */ ctlreg &= ~MASTER; if (cd->config.ifclock == SDL_CLOCK_MASTER) ctlreg |= MASTER; /* calculate the e1div bit */ ctlreg &= ~E1DIV; switch ((synreg = cd->config.ifsync)) { case SYNC1: case SYNC2: case SYNC3: case SYNC4: if (cd->spans[synreg - 1]->config.ifgtype == SDL_GTYPE_E1) ctlreg |= E1DIV; break; case SYNCEXTERN: if (ctlreg & MASTER) { swerr(); ctlreg &= ~MASTER; } if (cd->sg.sg != NULL && cd->sg.sg->master != NULL) { if (cd->sg.sg->ifgtype == SDL_GTYPE_E1) ctlreg |= E1DIV; break; } default: case SYNCSELF: ctlreg |= cd->clkreg; break; } cd->plx[INTCSR] = 0; /* disable interrupts */ if (cd->synreg != synreg) cd->eval_syncsrc = 1; /* reevaluate syncrhonization source */ cd->xlb[CTLREG] = cd->ctlreg = ctlreg; /* disable interrupts default mode */ cd->xlb[SYNREG] = cd->synreg = synreg; // cd->xlb[LEDREG] = cd->ledreg = 0; /* turn all led off */ /* leaved leds alone // */ // cd->xlb[TSTREG] = cd->tstreg = 0; /* don't drive TEST2 */ if (restart) { /* Easiest to distinguish functions be device rather than by card. */ switch (cd->device) { case XP_DEV_DS21354: case XP_DEV_DS21554: xp_e1_card_reconfig(cd); break; case XP_DEV_DS21352: case XP_DEV_DS21552: xp_t1_card_reconfig(cd); break; case XP_DEV_DS2155: case XP_DEV_DS21455: case XP_DEV_DS21458: xp_x1_card_reconfig(cd); break; default: swerr(); break; } /* reconfigure all spans */ for (span = 0; span < cd->ports; span++) { struct sp *sp; int chan; if ((sp = cd->spans[span]) == NULL) continue; /* Any full span remains a full span of the new type, but DS0a changes to DS0 on E1. */ switch (cd->config.ifgtype) { case SDL_GTYPE_E1: switch (sp->config.iftype) { case SDL_TYPE_E1: break; case SDL_TYPE_T1: case SDL_TYPE_J1: sp->config.iftype = sdl_default_e1_span.iftype; sp->config.ifrate = sdl_default_e1_span.ifrate; sp->config.ifblksize = sdl_default_e1_span.ifblksize; break; case SDL_TYPE_DS0A: sp->config.iftype = sdl_default_e1_chan.iftype; sp->config.ifrate = sdl_default_e1_chan.ifrate; case SDL_TYPE_DS0: sp->config.ifblksize = sdl_default_e1_chan.ifblksize; break; } sp->config.ifmode = sdl_default_e1_span.ifmode; sp->config.ifgtype = sdl_default_e1_span.ifgtype; sp->config.ifgrate = sdl_default_e1_span.ifgrate; sp->config.ifgmode = sdl_default_e1_span.ifgmode; sp->config.ifgcrc = sdl_default_e1_span.ifgcrc; sp->config.ifclock = sp->config.ifclock; sp->config.ifcoding = sdl_default_e1_span.ifcoding; sp->config.ifframing = sdl_default_e1_span.ifframing; /* reconfigure all chans */ for (chan = 0; chan < 32; chan++) { struct ch *ch; if ((ch = sp->chans[chan]) == NULL) continue; switch (ch->sdl.config.iftype) { case SDL_TYPE_T1: case SDL_TYPE_J1: ch->sdl.config.iftype = sdl_default_e1_span.iftype; ch->sdl.config.ifrate = sdl_default_e1_span.ifrate; ch->sdl.config.ifblksize = sdl_default_e1_span.ifblksize; break; case SDL_TYPE_DS0A: ch->sdl.config.iftype = sdl_default_e1_chan.iftype; ch->sdl.config.ifrate = sdl_default_e1_chan.ifrate; case SDL_TYPE_DS0: ch->sdl.config.ifblksize = sdl_default_e1_chan.ifblksize; break; } ch->sdl.config.ifmode = sdl_default_e1_chan.ifmode; } break; case SDL_GTYPE_T1: switch (sp->config.iftype) { case SDL_TYPE_E1: case SDL_TYPE_J1: sp->config.iftype = sdl_default_t1_span.iftype; sp->config.ifrate = sdl_default_t1_span.ifrate; sp->config.ifblksize = sdl_default_t1_span.ifblksize; break; case SDL_TYPE_DS0: case SDL_TYPE_DS0A: sp->config.ifblksize = sdl_default_t1_chan.ifblksize; break; } sp->config.ifmode = sdl_default_t1_span.ifmode; sp->config.ifgtype = sdl_default_t1_span.ifgtype; sp->config.ifgrate = sdl_default_t1_span.ifgrate; sp->config.ifgmode = sdl_default_t1_span.ifgmode; sp->config.ifgcrc = sdl_default_t1_span.ifgcrc; sp->config.ifclock = sp->config.ifclock; sp->config.ifcoding = sdl_default_t1_span.ifcoding; sp->config.ifframing = sdl_default_t1_span.ifframing; /* reconfigure all chans */ for (chan = 0; chan < 32; chan++) { struct ch *ch; if ((ch = sp->chans[chan]) == NULL) continue; switch (ch->sdl.config.iftype) { case SDL_TYPE_E1: case SDL_TYPE_J1: ch->sdl.config.iftype = sdl_default_t1_span.iftype; ch->sdl.config.ifrate = sdl_default_t1_span.ifrate; ch->sdl.config.ifblksize = sdl_default_t1_span.ifblksize; break; case SDL_TYPE_DS0: case SDL_TYPE_DS0A: ch->sdl.config.ifblksize = sdl_default_t1_chan.ifblksize; break; } ch->sdl.config.ifmode = sdl_default_t1_chan.ifmode; } break; case SDL_GTYPE_J1: switch (sp->config.iftype) { case SDL_TYPE_E1: case SDL_TYPE_T1: sp->config.iftype = sdl_default_j1_span.iftype; sp->config.ifrate = sdl_default_j1_span.ifrate; sp->config.ifblksize = sdl_default_j1_span.ifblksize; break; case SDL_TYPE_DS0: sp->config.iftype = sdl_default_j1_chan.iftype; sp->config.ifrate = sdl_default_j1_chan.ifrate; case SDL_TYPE_DS0A: sp->config.ifblksize = sdl_default_j1_chan.ifblksize; break; } sp->config.ifmode = sdl_default_j1_span.ifmode; sp->config.ifgtype = sdl_default_j1_span.ifgtype; sp->config.ifgrate = sdl_default_j1_span.ifgrate; sp->config.ifgmode = sdl_default_j1_span.ifgmode; sp->config.ifgcrc = sdl_default_j1_span.ifgcrc; sp->config.ifclock = sp->config.ifclock; sp->config.ifcoding = sdl_default_j1_span.ifcoding; sp->config.ifframing = sdl_default_j1_span.ifframing; /* reconfigure all chans */ for (chan = 0; chan < 32; chan++) { struct ch *ch; if ((ch = sp->chans[chan]) == NULL) continue; switch (ch->sdl.config.iftype) { case SDL_TYPE_T1: case SDL_TYPE_E1: ch->sdl.config.iftype = sdl_default_j1_span.iftype; ch->sdl.config.ifrate = sdl_default_j1_span.ifrate; ch->sdl.config.ifblksize = sdl_default_j1_span.ifblksize; break; case SDL_TYPE_DS0: ch->sdl.config.iftype = sdl_default_j1_chan.iftype; ch->sdl.config.ifrate = sdl_default_j1_chan.ifrate; case SDL_TYPE_DS0A: ch->sdl.config.ifblksize = sdl_default_j1_chan.ifblksize; break; } ch->sdl.config.ifmode = sdl_default_j1_chan.ifmode; } break; } for (chan = 0; chan < 32; chan++) { struct ch *ch; if ((ch = sp->chans[chan]) == NULL) continue; ch->sdl.config.ifgtype = sp->config.ifgtype; ch->sdl.config.ifgrate = sp->config.ifgrate; ch->sdl.config.ifgmode = sp->config.ifgmode; ch->sdl.config.ifgcrc = sp->config.ifgcrc; ch->sdl.config.ifclock = sp->config.ifclock; ch->sdl.config.ifcoding = sp->config.ifcoding; ch->sdl.config.ifframing = sp->config.ifframing; } xp_span_reconfig(sp); } } cd->plx[INTCSR] = PLX_INTENA; /* enable interrupts */ cd->xlb[CTLREG] = cd->ctlreg | (INTENA | DINTENA); /* enable interrupts and full mode */ } noinline __unlikely void xp_t1_card_reconfig(struct cd *cd) { int span, offset; /* setup T1 card defaults */ cd->config = sdl_default_t1_chan; /* zero all span registers */ for (span = 0; span < X400_SPANS; span++) for (offset = 0; offset < 160; offset++) cd->xlb[(span << 8) + offset] = 0x00; /* set up for interleaved serial bus operation, byte mode */ cd->xlb[0x094] = 0x09; cd->xlb[0x194] = 0x08; cd->xlb[0x294] = 0x08; cd->xlb[0x394] = 0x08; } noinline __unlikely void xp_e1_card_reconfig(struct cd *cd) { unsigned long timeout; int span, offset; /* setup E1 card defaults */ cd->config = sdl_default_e1_chan; /* zero all span registers */ for (span = 0; span < X400_SPANS; span++) for (offset = 0; offset < 256; offset++) cd->xlb[(span << 8) + offset] = 0x00; /* set up for interleaved serial bus operation, byte mode */ cd->xlb[0x0b5] = 0x09; /* master w/ 3 slaves, 8.192 MHz bus */ cd->xlb[0x1b5] = 0x08; /* IBO slave */ cd->xlb[0x2b5] = 0x08; /* IBO slave */ cd->xlb[0x3b5] = 0x08; /* IBO slave */ /* line interface reset */ cd->xlb[0x0aa] = 0x80; /* LIRST */ cd->xlb[0x1aa] = 0x80; /* LIRST */ cd->xlb[0x2aa] = 0x80; /* LIRST */ cd->xlb[0x3aa] = 0x80; /* LIRST */ /* wait for 40 ms */ timeout = (volatile unsigned long) jiffies + 100 * HZ / 1000; while ((volatile unsigned long) jiffies < timeout) ; /* release LIRST bit */ cd->xlb[0x0aa] = 0x80; /* not LIRST */ cd->xlb[0x1aa] = 0x80; /* not LIRST */ cd->xlb[0x2aa] = 0x80; /* not LIRST */ cd->xlb[0x3aa] = 0x80; /* not LIRST */ /* rewrite after LIRST */ cd->xlb[0x0b5] = 0x09; /* master w/ 3 slaves, 8.192 MHz bus */ cd->xlb[0x1b5] = 0x08; /* IBO slave */ cd->xlb[0x2b5] = 0x08; /* IBO slave */ cd->xlb[0x3b5] = 0x08; /* IBO slave */ /* FIXME: reconfigure ISR */ /* FIXME: have to reconfigure all spans now... */ } noinline __unlikely void xp_x1_card_reconfig(struct cd *cd) { unsigned long timeout; uint8_t reg00, lic2; switch (cd->config.ifgtype) { case SDL_GTYPE_E1: reg00 = 0x02; lic2 = 0x98; /* setup E1 card defaults */ cd->config = sdl_default_e1_chan; break; default: case SDL_GTYPE_NONE: case SDL_GTYPE_T1: reg00 = 0x00; lic2 = 0x18; /* setup T1 card defaults */ cd->config = sdl_default_t1_chan; break; case SDL_GTYPE_J1: reg00 = 0x00; lic2 = 0x18; /* setup J1 card defaults */ cd->config = sdl_default_j1_chan; break; } /* place all framers in E1, T1 or J1 mode */ cd->xlb[0x000] = reg00; cd->xlb[0x100] = reg00; cd->xlb[0x200] = reg00; cd->xlb[0x300] = reg00; /* set up for interleaved serial bus operation, byte mode */ cd->xlb[0x0c5] = 0x28 + 0; cd->xlb[0x1c5] = 0x28 + 1; cd->xlb[0x2c5] = 0x28 + 2; cd->xlb[0x3c5] = 0x28 + 3; /* release LIRST bit */ cd->xlb[0x079] = lic2; /* E1, normal, no LIRST */ cd->xlb[0x179] = lic2; /* E1, normal, no LIRST */ cd->xlb[0x279] = lic2; /* E1, normal, no LIRST */ cd->xlb[0x379] = lic2; /* E1, normal, no LIRST */ /* line interface reset */ cd->xlb[0x079] = lic2 | 0x40; /* E1, normal, LIRST */ cd->xlb[0x179] = lic2 | 0x40; /* E1, normal, LIRST */ cd->xlb[0x279] = lic2 | 0x40; /* E1, normal, LIRST */ cd->xlb[0x379] = lic2 | 0x40; /* E1, normal, LIRST */ /* wait for 40 ms */ timeout = (volatile unsigned long) jiffies + 100 * HZ / 1000; while ((volatile unsigned long) jiffies < timeout) ; /* release LIRST bit */ cd->xlb[0x079] = lic2; /* E1, normal, no LIRST */ cd->xlb[0x179] = lic2; /* E1, normal, no LIRST */ cd->xlb[0x279] = lic2; /* E1, normal, no LIRST */ cd->xlb[0x379] = lic2; /* E1, normal, no LIRST */ } /* * ------------------------------------------------------------------------ * * Timers * * ------------------------------------------------------------------------ */ enum { tall, t1, t2, t3, t4, t5, t6, t7, t8, t9 }; #if 1 noinline fastcall __hot void xp_stop_timer(struct ch *ch, toid_t *tidp, uint t) { toid_t tid_old; if (likely((tid_old = XCHG(tidp, 0)) != 0)) { LOGTE(ch2sid(ch), "-> T%u STOP <-", t); spin_unlock(&ch->lock); untimeout(tid_old); spin_lock(&ch->lock); } } noinline fastcall __hot void xp_start_timer(struct ch *ch, toid_t *tidp, timo_fcn_t *fnc, sl_ulong ticks, uint t) { toid_t tid_old; if (unlikely((tid_old = XCHG(tidp, 0)) != 0)) { LOGTE(ch2sid(ch), "-> T%u STOP <-", t); spin_unlock(&ch->lock); untimeout(tid_old); spin_lock(&ch->lock); } else LOGTE(ch2sid(ch), "-> T%d START <- (%u hz, HZ is %u)", t, ticks, (uint) HZ); *tidp = timeout(fnc, (caddr_t) ch, ticks); } #else static noinline fastcall void xp_stop_timer_t1(struct ch *ch) { LOGTE(ch2sid(ch), "-> T1 STOP <-"); printd(("%s: %p: -> T1 STOP <-\n", DRV_NAME, ch)); mi_timer_stop(ch->sl.timers.t1); } static noinline fastcall void xp_start_timer_t1(struct ch *ch) { LOGTE(ch2sid(ch), "-> T1 START <- (%lu hz, %u msec, HZ is %u)", drv_msectohz(ch->sl.config.t1), ch->sl.config.t1, (uint) HZ); printd(("%s: %p: -> T1 START <- (%lu hz, %u msec, HZ is %u)\n", DRV_NAME, ch, drv_msectohz(ch->sl.config.t1), ch->sl.config.t1, (uint) HZ)); mi_timer_MAC(ch->sl.timers.t1, ch->sl.config.t1); } static noinline fastcall void xp_stop_timer_t2(struct ch *ch) { LOGTE(ch2sid(ch), "-> T2 STOP <- "); printd(("%s: %p: -> T2 STOP <-\n", DRV_NAME, ch)); mi_timer_stop(ch->sl.timers.t2); } static noinline fastcall void xp_start_timer_t2(struct ch *ch) { LOGTE(ch2sid(ch), "-> T2 START <- (%lu hz, %u msec, HZ is %u)", drv_msectohz(ch->sl.config.t2), ch->sl.config.t2, (uint) HZ); printd(("%s: %p: -> T2 START <- (%lu hz, %u msec, HZ is %u)\n", DRV_NAME, ch, drv_msectohz(ch->sl.config.t2), ch->sl.config.t2, (uint) HZ)); mi_timer_MAC(ch->sl.timers.t2, ch->sl.config.t2); } static noinline fastcall void xp_stop_timer_t3(struct ch *ch) { LOGTE(ch2sid(ch), "-> T3 STOP <-"); printd(("%s: %p: -> T3 STOP <-\n", DRV_NAME, ch)); mi_timer_stop(ch->sl.timers.t3); } static noinline fastcall void xp_start_timer_t3(struct ch *ch) { LOGTE(ch2sid(ch), "-> T3 START <- (%lu hz, %u msec, HZ is %u)", drv_msectohz(ch->sl.config.t3), ch->sl.config.t3, (uint) HZ); printd(("%s: %p: -> T3 START <- (%lu hz, %u msec, HZ is %u)\n", DRV_NAME, ch, drv_msectohz(ch->sl.config.t3), ch->sl.config.t3, (uint) HZ)); mi_timer_MAC(ch->sl.timers.t3, ch->sl.config.t3); } static noinline fastcall void xp_stop_timer_t4(struct ch *ch) { LOGTE(ch2sid(ch), "-> T4 STOP <-"); printd(("%s: %p: -> T4 STOP <-\n", DRV_NAME, ch)); mi_timer_stop(ch->sl.timers.t4); } static noinline fastcall void xp_start_timer_t4(struct ch *ch) { LOGTE(ch2sid(ch), "-> T4 START <- (%lu hz, %u msec, HZ is %u)", drv_msectohz(ch->sl.statem.t4v), ch->sl.statem.t4v, (uint) HZ); printd(("%s: %p: -> T4 START <- (%lu hz, %u msec, HZ is %u)\n", DRV_NAME, ch, drv_msectohz(ch->sl.statem.t4v), ch->sl.statem.t4v, (uint) HZ)); mi_timer_MAC(ch->sl.timers.t4, ch->sl.statem.t4v); } static inline fastcall __hot_out void xp_stop_timer_t5(struct ch *ch) { LOGTE(ch2sid(ch), "-> T5 STOP <-"); printd(("%s: %p: -> T5 STOP <-\n", DRV_NAME, ch)); mi_timer_stop(ch->sl.timers.t5); } static inline fastcall __hot_out void xp_start_timer_t5(struct ch *ch) { LOGTE(ch2sid(ch), "-> T5 START <- (%lu hz, %u msec, HZ is %u)", drv_msectohz(ch->sl.config.t5), ch->sl.config.t5, (uint) HZ); printd(("%s: %p: -> T5 START <- (%lu hz, %u msec, HZ is %u)\n", DRV_NAME, ch, drv_msectohz(ch->sl.config.t5), ch->sl.config.t5, (uint) HZ)); mi_timer_MAC(ch->sl.timers.t5, ch->sl.config.t5); } static inline fastcall __hot_in void xp_stop_timer_t6(struct ch *ch) { LOGTE(ch2sid(ch), "-> T6 STOP <-"); printd(("%s: %p: -> T6 STOP <-\n", DRV_NAME, ch)); mi_timer_stop(ch->sl.timers.t6); } static inline fastcall __hot_in void xp_start_timer_t6(struct ch *ch) { LOGTE(ch2sid(ch), "-> T6 START <- (%lu hz, %u msec, HZ is %u)", drv_msectohz(ch->sl.config.t6), ch->sl.config.t6, (uint) HZ); printd(("%s: %p: -> T6 START <- (%lu hz, %u msec, HZ is %u)\n", DRV_NAME, ch, drv_msectohz(ch->sl.config.t6), ch->sl.config.t6, (uint) HZ)); mi_timer_MAC(ch->sl.timers.t6, ch->sl.config.t6); } static inline fastcall __hot_in void xp_stop_timer_t7(struct ch *ch) { LOGTE(ch2sid(ch), "-> T7 STOP <-"); printd(("%s: %p: -> T7 STOP <-\n", DRV_NAME, ch)); mi_timer_stop(ch->sl.timers.t7); } static inline fastcall __hot_in void xp_start_timer_t7(struct ch *ch) { LOGTE(ch2sid(ch), "-> T7 START <- (%lu hz, %u msec, HZ is %u)", drv_msectohz(ch->sl.config.t7), ch->sl.config.t7, (uint) HZ); printd(("%s: %p: -> T7 START <- (%lu hz, %u msec, HZ is %u)\n", DRV_NAME, ch, drv_msectohz(ch->sl.config.t7), ch->sl.config.t7, (uint) HZ)); mi_timer_MAC(ch->sl.timers.t7, ch->sl.config.t7); } static inline fastcall __hot_in void xp_stop_timer_t8(struct ch *ch) { LOGTE(ch2sid(ch), "-> T8 STOP <-"); printd(("%s: %p: -> T8 STOP <-\n", DRV_NAME, ch)); mi_timer_stop(ch->sdt.timers.t8); } static inline fastcall __hot_in void xp_start_timer_t8(struct ch *ch) { LOGTE(ch2sid(ch), "-> T8 START <- (%lu hz, %u msec, HZ is %u)", drv_msectohz(ch->sdt.config.t8), ch->sdt.config.t8, (uint) HZ); printd(("%s: %p: -> T8 START <- (%lu hz, %u msec, HZ is %u)\n", DRV_NAME, ch, drv_msectohz(ch->sdt.config.t8), ch->sdt.config.t8, (uint) HZ)); mi_timer_MAC(ch->sdt.timers.t8, ch->sdt.config.t8); } #if 0 static void xp_stop_timer_t9(struct ch *ch) { LOGTE(ch2sid(ch), "-> T9 STOP <-"); printd(("%s: %p: -> T9 STOP <-\n", DRV_NAME, ch)); mi_timer_stop(ch->sdl.timers.t9); } static void xp_start_timer_t9(struct ch *ch) { LOGTE(ch2sid(ch), "-> T9 START <- (%lu hz, %u msec, HZ is %u)", drv_msectohz(ch->sdl.config.t9), ch->sdl.config.t9, (uint) HZ); printd(("%s: %p: -> T9 START <- (%lu hz, %u msec, HZ is %u)\n", DRV_NAME, ch, drv_msectohz(ch->sdl.config.t9), ch->sdl.config.t9, (uint) HZ)); mi_timer_MAC(ch->sdl.timers.t9, ch->ch->sdl.config.t9); } #endif #endif #if 1 static inline fastcall __hot void xp_timer_stop(struct ch *ch, const uint t) { int single = 1; switch (t) { case tall: single = 0; /* fall through */ case t1: xp_stop_timer(ch, &ch->sl.timers.t1, t1); if (single) break; /* fall through */ case t2: xp_stop_timer(ch, &ch->sl.timers.t2, t2); if (single) break; /* fall through */ case t3: xp_stop_timer(ch, &ch->sl.timers.t3, t3); if (single) break; /* fall through */ case t4: xp_stop_timer(ch, &ch->sl.timers.t4, t4); if (single) break; /* fall through */ case t5: xp_stop_timer(ch, &ch->sl.timers.t5, t5); if (single) break; /* fall through */ case t6: xp_stop_timer(ch, &ch->sl.timers.t6, t6); if (single) break; /* fall through */ case t7: xp_stop_timer(ch, &ch->sl.timers.t7, t7); if (single) break; /* fall through */ case t8: xp_stop_timer(ch, &ch->sdt.timers.t8, t8); if (single) break; /* fall through */ #if 0 case t9: xp_stop_timer(ch, &ch->sdl.timers.t9, t9); if (single) break; /* fall through */ #endif break; default: __swerr(); break; } } #else static inline fastcall __hot void xp_timer_stop(struct ch *ch, const uint t) { int single = 1; switch (t) { case tall: single = 0; /* fall through */ case t1: xp_stop_timer_t1(ch); if (single) break; /* fall through */ case t2: xp_stop_timer_t2(ch); if (single) break; /* fall through */ case t3: xp_stop_timer_t3(ch); if (single) break; /* fall through */ case t4: xp_stop_timer_t4(ch); if (single) break; /* fall through */ case t5: xp_stop_timer_t5(ch); if (single) break; /* fall through */ case t6: xp_stop_timer_t6(ch); if (single) break; /* fall through */ case t7: xp_stop_timer_t7(ch); if (single) break; /* fall through */ case t8: xp_stop_timer_t8(ch); if (single) break; /* fall through */ #if 0 case t9: xp_stop_timer_t9(ch); if (single) break; /* fall through */ #endif break; default: swerr(); break; } } #endif #if 1 streamscall void xp_t1_expiry(caddr_t); streamscall void xp_t2_expiry(caddr_t); streamscall void xp_t3_expiry(caddr_t); streamscall void xp_t4_expiry(caddr_t); streamscall void xp_t5_expiry(caddr_t); streamscall void xp_t6_expiry(caddr_t); streamscall void xp_t7_expiry(caddr_t); streamscall void xp_t8_expiry(caddr_t); #if 0 streamscall void xp_t9_expiry(caddr_t); #endif static inline fastcall __hot void xp_timer_start(struct ch *ch, const uint t) { switch (t) { case t1: xp_start_timer(ch, &ch->sl.timers.t1, &xp_t1_expiry, ch->sl.config.t1, t); break; case t2: xp_start_timer(ch, &ch->sl.timers.t2, &xp_t2_expiry, ch->sl.config.t2, t); break; case t3: xp_start_timer(ch, &ch->sl.timers.t3, &xp_t3_expiry, ch->sl.config.t3, t); break; case t4: xp_start_timer(ch, &ch->sl.timers.t4, &xp_t4_expiry, ch->sl.statem.t4v, t); break; case t5: xp_start_timer(ch, &ch->sl.timers.t5, &xp_t5_expiry, ch->sl.config.t5, t); break; case t6: xp_start_timer(ch, &ch->sl.timers.t6, &xp_t6_expiry, ch->sl.config.t6, t); break; case t7: xp_start_timer(ch, &ch->sl.timers.t7, &xp_t7_expiry, ch->sl.config.t7, t); break; case t8: xp_start_timer(ch, &ch->sdt.timers.t8, &xp_t8_expiry, ch->sdt.config.t8, t); break; #if 0 case t9: xp_start_timer(ch, &ch->sdl.timers.t9, &xp_t9_expiry, ch->sdl.config.t9, t9); break; #endif default: __swerr(); break; } } #else static inline fastcall __hot void xp_timer_start(struct ch *ch, const uint t) { xp_timer_stop(ch, t); switch (t) { case t1: xp_start_timer_t1(ch); break; case t2: xp_start_timer_t2(ch); break; case t3: xp_start_timer_t3(ch); break; case t4: xp_start_timer_t4(ch); break; case t5: xp_start_timer_t5(ch); break; case t6: xp_start_timer_t6(ch); break; case t7: xp_start_timer_t7(ch); break; case t8: xp_start_timer_t8(ch); break; #if 0 case t9: xp_start_timer_t9(ch); break; #endif default: swerr(); break; } } #endif #if 0 noinline __unlikely void xp_free_timers(struct ch *ch) { mblk_t *tp; if ((tp = XCHG(&ch->sl.timers.t1, NULL))) mi_timer_free(tp); if ((tp = XCHG(&ch->sl.timers.t2, NULL))) mi_timer_free(tp); if ((tp = XCHG(&ch->sl.timers.t3, NULL))) mi_timer_free(tp); if ((tp = XCHG(&ch->sl.timers.t4, NULL))) mi_timer_free(tp); if ((tp = XCHG(&ch->sl.timers.t5, NULL))) mi_timer_free(tp); if ((tp = XCHG(&ch->sl.timers.t6, NULL))) mi_timer_free(tp); if ((tp = XCHG(&ch->sl.timers.t7, NULL))) mi_timer_free(tp); if ((tp = XCHG(&ch->sdt.timers.t8, NULL))) mi_timer_free(tp); #if 0 if ((tp = XCHG(&ch->sdl.timers.t9, NULL))) mi_timer_free(tp); #endif } #endif #if 0 noinline __unlikely int xp_alloc_timers(struct ch *ch, queue_t *q) { mblk_t *tp; /* SDL timer allocation */ #if 0 if (!(tp = ch->sdl.timers.t9 = mi_timer_alloc_MAC(q, sizeof(int)))) goto enobufs; *(int *) tp->b_rptr = t9; #endif /* SDT timer allocation */ if (!(tp = ch->sdt.timers.t8 = mi_timer_alloc_MAC(q, sizeof(int)))) goto enobufs; *(int *) tp->b_rptr = t8; /* SL timer allocation */ if (!(tp = ch->sl.timers.t7 = mi_timer_alloc_MAC(q, sizeof(int)))) goto enobufs; *(int *) tp->b_rptr = t7; if (!(tp = ch->sl.timers.t6 = mi_timer_alloc_MAC(q, sizeof(int)))) goto enobufs; *(int *) tp->b_rptr = t6; if (!(tp = ch->sl.timers.t5 = mi_timer_alloc_MAC(q, sizeof(int)))) goto enobufs; *(int *) tp->b_rptr = t5; if (!(tp = ch->sl.timers.t4 = mi_timer_alloc_MAC(q, sizeof(int)))) goto enobufs; *(int *) tp->b_rptr = t4; if (!(tp = ch->sl.timers.t3 = mi_timer_alloc_MAC(q, sizeof(int)))) goto enobufs; *(int *) tp->b_rptr = t3; if (!(tp = ch->sl.timers.t2 = mi_timer_alloc_MAC(q, sizeof(int)))) goto enobufs; *(int *) tp->b_rptr = t2; if (!(tp = ch->sl.timers.t1 = mi_timer_alloc_MAC(q, sizeof(int)))) goto enobufs; *(int *) tp->b_rptr = t1; return (0); enobufs: xp_free_timers(ch); return (-ENOBUFS); } #endif /* * ------------------------------------------------------------------------- * * Duration Statistics * * ------------------------------------------------------------------------- * * I don't really know what needs to be done with these now. I had them * working at some point, but now they are disconnected. These are for SS7 * duration statistics mandated by Q.752.2. TODO: These need to be hooked in * somehow. */ #if 0 noinline fastcall __unlikely void sl_is_stats(queue_t *q) { struct xp *xp = XP_PRIV(q); struct ch *ch = xp->ch; if (ch->sl.stamp.sl_dur_unavail) ch->sl.stats.sl_dur_unavail += jiffies - xchg(&ch->sl.stamp.sl_dur_unavail, 0); if (ch->sl.stamp.sl_dur_unavail_rpo) ch->sl.stats.sl_dur_unavail_rpo += jiffies - xchg(&ch->sl.stamp.sl_dur_unavail_rpo, 0); if (ch->sl.stamp.sl_dur_unavail_failed) ch->sl.stats.sl_dur_unavail_failed += jiffies - xchg(&ch->sl.stamp.sl_dur_unavail_failed, 0); ch->sl.stamp.sl_dur_in_service = jiffies; } noinline fastcall __unlikely void sl_oos_stats(queue_t *q) { struct xp *xp = XP_PRIV(q); struct ch *ch = xp->ch; if (ch->sl.stamp.sl_dur_in_service) ch->sl.stats.sl_dur_in_service += jiffies - xchg(&ch->sl.stamp.sl_dur_in_service, 0); if (ch->sl.stamp.sl_dur_unavail_rpo) ch->sl.stats.sl_dur_unavail_rpo += jiffies - xchg(&ch->sl.stamp.sl_dur_unavail_rpo, 0); if (ch->sl.stamp.sl_dur_unavail_failed) ch->sl.stats.sl_dur_unavail_failed += jiffies - xchg(&ch->sl.stamp.sl_dur_unavail_failed, 0); ch->sl.stamp.sl_dur_unavail = jiffies; } noinline fastcall __unlikely void sl_rpo_stats(queue_t *q) { struct xp *xp = XP_PRIV(q); struct ch *ch = xp->ch; if (ch->sl.stamp.sl_dur_unavail_rpo) ch->sl.stats.sl_dur_unavail_rpo += jiffies - xchg(&ch->sl.stamp.sl_dur_unavail_rpo, 0); } noinline fastcall __unlikely void sl_rpr_stats(queue_t *q) { struct xp *xp = XP_PRIV(q); struct ch *ch = xp->ch; if (ch->sl.stamp.sl_dur_unavail_rpo) ch->sl.stats.sl_dur_unavail_rpo += jiffies - xchg(&ch->sl.stamp.sl_dur_unavail_rpo, 0); } #endif /* * ------------------------------------------------------------------------- * * SL State Machines * * ------------------------------------------------------------------------- */ #define SN_OUTSIDE(lower,middle,upper) \ ( ( (lower) <= (upper) ) \ ? ( ( (middle) < (lower) ) || ( (middle) > (upper) ) ) \ : ( ( (middle) < (lower) ) && ( (middle) > (upper) ) ) \ ) /* * ----------------------------------------------------------------------- * * STATE MACHINES:- The order of the state machine primitives below may seem somewhat disorganized at first * glance; however, they have been ordered by dependency because they are all inline functions. You see, the L2 * state machine does not required multiple threading because there is never a requirement to invoke the * individual state machines concurrently. This works out good for the driver, because a primitive action * expands inline to the necessary procedure, while the source still takes the appearance of the SDL diagrams in * the SS7 specification for inspection and debugging. * * ----------------------------------------------------------------------- */ #define sl_cc_stop sl_cc_normal noinline fastcall void sl_cc_normal(struct ch *ch) { xp_timer_stop(ch, t5); ch->sl.statem.cc_state = SL_STATE_IDLE; } noinline fastcall void sl_rc_stop(struct ch *ch) { sl_cc_normal(ch); ch->sl.statem.rc_state = SL_STATE_IDLE; } noinline fastcall void sl_aerm_stop(struct ch *ch) { ch->sdt.statem.aerm_state = SDT_STATE_IDLE; ch->sdt.statem.Ti = ch->sdt.config.Tin; } noinline fastcall void sl_iac_stop(struct ch *ch) { if (ch->sl.statem.iac_state != SL_STATE_IDLE) { xp_timer_stop(ch, t3); xp_timer_stop(ch, t2); xp_timer_stop(ch, t4); sl_aerm_stop(ch); ch->sl.statem.emergency = 0; ch->sl.statem.iac_state = SL_STATE_IDLE; } } noinline fastcall void sl_txc_send_sios(struct ch *ch) { xp_timer_stop(ch, t7); if (((ch->option.pvar & SS7_PVAR_MASK) == SS7_PVAR_ANSI) && ((ch->option.pvar & SS7_PVAR_YR) > SS7_PVAR_88)) xp_timer_stop(ch, t6); ch->sl.statem.lssu_available = 1; ch->sl.statem.tx.sio = LSSU_SIOS; } noinline fastcall void sl_poc_stop(struct ch *ch) { ch->sl.statem.poc_state = SL_STATE_IDLE; } noinline fastcall void sl_eim_stop(struct ch *ch) { ch->sdt.statem.eim_state = SDT_STATE_IDLE; xp_timer_stop(ch, t8); } noinline fastcall void sl_suerm_stop(struct ch *ch) { sl_eim_stop(ch); ch->sdt.statem.suerm_state = SDT_STATE_IDLE; } noinline fastcall void sl_lsc_link_failure(struct ch *ch, sl_ulong reason) { if (ch->sl.statem.lsc_state != SL_STATE_OUT_OF_SERVICE) { ch->sl.statem.failure_reason = reason; sl_out_of_service_ind(ch); sl_iac_stop(ch); /* ok if not aligning */ xp_timer_stop(ch, t1); /* ok if not running */ sl_suerm_stop(ch); /* ok if not running */ sl_rc_stop(ch); sl_txc_send_sios(ch); sl_poc_stop(ch); /* ok if not ITUT */ ch->sl.statem.emergency = 0; ch->sl.statem.local_processor_outage = 0; ch->sl.statem.remote_processor_outage = 0; /* ok if not ANSI */ ch->sl.statem.lsc_state = SL_STATE_OUT_OF_SERVICE; } } noinline fastcall void sl_txc_send_sib(struct ch *ch) { ch->sl.statem.tx.sio = LSSU_SIB; ch->sl.statem.lssu_available = 1; } noinline fastcall void sl_txc_send_sipo(struct ch *ch) { xp_timer_stop(ch, t7); if (((ch->option.pvar & SS7_PVAR_MASK) == SS7_PVAR_ANSI) && ((ch->option.pvar & SS7_PVAR_YR) > SS7_PVAR_88)) xp_timer_stop(ch, t6); ch->sl.statem.tx.sio = LSSU_SIPO; ch->sl.statem.lssu_available = 1; } noinline fastcall void sl_txc_send_sio(struct ch *ch) { ch->sl.statem.tx.sio = LSSU_SIO; ch->sl.statem.lssu_available = 1; } noinline fastcall void sl_txc_send_sin(struct ch *ch) { ch->sl.statem.tx.sio = LSSU_SIN; ch->sl.statem.lssu_available = 1; } noinline fastcall void sl_txc_send_sie(struct ch *ch) { ch->sl.statem.tx.sio = LSSU_SIE; ch->sl.statem.lssu_available = 1; } static inline fastcall __hot_write void sl_txc_send_msu(struct ch *ch) { if (ch->sl.rtb.q_count) xp_timer_start(ch, t7); ch->sl.statem.msu_inhibited = 0; ch->sl.statem.lssu_available = 0; } noinline fastcall void sl_txc_send_fisu(struct ch *ch) { xp_timer_stop(ch, t7); if (((ch->option.pvar & SS7_PVAR_MASK) == SS7_PVAR_ANSI) && ((ch->option.pvar & SS7_PVAR_YR) > SS7_PVAR_88)) if (!(ch->option.popt & SS7_POPT_PCR)) xp_timer_stop(ch, t6); ch->sl.statem.msu_inhibited = 1; ch->sl.statem.lssu_available = 0; } static inline fastcall void sl_txc_fsnx_value(struct ch *ch) { if (ch->sl.statem.tx.X.fsn != ch->sl.statem.rx.X.fsn) ch->sl.statem.tx.X.fsn = ch->sl.statem.rx.X.fsn; } noinline fastcall void sl_txc_nack_to_be_sent(struct ch *ch) { ch->sl.statem.tx.N.bib = ch->sl.statem.tx.N.bib ? 0 : ch->sl.statem.ib_mask; } noinline fastcall __unlikely void sl_lsc_rtb_cleared(struct ch *ch) { if (ch->sl.statem.lsc_state == SL_STATE_PROCESSOR_OUTAGE) { ch->sl.statem.remote_processor_outage = 0; if (ch->sl.statem.local_processor_outage) return; sl_remote_processor_recovered_ind(ch); sl_rtb_cleared_ind(ch, NULL, NULL); sl_txc_send_msu(ch); ch->sl.statem.lsc_state = SL_STATE_IN_SERVICE; } } STATIC fastcall __hot_write int sl_check_congestion(struct ch *ch, queue_t *q, mblk_t *mp); static inline fastcall __hot void sl_txc_bsnr_and_bibr(struct ch *ch) { int pcr = ch->option.popt & SS7_POPT_PCR; ch->sl.statem.tx.R.bsn = ch->sl.statem.rx.R.bsn; ch->sl.statem.tx.R.bib = ch->sl.statem.rx.R.bib; if (ch->sl.statem.clear_rtb) { bufq_purge(&ch->sl.rtb); ch->sl.statem.Ct = 0; sl_check_congestion(ch, NULL, NULL); ch->sl.statem.tx.F.fsn = (ch->sl.statem.tx.R.bsn + 1) & ch->sl.statem.sn_mask; ch->sl.statem.tx.L.fsn = ch->sl.statem.tx.R.bsn; ch->sl.statem.tx.N.fsn = ch->sl.statem.tx.R.bsn; ch->sl.statem.tx.N.fib = ch->sl.statem.tx.R.bib; ch->sl.statem.Z = (ch->sl.statem.tx.R.bsn + 1) & ch->sl.statem.sn_mask; ch->sl.statem.z_ptr = NULL; /* FIXME: handle error return */ sl_lsc_rtb_cleared(ch); ch->sl.statem.clear_rtb = 0; ch->sl.statem.rtb_full = 0; return; } if (ch->sl.statem.tx.F.fsn != ((ch->sl.statem.tx.R.bsn + 1) & ch->sl.statem.sn_mask)) { if (ch->sl.statem.sib_received) { ch->sl.statem.sib_received = 0; xp_timer_stop(ch, t6); } do { freemsg(bufq_dequeue(&ch->sl.rtb)); ch->sl.statem.Ct--; ch->sl.statem.tx.F.fsn = (ch->sl.statem.tx.F.fsn + 1) & ch->sl.statem.sn_mask; } while (ch->sl.statem.tx.F.fsn != ((ch->sl.statem.tx.R.bsn + 1) & ch->sl.statem.sn_mask)); sl_check_congestion(ch, NULL, NULL); if (ch->sl.rtb.q_count == 0) xp_timer_stop(ch, t7); else xp_timer_start(ch, t7); if (!pcr || (ch->sl.rtb.q_msgs < ch->sl.config.N1 && ch->sl.rtb.q_count < ch->sl.config.N2)) ch->sl.statem.rtb_full = 0; if (SN_OUTSIDE(ch->sl.statem.tx.F.fsn, ch->sl.statem.Z, ch->sl.statem.tx.L.fsn) || !ch->sl.rtb.q_count) { ch->sl.statem.Z = ch->sl.statem.tx.F.fsn; ch->sl.statem.z_ptr = ch->sl.rtb.q_head; } } if (pcr) return; if (ch->sl.statem.tx.N.fib != ch->sl.statem.tx.R.bib) { if (ch->sl.statem.sib_received) { ch->sl.statem.sib_received = 0; xp_timer_stop(ch, t6); } ch->sl.statem.tx.N.fib = ch->sl.statem.tx.R.bib; ch->sl.statem.tx.N.fsn = (ch->sl.statem.tx.F.fsn - 1) & ch->sl.statem.sn_mask; if ((ch->sl.statem.z_ptr = ch->sl.rtb.q_head) != NULL) ch->sl.statem.retrans_cycle = 1; return; } } noinline fastcall void sl_txc_sib_received(struct ch *ch) { /* FIXME: consider these variations for all */ if (((ch->option.pvar & SS7_PVAR_MASK) == SS7_PVAR_ANSI) && ((ch->option.pvar & SS7_PVAR_YR) > SS7_PVAR_88)) if (ch->sl.statem.lssu_available && ch->sl.statem.tx.sio != LSSU_SIB) return; if (ch->option.pvar != SS7_PVAR_ITUT_93) if (!ch->sl.rtb.q_count) return; if (!ch->sl.statem.sib_received) { xp_timer_start(ch, t6); ch->sl.statem.sib_received = 1; } xp_timer_start(ch, t7); } noinline fastcall __unlikely void sl_txc_clear_rtb(struct ch *ch, queue_t *q, mblk_t *mp) { bufq_purge(&ch->sl.rtb); ch->sl.statem.Ct = 0; ch->sl.statem.clear_rtb = 1; ch->sl.statem.rtb_full = 0; /* added */ /* FIXME: should probably follow more of the ITUT flush_buffers stuff like reseting Z and FSNF, FSNL, FSNT. */ sl_check_congestion(ch, q, mp); } noinline fastcall __unlikely void sl_txc_clear_tb(struct ch *ch, queue_t *q, mblk_t *mp) { bufq_purge(&ch->sl.tb); sl_flush_wq(ch); ch->sl.statem.Cm = 0; sl_check_congestion(ch, q, mp); } noinline fastcall __unlikely void sl_txc_flush_buffers(struct ch *ch) { bufq_purge(&ch->sl.rtb); ch->sl.statem.rtb_full = 0; ch->sl.statem.Ct = 0; bufq_purge(&ch->sl.tb); sl_flush_wq(ch); ch->sl.statem.Cm = 0; ch->sl.statem.Z = 0; ch->sl.statem.z_ptr = NULL; /* Z =0 error in ITUT 93 and ANSI */ ch->sl.statem.Z = ch->sl.statem.tx.F.fsn = (ch->sl.statem.tx.R.bsn + 1) & ch->sl.statem.sn_mask; ch->sl.statem.tx.L.fsn = ch->sl.statem.rx.R.bsn; ch->sl.statem.rx.T.fsn = ch->sl.statem.rx.R.bsn; xp_timer_stop(ch, t7); return; } static inline fastcall __hot_in void sl_rc_fsnt_value(struct ch *ch) { ch->sl.statem.rx.T.fsn = ch->sl.statem.tx.N.fsn; } noinline fastcall __unlikely int sl_txc_retrieval_request_and_fsnc(struct ch *ch, queue_t *q, mblk_t *rp, sl_ulong fsnc) { mblk_t *mp; int err; ch->sl.statem.tx.C.fsn = fsnc & (ch->sl.statem.sn_mask); /* * FIXME: Q.704/5.7.2 states: * * 5.7.2 If a changeover order or acknowledgement containing an unreasonable value of the forward * sequence number is received, no buffer updating or retrieval is performed, and new traffic is started * on the alternative signalling link(s). * * It will be necessary to check FSNC for "reasonableness" here and flush RTB and TB and return * retrieval-complete indication with a return code of "unreasonable FSNC". * * (Tell the SIGTRAN working group and M2UA guys about this!) */ while (ch->sl.rtb.q_count && ch->sl.statem.tx.F.fsn != ((fsnc + 1) & ch->sl.statem.sn_mask)) { freemsg(bufq_dequeue(&ch->sl.rtb)); ch->sl.statem.Ct--; ch->sl.statem.tx.F.fsn = (ch->sl.statem.tx.F.fsn + 1) & ch->sl.statem.sn_mask; } while ((mp = bufq_dequeue(&ch->sl.tb))) { ch->sl.statem.Cm--; bufq_queue(&ch->sl.rtb, mp); ch->sl.statem.Ct++; if (!ch->sl.statem.Cm) qenable(WR(q)); } ch->sl.statem.Z = ch->sl.statem.tx.F.fsn = (ch->sl.statem.tx.C.fsn + 1) & ch->sl.statem.sn_mask; while ((mp = bufq_dequeue(&ch->sl.rtb))) { ch->sl.statem.Ct--; if ((err = sl_retrieved_message_ind(ch, q, mp))) { /* FIXME: put mp back on queue or we leak a buffer */ return (err); } } ch->sl.statem.rtb_full = 0; sl_retrieval_complete_ind(ch, q, rp); ch->sl.statem.Cm = 0; ch->sl.statem.Ct = 0; ch->sl.statem.tx.N.fsn = ch->sl.statem.tx.L.fsn = ch->sl.statem.tx.C.fsn; return (0); } static inline fastcall __hot_write void sl_daedt_fisu(struct ch *ch, mblk_t *mp) { if (ch->option.popt & SS7_POPT_XSN) { *(sl_ushort *) mp->b_wptr = htons(ch->sl.statem.tx.N.bsn | ch->sl.statem.tx.N.bib); mp->b_wptr += sizeof(sl_ushort); *(sl_ushort *) mp->b_wptr = htons(ch->sl.statem.tx.N.fsn | ch->sl.statem.tx.N.fib); mp->b_wptr += sizeof(sl_ushort); *(sl_ushort *) mp->b_wptr = 0; mp->b_wptr += sizeof(sl_ushort); } else { *(sl_uchar *) mp->b_wptr = (ch->sl.statem.tx.N.bsn | ch->sl.statem.tx.N.bib); mp->b_wptr += sizeof(sl_uchar); *(sl_uchar *) mp->b_wptr = (ch->sl.statem.tx.N.fsn | ch->sl.statem.tx.N.fib); mp->b_wptr += sizeof(sl_uchar); *(sl_uchar *) mp->b_wptr = 0; mp->b_wptr += sizeof(sl_uchar); } } noinline fastcall __hot_write void sl_daedt_lssu(struct ch *ch, mblk_t *mp) { if (ch->option.popt & SS7_POPT_XSN) { *(sl_ushort *) mp->b_wptr = htons(ch->sl.statem.tx.N.bsn | ch->sl.statem.tx.N.bib); mp->b_wptr += sizeof(sl_ushort); *(sl_ushort *) mp->b_wptr = htons(ch->sl.statem.tx.N.fsn | ch->sl.statem.tx.N.fib); mp->b_wptr += sizeof(sl_ushort); *(sl_ushort *) mp->b_wptr = htons(1); mp->b_wptr += sizeof(sl_ushort); } else { *(sl_uchar *) mp->b_wptr = (ch->sl.statem.tx.N.bsn | ch->sl.statem.tx.N.bib); mp->b_wptr += sizeof(sl_uchar); *(sl_uchar *) mp->b_wptr = (ch->sl.statem.tx.N.fsn | ch->sl.statem.tx.N.fib); mp->b_wptr += sizeof(sl_uchar); *(sl_uchar *) mp->b_wptr = 1; mp->b_wptr += sizeof(sl_uchar); } *(sl_uchar *) mp->b_wptr = (ch->sl.statem.tx.sio); mp->b_wptr += sizeof(sl_uchar); } static inline fastcall __hot_write void sl_daedt_msu(struct ch *ch, mblk_t *mp) { int len = msgdsize(mp); if (ch->option.popt & SS7_POPT_XSN) { ((sl_ushort *) mp->b_rptr)[0] = htons(ch->sl.statem.tx.N.bsn | ch->sl.statem.tx.N.bib); ((sl_ushort *) mp->b_rptr)[1] = htons(ch->sl.statem.tx.N.fsn | ch->sl.statem.tx.N.fib); ((sl_ushort *) mp->b_rptr)[2] = htons(len - 6 < 512 ? len - 6 : 511); } else { ((sl_uchar *) mp->b_rptr)[0] = (ch->sl.statem.tx.N.bsn | ch->sl.statem.tx.N.bib); ((sl_uchar *) mp->b_rptr)[1] = (ch->sl.statem.tx.N.fsn | ch->sl.statem.tx.N.fib); ((sl_uchar *) mp->b_rptr)[2] = (len - 3 < 64 ? len - 3 : 63); } } static inline fastcall __hot_out mblk_t * sl_txc_transmission_request(struct ch *ch) { mblk_t *mp = NULL; int pcr; if (ch->sl.statem.txc_state != SL_STATE_IN_SERVICE) return (mp); pcr = ch->option.popt & SS7_POPT_PCR; if (ch->sl.statem.lssu_available) { if ((mp = ss7_fast_allocb(&xp_bufpool, 7, BPRI_HI))) { if (ch->sl.statem.tx.sio == LSSU_SIB) { ch->sl.stats.sl_sibs_sent++; ch->sl.statem.lssu_available = 0; } ch->sl.statem.tx.N.fsn = ch->sl.statem.tx.L.fsn; ch->sl.statem.tx.N.bib = ch->sl.statem.tx.N.bib; ch->sl.statem.tx.N.bsn = (ch->sl.statem.tx.X.fsn - 1) & ch->sl.statem.sn_mask; ch->sl.statem.tx.N.fib = ch->sl.statem.tx.N.fib; sl_daedt_lssu(ch, mp); } return (mp); } if (ch->sl.statem.msu_inhibited) { if ((mp = ss7_fast_allocb(&xp_bufpool, 6, BPRI_HI))) { ch->sl.statem.tx.N.fsn = ch->sl.statem.tx.L.fsn; ch->sl.statem.tx.N.bib = ch->sl.statem.tx.N.bib; ch->sl.statem.tx.N.bsn = (ch->sl.statem.tx.X.fsn - 1) & ch->sl.statem.sn_mask; ch->sl.statem.tx.N.fib = ch->sl.statem.tx.N.fib; sl_daedt_fisu(ch, mp); } return (mp); } if (pcr) { if ((ch->sl.rtb.q_msgs < ch->sl.config.N1) && (ch->sl.rtb.q_count < ch->sl.config.N2)) { ch->sl.statem.forced_retransmission = 0; ch->sl.statem.rtb_full = 0; } if (ch->sl.tb.q_count && ch->sl.statem.rtb_full) ch->sl.statem.forced_retransmission = 1; } if ((!pcr && ch->sl.statem.retrans_cycle) || (pcr && (ch->sl.statem.forced_retransmission || (!ch->sl.tb.q_count && ch->sl.rtb.q_count)))) { mblk_t *bp; if ((bp = ch->sl.statem.z_ptr) && !(mp = dupmsg(bp))) return (mp); if (!bp && pcr) { if ((bp = ch->sl.statem.z_ptr = ch->sl.rtb.q_head) && !(mp = dupmsg(bp))) return (mp); ch->sl.statem.Z = ch->sl.statem.tx.F.fsn; } if (mp) { ch->sl.statem.z_ptr = bp->b_next; if (pcr) { ch->sl.statem.tx.N.fsn = ch->sl.statem.Z; ch->sl.statem.tx.N.fib = ch->sl.statem.tx.N.fib; ch->sl.statem.tx.N.bsn = (ch->sl.statem.tx.X.fsn - 1) & ch->sl.statem.sn_mask; ch->sl.statem.tx.N.bib = ch->sl.statem.tx.N.bib; ch->sl.statem.Z = (ch->sl.statem.Z + 1) & ch->sl.statem.sn_mask; } else { ch->sl.statem.tx.N.fsn = (ch->sl.statem.tx.N.fsn + 1) & ch->sl.statem.sn_mask; ch->sl.statem.tx.N.fib = ch->sl.statem.tx.N.fib; ch->sl.statem.tx.N.bsn = (ch->sl.statem.tx.X.fsn - 1) & ch->sl.statem.sn_mask; ch->sl.statem.tx.N.bib = ch->sl.statem.tx.N.bib; } sl_daedt_msu(ch, mp); if (ch->sl.statem.tx.N.fsn == ch->sl.statem.tx.L.fsn || ch->sl.statem.z_ptr == NULL) ch->sl.statem.retrans_cycle = 0; } return (mp); } if ((!pcr && (!ch->sl.tb.q_count || ch->sl.statem.rtb_full)) || (pcr && (!ch->sl.tb.q_count && !ch->sl.rtb.q_count))) { if ((mp = ss7_fast_allocb(&xp_bufpool, 6, BPRI_HI))) { ch->sl.statem.tx.N.fsn = ch->sl.statem.tx.L.fsn; ch->sl.statem.tx.N.bib = ch->sl.statem.tx.N.bib; ch->sl.statem.tx.N.bsn = (ch->sl.statem.tx.X.fsn - 1) & ch->sl.statem.sn_mask; ch->sl.statem.tx.N.fib = ch->sl.statem.tx.N.fib; sl_daedt_fisu(ch, mp); } return (mp); } else { spin_lock(&ch->sl.tb.q_lock); if ((mp = bufq_head(&ch->sl.tb)) && (mp = dupmsg(mp))) { mblk_t *bp = __bufq_dequeue(&ch->sl.tb); spin_unlock(&ch->sl.tb.q_lock); ch->sl.statem.Cm--; if (!ch->sl.statem.Cm) sl_enable_rq(ch); ch->sl.statem.tx.L.fsn = (ch->sl.statem.tx.L.fsn + 1) & ch->sl.statem.sn_mask; ch->sl.statem.tx.N.fsn = ch->sl.statem.tx.L.fsn; if (!ch->sl.rtb.q_count) xp_timer_start(ch, t7); bufq_queue(&ch->sl.rtb, bp); ch->sl.statem.Ct++; sl_rc_fsnt_value(ch); if (pcr) { if ((ch->sl.rtb.q_msgs >= ch->sl.config.N1) || (ch->sl.rtb.q_count >= ch->sl.config.N2)) { ch->sl.statem.rtb_full = 1; ch->sl.statem.forced_retransmission = 1; } } else { if ((ch->sl.rtb.q_msgs >= ch->sl.config.N1) || (ch->sl.rtb.q_count >= ch->sl.config.N2) || (ch->sl.statem.tx.L.fsn == ((ch->sl.statem.tx.F.fsn - 2) & ch->sl.statem.sn_mask))) ch->sl.statem.rtb_full = 1; } ch->sl.statem.tx.N.bib = ch->sl.statem.tx.N.bib; ch->sl.statem.tx.N.bsn = (ch->sl.statem.tx.X.fsn - 1) & ch->sl.statem.sn_mask; ch->sl.statem.tx.N.fib = ch->sl.statem.tx.N.fib; sl_daedt_msu(ch, mp); } else spin_unlock(&ch->sl.tb.q_lock); return (mp); } } noinline fastcall __unlikely void sl_daedr_start(struct ch *ch) { ch->sdt.statem.daedr_state = SDT_STATE_IN_SERVICE; ch->sdl.statem.rx_state = SDL_STATE_IN_SERVICE; ch->sdl.config.ifflags |= (SDL_IF_UP | SDL_IF_RX_RUNNING); } noinline fastcall __unlikely void sl_rc_start(struct ch *ch) { if (ch->sl.statem.rc_state == SL_STATE_IDLE) { ch->sl.statem.rx.X.fsn = 0; ch->sl.statem.rx.X.fib = ch->sl.statem.ib_mask; ch->sl.statem.rx.F.fsn = 0; ch->sl.statem.rx.T.fsn = ch->sl.statem.sn_mask; ch->sl.statem.rtr = 0; /* Basic only (note 1). */ if (((ch->option.pvar & SS7_PVAR_MASK) == SS7_PVAR_ANSI) && ((ch->option.pvar & SS7_PVAR_YR) > SS7_PVAR_88)) ch->sl.statem.msu_fisu_accepted = 1; else ch->sl.statem.msu_fisu_accepted = 0; ch->sl.statem.abnormal_bsnr = 0; ch->sl.statem.abnormal_fibr = 0; /* Basic only (note 1). */ ch->sl.statem.congestion_discard = 0; ch->sl.statem.congestion_accept = 0; sl_daedr_start(ch); ch->sl.statem.rc_state = SL_STATE_IN_SERVICE; return; /* * Note 1 - Although rtr and abnormal_fibr are only applicable to the Basic procedure (and * not PCR), these state machine variables are never examined by PCR routines, so PCR and * basic can share the same start procedures. */ } } noinline fastcall void sl_rc_reject_msu_fisu(struct ch *ch) { ch->sl.statem.msu_fisu_accepted = 0; } noinline fastcall void sl_rc_accept_msu_fisu(struct ch *ch) { ch->sl.statem.msu_fisu_accepted = 1; } noinline fastcall __unlikely void sl_rc_retrieve_fsnx(struct ch *ch) { sl_txc_fsnx_value(ch); /* error in 93 spec */ ch->sl.statem.congestion_discard = 0; ch->sl.statem.congestion_accept = 0; sl_cc_normal(ch); ch->sl.statem.rtr = 0; /* basic only */ } noinline fastcall __unlikely void sl_rc_align_fsnx(struct ch *ch) { sl_txc_fsnx_value(ch); } noinline fastcall __unlikely void sl_rc_clear_rb(struct ch *ch, queue_t *q, mblk_t *mp) { bufq_purge(&ch->sl.rb); sl_flush_rq(ch); ch->sl.statem.Cr = 0; sl_rb_cleared_ind(ch, q, mp); } noinline fastcall __unlikely void sl_rc_retrieve_bsnt(struct ch *ch, queue_t *q, mblk_t *mp) { ch->sl.statem.rx.T.bsn = (ch->sl.statem.rx.X.fsn - 1) & 0x7F; sl_bsnt_ind(ch, q, mp); } noinline fastcall void sl_cc_busy(struct ch *ch) { if (ch->sl.statem.cc_state == SL_STATE_NORMAL) { sl_txc_send_sib(ch); xp_timer_start(ch, t5); ch->sl.statem.cc_state = SL_STATE_BUSY; } } noinline fastcall __unlikely void sl_rc_congestion_discard(struct ch *ch) { ch->sl.statem.congestion_discard = 1; sl_cc_busy(ch); } noinline fastcall __unlikely void sl_rc_congestion_accept(struct ch *ch) { ch->sl.statem.congestion_accept = 1; sl_cc_busy(ch); } noinline fastcall __unlikely void sl_rc_no_congestion(struct ch *ch) { ch->sl.statem.congestion_discard = 0; ch->sl.statem.congestion_accept = 0; sl_cc_normal(ch); sl_txc_fsnx_value(ch); if (ch->sl.statem.rtr == 1) { /* rtr never set for PCR */ sl_txc_nack_to_be_sent(ch); ch->sl.statem.rx.X.fib = ch->sl.statem.rx.X.fib ? 0 : ch->sl.statem.ib_mask; } } noinline fastcall __unlikely void sl_lsc_congestion_discard(struct ch *ch) { sl_rc_congestion_discard(ch); ch->sl.statem.l3_congestion_detect = 1; } noinline fastcall __unlikely void sl_lsc_congestion_accept(struct ch *ch) { sl_rc_congestion_accept(ch); ch->sl.statem.l3_congestion_detect = 1; } noinline fastcall __unlikely void sl_lsc_no_congestion(struct ch *ch) { sl_rc_no_congestion(ch); ch->sl.statem.l3_congestion_detect = 0; } noinline fastcall void sl_lsc_sio(struct ch *ch) { switch (ch->sl.statem.lsc_state) { case SL_STATE_OUT_OF_SERVICE: case SL_STATE_INITIAL_ALIGNMENT: break; default: xp_timer_stop(ch, t1); /* ok if not running */ ch->sl.statem.failure_reason = SL_FAIL_RECEIVED_SIO; sl_out_of_service_ind(ch); sl_rc_stop(ch); sl_suerm_stop(ch); sl_poc_stop(ch); /* ok if ANSI */ sl_txc_send_sios(ch); ch->sl.statem.emergency = 0; /* FIXME: reinspect */ ch->sl.statem.local_processor_outage = 0; ch->sl.statem.remote_processor_outage = 0; /* ok if ITUT */ ch->sl.statem.lsc_state = SL_STATE_OUT_OF_SERVICE; break; } } noinline fastcall void sl_lsc_alignment_not_possible(struct ch *ch) { ch->sl.statem.failure_reason = SL_FAIL_ALIGNMENT_NOT_POSSIBLE; sl_out_of_service_ind(ch); sl_rc_stop(ch); sl_txc_send_sios(ch); ch->sl.statem.local_processor_outage = 0; ch->sl.statem.emergency = 0; ch->sl.statem.lsc_state = SL_STATE_OUT_OF_SERVICE; ch->sl.stats.sl_fail_align_or_proving++; } noinline fastcall void sl_iac_sio(struct ch *ch) { switch (ch->sl.statem.iac_state) { case SL_STATE_NOT_ALIGNED: xp_timer_stop(ch, t2); if (ch->sl.statem.emergency) { ch->sl.statem.t4v = ch->sl.config.t4e; printd(("Sending SIE at %lu\n", jiffies)); sl_txc_send_sie(ch); } else { ch->sl.statem.t4v = ch->sl.config.t4n; sl_txc_send_sin(ch); } xp_timer_start(ch, t3); ch->sl.statem.iac_state = SL_STATE_ALIGNED; break; case SL_STATE_PROVING: xp_timer_stop(ch, t4); sl_aerm_stop(ch); xp_timer_start(ch, t3); ch->sl.statem.iac_state = SL_STATE_ALIGNED; break; } } noinline fastcall void sl_iac_sios(struct ch *ch) { switch (ch->sl.statem.iac_state) { case SL_STATE_ALIGNED: case SL_STATE_PROVING: xp_timer_stop(ch, t4); /* ok if not running */ sl_lsc_alignment_not_possible(ch); sl_aerm_stop(ch); /* ok if not running */ xp_timer_stop(ch, t3); /* ok if not running */ ch->sl.statem.emergency = 0; ch->sl.statem.iac_state = SL_STATE_IDLE; break; } } noinline fastcall void sl_lsc_sios(struct ch *ch) { switch (ch->sl.statem.lsc_state) { case SL_STATE_ALIGNED_READY: case SL_STATE_ALIGNED_NOT_READY: xp_timer_stop(ch, t1); /* ok to stop if not running */ case SL_STATE_IN_SERVICE: case SL_STATE_PROCESSOR_OUTAGE: ch->sl.statem.failure_reason = SL_FAIL_RECEIVED_SIOS; sl_out_of_service_ind(ch); sl_suerm_stop(ch); /* ok to stop if not running */ sl_rc_stop(ch); sl_poc_stop(ch); /* ok if ANSI */ sl_txc_send_sios(ch); ch->sl.statem.emergency = 0; ch->sl.statem.local_processor_outage = 0; ch->sl.statem.remote_processor_outage = 0; /* ok if ITU */ ch->sl.statem.lsc_state = SL_STATE_OUT_OF_SERVICE; break; } } noinline fastcall __unlikely void sl_lsc_no_processor_outage(struct ch *ch) { if (ch->sl.statem.lsc_state == SL_STATE_PROCESSOR_OUTAGE) { ch->sl.statem.processor_outage = 0; if (!ch->sl.statem.l3_indication_received) { return; } ch->sl.statem.l3_indication_received = 0; sl_txc_send_msu(ch); ch->sl.statem.local_processor_outage = 0; sl_rc_accept_msu_fisu(ch); ch->sl.statem.lsc_state = SL_STATE_IN_SERVICE; } } noinline fastcall __unlikely void sl_poc_remote_processor_recovered(struct ch *ch) { switch (ch->sl.statem.poc_state) { case SL_STATE_REMOTE_PROCESSOR_OUTAGE: /* Indication moved from caller to remove spurious remote processor recovered indications. */ sl_remote_processor_recovered_ind(ch); sl_lsc_no_processor_outage(ch); ch->sl.statem.poc_state = SL_STATE_IDLE; break; case SL_STATE_BOTH_PROCESSORS_OUT: /* Indication moved from caller to remove spurious remote processor recovered indications. */ sl_remote_processor_recovered_ind(ch); ch->sl.statem.poc_state = SL_STATE_LOCAL_PROCESSOR_OUTAGE; break; } } noinline fastcall void sl_lsc_fisu_msu_received(struct ch *ch) { switch (ch->sl.statem.lsc_state) { case SL_STATE_ALIGNED_READY: ch->sl.statem.failure_reason = 0; sl_in_service_ind(ch); if (ch->option.pvar == SS7_PVAR_ITUT_93) sl_rc_accept_msu_fisu(ch); /* unnecessary */ xp_timer_stop(ch, t1); sl_txc_send_msu(ch); ch->sl.statem.lsc_state = SL_STATE_IN_SERVICE; break; case SL_STATE_ALIGNED_NOT_READY: ch->sl.statem.failure_reason = 0; sl_in_service_ind(ch); xp_timer_stop(ch, t1); ch->sl.statem.lsc_state = SL_STATE_PROCESSOR_OUTAGE; break; case SL_STATE_PROCESSOR_OUTAGE: if (((ch->option.pvar & SS7_PVAR_MASK) == SS7_PVAR_ANSI) && ((ch->option.pvar & SS7_PVAR_YR) > SS7_PVAR_88)) { /* * A deviation from the SDLs has been placed here to limit the number of remote * processor recovered indications which are delivered to L3. One indication is * sufficient. */ if (ch->sl.statem.remote_processor_outage) { sl_remote_processor_recovered_ind(ch); ch->sl.statem.remote_processor_outage = 0; } } else { sl_poc_remote_processor_recovered(ch); } break; } } noinline fastcall __unlikely void sl_poc_remote_processor_outage(struct ch *ch) { switch (ch->sl.statem.poc_state) { case SL_STATE_IDLE: /* Moved here from caller to limit the number of remote processor outage indications delivered to L3. */ sl_remote_processor_outage_ind(ch, NULL, NULL); ch->sl.statem.poc_state = SL_STATE_REMOTE_PROCESSOR_OUTAGE; break; case SL_STATE_LOCAL_PROCESSOR_OUTAGE: /* Moved here from caller to limit the number of remote processor outage indications delivered to L3. */ sl_remote_processor_outage_ind(ch, NULL, NULL); ch->sl.statem.poc_state = SL_STATE_BOTH_PROCESSORS_OUT; break; } } noinline fastcall __unlikely void sl_lsc_sib(struct ch *ch) { switch (ch->sl.statem.lsc_state) { case SL_STATE_IN_SERVICE: case SL_STATE_PROCESSOR_OUTAGE: sl_txc_sib_received(ch); break; } } noinline fastcall __unlikely void sl_lsc_sipo(struct ch *ch) { switch (ch->sl.statem.lsc_state) { case SL_STATE_ALIGNED_READY: if (((ch->option.pvar & SS7_PVAR_MASK) == SS7_PVAR_ANSI) && ((ch->option.pvar & SS7_PVAR_YR) > SS7_PVAR_88)) { xp_timer_stop(ch, t1); sl_remote_processor_outage_ind(ch, NULL, NULL); ch->sl.statem.remote_processor_outage = 1; ch->sl.statem.lsc_state = SL_STATE_PROCESSOR_OUTAGE; } else { xp_timer_stop(ch, t1); sl_poc_remote_processor_outage(ch); ch->sl.statem.lsc_state = SL_STATE_PROCESSOR_OUTAGE; } break; case SL_STATE_ALIGNED_NOT_READY: if (((ch->option.pvar & SS7_PVAR_MASK) == SS7_PVAR_ANSI) && ((ch->option.pvar & SS7_PVAR_YR) > SS7_PVAR_88)) { sl_remote_processor_outage_ind(ch, NULL, NULL); ch->sl.statem.remote_processor_outage = 1; xp_timer_stop(ch, t1); ch->sl.statem.lsc_state = SL_STATE_PROCESSOR_OUTAGE; } else { sl_poc_remote_processor_outage(ch); xp_timer_stop(ch, t1); ch->sl.statem.lsc_state = SL_STATE_PROCESSOR_OUTAGE; } break; case SL_STATE_IN_SERVICE: if (((ch->option.pvar & SS7_PVAR_MASK) == SS7_PVAR_ANSI) && ((ch->option.pvar & SS7_PVAR_YR) > SS7_PVAR_88)) { sl_txc_send_fisu(ch); sl_remote_processor_outage_ind(ch, NULL, NULL); ch->sl.statem.remote_processor_outage = 1; sl_rc_align_fsnx(ch); sl_cc_stop(ch); ch->sl.statem.lsc_state = SL_STATE_PROCESSOR_OUTAGE; } else { sl_txc_send_fisu(ch); sl_poc_remote_processor_outage(ch); ch->sl.statem.processor_outage = 1; /* remote? */ ch->sl.statem.lsc_state = SL_STATE_PROCESSOR_OUTAGE; } break; case SL_STATE_PROCESSOR_OUTAGE: if (((ch->option.pvar & SS7_PVAR_MASK) == SS7_PVAR_ANSI) && ((ch->option.pvar & SS7_PVAR_YR) > SS7_PVAR_88)) { #if 0 ch->sl.statem.remote_processor_outage = 1; sl_remote_processor_outage_ind(ch, NULL, NULL); #else /* * A deviation from the SDLs has been placed here to limit the number of * remote processor outage indications which are delivered to L3. One * indication is sufficient. */ if (!ch->sl.statem.remote_processor_outage) { ch->sl.statem.remote_processor_outage = 1; sl_remote_processor_outage_ind(ch, NULL, NULL); } #endif } else { sl_poc_remote_processor_outage(ch); } break; } } noinline fastcall __unlikely void sl_poc_local_processor_outage(struct ch *ch) { switch (ch->sl.statem.poc_state) { case SL_STATE_IDLE: ch->sl.statem.poc_state = SL_STATE_LOCAL_PROCESSOR_OUTAGE; return; case SL_STATE_REMOTE_PROCESSOR_OUTAGE: ch->sl.statem.poc_state = SL_STATE_BOTH_PROCESSORS_OUT; return; } } noinline fastcall __unlikely void sl_eim_start(struct ch *ch) { ch->sdt.statem.Ce = 0; ch->sdt.statem.interval_error = 0; ch->sdt.statem.su_received = 0; xp_timer_start(ch, t8); ch->sdt.statem.eim_state = SDT_STATE_MONITORING; } noinline fastcall __unlikely void sl_suerm_start(struct ch *ch) { if (ch->option.popt & SS7_POPT_HSL) sl_eim_start(ch); else { ch->sdt.statem.Cs = 0; ch->sdt.statem.Ns = 0; ch->sdt.statem.suerm_state = SDT_STATE_IN_SERVICE; } } noinline fastcall __unlikely void sl_lsc_alignment_complete(struct ch *ch) { if (ch->sl.statem.lsc_state == SL_STATE_INITIAL_ALIGNMENT) { sl_suerm_start(ch); xp_timer_start(ch, t1); if (ch->sl.statem.local_processor_outage) { if (((ch->option.pvar & SS7_PVAR_MASK) != SS7_PVAR_ANSI) || ((ch->option.pvar & SS7_PVAR_YR) <= SS7_PVAR_88)) sl_poc_local_processor_outage(ch); sl_txc_send_sipo(ch); if (ch->option.pvar != SS7_PVAR_ITUT_93) /* possible error */ sl_rc_reject_msu_fisu(ch); ch->sl.statem.lsc_state = SL_STATE_ALIGNED_NOT_READY; } else { sl_txc_send_msu(ch); /* changed from send_fisu for Q.781 */ sl_rc_accept_msu_fisu(ch); /* error in ANSI spec? */ ch->sl.statem.lsc_state = SL_STATE_ALIGNED_READY; } } } noinline fastcall void sl_lsc_sin(struct ch *ch) { switch (ch->sl.statem.lsc_state) { case SL_STATE_IN_SERVICE: ch->sl.statem.failure_reason = SL_FAIL_RECEIVED_SIN; sl_out_of_service_ind(ch); sl_suerm_stop(ch); sl_rc_stop(ch); sl_txc_send_sios(ch); ch->sl.statem.emergency = 0; ch->sl.statem.lsc_state = SL_STATE_OUT_OF_SERVICE; break; case SL_STATE_PROCESSOR_OUTAGE: ch->sl.statem.failure_reason = SL_FAIL_RECEIVED_SIN; sl_out_of_service_ind(ch); sl_suerm_stop(ch); sl_rc_stop(ch); sl_poc_stop(ch); /* ok if not ITUT */ sl_txc_send_sios(ch); ch->sl.statem.emergency = 0; ch->sl.statem.local_processor_outage = 0; ch->sl.statem.remote_processor_outage = 0; /* ok if not ANSI */ ch->sl.statem.lsc_state = SL_STATE_OUT_OF_SERVICE; break; } } noinline fastcall __unlikely void sl_aerm_set_ti_to_tie(struct ch *ch) { if (ch->sdt.statem.aerm_state == SDT_STATE_IDLE) ch->sdt.statem.Ti = ch->sdt.config.Tie; } noinline fastcall __unlikely void sl_aerm_start(struct ch *ch) { ch->sdt.statem.Ca = 0; ch->sdt.statem.aborted_proving = 0; ch->sdt.statem.aerm_state = SDT_STATE_MONITORING; } noinline fastcall void sl_iac_sin(struct ch *ch) { switch (ch->sl.statem.iac_state) { case SL_STATE_NOT_ALIGNED: xp_timer_stop(ch, t2); if (ch->sl.statem.emergency) { ch->sl.statem.t4v = ch->sl.config.t4e; sl_txc_send_sie(ch); } else { ch->sl.statem.t4v = ch->sl.config.t4n; sl_txc_send_sin(ch); } xp_timer_start(ch, t3); ch->sl.statem.iac_state = SL_STATE_ALIGNED; return; case SL_STATE_ALIGNED: xp_timer_stop(ch, t3); if (ch->sl.statem.t4v == ch->sl.config.t4e) sl_aerm_set_ti_to_tie(ch); sl_aerm_start(ch); xp_timer_start(ch, t4); ch->sl.statem.further_proving = 0; ch->sl.statem.Cp = 0; ch->sl.statem.iac_state = SL_STATE_PROVING; return; } } noinline fastcall void sl_lsc_sie(struct ch *ch) { switch (ch->sl.statem.lsc_state) { case SL_STATE_IN_SERVICE: ch->sl.statem.failure_reason = SL_FAIL_RECEIVED_SIE; sl_out_of_service_ind(ch); sl_suerm_stop(ch); sl_rc_stop(ch); sl_txc_send_sios(ch); ch->sl.statem.emergency = 0; ch->sl.statem.lsc_state = SL_STATE_OUT_OF_SERVICE; break; case SL_STATE_PROCESSOR_OUTAGE: ch->sl.statem.failure_reason = SL_FAIL_RECEIVED_SIE; sl_out_of_service_ind(ch); sl_suerm_stop(ch); sl_rc_stop(ch); sl_poc_stop(ch); /* ok if not ITUT */ sl_txc_send_sios(ch); ch->sl.statem.emergency = 0; ch->sl.statem.local_processor_outage = 0; ch->sl.statem.remote_processor_outage = 0; /* ok if not ANSI */ ch->sl.statem.lsc_state = SL_STATE_OUT_OF_SERVICE; break; } } noinline fastcall void sl_iac_sie(struct ch *ch) { switch (ch->sl.statem.iac_state) { case SL_STATE_NOT_ALIGNED: xp_timer_stop(ch, t2); if (ch->sl.statem.emergency) { ch->sl.statem.t4v = ch->sl.config.t4e; sl_txc_send_sie(ch); } else { ch->sl.statem.t4v = ch->sl.config.t4e; /* yes e */ sl_txc_send_sin(ch); } xp_timer_start(ch, t3); ch->sl.statem.iac_state = SL_STATE_ALIGNED; return; case SL_STATE_ALIGNED: printd(("Receiving SIE at %lu\n", jiffies)); ch->sl.statem.t4v = ch->sl.config.t4e; xp_timer_stop(ch, t3); sl_aerm_set_ti_to_tie(ch); sl_aerm_start(ch); xp_timer_start(ch, t4); ch->sl.statem.further_proving = 0; ch->sl.statem.Cp = 0; ch->sl.statem.iac_state = SL_STATE_PROVING; return; case SL_STATE_PROVING: if (ch->sl.statem.t4v == ch->sl.config.t4e) return; xp_timer_stop(ch, t4); ch->sl.statem.t4v = ch->sl.config.t4e; sl_aerm_stop(ch); sl_aerm_set_ti_to_tie(ch); sl_aerm_start(ch); xp_timer_start(ch, t4); ch->sl.statem.further_proving = 0; return; } } /* * -------------------------------------------------------------------------- * * These congestion functions are implementation dependent. We should define a congestion onset * level and set congestion accept at that point. We should also define a second congestion onset * level and set congestion discard at that point. For STREAMS, the upstream congestion can be * detected in two ways: 1) canputnext(): is the upstream module flow controlled; and, 2) canput(): * are we flow controlled. If the upstream module is flow controlled, then we can accept MSUs and * place them on our own read queue. If we are flow contolled, then we have no choice but to * discard the message. In addition, and because upstream message processing times are likely more * sensitive to the number of backlogged messages than they are to the number of backlogged message * octets, we have some configurable thresholds of backlogging and keep track of backlogged * messages. * * -------------------------------------------------------------------------- */ static inline fastcall __hot void sl_rb_congestion_function(struct ch *ch) { if (!ch->sl.statem.l3_congestion_detect) { struct xp *xp = ch->xp; if (ch->sl.statem.l2_congestion_detect) { if (ch->sl.statem.Cr <= ch->sl.config.rb_abate && (!xp || canputnext(xp->rq))) { sl_rc_no_congestion(ch); ch->sl.statem.l2_congestion_detect = 0; } } else { if (ch->sl.statem.Cr >= ch->sl.config.rb_discard || (xp && !canput(xp->rq))) { sl_rc_congestion_discard(ch); ch->sl.statem.l2_congestion_detect = 1; } else if (ch->sl.statem.Cr >= ch->sl.config.rb_accept || (xp && !canputnext(xp->rq))) { sl_rc_congestion_accept(ch); ch->sl.statem.l2_congestion_detect = 1; } } } } static inline fastcall __hot_in void sl_rc_signal_unit(struct ch *ch, mblk_t *mp) { int pcr = ch->option.popt & SS7_POPT_PCR; if (ch->sl.statem.rc_state != SL_STATE_IN_SERVICE) { freemsg(mp); return; } /* Note: the driver must check that the length of the frame is within appropriate bounds as specified by the DAEDR in Q.703. If the length of the frame is incorrect, it should indicate daedr_error_frame rather than daedr_received_frame. */ if (ch->option.popt & SS7_POPT_XSN) { ch->sl.statem.rx.R.bsn = ntohs(*((sl_ushort *) mp->b_rptr)) & 0x0fff; ch->sl.statem.rx.R.bib = ntohs(*(sl_ushort *) mp->b_rptr++) & 0x8000; ch->sl.statem.rx.R.fsn = ntohs(*((sl_ushort *) mp->b_rptr)) & 0x0fff; ch->sl.statem.rx.R.fib = ntohs(*(sl_ushort *) mp->b_rptr++) & 0x8000; ch->sl.statem.rx.len = ntohs(*(sl_ushort *) mp->b_rptr++) & 0x01ff; } else { ch->sl.statem.rx.R.bsn = *mp->b_rptr & 0x7f; ch->sl.statem.rx.R.bib = *mp->b_rptr++ & 0x80; ch->sl.statem.rx.R.fsn = *mp->b_rptr & 0x7f; ch->sl.statem.rx.R.fib = *mp->b_rptr++ & 0x80; ch->sl.statem.rx.len = *mp->b_rptr++ & 0x3f; } if (ch->sl.statem.rx.len == 1) { ch->sl.statem.rx.sio = *mp->b_rptr++ & 0x07; } if (ch->sl.statem.rx.len == 2) { ch->sl.statem.rx.sio = *mp->b_rptr++ & 0x07; ch->sl.statem.rx.sio = *mp->b_rptr++ & 0x07; } #if 0 ptrace(("rx: bsn=%x, bib=%x, fsn=%x, fib=%x, len=%d, sio=%d\n", ch->sl.statem.rx.R.bsn, ch->sl.statem.rx.R.bib, ch->sl.statem.rx.R.fsn, ch->sl.statem.rx.R.fib, ch->sl.statem.rx.len, ch->sl.statem.rx.sio)); #endif if (((ch->sl.statem.rx.len) == 1) || ((ch->sl.statem.rx.len) == 2)) { switch (ch->sl.statem.rx.sio) { case LSSU_SIO:{ sl_iac_sio(ch); sl_lsc_sio(ch); break; } case LSSU_SIN:{ sl_iac_sin(ch); sl_lsc_sin(ch); break; } case LSSU_SIE:{ sl_iac_sie(ch); sl_lsc_sie(ch); break; } case LSSU_SIOS:{ sl_iac_sios(ch); sl_lsc_sios(ch); break; } case LSSU_SIPO:{ sl_lsc_sipo(ch); break; } case LSSU_SIB:{ sl_lsc_sib(ch); break; } } freemsg(mp); return; } if (SN_OUTSIDE (((ch->sl.statem.rx.F.fsn - 1) & ch->sl.statem.sn_mask), ch->sl.statem.rx.R.bsn, ch->sl.statem.rx.T.fsn)) { if (ch->sl.statem.abnormal_bsnr) { sl_lsc_link_failure(ch, SL_FAIL_ABNORMAL_BSNR); ch->sl.statem.rc_state = SL_STATE_IDLE; freemsg(mp); return; } else { ch->sl.statem.abnormal_bsnr = 1; ch->sl.statem.unb = 0; freemsg(mp); return; } } if (ch->sl.statem.abnormal_bsnr) { if (ch->sl.statem.unb == 1) { ch->sl.statem.abnormal_bsnr = 0; } else { ch->sl.statem.unb = 1; freemsg(mp); return; } } if (pcr) { sl_lsc_fisu_msu_received(ch); sl_txc_bsnr_and_bibr(ch); ch->sl.statem.rx.F.fsn = (ch->sl.statem.rx.R.bsn + 1) & ch->sl.statem.sn_mask; if (!ch->sl.statem.msu_fisu_accepted) { freemsg(mp); return; } sl_rb_congestion_function(ch); if (ch->sl.statem.congestion_discard) { sl_cc_busy(ch); freemsg(mp); return; } if ((ch->sl.statem.rx.R.fsn == ch->sl.statem.rx.X.fsn) && (ch->sl.statem.rx.len > 2)) { if (sl_pdu_ind(ch, mp) == 0) { ch->sl.statem.rx.X.fsn = (ch->sl.statem.rx.X.fsn + 1) & ch->sl.statem.sn_mask; ch->sl.statem.Cr++; if (ch->sl.statem.congestion_accept) sl_cc_busy(ch); else sl_txc_fsnx_value(ch); } else { /* same as congestion discard */ sl_cc_busy(ch); freemsg(mp); } return; } else { freemsg(mp); return; } return; } if (ch->sl.statem.rx.R.fib == ch->sl.statem.rx.X.fib) { if (ch->sl.statem.abnormal_fibr) { if (ch->sl.statem.unf == 1) { ch->sl.statem.abnormal_fibr = 0; } else { ch->sl.statem.unf = 1; freemsg(mp); return; } } sl_lsc_fisu_msu_received(ch); sl_txc_bsnr_and_bibr(ch); ch->sl.statem.rx.F.fsn = (ch->sl.statem.rx.R.bsn + 1) & ch->sl.statem.sn_mask; if (!ch->sl.statem.msu_fisu_accepted) { freemsg(mp); return; } sl_rb_congestion_function(ch); if (ch->sl.statem.congestion_discard) { ch->sl.statem.rtr = 1; freemsg(mp); sl_cc_busy(ch); return; } if ((ch->sl.statem.rx.R.fsn == ch->sl.statem.rx.X.fsn) && (ch->sl.statem.rx.len > 2)) { if (sl_pdu_ind(ch, mp) == 0) { ch->sl.statem.rx.X.fsn = (ch->sl.statem.rx.X.fsn + 1) & ch->sl.statem.sn_mask; ch->sl.statem.rtr = 0; ch->sl.statem.Cr++; if (ch->sl.statem.congestion_accept) sl_cc_busy(ch); else sl_txc_fsnx_value(ch); } else { /* same as congestion discard */ ch->sl.statem.rtr = 1; freemsg(mp); sl_cc_busy(ch); } return; } if ((ch->sl.statem.rx.R.fsn == ((ch->sl.statem.rx.X.fsn - 1) & ch->sl.statem.sn_mask))) { freemsg(mp); return; } else { if (ch->sl.statem.congestion_accept) { ch->sl.statem.rtr = 1; sl_cc_busy(ch); /* not required? */ freemsg(mp); return; } else { sl_txc_nack_to_be_sent(ch); ch->sl.statem.rtr = 1; ch->sl.statem.rx.X.fib = ch->sl.statem.rx.X.fib ? 0 : ch->sl.statem.ib_mask; freemsg(mp); return; } } } else { if (ch->sl.statem.abnormal_fibr) { sl_lsc_link_failure(ch, SL_FAIL_ABNORMAL_FIBR); freemsg(mp); return; } if (ch->sl.statem.rtr == 1) { ch->sl.stats.sl_nacks_received++; sl_txc_bsnr_and_bibr(ch); ch->sl.statem.rx.F.fsn = (ch->sl.statem.rx.R.bsn + 1) & ch->sl.statem.sn_mask; freemsg(mp); return; } ch->sl.statem.abnormal_fibr = 1; ch->sl.statem.unf = 0; freemsg(mp); return; } } noinline fastcall __unlikely void sl_lsc_stop(struct ch *ch) { if (ch->sl.statem.lsc_state != SL_STATE_OUT_OF_SERVICE) { sl_iac_stop(ch); /* ok if not running */ xp_timer_stop(ch, t1); /* ok if not running */ sl_rc_stop(ch); sl_suerm_stop(ch); /* ok if not running */ sl_poc_stop(ch); /* ok if not running or not ITUT */ sl_txc_send_sios(ch); ch->sl.statem.emergency = 0; ch->sl.statem.local_processor_outage = 0; ch->sl.statem.remote_processor_outage = 0; /* ok of not ANSI */ ch->sl.statem.lsc_state = SL_STATE_OUT_OF_SERVICE; } } noinline fastcall __unlikely void sl_lsc_clear_rtb(struct ch *ch, queue_t *q, mblk_t *mp) { if (ch->sl.statem.lsc_state == SL_STATE_PROCESSOR_OUTAGE) { ch->sl.statem.local_processor_outage = 0; sl_txc_send_fisu(ch); sl_txc_clear_rtb(ch, q, mp); } else freemsg(mp); } noinline fastcall void sl_iac_correct_su(struct ch *ch) { if (ch->sl.statem.iac_state == SL_STATE_PROVING) { if (ch->sl.statem.further_proving) { xp_timer_stop(ch, t4); sl_aerm_start(ch); xp_timer_start(ch, t4); ch->sl.statem.further_proving = 0; } } } noinline fastcall __unlikely void sl_iac_abort_proving(struct ch *ch) { if (ch->sl.statem.iac_state == SL_STATE_PROVING) { ch->sl.statem.Cp++; if (ch->sl.statem.Cp == ch->sl.config.M) { sl_lsc_alignment_not_possible(ch); xp_timer_stop(ch, t4); sl_aerm_stop(ch); ch->sl.statem.emergency = 0; ch->sl.statem.iac_state = SL_STATE_IDLE; return; } ch->sl.statem.further_proving = 1; } } #define sl_lsc_flush_buffers sl_lsc_clear_buffers noinline fastcall __unlikely void sl_lsc_clear_buffers(struct ch *ch, queue_t *q, mblk_t *mp) { switch (ch->sl.statem.lsc_state) { case SL_STATE_OUT_OF_SERVICE: if (((ch->option.pvar & SS7_PVAR_MASK) == SS7_PVAR_ANSI) && ((ch->option.pvar & SS7_PVAR_YR) > SS7_PVAR_88)) { sl_rtb_cleared_ind(ch, q, mp); ch->sl.statem.local_processor_outage = 0; /* ??? */ } break; case SL_STATE_INITIAL_ALIGNMENT: if (((ch->option.pvar & SS7_PVAR_MASK) == SS7_PVAR_ANSI) && ((ch->option.pvar & SS7_PVAR_YR) > SS7_PVAR_88)) { sl_rtb_cleared_ind(ch, q, mp); ch->sl.statem.local_processor_outage = 0; } break; case SL_STATE_ALIGNED_NOT_READY: if (((ch->option.pvar & SS7_PVAR_MASK) == SS7_PVAR_ANSI) && ((ch->option.pvar & SS7_PVAR_YR) > SS7_PVAR_88)) { sl_rtb_cleared_ind(ch, q, mp); ch->sl.statem.local_processor_outage = 0; sl_txc_send_fisu(ch); ch->sl.statem.lsc_state = SL_STATE_ALIGNED_READY; } break; case SL_STATE_PROCESSOR_OUTAGE: if (((ch->option.pvar & SS7_PVAR_MASK) == SS7_PVAR_ANSI) && ((ch->option.pvar & SS7_PVAR_YR) > SS7_PVAR_88)) { ch->sl.statem.local_processor_outage = 0; sl_rc_clear_rb(ch, q, mp); sl_rc_accept_msu_fisu(ch); sl_txc_send_fisu(ch); sl_txc_clear_tb(ch, q, NULL); sl_txc_clear_rtb(ch, q, NULL); } else { sl_txc_flush_buffers(ch); ch->sl.statem.l3_indication_received = 1; if (ch->sl.statem.processor_outage) return; ch->sl.statem.l3_indication_received = 0; sl_txc_send_msu(ch); ch->sl.statem.local_processor_outage = 0; sl_rc_accept_msu_fisu(ch); ch->sl.statem.lsc_state = SL_STATE_IN_SERVICE; } break; default: freemsg(mp); break; } } noinline fastcall __unlikely void sl_lsc_continue(struct ch *ch) { if (ch->sl.statem.lsc_state == SL_STATE_PROCESSOR_OUTAGE) { ch->sl.statem.l3_indication_received = 1; if (ch->sl.statem.processor_outage) { return; } ch->sl.statem.l3_indication_received = 0; sl_txc_send_msu(ch); ch->sl.statem.local_processor_outage = 0; sl_rc_accept_msu_fisu(ch); ch->sl.statem.lsc_state = SL_STATE_IN_SERVICE; } } noinline fastcall __unlikely void sl_poc_local_processor_recovered(struct ch *ch) { switch (ch->sl.statem.poc_state) { case SL_STATE_LOCAL_PROCESSOR_OUTAGE: sl_lsc_no_processor_outage(ch); ch->sl.statem.poc_state = SL_STATE_IDLE; return; case SL_STATE_BOTH_PROCESSORS_OUT: ch->sl.statem.poc_state = SL_STATE_REMOTE_PROCESSOR_OUTAGE; return; } } #define sl_lsc_resume sl_lsc_local_processor_recovered noinline fastcall __unlikely int sl_lsc_local_processor_recovered(struct ch *ch, queue_t *q, mblk_t *mp) { switch (ch->sl.statem.lsc_state) { case SL_STATE_OUT_OF_SERVICE: ch->sl.statem.local_processor_outage = 0; break; case SL_STATE_INITIAL_ALIGNMENT: ch->sl.statem.local_processor_outage = 0; break; case SL_STATE_ALIGNED_READY: break; case SL_STATE_ALIGNED_NOT_READY: if (((ch->option.pvar & SS7_PVAR_MASK) != SS7_PVAR_ANSI) || ((ch->option.pvar & SS7_PVAR_YR) <= SS7_PVAR_88)) sl_poc_local_processor_recovered(ch); ch->sl.statem.local_processor_outage = 0; sl_txc_send_fisu(ch); if (ch->option.pvar == SS7_PVAR_ITUT_96) sl_rc_accept_msu_fisu(ch); ch->sl.statem.lsc_state = SL_STATE_ALIGNED_READY; break; case SL_STATE_PROCESSOR_OUTAGE: if (((ch->option.pvar & SS7_PVAR_MASK) != SS7_PVAR_ANSI) || ((ch->option.pvar & SS7_PVAR_YR) <= SS7_PVAR_88)) { sl_poc_local_processor_recovered(ch); sl_rc_retrieve_fsnx(ch); if (ch->sl.statem.poc_state != SL_STATE_IDLE) sl_txc_send_fisu(ch); /* note 3: in fisu BSN <= FSNX-1 */ // ch->sl.statem.lsc_state = SL_STATE_IN_SERVICE; } else { ch->sl.statem.local_processor_outage = 0; sl_rc_accept_msu_fisu(ch); if (ch->sl.statem.remote_processor_outage) { sl_txc_send_fisu(ch); return sl_remote_processor_outage_ind(ch, q, mp); } sl_txc_send_msu(ch); ch->sl.statem.lsc_state = SL_STATE_IN_SERVICE; } break; } freemsg(mp); return (0); } #define sl_lsc_level_3_failure sl_lsc_local_processor_outage noinline fastcall __unlikely void sl_lsc_local_processor_outage(struct ch *ch) { switch (ch->sl.statem.lsc_state) { case SL_STATE_OUT_OF_SERVICE: case SL_STATE_INITIAL_ALIGNMENT: ch->sl.statem.local_processor_outage = 1; return; case SL_STATE_ALIGNED_READY: if (((ch->option.pvar & SS7_PVAR_MASK) == SS7_PVAR_ANSI) && ((ch->option.pvar & SS7_PVAR_YR) > SS7_PVAR_88)) ch->sl.statem.local_processor_outage = 1; else sl_poc_local_processor_outage(ch); sl_txc_send_sipo(ch); if (ch->option.pvar != SS7_PVAR_ITUT_93) /* possible error 93 specs */ sl_rc_reject_msu_fisu(ch); ch->sl.statem.lsc_state = SL_STATE_ALIGNED_NOT_READY; return; case SL_STATE_IN_SERVICE: if (((ch->option.pvar & SS7_PVAR_MASK) == SS7_PVAR_ANSI) && ((ch->option.pvar & SS7_PVAR_YR) > SS7_PVAR_88)) { ch->sl.statem.local_processor_outage = 1; } else { sl_poc_local_processor_outage(ch); ch->sl.statem.processor_outage = 1; } sl_txc_send_sipo(ch); sl_rc_reject_msu_fisu(ch); if (((ch->option.pvar & SS7_PVAR_MASK) == SS7_PVAR_ANSI) && ((ch->option.pvar & SS7_PVAR_YR) > SS7_PVAR_88)) { sl_rc_align_fsnx(ch); sl_cc_stop(ch); } ch->sl.statem.lsc_state = SL_STATE_PROCESSOR_OUTAGE; return; case SL_STATE_PROCESSOR_OUTAGE: if (((ch->option.pvar & SS7_PVAR_MASK) == SS7_PVAR_ANSI) && ((ch->option.pvar & SS7_PVAR_YR) > SS7_PVAR_88)) ch->sl.statem.local_processor_outage = 1; else sl_poc_local_processor_outage(ch); sl_txc_send_sipo(ch); return; } } noinline fastcall __unlikely void sl_iac_emergency(struct ch *ch) { switch (ch->sl.statem.iac_state) { case SL_STATE_PROVING: sl_txc_send_sie(ch); xp_timer_stop(ch, t4); ch->sl.statem.t4v = ch->sl.config.t4e; sl_aerm_stop(ch); sl_aerm_set_ti_to_tie(ch); sl_aerm_start(ch); xp_timer_start(ch, t4); ch->sl.statem.further_proving = 0; return; case SL_STATE_ALIGNED: sl_txc_send_sie(ch); ch->sl.statem.t4v = ch->sl.config.t4e; return; case SL_STATE_IDLE: case SL_STATE_NOT_ALIGNED: ch->sl.statem.emergency = 1; } } noinline fastcall __unlikely void sl_lsc_emergency(struct ch *ch) { ch->sl.statem.emergency = 1; sl_iac_emergency(ch); /* added to pass Q.781/Test 1.20 */ } noinline fastcall __unlikely void sl_lsc_emergency_ceases(struct ch *ch) { ch->sl.statem.emergency = 0; } noinline fastcall __unlikely void sl_iac_start(struct ch *ch) { if (ch->sl.statem.iac_state == SL_STATE_IDLE) { sl_txc_send_sio(ch); xp_timer_start(ch, t2); ch->sl.statem.iac_state = SL_STATE_NOT_ALIGNED; } } noinline fastcall __unlikely void sl_daedt_start(struct ch *ch) { ch->sdt.statem.daedt_state = SDT_STATE_IN_SERVICE; ch->sdl.statem.tx_state = SDL_STATE_IN_SERVICE; ch->sdl.config.ifflags |= (SDL_IF_UP | SDL_IF_TX_RUNNING); } noinline fastcall __unlikely void sl_txc_start(struct ch *ch) { ch->sl.statem.forced_retransmission = 0; /* ok if basic */ ch->sl.statem.sib_received = 0; ch->sl.statem.Ct = 0; ch->sl.statem.rtb_full = 0; ch->sl.statem.clear_rtb = 0; /* ok if ITU */ if (((ch->option.pvar & SS7_PVAR_MASK) == SS7_PVAR_ANSI) && ((ch->option.pvar & SS7_PVAR_YR) > SS7_PVAR_88)) { ch->sl.statem.tx.sio = LSSU_SIOS; ch->sl.statem.lssu_available = 1; } ch->sl.statem.msu_inhibited = 0; if (ch->option.popt & SS7_POPT_XSN) { ch->sl.statem.sn_mask = 0x7fff; ch->sl.statem.ib_mask = 0x8000; } else { ch->sl.statem.sn_mask = 0x7f; ch->sl.statem.ib_mask = 0x80; } ch->sl.statem.tx.L.fsn = ch->sl.statem.tx.N.fsn = ch->sl.statem.sn_mask; ch->sl.statem.tx.X.fsn = 0; ch->sl.statem.tx.N.fib = ch->sl.statem.tx.N.bib = ch->sl.statem.ib_mask; ch->sl.statem.tx.F.fsn = 0; ch->sl.statem.Cm = 0; ch->sl.statem.Z = 0; ch->sl.statem.z_ptr = NULL; /* ok if basic */ if (ch->sl.statem.txc_state == SL_STATE_IDLE) { if (((ch->option.pvar & SS7_PVAR_MASK) != SS7_PVAR_ANSI) || ((ch->option.pvar & SS7_PVAR_YR) <= SS7_PVAR_88)) ch->sl.statem.lssu_available = 0; sl_daedt_start(ch); } ch->sl.statem.txc_state = SL_STATE_IN_SERVICE; return; } noinline fastcall __unlikely void sl_lsc_start(struct ch *ch) { switch (ch->sl.statem.lsc_state) { case SL_STATE_OUT_OF_SERVICE: sl_rc_start(ch); sl_txc_start(ch); /* Note 2 */ if (ch->sl.statem.emergency) sl_iac_emergency(ch); sl_iac_start(ch); ch->sl.statem.lsc_state = SL_STATE_INITIAL_ALIGNMENT; } } /* * Note 2: There is a difference here between ANSI_92 and ITUT_93/96 in that the transmitters in * the ANSI_92 case may transmit one or two SIOSs before transmitting the first SIO of the initial * alignment procedure. ITUT will continue idling FISU or LSSU as before the start, then transmit * the first SIO. These are equivalent. Because the LSC is in the OUT OF SERVICE state, the * transmitters should be idling SIOS anyway. */ noinline fastcall __unlikely void sl_lsc_retrieve_bsnt(struct ch *ch, queue_t *q, mblk_t *mp) { switch (ch->sl.statem.lsc_state) { case SL_STATE_OUT_OF_SERVICE: case SL_STATE_PROCESSOR_OUTAGE: sl_rc_retrieve_bsnt(ch, q, mp); break; default: freemsg(mp); break; } } noinline fastcall __unlikely int sl_lsc_retrieval_request_and_fsnc(struct ch *ch, queue_t *q, mblk_t *mp, sl_ulong fsnc) { switch (ch->sl.statem.lsc_state) { case SL_STATE_OUT_OF_SERVICE: case SL_STATE_PROCESSOR_OUTAGE: return sl_txc_retrieval_request_and_fsnc(ch, q, mp, fsnc); default: freemsg(mp); return (0); } } noinline fastcall __unlikely void sl_aerm_set_ti_to_tin(struct ch *ch) { if (ch->sdt.statem.aerm_state == SDT_STATE_IDLE) ch->sdt.statem.Ti = ch->sdt.config.Tin; } /** sl_lsc_power_on: - power on the link * @ch: channel structure (locked) * * This power-on sequence should only be performed once, regardless of how many times the device * driver is opened or closed. This initializes the transmitters to send SIOS and should never be * changed hence. * * Note 3: There is a difference here between ANSI_92 and ITUT_93/96 in that the transmitters in * the ITUT case may transmit one or two FISUs before transmitting SIOS on initial power-up. ANSI * will send SIOS on power-up. ANSI is the correct procedure as transmitters should always idle * SIOS on power-up. */ noinline fastcall __unlikely void sl_lsc_power_on(struct ch *ch) { switch (ch->sl.statem.lsc_state) { case SL_STATE_POWER_OFF: sl_txc_start(ch); /* Note 3 */ sl_txc_send_sios(ch); /* not necessary for ANSI */ sl_aerm_set_ti_to_tin(ch); ch->sl.statem.local_processor_outage = 0; ch->sl.statem.emergency = 0; ch->sl.statem.lsc_state = SL_STATE_OUT_OF_SERVICE; } } /** sl_check_congedstion: - transmit congestion algorithm * @ch: channel structure (locked) * @q: active queue (write queue or NULL) * @mp: message to reuse (or NULL) * * The transmit congestion algorithm is an implementation dependent algorithm but is suggested as * being based on TB and/or RTB buffer occupancy. With STREAMS we can use octet count buffer * occupancy over message count occupancy, because congestion in transmission is more related to * octet count (because it determines transmission latency). * * We check the total buffer occupancy and apply the necessary congestion control signal as per * configured abatement, onset and discard thresholds. */ STATIC fastcall __hot_write int sl_check_congestion(struct ch *ch, queue_t *q, mblk_t *mp) { unsigned int occupancy = sl_count_rq(ch) + ch->sl.tb.q_count + ch->sl.rtb.q_count; int old_cong_status = ch->sl.statem.cong_status; int old_disc_status = ch->sl.statem.disc_status; int multi = ch->option.popt & SS7_POPT_MPLEV; switch (ch->sl.statem.cong_status) { case 0: if (occupancy < ch->sl.config.tb_onset_1) break; ch->sl.statem.cong_status = 1; if (occupancy < ch->sl.config.tb_discd_1) break; ch->sl.statem.disc_status = 1; if (occupancy < ch->sl.config.tb_onset_2 || !multi) break; ch->sl.statem.cong_status = 2; if (occupancy < ch->sl.config.tb_discd_2) break; ch->sl.statem.disc_status = 2; if (occupancy < ch->sl.config.tb_onset_3) break; ch->sl.statem.cong_status = 3; if (occupancy < ch->sl.config.tb_discd_3) break; ch->sl.statem.disc_status = 3; break; case 1: if (occupancy < ch->sl.config.tb_abate_1) { ch->sl.statem.cong_status = 0; ch->sl.statem.disc_status = 0; break; } if (occupancy < ch->sl.config.tb_onset_2 || !multi) break; ch->sl.statem.cong_status = 2; if (occupancy < ch->sl.config.tb_discd_2) break; ch->sl.statem.disc_status = 2; if (occupancy < ch->sl.config.tb_onset_3) break; ch->sl.statem.cong_status = 3; if (occupancy < ch->sl.config.tb_discd_3) break; ch->sl.statem.disc_status = 3; break; case 2: if (occupancy < ch->sl.config.tb_abate_1) { ch->sl.statem.cong_status = 0; ch->sl.statem.disc_status = 0; break; } if (occupancy < ch->sl.config.tb_abate_2 || !multi) { ch->sl.statem.cong_status = 1; ch->sl.statem.disc_status = 1; break; } if (occupancy < ch->sl.config.tb_onset_3) break; ch->sl.statem.cong_status = 3; if (occupancy < ch->sl.config.tb_discd_3) break; ch->sl.statem.disc_status = 3; break; case 3: if (occupancy < ch->sl.config.tb_abate_1) { ch->sl.statem.cong_status = 0; ch->sl.statem.disc_status = 0; break; } if (occupancy < ch->sl.config.tb_abate_2 || !multi) { ch->sl.statem.cong_status = 1; ch->sl.statem.disc_status = 1; break; } if (occupancy < ch->sl.config.tb_abate_3) { ch->sl.statem.cong_status = 2; ch->sl.statem.disc_status = 2; break; } break; } if (ch->sl.statem.cong_status != old_cong_status || ch->sl.statem.disc_status != old_disc_status) { if (ch->sl.statem.cong_status < old_cong_status) return sl_link_congestion_ceased_ind(ch, q, mp); else { if (ch->sl.statem.cong_status > old_cong_status) { if ((ch->sl.notify.events & SL_EVT_CONGEST_ONSET_IND) && !ch->sl.stats.sl_cong_onset_ind[ch->sl.statem.cong_status]++) { return sl_link_congested_ind(ch, q, mp); } } else { if ((ch->sl.notify.events & SL_EVT_CONGEST_DISCD_IND) && !ch->sl.stats.sl_cong_discd_ind[ch->sl.statem.disc_status]++) { return sl_link_congested_ind(ch, q, mp); } } return sl_link_congested_ind(ch, q, mp); } } freemsg(mp); return (0); } static inline fastcall __hot_write void sl_txc_message_for_transmission(struct ch *ch, queue_t *q, mblk_t *mp) { bufq_queue(&ch->sl.tb, mp); ch->sl.statem.Cm++; sl_check_congestion(ch, q, mp); } static inline fastcall __hot_write int sl_lsc_pdu(struct ch *ch, queue_t *q, mblk_t *mp) { mblk_t *dp = mp; int hlen = (ch->option.popt & SS7_POPT_XSN) ? 6 : 3; ensure(dp, return (-EFAULT)); if (ch->sl.tb.q_count > 1024) return (-ENOBUFS); /* preferred method of sending data is just M_DATA blocks */ if (likely(DB_TYPE(dp) == M_DATA)) mp = NULL; else dp = mp->b_cont; ensure(dp, return (-EFAULT)); /* FIXME: duplicate message (dp) to xray chain here.... */ if (mp) { /* transform M_PROTO block into header */ mp->b_band = 0; mp->b_flag = 0; DB_TYPE(mp) = M_DATA; mp->b_rptr = DB_BASE(mp); mp->b_wptr = mp->b_rptr + hlen; } else if (MBLKHEAD(dp) >= hlen) { /* enough headroom for header in same block */ /* this needs to be marked as for transmission somehow */ mp = dp; mp->b_rptr -= hlen; } else if ((mp = mi_allocb(q, hlen, BPRI_MED))) { /* allocated a new block just for header */ /* this needs to be marked as for transmission somehow */ mp->b_cont = dp; mp->b_wptr = mp->b_rptr + hlen; } else { return (-ENOBUFS); } sl_txc_message_for_transmission(ch, q, mp); return (0); } noinline fastcall void sl_aerm_su_in_error(struct ch *ch) { if (ch->sdt.statem.aerm_state == SDT_STATE_MONITORING) { ch->sdt.statem.Ca++; if (ch->sdt.statem.Ca == ch->sdt.statem.Ti) { ch->sdt.statem.aborted_proving = 1; sl_iac_abort_proving(ch); ch->sdt.statem.Ca--; ch->sdt.statem.aerm_state = SDT_STATE_IDLE; } } } static inline fastcall __hot_in void sl_aerm_correct_su(struct ch *ch) { if (ch->sdt.statem.aerm_state == SDT_STATE_IDLE) { if (ch->sdt.statem.aborted_proving) { sl_iac_correct_su(ch); ch->sdt.statem.aborted_proving = 0; } } } noinline fastcall void sl_suerm_su_in_error(struct ch *ch) { if (ch->sdt.statem.suerm_state == SDT_STATE_IN_SERVICE) { ch->sdt.statem.Cs++; if (ch->sdt.statem.Cs >= ch->sdt.config.T) { sl_lsc_link_failure(ch, SL_FAIL_SUERM_EIM); ch->sdt.statem.Ca--; ch->sdt.statem.suerm_state = SDT_STATE_IDLE; return; } ch->sdt.statem.Ns++; if (ch->sdt.statem.Ns >= ch->sdt.config.D) { ch->sdt.statem.Ns = 0; if (ch->sdt.statem.Cs) ch->sdt.statem.Cs--; } } } noinline fastcall void sl_eim_su_in_error(struct ch *ch) { if (ch->sdt.statem.eim_state == SDT_STATE_MONITORING) ch->sdt.statem.interval_error = 1; } static inline fastcall __hot_in void sl_suerm_correct_su(struct ch *ch) { if (ch->sdt.statem.suerm_state == SDT_STATE_IN_SERVICE) { ch->sdt.statem.Ns++; if (ch->sdt.statem.Ns >= ch->sdt.config.D) { ch->sdt.statem.Ns = 0; if (ch->sdt.statem.Cs) ch->sdt.statem.Cs--; } } } static inline fastcall __hot_in void sl_eim_correct_su(struct ch *ch) { if (ch->sdt.statem.eim_state == SDT_STATE_MONITORING) ch->sdt.statem.su_received = 1; } static inline fastcall __hot_in void sl_daedr_correct_su(struct ch *ch) { sl_eim_correct_su(ch); sl_suerm_correct_su(ch); sl_aerm_correct_su(ch); } /* * Hooks to Soft-HDLC * ----------------------------------- */ noinline fastcall void sl_daedr_su_in_error(struct ch *ch) { if (ch->sl.statem.lsc_state != SL_STATE_POWER_OFF) { sl_eim_su_in_error(ch); sl_suerm_su_in_error(ch); sl_aerm_su_in_error(ch); } else { /* cancel compression */ if (ch->rx.cmp) { printd(("SU in error\n")); ss7_fast_freemsg(&xp_bufpool, xchg(&ch->rx.cmp, NULL)); } } return; } /** sl_daedr_received_bits: - process received frames * @ch: time slot structure * @mp: the received frame * * This is the point at which we decide whether to deliver the frame at this point or pass it on. * When the signalling link is powered up, pass the frame to the signalling link, otherwise, * deliver it up as a signalling terminal frame. This is the point at which we need to decide what * to do about monitoring the receive at the SDT level. We are still in a tasklet context here and * we were called from xp_rx_block() which we want to loop through each signalling link's 8 bytes * of data. * * This is the place to do all monitoring taps. We have a frame. For DLT_MTP2_WITH_PHDR stick * link info in header and deliver entire frame. For DLT_MTP, deliver entire frame. For DLT_MTP3, * strip the link level header and deliver remaining frame. */ static inline fastcall __hot_in void sl_daedr_received_bits(struct ch *ch, mblk_t *mp) { if (ch->sl.statem.lsc_state != SL_STATE_POWER_OFF) { sl_rc_signal_unit(ch, mp); sl_daedr_correct_su(ch); } else { int i, len, mlen = (ch->option.popt & SS7_POPT_XSN) ? 8 : 5; if (mp) { len = msgdsize(mp); if (ch->rx.cmp) { #if 0 if (ch->rx.repeat > 50) goto no_match; #endif if (len > mlen || len != msgdsize(ch->rx.cmp)) goto no_match; for (i = 0; i < len; i++) if (mp->b_rptr[i] != ch->rx.cmp->b_rptr[i]) goto no_match; ch->rx.repeat++; ch->sdt.stats.rx_sus_compressed++; freemsg(mp); return; no_match: if (ch->rx.repeat) { #if 0 mblk_t *cd; if ((cd = dupb(ch->rx.cmp))) if (sdt_rc_signal_unit_ind(ch, cd, ch->rx.repeat)) { ch->sdt.stats.rx_buffer_overflows++; freeb(cd); } #endif ch->rx.repeat = 0; } } if (len <= mlen) { if (ch->rx.cmp || (ch->rx.cmp = ss7_fast_allocb(&xp_bufpool, mlen, BPRI_HI))) { bcopy(mp->b_rptr, ch->rx.cmp->b_rptr, len); ch->rx.cmp->b_wptr = ch->rx.cmp->b_rptr + len; ch->rx.repeat = 0; } } if (sdt_rc_signal_unit_ind(ch, mp, 1)) { ch->sdt.stats.rx_buffer_overflows++; freemsg(mp); } } else swerr(); } } static inline fastcall __hot_out mblk_t * sl_daedt_transmission_request(struct ch *ch) { mblk_t *mp; if (ch->sl.statem.lsc_state != SL_STATE_POWER_OFF) { if (!(mp = sl_txc_transmission_request(ch))) ch->sdt.stats.tx_buffer_overflows++; return (mp); } else if (ch->sdt.statem.daedt_state != SDT_STATE_IDLE) { if ((mp = bufq_dequeue(&ch->sdt.tb))) { int len = msgdsize(mp); int hlen = (ch->option.popt & SS7_POPT_XSN) ? 6 : 3; int mlen = hlen + 2; if (!ch->sdt.tb.q_count < 512 && sl_count_rq(ch)) sl_enable_rq(ch); /* back-enable */ if (mlen < len) goto dont_repeat; if (mlen == len + 1 || mlen == len + 2) { int li, sio; if (ch->option.popt & SS7_POPT_XSN) { li = ((mp->b_rptr[5] << 8) | mp->b_rptr[4]) & 0x1ff; sio = mp->b_rptr[6]; } else { li = mp->b_rptr[2] & 0x3f; sio = mp->b_rptr[3]; } if (li != mlen - len) goto dont_repeat; switch (sio) { case LSSU_SIO: case LSSU_SIN: case LSSU_SIE: case LSSU_SIOS: case LSSU_SIPO: break; case LSSU_SIB: default: goto dont_repeat; } } if (ch->tx.cmp || (ch->tx.cmp = ss7_fast_allocb(&xp_bufpool, mlen, BPRI_HI))) { mblk_t *cd = ch->tx.cmp; if (len > mlen) len = hlen; cd->b_rptr = DB_BASE(cd); bcopy(mp->b_rptr, cd->b_rptr, len); cd->b_wptr = cd->b_rptr + len; /* always correct length indicator */ if (ch->option.popt & SS7_POPT_XSN) { cd->b_rptr[4] &= 0x00; cd->b_rptr[5] &= 0xfe; cd->b_rptr[4] += (len - hlen); } else { cd->b_rptr[2] &= 0xc0; cd->b_rptr[2] += (len - hlen); } ch->tx.repeat = 0; return (mp); } dont_repeat: if (ch->tx.cmp) ss7_fast_freemsg(&xp_bufpool, xchg(&ch->tx.cmp, NULL)); } else { if ((mp = ch->tx.cmp)) { mp->b_rptr = DB_BASE(mp); ch->sdt.stats.tx_sus_repeated++; ch->tx.repeat++; } else ch->sdt.stats.tx_buffer_overflows++; } return (mp); } else if (ch->sdl.statem.tx_state != SDL_STATE_IDLE) { if ((mp = bufq_dequeue(&ch->sdl.tb))) { if (ch->sdl.tb.q_count < 32 && sl_count_rq(ch)) sl_enable_rq(ch); } else ch->sdl.stats.tx_buffer_overflows++; return (mp); } else { return (NULL); } } /* * ======================================================================== * * Events from below * * ======================================================================== */ /* * ------------------------------------------------------------------------- * * SL events from below (timeouts) * * ------------------------------------------------------------------------- * Timeouts need to be reworked so that they are independent of a queue. */ /** xp_t1_timeout: - T1 expiry * @ch: channel structure (locked) */ noinline fastcall __unlikely void xp_t1_timeout(struct ch *ch) { LOGTO(ch2sid(ch), "-> T1 TIMEOUT <-"); ch->sl.statem.failure_reason = SL_FAIL_T1_TIMEOUT; sl_out_of_service_ind(ch); sl_rc_stop(ch); sl_suerm_stop(ch); sl_txc_send_sios(ch); ch->sl.statem.emergency = 0; if (ch->sl.statem.lsc_state == SL_STATE_ALIGNED_NOT_READY) { sl_poc_stop(ch); /* ok if ANSI */ ch->sl.statem.local_processor_outage = 0; } ch->sl.statem.lsc_state = SL_STATE_OUT_OF_SERVICE; } /** xp_t2_timeout: - T2 expiry * @ch: channel structure (locked) */ noinline fastcall __unlikely void xp_t2_timeout(struct ch *ch) { LOGTO(ch2sid(ch), "-> T2 TIMEOUT <-"); if (ch->sl.statem.iac_state == SL_STATE_NOT_ALIGNED) { sl_lsc_alignment_not_possible(ch); ch->sl.statem.emergency = 0; ch->sl.statem.iac_state = SL_STATE_IDLE; } } /** xp_t3_timeout: - T3 expiry * @ch: channel structure (locked) */ noinline fastcall __unlikely void xp_t3_timeout(struct ch *ch) { LOGTO(ch2sid(ch), "-> T3 TIMEOUT <-"); if (ch->sl.statem.iac_state == SL_STATE_ALIGNED) { sl_lsc_alignment_not_possible(ch); ch->sl.statem.emergency = 0; ch->sl.statem.iac_state = SL_STATE_IDLE; } } /** xp_t4_timeout: - T4 expiry * @ch: channel structure (locked) */ noinline fastcall __unlikely void xp_t4_timeout(struct ch *ch) { LOGTO(ch2sid(ch), "-> T4 TIMEOUT <-"); if (ch->sl.statem.iac_state == SL_STATE_PROVING) { if (ch->sl.statem.further_proving) { sl_aerm_start(ch); xp_timer_start(ch, t4); ch->sl.statem.further_proving = 0; } else { sl_lsc_alignment_complete(ch); sl_aerm_stop(ch); ch->sl.statem.emergency = 0; ch->sl.statem.iac_state = SL_STATE_IDLE; } } } /** xp_t5_timeout: - T5 expiry * @ch: channel structure (locked) */ noinline fastcall __unlikely void xp_t5_timeout(struct ch *ch) { LOGTO(ch2sid(ch), "-> T5 TIMEOUT <-"); if (ch->sl.statem.cc_state == SL_STATE_BUSY) { sl_txc_send_sib(ch); xp_timer_start(ch, t5); } } /** xp_t6_timeout: - T6 expiry * @ch: channel structure (locked) */ noinline fastcall __unlikely void xp_t6_timeout(struct ch *ch) { LOGTO(ch2sid(ch), "-> T6 TIMEOUT <-"); sl_lsc_link_failure(ch, SL_FAIL_CONG_TIMEOUT); ch->sl.statem.sib_received = 0; xp_timer_stop(ch, t7); } /** xp_t7_timeout: - T7 expiry * @ch: channel structure (locked) */ noinline fastcall __unlikely void xp_t7_timeout(struct ch *ch) { LOGTO(ch2sid(ch), "-> T7 TIMEOUT <-"); sl_lsc_link_failure(ch, SL_FAIL_ACK_TIMEOUT); xp_timer_stop(ch, t6); if (((ch->option.pvar & SS7_PVAR_MASK) != SS7_PVAR_ANSI) || ((ch->option.pvar & SS7_PVAR_YR) <= SS7_PVAR_88)) ch->sl.statem.sib_received = 0; } /** xp_t8_timeout: - T8 expiry * @ch: channel structure (locked) */ noinline fastcall void xp_t8_timeout(struct ch *ch) { LOGTO(ch2sid(ch), "-> T8 TIMEOUT <-"); if (ch->sdt.statem.eim_state == SDT_STATE_MONITORING) { xp_timer_start(ch, t8); if (ch->sdt.statem.su_received) { ch->sdt.statem.su_received = 0; if (!ch->sdt.statem.interval_error) { if ((ch->sdt.statem.Ce -= ch->sdt.config.De) < 0) ch->sdt.statem.Ce = 0; return; } } ch->sdt.statem.Ce += ch->sdt.config.Ue; if (ch->sdt.statem.Ce > ch->sdt.config.Te) { sl_lsc_link_failure(ch, SL_FAIL_SUERM_EIM); ch->sdt.statem.eim_state = SDT_STATE_IDLE; } ch->sdt.statem.interval_error = 0; } } static inline fastcall __unlikely void xp_expiry(struct ch *ch, const uint t) { spin_lock_bh(&ch->lock); { switch (t) { case t1: if (likely(ch->sl.timers.t1 != 0)) xp_t1_timeout(ch); break; case t2: if (likely(ch->sl.timers.t2 != 0)) xp_t2_timeout(ch); break; case t3: if (likely(ch->sl.timers.t3 != 0)) xp_t3_timeout(ch); break; case t4: if (likely(ch->sl.timers.t4 != 0)) xp_t4_timeout(ch); break; case t5: if (likely(ch->sl.timers.t5 != 0)) xp_t5_timeout(ch); break; case t6: if (likely(ch->sl.timers.t6 != 0)) xp_t6_timeout(ch); break; case t7: if (likely(ch->sl.timers.t7 != 0)) xp_t7_timeout(ch); break; case t8: if (likely(ch->sdt.timers.t8 != 0)) xp_t8_timeout(ch); break; #if 0 case t9: if (likely(ch->sdl.timers.t9 != 0)) xp_t9_timeout(ch); break; #endif default: swerr(); break; } } spin_unlock_bh(&ch->lock); } streamscall void xp_t1_expiry(caddr_t data) { xp_expiry((struct ch *) data, t1); } streamscall void xp_t2_expiry(caddr_t data) { xp_expiry((struct ch *) data, t2); } streamscall void xp_t3_expiry(caddr_t data) { xp_expiry((struct ch *) data, t3); } streamscall void xp_t4_expiry(caddr_t data) { xp_expiry((struct ch *) data, t4); } streamscall void xp_t5_expiry(caddr_t data) { xp_expiry((struct ch *) data, t5); } streamscall void xp_t6_expiry(caddr_t data) { xp_expiry((struct ch *) data, t6); } streamscall void xp_t7_expiry(caddr_t data) { xp_expiry((struct ch *) data, t7); } streamscall void xp_t8_expiry(caddr_t data) { xp_expiry((struct ch *) data, t8); } #if 0 streamscall void xp_t9_expiry(caddr_t data) { xp_expiry((struct ch *) data, t9); } #endif /* * ======================================================================== * * Soft-HDLC * * ======================================================================== */ #define SDT_TX_STATES 5 #define SDT_RX_STATES 16 #define SDT_TX_BUFSIZE PAGE_SIZE #define SDT_RX_BUFSIZE PAGE_SIZE #define SDT_CRC_TABLE_LENGTH 512 #define SDT_TX_TABLE_LENGTH (2* SDT_TX_STATES * 256) #define SDT_RX_TABLE_LENGTH (2* SDT_RX_STATES * 256) typedef struct tx_entry { uint bit_string:10 __attribute__ ((packed)); /* the output string */ uint bit_length:2 __attribute__ ((packed)); /* length in excess of 8 bits of output string */ uint state:3 __attribute__ ((packed)); /* new state */ } tx_entry_t; typedef struct rx_entry { uint bit_string:12 __attribute__ ((packed)); uint bit_length:4 __attribute__ ((packed)); uint state:4 __attribute__ ((packed)); uint sync:1 __attribute__ ((packed)); uint hunt:1 __attribute__ ((packed)); uint flag:1 __attribute__ ((packed)); uint idle:1 __attribute__ ((packed)); } rx_entry_t; typedef uint16_t bc_entry_t; STATIC bc_entry_t *bc_table = NULL; STATIC tx_entry_t *tx_table = NULL; STATIC rx_entry_t *rx_table = NULL; STATIC rx_entry_t *rx_table7 = NULL; STATIC size_t bc_order = 0; STATIC size_t tx_order = 0; STATIC size_t rx_order = 0; STATIC INLINE tx_entry_t * tx_index(uint j, uint k) { return &tx_table[(j << 8) | k]; } STATIC INLINE rx_entry_t * rx_index7(uint j, uint k) { return &rx_table7[(j << 8) | k]; } STATIC INLINE rx_entry_t * rx_index8(uint j, uint k) { return &rx_table[(j << 8) | k]; } /* * TX BITSTUFF * ----------------------------------- * Bitstuff an octet and shift residue for output. */ static inline fastcall __hot_out void xp_tx_bitstuff(xp_path_t * tx, uchar byte) { tx_entry_t *t = tx_index(tx->state, byte); tx->state = t->state; tx->residue <<= 8 + t->bit_length; tx->residue |= t->bit_string; tx->rbits += 8 + t->bit_length; } #define TX_MODE_IDLE 0 /* generating mark idle */ #define TX_MODE_FLAG 1 /* generating flag idle */ #define TX_MODE_BOF 2 /* generating bof flag */ #define TX_MODE_MOF 3 /* generating frames */ #define TX_MODE_BCC 4 /* generating bcc bytes */ /** xp_tx_block: - TX BLOCK * @ch: channel structure (locked) * @bp: beg tx block pointer (with offset) * @be: end tx block pointer (without offset) * @stats: channel statistics * @type: channel type * * Generate a block for transmission for a channel or span. We generate an entire transmit block. * If there are not sufficient messages to build the transmit block we will repeat FISU/LSSU or * idle flags. */ noinline fastcall __hot_out void xp_tx_block(struct ch *ch, uchar *bp, uchar *be, sdt_stats_t * stats, const sl_ulong type) { register xp_path_t *tx = &ch->tx; int chan = 1; if (ch->sdt.statem.daedt_state != SDT_STATE_IDLE) { if (tx->mode == TX_MODE_IDLE || tx->mode == TX_MODE_FLAG) { if (!tx->nxt) { next_message: if (tx->msg && tx->msg != tx->cmp) freemsg(tx->msg); if ((tx->msg = tx->nxt = sl_daedt_transmission_request(ch))) tx->mode = TX_MODE_BOF; } } /* check if transmission block complete */ for (; bp < be; bp += 128) { check_rbits: /* drain residue bits, if necessary */ if (tx->rbits >= 8) { drain_rbits: /* drain residue bits */ tx->rbits -= 8; ch->sdl.stats.tx_octets++; switch (type) { default: case SDL_TYPE_DS0: /* is this & 0xFE or & 0x7F ? */ *bp = tx->residue >> tx->rbits; break; case SDL_TYPE_DS0A: *bp = tx->residue >> tx->rbits; tx->rbits += 1; break; case SDL_TYPE_T1: *(bp + (xp_t1_chan_map[chan] << 2)) = tx->residue >> tx->rbits; if (++chan > 24) chan = 1; break; case SDL_TYPE_J1: *(bp + (xp_t1_chan_map[chan] << 2)) = tx->residue >> tx->rbits; tx->rbits += 1; if (++chan > 24) chan = 1; break; case SDL_TYPE_E1: *(bp + (xp_e1_chan_map[chan] << 2)) = tx->residue >> tx->rbits; if (++chan > 31) chan = 1; break; } if (chan > 1) goto check_rbits; continue; } switch (tx->mode) { case TX_MODE_IDLE: /* mark idle */ tx->residue <<= 8; tx->residue |= 0xff; tx->rbits += 8; goto drain_rbits; case TX_MODE_FLAG: /* idle flags */ tx->residue <<= 8; tx->residue |= 0x7e; tx->rbits += 8; goto drain_rbits; case TX_MODE_BOF: /* add opening flag (also closing flag) */ switch (ch->sdt.config.f) { default: case SDT_FLAGS_ONE: tx->residue <<= 8; tx->residue |= 0x7e; tx->rbits += 8; break; case SDT_FLAGS_SHARED: tx->residue <<= 15; tx->residue |= 0x3f7e; tx->rbits += 15; break; case SDT_FLAGS_TWO: tx->residue <<= 16; tx->residue |= 0x7e7e; tx->rbits += 16; break; case SDT_FLAGS_THREE: tx->residue <<= 24; tx->residue |= 0x7e7e7e; tx->rbits += 24; break; } tx->state = 0; tx->bcc = 0xffff; tx->mode = TX_MODE_MOF; goto drain_rbits; case TX_MODE_MOF: /* transmit frame bytes */ if (tx->nxt->b_rptr < tx->nxt->b_wptr || (tx->nxt = tx->nxt->b_cont)) { /* continuing in message */ uint byte = *tx->nxt->b_rptr++; tx->bcc = (tx->bcc >> 8) ^ bc_table[(tx->bcc ^ byte) & 0x00ff]; xp_tx_bitstuff(tx, byte); stats->tx_bytes++; goto drain_rbits; } /* finished message: add 1st bcc byte */ tx->bcc = ~(tx->bcc); xp_tx_bitstuff(tx, tx->bcc); tx->mode = TX_MODE_BCC; goto drain_rbits; case TX_MODE_BCC: /* add 2nd bcc byte */ xp_tx_bitstuff(tx, tx->bcc >> 8); stats->tx_sus++; tx->mode = TX_MODE_FLAG; goto next_message; } swerr(); } } else if (ch->sdl.statem.tx_state != SDL_STATE_IDLE) { for (; bp < be; bp += 128) { do { if (tx->nxt) { do { if (tx->nxt->b_rptr < tx->nxt->b_wptr) goto tx_process_block; } while ((tx->nxt = tx->nxt->b_cont)); } /* next block */ if (tx->msg) ss7_fast_freemsg(&xp_bufpool, tx->msg); if (!(tx->msg = tx->nxt = sl_daedt_transmission_request(ch))) { ch->sdl.stats.tx_buffer_overflows++; return; } tx_process_block: switch (type) { default: case SDL_TYPE_DS0: case SDL_TYPE_DS0A: *bp = *tx->nxt->b_rptr++; chan = 1; break; case SDL_TYPE_T1: case SDL_TYPE_J1: *(bp + (xp_t1_chan_map[chan] << 2)) = *tx->nxt->b_rptr++; if (++chan > 24) chan = 1; break; case SDL_TYPE_E1: *(bp + (xp_e1_chan_map[chan] << 2)) = *tx->nxt->b_rptr++; if (++chan > 31) chan = 1; break; } ch->sdl.stats.tx_octets++; while (tx->nxt && tx->nxt->b_rptr >= tx->nxt->b_wptr) tx->nxt = tx->nxt->b_cont; } while (chan > 1); } } } /** xp_tx_idle: - TX IDLE * @bp: beg tx block pointer (with offset) * @be: end tx block pointer (without offset) * @type: channel type * * Writes idle (silent) code for a given channel. We should be able to get rid of this routine * when we are properly using the per-channel on-chip idle code generation features of the Dallas * framer chips. * * TODO: Use the framer chip to automagically generate idle code instead of using this function. */ noinline fastcall __hot_out void xp_tx_idle(uchar *bp, uchar *be, const sl_ulong type) { int chan; for (; bp < be; bp += 128) { switch (type) { default: case SDL_TYPE_DS0: *bp = 0xff; continue; case SDL_TYPE_DS0A: *bp = 0x7f; continue; case SDL_TYPE_T1: case SDL_TYPE_J1: for (chan = 1; chan <= 24; chan++) *(bp + (xp_t1_chan_map[chan] << 2)) = 0x7f; continue; case SDL_TYPE_E1: for (chan = 1; chan <= 31; chan++) *(bp + (xp_e1_chan_map[chan] << 2)) = 0xff; continue; } } } /** xp_rx_linkb: - link a buffer * @rx: rx path structure pointer * * Link a buffer to existing message or create new message with buffer. */ static inline fastcall __hot_in void xp_rx_linkb(xp_path_t * rx) { if (rx->msg) linkb(rx->msg, rx->nxt); else rx->msg = rx->nxt; rx->nxt = NULL; return; } #define RX_MODE_IDLE 0 #define RX_MODE_HUNT 1 /* hunting for flags */ #define RX_MODE_SYNC 2 /* between frames */ #define RX_MODE_MOF 3 /* middle of frame */ /** xp_rx_block: - RX BLOCK * @ch: channel structure (locked) * @bp: beg rx block pointer (with offset) * @be: end rx block pointer (without offset) * @stats: channel statistics * @type: channel type * * Process a receive block for a channel or span. We process all of the octets in the receive * block. Any complete messages will be delivered to the upper layer if the upper layer is not * congested. If the upper layer is congested we discard the message and indicate receive * congestion. The upper layer should be sensitive to its receive queue backlog and start sending * SIB when required. We do not use backenabling from the upper layer. We merely start discarding * complete messages when the upper layer is congested. */ noinline fastcall __hot_in void xp_rx_block(struct ch *ch, uchar *bp, uchar *be, sdt_stats_t * stats, const sl_ulong type) { int chan = 1; register xp_path_t *rx = &ch->rx; if (ch->sdt.statem.daedr_state != SDT_STATE_IDLE) { int xsn = ch->option.popt & SS7_POPT_XSN; int M, mlen, hlen, N = ch->sdt.config.N; if (!xsn) { hlen = 3; mlen = 0x3f; } else { hlen = 6; mlen = 0x1ff; } M = ch->sdt.config.m + 1 + hlen; for (; bp < be; bp += 128) { rx_entry_t *r; next_channel: ch->sdl.stats.rx_octets++; switch (type) { default: case SDL_TYPE_DS0: _printd(("Rx: %p: 0x%02x\n", ch, *bp)); r = rx_index8(rx->state, *bp); break; case SDL_TYPE_DS0A: r = rx_index7(rx->state, *bp); break; case SDL_TYPE_T1: r = rx_index8(rx->state, *(bp + (xp_t1_chan_map[chan] << 2))); if (++chan > 24) chan = 1; break; case SDL_TYPE_J1: r = rx_index7(rx->state, *(bp + (xp_t1_chan_map[chan] << 2))); if (++chan > 24) chan = 1; break; case SDL_TYPE_E1: r = rx_index8(rx->state, *(bp + (xp_e1_chan_map[chan] << 2))); if (++chan > 31) chan = 1; break; } rx->state = r->state; switch (rx->mode) { case RX_MODE_MOF: if (!r->sync && r->bit_length) { rx->residue |= r->bit_string << rx->rbits; rx->rbits += r->bit_length; } if (!r->flag) { if (r->hunt || r->idle) goto aborted; while (rx->rbits > 16) { if (rx->nxt && rx->nxt->b_wptr >= DB_LIM(rx->nxt)) xp_rx_linkb(rx); if (!rx->nxt && !(rx->nxt = ss7_fast_allocb(&xp_bufpool, FASTBUF, BPRI_HI))) goto buffer_overflow; rx->bcc = (rx->bcc >> 8) ^ bc_table[(rx->bcc ^ rx->residue) & 0x00ff]; *rx->nxt->b_wptr++ = rx->residue; stats->rx_bytes++; rx->residue >>= 8; rx->rbits -= 8; rx->bytes++; if (rx->bytes > M) goto frame_too_long; } } else { uint len, li; if (rx->rbits != 16) goto residue_error; if (((~rx->bcc) & 0xffff) != (rx->residue & 0xffff)) goto crc_error; if (rx->bytes < hlen) goto frame_too_short; xp_rx_linkb(rx); if (!xsn) li = rx->msg->b_rptr[2] & mlen; else li = ((rx->msg->b_rptr[5] << 8) | rx->msg->b_rptr[4]) & mlen; len = rx->bytes - hlen; if (len != li && (li != mlen || len <= li)) goto length_error; stats->rx_sus++; sl_daedr_received_bits(ch, xchg(&rx->msg, NULL)); new_frame: rx->mode = RX_MODE_SYNC; rx->residue = 0; rx->rbits = 0; rx->bytes = 0; rx->bcc = 0xffff; if (r->sync) { begin_frame: if (r->bit_length) { rx->mode = RX_MODE_MOF; rx->residue = r->bit_string; rx->rbits = r->bit_length; rx->bytes = 0; rx->bcc = 0xffff; } } } break; frame_too_long: stats->rx_frame_too_long++; stats->rx_frame_errors++; goto abort_frame; buffer_overflow: stats->rx_buffer_overflows++; goto abort_frame; aborted: stats->rx_aborts++; stats->rx_frame_errors++; goto abort_frame; length_error: stats->rx_length_error++; goto abort_frame; frame_too_short: stats->rx_frame_too_short++; stats->rx_frame_errors++; goto abort_frame; crc_error: stats->rx_crc_errors++; goto abort_frame; residue_error: stats->rx_residue_errors++; stats->rx_frame_errors++; goto abort_frame; abort_frame: if (rx->nxt) ss7_fast_freemsg(&xp_bufpool, xchg(&rx->nxt, NULL)); if (rx->msg) ss7_fast_freemsg(&xp_bufpool, xchg(&rx->msg, NULL)); stats->rx_sus_in_error++; sl_daedr_su_in_error(ch); if (r->flag) goto new_frame; goto start_hunt; case RX_MODE_SYNC: if (!r->hunt && !r->idle) goto begin_frame; start_hunt: if (r->idle) rx->mode = RX_MODE_IDLE; else rx->mode = RX_MODE_HUNT; stats->rx_sync_transitions++; rx->octets = 0; break; case RX_MODE_IDLE: if (!r->idle) rx->mode = RX_MODE_HUNT; /* fall through */ case RX_MODE_HUNT: if (!r->flag) { if (r->idle && rx->mode != RX_MODE_IDLE) rx->mode = RX_MODE_IDLE; if ((++rx->octets) >= N) { stats->rx_sus_in_error++; sl_daedr_su_in_error(ch); rx->octets -= N; } stats->rx_bits_octet_counted += 8; break; } stats->rx_sync_transitions++; goto new_frame; default: swerr(); goto abort_frame; } if (chan > 1) goto next_channel; } } else if (ch->sdl.statem.rx_state != SDL_STATE_IDLE) { for (; bp < be; bp += 128) { do { if (rx->nxt) { if (rx->nxt->b_wptr < rx->nxt->b_rptr + ch->sdl.config.ifblksize) goto rx_process_block; if (sdl_received_bits_ind(ch, rx->nxt)) { ch->sdl.stats.rx_buffer_overflows++; goto rx_process_block; } } /* new block */ if (!(rx->nxt = ss7_fast_allocb(&xp_bufpool, FASTBUF, BPRI_HI))) { ch->sdl.stats.rx_buffer_overflows++; return; } rx_process_block: switch (type) { default: case SDL_TYPE_DS0: case SDL_TYPE_DS0A: *rx->nxt->b_wptr++ = *bp; chan = 1; break; case SDL_TYPE_T1: case SDL_TYPE_J1: *rx->nxt->b_wptr++ = *(bp + (xp_t1_chan_map[chan] << 2)); if (++chan > 24) chan = 1; break; case SDL_TYPE_E1: *rx->nxt->b_wptr++ = *(bp + (xp_e1_chan_map[chan] << 2)); if (++chan > 31) chan = 1; break; } ch->sdl.stats.rx_octets++; } while (chan > 1); } } } /* * ------------------------------------------------------------------------- * * Table allocation and generation * * ------------------------------------------------------------------------- * All Soft HDLC lookup stables are generated at module load time. This permits the tables to be * page-aligned in kernel memory for maximum cache performance. */ /** bc_table_value: - BC (Block Check) CRC Table Entries: * @bit_string: the bit string to block check * @bit_length: the length (in bits) of the bit string * * RC tables perform CRC calculation on received bits after zero deletion and delimitation. */ STATIC __devinit bc_entry_t bc_table_value(int bit_string, int bit_length) { int pos; for (pos = 0; pos < bit_length; pos++) { if (bit_string & 0x1) bit_string = (bit_string >> 1) ^ 0x8408; else bit_string >>= 1; } return (bit_string); } /** tx_table_valueN: - TX (Transmission) Table Entries: * @state: transmitter state * @byte: byte to transmit * @len: number of bits in byte (7 or 8). * * TX table performs zero insertion and bit reversal on frame and CRC bit streams. */ static __devinit struct tx_entry tx_table_valueN(int state, uint8_t byte, int len) { struct tx_entry result = { 0, }; int bit_mask = 0x80; result.state = state; result.bit_length = 0; while (len--) { if (byte & 0x01) { result.bit_string |= bit_mask; if (result.state++ == 4) { result.state = 0; result.bit_length++; result.bit_string <<= 1; } } else result.state = 0; bit_mask >>= 1; byte >>= 1; } return result; } /** tx_table_value: - TX (Transmission) Table Entries * @state: transmitter state * @byte: byte to transmit * * TX table performs zero insertion and bit reversal on frame and CRC bit streams. */ STATIC __devinit tx_entry_t tx_table_value(int state, uint8_t byte) { return tx_table_valueN(state, byte, 8); } /** rx_table_valueN: - RX (Receive) Table Entries: * @state: receiver state * @byte: byte received * @len: number of bits in byte (7 or 8) * * RX table performs zero deletion, flag and abort detection, BOF and EOF detection, residue, and * bit reversal on received bit streams. */ static __devinit struct rx_entry rx_table_valueN(int state, uint8_t byte, int len) { struct rx_entry result = { 0, }; int bit_mask = 1; result.state = state; while (len--) { switch (result.state) { case 0: /* 0 *//* zero not belonging to shared flag nor stuffing bit deletion */ if (byte & 0x80) { result.state = 1; } else { bit_mask <<= 1; result.bit_length += 1; result.state = 0; } break; case 1: /* 01 */ if (byte & 0x80) { result.state = 2; } else { bit_mask <<= 1; result.bit_string |= bit_mask; bit_mask <<= 1; result.bit_length += 2; result.state = 0; } break; case 2: /* 011 */ if (byte & 0x80) { result.state = 3; } else { bit_mask <<= 1; result.bit_string |= bit_mask; bit_mask <<= 1; result.bit_string |= bit_mask; bit_mask <<= 1; result.bit_length += 3; result.state = 0; } break; case 3: /* 0111 */ if (byte & 0x80) { result.state = 4; } else { bit_mask <<= 1; result.bit_string |= bit_mask; bit_mask <<= 1; result.bit_string |= bit_mask; bit_mask <<= 1; result.bit_string |= bit_mask; bit_mask <<= 1; result.bit_length += 4; result.state = 0; } break; case 4: /* 01111 */ if (byte & 0x80) { result.state = 5; } else { bit_mask <<= 1; result.bit_string |= bit_mask; bit_mask <<= 1; result.bit_string |= bit_mask; bit_mask <<= 1; result.bit_string |= bit_mask; bit_mask <<= 1; result.bit_string |= bit_mask; bit_mask <<= 1; result.bit_length += 5; result.state = 0; } break; case 5: /* 011111 */ if (byte & 0x80) { result.state = 7; } else { bit_mask <<= 1; result.bit_string |= bit_mask; bit_mask <<= 1; result.bit_string |= bit_mask; bit_mask <<= 1; result.bit_string |= bit_mask; bit_mask <<= 1; result.bit_string |= bit_mask; bit_mask <<= 1; result.bit_string |= bit_mask; bit_mask <<= 1; result.bit_length += 6; result.state = 6; } break; case 6: /* [0]11111[0] *//* bit deletion */ if (byte & 0x80) { result.state = 9; } else { result.state = 0; } break; case 7: /* 0111111 */ result.sync = 0; result.idle = 0; if (byte & 0x80) { bit_mask <<= 1; result.bit_length += 1; result.flag = 0; result.hunt = 1; result.state = 15; } else { result.flag = 1; result.hunt = 0; result.state = 8; } break; case 8: /* 0111110 */ bit_mask = 1; result.bit_string = 0; result.bit_length = 0; result.sync = 1; result.flag = 1; result.hunt = 0; result.idle = 0; if (byte & 0x80) { result.state = 9; } else { result.state = 0; } break; case 9: /* [0]1 *//* zero from end of flag or bit deletion */ result.idle = 0; if (byte & 0x80) { result.state = 10; } else { result.bit_string |= bit_mask; bit_mask <<= 1; result.bit_length += 1; result.state = 0; } break; case 10: /* [0]11 */ result.idle = 0; if (byte & 0x80) { result.state = 11; } else { result.bit_string |= bit_mask; bit_mask <<= 1; result.bit_string |= bit_mask; bit_mask <<= 1; result.bit_length += 2; result.state = 0; } break; case 11: /* [0]111 */ result.idle = 0; if (byte & 0x80) { result.state = 12; } else { result.bit_string |= bit_mask; bit_mask <<= 1; result.bit_string |= bit_mask; bit_mask <<= 1; result.bit_string |= bit_mask; bit_mask <<= 1; result.bit_length += 3; result.state = 0; } break; case 12: /* [0]1111 */ result.idle = 0; if (byte & 0x80) { result.state = 13; } else { result.bit_string |= bit_mask; bit_mask <<= 1; result.bit_string |= bit_mask; bit_mask <<= 1; result.bit_string |= bit_mask; bit_mask <<= 1; result.bit_string |= bit_mask; bit_mask <<= 1; result.bit_length += 4; result.state = 0; } break; case 13: /* [0]11111 */ result.idle = 0; if (byte & 0x80) { result.state = 14; } else { result.bit_string |= bit_mask; bit_mask <<= 1; result.bit_string |= bit_mask; bit_mask <<= 1; result.bit_string |= bit_mask; bit_mask <<= 1; result.bit_string |= bit_mask; bit_mask <<= 1; result.bit_string |= bit_mask; bit_mask <<= 1; result.bit_length += 5; result.state = 6; } break; case 14: /* [0]111111 */ result.sync = 0; result.idle = 0; if (byte & 0x80) { result.flag = 0; result.hunt = 1; result.state = 15; } else { result.flag = 1; result.hunt = 0; result.state = 8; } break; case 15: /* ...1111111 *//* 7 ones (or 8 ones) */ result.sync = 0; result.flag = 0; result.hunt = 1; if (byte & 0x80) { result.idle = 1; result.state = 15; } else { result.idle = 0; result.state = 0; } break; } byte <<= 1; } return result; } /** rx_table_value7: - RX (Receive) Table Entries (7-bit table) * @state: receiver state * @byte: byte received * * RX table performs zero deletion, flag and abort detection, BOF and EOF detection, residue, and * bit reversal on received bit streams. */ STATIC __devinit rx_entry_t rx_table_value7(int state, uint8_t byte) { return rx_table_valueN(state, byte, 7); } /** rx_table_value7: - RX (Receive) Table Entries (8-bit table) * @state: receiver state * @byte: byte received * * RX table performs zero deletion, flag and abort detection, BOF and EOF detection, residue, and * bit reversal on received bit streams. */ STATIC __devinit rx_entry_t rx_table_value8(int state, uint8_t byte) { return rx_table_valueN(state, byte, 8); } /** tx_table_generate: - TX (Transmit) Table * * There is one TX table for 8-bit (octet) output values. The table has 256 entries and is used to * perform, for one sample, zero insertion on frame bits for the transmitted bitstream. */ STATIC __devinit void tx_table_generate(void) { int j, k; for (j = 0; j < SDT_TX_STATES; j++) for (k = 0; k < 256; k++) *tx_index(j, k) = tx_table_value(j, k); } /** rx_table_generate7: - RX (Received) Tables (7-bit table) * * There are two RX tables: one for 8 bit (octet) values, another for 7 bit (DS0A operation). Each * table has 256 entries and is used to perform, for one sample, zero deletion, abort detection, * flag detection and residue calculation on the received bitstream. */ STATIC __devinit void rx_table_generate7(void) { int j, k; for (j = 0; j < SDT_RX_STATES; j++) for (k = 0; k < 256; k++) *rx_index7(j, k) = rx_table_value7(j, k); } /** rx_table_generate8: - RX (Received) Tables (8-bit table) * * There are two RX tables: one for 8 bit (octet) values, another for 7 bit (DS0A operation). Each * table has 256 entries and is used to perform, for one sample, zero deletion, abort detection, * flag detection and residue calculation on the received bitstream. */ STATIC __devinit void rx_table_generate8(void) { int j, k; for (j = 0; j < SDT_RX_STATES; j++) for (k = 0; k < 256; k++) *rx_index8(j, k) = rx_table_value8(j, k); } /** bc_table_generate: - BC (CRC) Tables * * CRC table organization: This is a CRC table which contains lookups for all bit lengths less * than or equal to 8. There are 512 entries. The first 256 entries are for 8-bit bit lengths, * the next 128 entries are for 7-bit bit lengths, the next 64 entries for 6-bit bit lengths, etc. */ STATIC __devinit void bc_table_generate(void) { int pos = 0, bit_string, bit_length = 8, bit_mask = 0x100; do { for (bit_string = 0; bit_string < bit_mask; bit_string++, pos++) bc_table[pos] = bc_table_value(bit_string, bit_length); bit_length--; } while ((bit_mask >>= 1)); } /** xp_init_tables: - Table allocation and generation. * * There are 4 mostly read-only tables to allocate and initialize for SOFT-HDLC operation. This * procedure allocated and initializes (calculates) the tables. */ noinline __devinit int xp_init_tables(void) { size_t length; length = SDT_CRC_TABLE_LENGTH * sizeof(bc_entry_t); for (bc_order = 0; PAGE_SIZE << bc_order < length; bc_order++) ; if (!(bc_table = (bc_entry_t *) __get_free_pages(GFP_KERNEL, bc_order))) { cmn_err(CE_PANIC, "%s: Cannot allocated bc_table", __FUNCTION__); goto bc_failed; } printd(("%s: allocated BC table size %u kernel pages\n", DRV_NAME, 1 << bc_order)); length = SDT_TX_TABLE_LENGTH * sizeof(tx_entry_t); for (tx_order = 0; PAGE_SIZE << tx_order < length; tx_order++) ; if (!(tx_table = (tx_entry_t *) __get_free_pages(GFP_KERNEL, tx_order))) { cmn_err(CE_PANIC, "%s: Cannot allocated tx_table", __FUNCTION__); goto tx_failed; } printd(("%s: allocated Tx table size %u kernel pages\n", DRV_NAME, 1 << tx_order)); length = 2 * (SDT_RX_TABLE_LENGTH * sizeof(rx_entry_t)); for (rx_order = 0; PAGE_SIZE << rx_order < length; rx_order++) ; if (!(rx_table = (rx_entry_t *) __get_free_pages(GFP_KERNEL, rx_order))) { cmn_err(CE_PANIC, "%s: Cannot allocated rx_table", __FUNCTION__); goto rx_failed; } printd(("%s: allocated Rx table size %u kernel pages\n", DRV_NAME, 1 << rx_order)); rx_table7 = (rx_entry_t *) (((uint8_t *) rx_table) + (PAGE_SIZE << (rx_order - 1))); bc_table_generate(); printd(("%s: generated BC table\n", DRV_NAME)); tx_table_generate(); printd(("%s: generated 8-bit Tx table\n", DRV_NAME)); rx_table_generate8(); printd(("%s: generated 8-bit Rx table\n", DRV_NAME)); rx_table_generate7(); printd(("%s: generated 7-bit Rx table\n", DRV_NAME)); return (0); rx_failed: free_pages((unsigned long) tx_table, xchg(&tx_order, 0)); tx_order = 0; tx_failed: free_pages((unsigned long) bc_table, xchg(&bc_order, 0)); bc_order = 0; bc_failed: return (-ENOMEM); } /** xp_free_tables: - Table free. * * There are 4 mostly read-only tables that were allocated and initialized for SOFT-HDLC operation. * These tables are freed here. */ noinline int xp_free_tables(void) { free_pages((unsigned long) bc_table, bc_order); printd(("%s: freed BC table kernel pages\n", DRV_NAME)); free_pages((unsigned long) tx_table, tx_order); printd(("%s: freed Tx table kernel pages\n", DRV_NAME)); free_pages((unsigned long) rx_table, rx_order); printd(("%s: freed Rx table kernel pages\n", DRV_NAME)); return (0); } /* * ========================================================================= * * EVENTS From Above * * ========================================================================= */ /* * M_DATA * ----------------------------------- */ /** xp_send_data: - process M_DATA message * @xp: private structure (locked) * @q: active queue (write queue) * @mp: the M_DATA message * * Note that we discard M_DATA messages when we are in the wrong state because the state may have * changed with data in queue. In reality, we should always send a M_FLUSH message upstream in * such a case before changing the state, so it still represents a software error. */ static inline fastcall __hot_write int xp_send_data(struct xp *xp, queue_t *q, mblk_t *mp) { struct ch *ch; int err = 0; if (unlikely((ch = xp->ch) == NULL)) goto discard; if (unlikely(xp_get_state(xp) != LMI_ENABLED)) goto eproto; spin_lock_bh(&ch->lock); { if (ch->sl.statem.lsc_state != SL_STATE_POWER_OFF) { /* SL mode */ if ((err = sl_lsc_pdu(ch, q, mp)) == 0) mp = NULL; } else if (ch->sdt.statem.daedt_state != SDT_STATE_IDLE) { /* SDT mode */ if (ch->sdt.tb.q_count > 1024) err = -EBUSY; else { /* FIXME: duplicate messages to the SDT xray chain here... Also, needs to be marked as the transmission direction, so add an SDT_DAEDT_TRANSMISSION_REQ control block. */ bufq_queue(&ch->sdt.tb, mp); mp = NULL; } } else if (ch->sdl.statem.tx_state != SDL_STATE_IDLE) { /* SDL mode */ if (ch->sdl.tb.q_count > 64) err = -EBUSY; else { /* FIXME: duplicate messages to the SDL xray chain here... Also, needs to be marked as the transmission direction, so add an SDL_BITS_FOR_TRANSMISSION control block. */ bufq_queue(&ch->sdl.tb, mp); mp = NULL; } } else { /* discard when not active */ } } spin_unlock_bh(&ch->lock); if (mp && !err) freemsg(mp); return (err); eproto: return m_error(xp, q, mp, EPROTO); discard: freemsg(mp); return (0); } /** sl_pdu_req: - process SL_PDU_REQ primitive * @xp: private structure (locked) * @q: active queue (write queue) * @mp: the SL_PDU_REQ primitive */ static inline fastcall __hot_write int sl_pdu_req(struct xp *xp, queue_t *q, mblk_t *mp) { struct ch *ch; int err = 1; if (likely((ch = xp->ch) != NULL)) { spin_lock_bh(&ch->lock); { err = sl_lsc_pdu(ch, q, mp); } spin_unlock_bh(&ch->lock); } if (unlikely(err == 1)) { freemsg(mp); return (0); } return (err); } /** sl_emergency_req: - process SL_EMERGENCY_REQ primitive * @ch: channel structure (locked) * @q: active queue (write queue) * @mp: the SL_EMERGENCY_REQ primitive * * Emergency can be set or cleared on a signalling link at any time that the interface is enabled: * even before starting the signalling link. */ noinline fastcall __unlikely int sl_emergency_req(struct ch *ch, queue_t *q, mblk_t *mp) { sl_lsc_emergency(ch); freemsg(mp); return (0); } /** sl_emergency_ceases_req: - process SL_EMERGENCY_CEASES_REQ primitive * @ch: channel structure (locked) * @q: active queue (write queue) * @mp: the SL_EMERGENCY_CEASES_REQ primitive * * Emergency can be set or cleared on a signalling link at any time that the interface is enabled: * even before starting the signalling link. */ noinline fastcall __unlikely int sl_emergency_ceases_req(struct ch *ch, queue_t *q, mblk_t *mp) { sl_lsc_emergency_ceases(ch); freemsg(mp); return (0); } /** sl_start_req: - process SL_START_REQ primitive * @ch: channel structure (locked) * @q: active queue (write queue) * @mp: the SL_START_REQ primitive * * SL_START_REQ can be issued on an interface at any time that it is enabled. */ noinline fastcall __unlikely int sl_start_req(struct ch *ch, queue_t *q, mblk_t *mp) { sl_lsc_start(ch); freemsg(mp); return (0); } /** sl_stop_req: - process SL_STOP_REQ primitive * @ch: channel structure (locked) * @q: active queue (write queue) * @mp: the SL_STOP_REQ primitive * * SL_STOP_REQ can be issued on an interface at any time that it is enabled. */ noinline fastcall __unlikely int sl_stop_req(struct ch *ch, queue_t *q, mblk_t *mp) { sl_lsc_stop(ch); freemsg(mp); return (0); } /** sl_retrieve_bsnt_req: - process SL_RETRIEVE_BSNT_REQ primitive * @ch: channel structure (locked) * @q: active queue (write queue) * @mp: the SL_RETRIEVE_BSNT_REQ primitive * * SL_RETRIEVE_BSNT_REQ can be issued on an interface at any time that it is enabled. */ noinline fastcall __unlikely int sl_retrieve_bsnt_req(struct ch *ch, queue_t *q, mblk_t *mp) { sl_lsc_retrieve_bsnt(ch, q, mp); return (0); } /** sl_retrieval_request_and_fsnc_req: - process SL_RETRIEVAL_REQUEST_AND_FSNC_REQ * @ch: channel structure (locked) * @q: active queue (write queue) * @mp: the SL_RETRIEVAL_REQUEST_AND_FSNC_REQ primitive * * SL_RETRIEVAL_REQUEST_AND_FSNC_REQ can be issued on an interface at any time that it is enabled. */ noinline fastcall __unlikely int sl_retrieval_request_and_fsnc_req(struct ch *ch, queue_t *q, mblk_t *mp) { sl_retrieval_req_and_fsnc_t *p = ((typeof(p)) mp->b_rptr); if (unlikely(!MBLKIN(mp, 0, sizeof(*p)))) return (-EMSGSIZE); return sl_lsc_retrieval_request_and_fsnc(ch, q, mp, p->sl_fsnc); } /** sl_clear_buffers_req: - process SL_CLEAR_BUFFERS_REQ primitive * @ch: channel structure (locked) * @q: active queue (write queue) * @mp: the SL_CLEAR_BUFFERS_REQ primitive * * SL_CLEAR_BUFFERS_REQ can be issued on an interface at any time that it is enabled. */ noinline fastcall __unlikely int sl_clear_buffers_req(struct ch *ch, queue_t *q, mblk_t *mp) { sl_lsc_clear_buffers(ch, q, mp); return (0); } /** sl_clear_rtb_req: - process SL_CLEAR_RTB_REQ primitive * @ch: channel structure (locked) * @q: active queue (write queue) * @mp: the SL_CLEAR_RTB_REQ primitive * * SL_CLEAR_RTB_REQ can be issued on an interface at any time that it is enabled. */ noinline fastcall __unlikely int sl_clear_rtb_req(struct ch *ch, queue_t *q, mblk_t *mp) { sl_lsc_clear_rtb(ch, q, mp); return (0); } /** sl_continue_req: - process SL_CONTINUE_REQ primitive * @ch: channel structure (locked) * @q: active queue (write queue) * @mp: the SL_CONTINUE_REQ primitive * * SL_CONTINUE_REQ can be issued on an interface any time that the interface is enabled. */ noinline fastcall __unlikely int sl_continue_req(struct ch *ch, queue_t *q, mblk_t *mp) { sl_lsc_continue(ch); freemsg(mp); return (0); } /** sl_local_processor_outage_req: - process SL_LOCAL_PROCESSOR_OUTAGE primitive * @ch: channel structure (locked) * @q: active queue (write queue) * @mp: the SL_LOCAL_PROCESSOR_OUTAGE_REQ primitive * * SL_LOCAL_PROCESSOR_OUTAGE_REQ can be issued on an interface any time that the interface is * enabled. For a signalling link in the out-of-service or initial-alignment state, this primitive * has no effect other than setting the local processor outage flag. * * The actions taken by this primitive should also be taken when the interface closes while the * interace is enabled. * * Note: this signal is largely synthetic and is provided to support M2UA where the connection to * level 3 exists remote to the signalling link implementation. */ noinline fastcall __unlikely int sl_local_processor_outage_req(struct ch *ch, queue_t *q, mblk_t *mp) { sl_lsc_local_processor_outage(ch); freemsg(mp); return (0); } /** sl_resume_req: - process SL_RESUME_REQ primitive * @ch: channel structure (locked) * @q: active queue (write queue) * @mp: the SL_RESUME_REQ primitive * * SL_RESUME_REQ can be issued on an interface any time that the interface is enabled. When the * link is not running, this has no effect other than to reset local processor outage condition. * When the link is in service without a local processor outage condition, this primitive has no * effect. * * To support detaching from signalling links that are left operating, an SL_RESUME_REQ should be * considered as the same as SL_START_REQ when the LSC state is out-of-service. Also, the * SL_START_REQ should be considered as the same as SL_RESUME_REQ when the LSC state is * processor-outage with a local-processor-outage marked. */ noinline fastcall __unlikely int sl_resume_req(struct ch *ch, queue_t *q, mblk_t *mp) { return sl_lsc_resume(ch, q, mp); } /** sl_congestion_discard_req: - process SL_CONGESTION_DISCARD_REQ primitive * @ch: channel structure (locked) * @q: active queue (write queue) * @mp: the SL_CONGESTION_DISCARD_REQ primitive * * SL_CONGESTION_DISCARD_REQ can be issued on an interface any time that the interface is enabled. * When the link is not running, this has no effect other than to set the congestion-discard and * marking level 3 congestion detected. * * There are two receive congestion methods: (1) external, where level 3 detects congestion; and, * (2) internal, where level 2 automatically detects congestion. SL_CONGESTION_DISCARD_REQ marks * level 3 congestion as congestion discard and the internal method is no longer used to detect * congestion. * * Note: this signal is largely synthetic and is provided to support M2UA where a buffer exists * remote to the signalling link implementation. */ noinline fastcall __unlikely int sl_congestion_discard_req(struct ch *ch, queue_t *q, mblk_t *mp) { sl_lsc_congestion_discard(ch); freemsg(mp); return (0); } /** sl_congestion_accept_req: - process SL_CONGESTION_ACCEPT_REQ primitive * @ch: channel structure (locked) * @q: active queue (write queue) * @mp: the SL_CONGESTION_ACCEPT_REQ primitive * * SL_CONGESTION_ACCEPT_REQ can be issued on an interface any time that the interface is enabled. * When the link is not running, this has no effect other than to set the congestion-discard and * marking level 3 congestion detected. * * There are two receive congestion methods: (1) external, where level 3 detects congestion; and, * (2) internal, where level 2 automatically detects congestion. SL_CONGESTION_ACCEPT_REQ marks * level 3 congestion as congestion accept and the internal method is no longer used to detect * congestion. * * Note: this signal is largely synthetic and is provided to support M2UA where a buffer exists * remote to the signalling link implementation. */ noinline fastcall __unlikely int sl_congestion_accept_req(struct ch *ch, queue_t *q, mblk_t *mp) { sl_lsc_congestion_accept(ch); freemsg(mp); return (0); } /** sl_no_congestion_req: - process SL_NO_CONGESTION_REQ primitive * @ch: channel structure (locked) * @q: active queue (write queue) * @mp: the SL_NO_CONGESTION_REQ primitive * * SL_NO_CONGESTION_REQ can be issued on an interface any time that the interface is enabled. When * the link is not running, this has no effect other than to clear congestion-discard and * congestion-accept and clearing level 3 congestion detected. * * There are two receive congestion methods: (1) external, where level 3 detects congestion; and, * (2) internal, where level 2 automatically detects congestion. SL_NO_CONGESTION_REQ marks level * 3 congestion as no congestion and the internal method is used to detect congestion. * * Note: this signal is largely synthetic and is provided to support M2UA where a buffer exists * remote to the signalling link implementation. */ noinline fastcall __unlikely int sl_no_congestion_req(struct ch *ch, queue_t *q, mblk_t *mp) { sl_lsc_no_congestion(ch); freemsg(mp); return (0); } /** sl_power_on_req: - process SL_POWER_ON_REQ primitive * @ch: channel structure (locked) * @q: active queue (write queue) * @mp: the SL_POWER_ON_REQ primitive * * SL_POWER_ON_REQ can be issued on an interface any time that the interface is enabled. Any time * that the LSC state is other than SL_STATE_POWER_OFF, this primitive has no effect on the state * machine. */ noinline fastcall __unlikely int sl_power_on_req(struct ch *ch, queue_t *q, mblk_t *mp) { sl_lsc_power_on(ch); freemsg(mp); return (0); } #if 0 /* * SL_OPTMGMT_REQ * ----------------------------------- */ noinline fastcall __unlikely int sl_optmgmt_req(queue_t *q, mblk_t *mp) { } /* * SL_NOTIFY_REQ * ----------------------------------- */ noinline fastcall __unlikely int sl_notify_req(queue_t *q, mblk_t *mp) { } #endif /* * ------------------------------------------------------------------------- * * SDT Primitives * * ------------------------------------------------------------------------- */ /** sdt_daedt_transmission_req: - process SDT_DAEDT_TRANSMISSION_REQ primitive * @xp: private structure (locked) * @q: active queue (write queue) * @mp: the SDT_DAEDT_TRANSMISSION_REQ primitive * * Non-preferred way of sending frames. One should just send M_DATA blocks. We used to just strip * the redundant M_PROTO and put the M_DATA on the queue, but now we handle it here. */ noinline fastcall __hot_write int sdt_daedt_transmission_req(struct xp *xp, queue_t *q, mblk_t *mp) { struct ch *ch; int err = 0; if (likely((ch = xp->ch) != NULL)) { spin_lock_bh(&ch->lock); { if (likely(ch->sdt.statem.daedt_state != SDT_STATE_IDLE)) { if (unlikely(ch->sdt.tb.q_count > 1024)) err = -EBUSY; else { mblk_t *dp; /* FIXME: duplicate messages to the SDT xray chain here... Also, needs to be marked as the transmission direction, so just keep the M_PROTO block. */ if (likely((dp = XCHG(&mp->b_cont, NULL)) != NULL)) bufq_queue(&ch->sdt.tb, dp); } } } spin_unlock_bh(&ch->lock); } if (likely(!err)) freemsg(mp); return (err); } /** sdt_daedt_start_req: - process SDT_DAEDT_START_REQ primitive * @ch: channel structure (locked) * @q: active queue (write queue) * @mp: the SDT_DAEDT_START_REQ primitive */ noinline fastcall __unlikely int sdt_daedt_start_req(struct ch *ch, queue_t *q, mblk_t *mp) { sl_daedt_start(ch); freemsg(mp); return (0); } /** sdt_daedr_start_req: - process SDT_DAEDR_START_REQ primitive * @ch: channel structure (locked) * @q: active queue (write queue) * @mp: the SDT_DAEDR_START_REQ primitive */ noinline fastcall __unlikely int sdt_daedr_start_req(struct ch *ch, queue_t *q, mblk_t *mp) { sl_daedr_start(ch); freemsg(mp); return (0); } /** sdt_aerm_start_req: - process SDT_AERM_START_REQ primitive * @ch: channel structure (locked) * @q: active queue (write queue) * @mp: the SDT_AERM_START_REQ primitive */ noinline fastcall __unlikely int sdt_aerm_start_req(struct ch *ch, queue_t *q, mblk_t *mp) { sl_aerm_start(ch); freemsg(mp); return (0); } /** sdt_aerm_stop_req: - process SDT_AERM_STOP_REQ primitive * @ch: channel structure (locked) * @q: active queue (write queue) * @mp: the SDT_AERM_STOP_REQ primitive */ noinline fastcall __unlikely int sdt_aerm_stop_req(struct ch *ch, queue_t *q, mblk_t *mp) { sl_aerm_stop(ch); freemsg(mp); return (0); } /** sdt_aerm_set_ti_to_tin_req: - process SDT_AERM_SET_TI_TO_TIN_REQ primitive * @ch: channel structure (locked) * @q: active queue (write queue) * @mp: the SDT_AERM_SET_TI_TO_TIN_REQ primitive */ noinline fastcall __unlikely int sdt_aerm_set_ti_to_tin_req(struct ch *ch, queue_t *q, mblk_t *mp) { sl_aerm_set_ti_to_tin(ch); freemsg(mp); return (0); } /** sdt_aerm_set_ti_to_tie_req: - process SDT_AERM_SET_TI_TO_TIE_REQ primitive * @ch: channel structure (locked) * @q: active queue (write queue) * @mp: the SDT_AERM_SET_TI_TO_TIE_REQ primitive */ noinline fastcall __unlikely int sdt_aerm_set_ti_to_tie_req(struct ch *ch, queue_t *q, mblk_t *mp) { sl_aerm_set_ti_to_tie(ch); freemsg(mp); return (0); } /** sdt_suerm_start_req: - process SDT_SUERM_START_REQ primitive * @ch: channel structure (locked) * @q: active queue (write queue) * @mp: the SDT_SUERM_START_REQ primitive */ noinline fastcall __unlikely int sdt_suerm_start_req(struct ch *ch, queue_t *q, mblk_t *mp) { sl_suerm_start(ch); freemsg(mp); return (0); } /** sdt_suerm_stop_req: - process SDT_SUERM_STOP_REQ primitive * @ch: private structure (locked) * @q: active queue (write queue) * @mp: the SDT_SUERM_STOP_REQ primitive */ noinline fastcall __unlikely int sdt_suerm_stop_req(struct ch *ch, queue_t *q, mblk_t *mp) { sl_suerm_stop(ch); freemsg(mp); return (0); } /* * ------------------------------------------------------------------------- * * SDL Primitives * * ------------------------------------------------------------------------- */ /** sdl_bits_for_transmission_req: - process SDL_BITS_FOR_TRANSMISSION_REQ primitive * @xp: private structure (locked) * @q: active queue (write queue) * @mp: the SDL_BITS_FOR_TRANSMISSION_REQ primitive * * Non-preferred method. Normally one should just send M_DATA blocks. We used to just strip off * the redundant M_PROTO and put it back on the queue, but now we handle it here. */ noinline fastcall __hot_write int sdl_bits_for_transmission_req(struct xp *xp, queue_t *q, mblk_t *mp) { struct ch *ch; int err = 0; if (likely((ch = xp->ch) != NULL)) { spin_lock_bh(&ch->lock); { if (likely(ch->sdl.statem.tx_state != SDL_STATE_IDLE)) { if (unlikely(ch->sdl.tb.q_count > 64)) err = -EBUSY; else { mblk_t *dp; /* FIXME: duplicate messages to the SDL xray chain here... Also, needs to be marked as the transmission direction, so just keep the M_PROTO block. */ if (likely((dp = XCHG(&mp->b_cont, NULL)) != NULL)) bufq_queue(&ch->sdl.tb, dp); } } } spin_unlock_bh(&ch->lock); } if (likely(!err)) freemsg(mp); return (err); } /** sdl_connect_req: - process SDL_CONNECT_REQ primitive * @ch: channel structure (locked) * @q: active queue (write queue) * @mp: the SDL_CONNECT_REQ primitive */ noinline fastcall __unlikely int sdl_connect_req(struct ch *ch, queue_t *q, mblk_t *mp) { sdl_connect_req_t *p = (typeof(p)) mp->b_rptr; if (unlikely(!MBLKIN(mp, 0, sizeof(*p)))) return (-EMSGSIZE); if (p->sdl_flags & SDL_RX_DIRECTION) { LOGNO(ch2sid(ch), "Enabling Rx"); ch->sdl.config.ifflags |= SDL_IF_RX_RUNNING; ch->sdl.statem.rx_state = SDL_STATE_IN_SERVICE; } if (p->sdl_flags & SDL_TX_DIRECTION) { LOGNO(ch2sid(ch), "Enabling Tx"); ch->sdl.config.ifflags |= SDL_IF_TX_RUNNING; ch->sdl.statem.tx_state = SDL_STATE_IN_SERVICE; } if ((ch->sdl.config.ifflags & (SDL_IF_TX_RUNNING | SDL_IF_RX_RUNNING))) { LOGNO(ch2sid(ch), "Marking interface up"); ch->sdl.config.ifflags |= SDL_IF_UP; } freemsg(mp); return (0); } /** sdl_disconnect_req: - process SDL_DISCONNECT_REQ primitive * @ch: channel structure (locked) * @q: active queue (write queue) * @mp: the SDL_DISCONNECT_REQ primitive */ noinline fastcall __unlikely int sdl_disconnect_req(struct ch *ch, queue_t *q, mblk_t *mp) { sdl_disconnect_req_t *p = (typeof(p)) mp->b_rptr; if (unlikely(!MBLKIN(mp, 0, sizeof(*p)))) return (-EMSGSIZE); if (p->sdl_flags & SDL_RX_DIRECTION) { ch->sdl.config.ifflags &= ~SDL_IF_RX_RUNNING; ch->sdl.statem.rx_state = SDL_STATE_IDLE; LOGNO(ch2sid(ch), "Disabling Rx"); } if (p->sdl_flags & SDL_TX_DIRECTION) { ch->sdl.config.ifflags &= ~SDL_IF_TX_RUNNING; ch->sdl.statem.tx_state = SDL_STATE_IDLE; LOGNO(ch2sid(ch), "Disabling Tx"); } if (!(ch->sdl.config.ifflags & (SDL_IF_TX_RUNNING | SDL_IF_RX_RUNNING))) { LOGNO(ch2sid(ch), "Marking interface down"); ch->sdl.config.ifflags &= ~SDL_IF_UP; } freemsg(mp); return (0); } /* * ------------------------------------------------------------------------- * * LMI primitives * * ------------------------------------------------------------------------- */ /** lmi_info_req: - process LMI_INFO_REQ primitive * @xp: private structure (locked) * @q: active queue (write queue) * @mp: the LMI_INFO_REQ primitive */ noinline fastcall __unlikely int lmi_info_req(struct xp *xp, queue_t *q, mblk_t *mp) { uint16_t ppa; caddr_t ppa_ptr = NULL; size_t ppa_len = 0; switch (xp_get_state(xp)) { struct ch *ch; case LMI_ENABLED: case LMI_DISABLED: if ((ch = xp->ch)) { ppa = ch->ppa; ppa_ptr = (caddr_t) &ppa; ppa_len = sizeof(ppa); } break; } return lmi_info_ack(xp, q, mp, ppa_ptr, ppa_len); } /** lmi_attach_req: - process LMI_ATTACH_REQ primitive * @xp: private structure (locked) * @q: active queue (write queue) * @mp: the LMI_ATTACH_REQ primitive * * LMI_ATTACH_REQ results in attaching the xp structure to the appropriate ch structure. * * We used to bind the xp structure to the ch structure when performing an attach. However, this * meant that one could not open a signalling link, attach to a ppa, perform some ioctls, and then * detach and close. What we do now is a semi-attachment: we link the xp structure to the ch * structure but not vise versa. The difference is that the ch structure can be attached to a * different xp structure in an active connection. */ noinline fastcall __unlikely int lmi_attach_req(struct xp *xp, queue_t *q, mblk_t *mp) { lmi_attach_req_t *p = ((typeof(p)) mp->b_rptr); uint16_t ppa; int card, span, chan; if (!MBLKIN(mp, 0, sizeof(*p))) goto badprim; if (xp_get_state(xp) != LMI_UNATTACHED) goto outstate; if (!MBLKIN(mp, p->lmi_ppa_offset, p->lmi_ppa_length)) goto badppa; if (p->lmi_ppa_length != sizeof(ppa)) goto badppa; xp_set_state(xp, LMI_ATTACH_PENDING); ppa = *(typeof(ppa) *) (mp->b_rptr + p->lmi_ppa_offset); read_lock(&xp_core_lock); { struct cd *cd; struct sp *sp; struct ch *ch; /* check card */ card = (ppa >> 12) & 0x0f; if (card < 0 || card > X400_CARDS - 1) { read_unlock(&xp_core_lock); goto badcard; } if (!(cd = x400p_cards[card])) { read_unlock(&xp_core_lock); goto nocard; } /* check span */ span = (ppa >> 8) & 0x0f; if (span < 0 || span > cd->ports - 1) { read_unlock(&xp_core_lock); goto badspan; } if (!(sp = cd->spans[span])) { read_unlock(&xp_core_lock); goto nospan; } #ifdef DEBUG if (sp->config.ifgtype != SDL_GTYPE_E1 && sp->config.ifgtype != SDL_GTYPE_T1 && sp->config.ifgtype != SDL_GTYPE_J1) { read_unlock(&xp_core_lock); swerr(); goto efault; } #endif /* check chan */ chan = (ppa >> 0) & 0xff; switch (sp->config.ifgtype) { case SDL_GTYPE_E1: if (chan < 0 || chan > 31) { read_unlock(&xp_core_lock); goto badchan; } break; case SDL_GTYPE_T1: case SDL_GTYPE_J1: if (chan < 0 || chan > 24) { read_unlock(&xp_core_lock); goto badchan; } break; default: read_unlock(&xp_core_lock); goto badppa; } if (!(ch = sp->chans[chan])) { read_unlock(&xp_core_lock); goto nochan; } #if 0 if ((ch = sp->chans[0]) && ch->xp) { read_unlock(&xp_core_lock); goto chanbusy; } if (chan == 0) { int c; switch (sp->config.ifgtype) { case SDL_GTYPE_E1: for (c = 1; c < 32; c++) { if (!(ch = sp->chans[c])) continue; if (ch->xp) goto chanbusy; } break; case SDL_GTYPE_T1: case SDL_GTYPE_J1: for (c = 1; c < 25; c++) { if (!(ch = sp->chans[c])) continue; if (ch->xp) goto chanbusy; } break; default: goto badppa; } } else { if ((ch = sp->chans[chan])) if (ch->xp) goto chanbusy; } #endif ch = sp->chans[chan]; xp->card = card; xp->span = span; xp->chan = chan; xp->ch = ch_get(ch); #if 0 ch->xp = xp; #endif } read_unlock(&xp_core_lock); LOGNO(xp2sid(xp), "INFO: attached card %d, span %d, chan %d", card, span, chan); lmi_ok_ack(xp, q, mp, LMI_DISABLED, LMI_ATTACH_REQ); return (0); #ifdef DEBUG efault: return (-EFAULT); #endif outstate: LOGNO(xp2sid(xp), "%s: ERROR: interface out of state", __FUNCTION__); return (-EPROTO); badprim: LOGNO(xp2sid(xp), "%s: ERROR: primitive too small = %ld bytes", __FUNCTION__, (long) MBLKSIZE(mp)); return (-EINVAL); badcard: LOGNO(xp2sid(xp), "%s: ERROR: invalid card %d", __FUNCTION__, card); goto badppa; nocard: LOGNO(xp2sid(xp), "%s: ERROR: unallocated card %d", __FUNCTION__, card); goto badppa; badspan: LOGNO(xp2sid(xp), "%s: ERROR: invalid span %d", __FUNCTION__, span); goto badppa; nospan: LOGNO(xp2sid(xp), "%s: ERROR: unallocated span %d", __FUNCTION__, span); goto badppa; badchan: LOGNO(xp2sid(xp), "%s: ERROR: invalid chan %d", __FUNCTION__, chan); goto badppa; nochan: LOGNO(xp2sid(xp), "%s: ERROR: unallocated chan %d", __FUNCTION__, chan); goto badppa; #if 0 chanbusy: LOGNO(xp2sid(xp), "%s: ERROR: already in use, chan %d", __FUNCTION__, chan); goto badppa; #endif badppa: return (-EADDRNOTAVAIL); } /** lmi_detach_req: - process LMI_DETACH_REQ primtive * @xp: private structure (locked) * @q: active queue (write queue) * @mp: the LMI_DETACH_REQ primitive * * LMI_DETACH_REQ results in detaching the xp structure from the ch structure to which it is * attached. */ noinline fastcall __unlikely int lmi_detach_req(struct xp *xp, queue_t *q, mblk_t *mp) { struct ch *ch; psw_t flags; /* validate detach */ if (xp_get_state(xp) != LMI_DISABLED) goto outstate; xp_set_state(xp, LMI_DETACH_PENDING); write_lock_irqsave(&xp_core_lock, flags); { ch = XCHG(&xp->ch, NULL); #ifdef DEBUG if (ch == NULL) { write_unlock_irqrestore(&xp_core_lock, flags); goto efault; } #endif ch_put(ch); xp->card = -1; xp->span = -1; xp->chan = -1; } write_unlock_irqrestore(&xp_core_lock, flags); lmi_ok_ack(xp, q, mp, LMI_UNATTACHED, LMI_DETACH_REQ); return (0); outstate: LOGNO(xp2sid(xp), "%s: ERROR: interface out of state", __FUNCTION__); return (-EPROTO); #ifdef DEBUG efault: LOGERR(xp2sid(xp), "%s: SWERR: not attached", __FUNCTION__); return (-EFAULT); #endif } /** startup_span: - startup span if not already running * @sp: span structure pointer */ noinline fastcall __unlikely void startup_span(struct sp *sp) { if (!(sp->config.ifflags & SDL_IF_UP)) { /* need to bring up span */ struct cd *cd = sp->cd; psw_t flags = 0; spin_lock_irqsave(&cd->lock, flags); sp->config.ifflags |= (SDL_IF_UP | SDL_IF_TX_RUNNING | SDL_IF_RX_RUNNING); /* enable interrupts */ cd->xlb[CTLREG] = cd->ctlreg | (INTENA | DINTENA); spin_unlock_irqrestore(&cd->lock, flags); } } /** lmi_enable_req: - process LMI_ENABLE_REQ primitive * @xp: private structure (locked) * @q: active queue (write queue) * @mp: the LMI_ENABLE_REQ primitive * * LMI_ENABLE_REQ used to configure the timeslot for operation and start up the span if it was not * already started, * * We use to bind the xp structure to the ch structure when performing an attach. However, this * meant that one could not open a signalling link, attach to a ppa, perform some ioctls, and then * detach and close. What we do now is a semi-attachment: we link the xp structure to the ch * structure but no vise versa. The ch structure is only linked back to a xp structure on enable. */ noinline fastcall __unlikely int lmi_enable_req(struct xp *xp, queue_t *q, mblk_t *mp) { struct ch *ch; struct sp *sp; psw_t flags; int chan = xp->chan; /* validate enable */ if (xp_get_state(xp) != LMI_DISABLED) goto outstate; if (!(ch = xp->ch)) { ptrace(("%s: ERROR: out of state: no chan pointer\n", DRV_NAME)); goto outstate; } if (!(sp = ch->sp)) { ptrace(("%s: ERROR: out of state: no span pointer\n", DRV_NAME)); goto outstate; } printd(("%s: %p: performing enable\n", DRV_NAME, xp)); xp_set_state(xp, LMI_ENABLE_PENDING); spin_lock_irqsave(&ch->lock, flags); { if (ch->sdl.config.ifflags & SDL_IF_UP) { spin_unlock_irqrestore(&ch->lock, flags); ptrace(("%s: ERROR: out of state: device already up\n", DRV_NAME)); goto outstate; } if (ch->xp != NULL) { spin_unlock_irqrestore(&ch->lock, flags); goto chanbusy; } if (chan == 0) { int c; for (c = 1; c < 32; c++) { if (sp->chans[c] == NULL) continue; if (sp->chans[c]->xp != NULL) { spin_unlock_irqrestore(&ch->lock, flags); goto chanbusy; } } } else { if (sp->chans[0]->xp != NULL) { spin_unlock_irqrestore(&ch->lock, flags); goto chanbusy; } } /* commit enable */ ch->xp = xp; ch->sdl.config.ifflags |= SDL_IF_UP; } spin_unlock_irqrestore(&ch->lock, flags); startup_span(sp); xp_set_state(xp, LMI_ENABLED); lmi_enable_con(xp, q, mp); return (0); outstate: LOGNO(xp2sid(xp), "%s: ERROR: out of state: state = %u", __FUNCTION__, xp_get_state(xp)); return (-EPROTO); chanbusy: LOGNO(xp2sid(xp), "%s: ERROR: already in use, chan %d", __FUNCTION__, chan); return (-EADDRNOTAVAIL); } /** lmi_disable_req: - process LMI_DISABLE_REQ primitive * @xp: private structure (locked) * @q: active queue (write queue) * @mp: the LMI_DISABLE_REQ primitive */ noinline fastcall __unlikely int lmi_disable_req(struct xp *xp, queue_t *q, mblk_t *mp) { struct ch *ch = xp->ch; struct sp *sp; struct cd *cd; /* validate disable */ if (xp_get_state(xp) != LMI_ENABLED) goto lmi_outstate; xp_set_state(xp, LMI_DISABLE_PENDING); /* commit disable */ if ((sp = ch->sp) && (cd = sp->cd)) { psw_t flags = 0; spin_lock_irqsave(&cd->lock, flags); { int chan, boff; uchar idle, *base = (uchar *) cd->wbuf + span_to_byte(sp->span); switch (cd->config.ifgtype) { case SDL_GTYPE_T1: case SDL_GTYPE_J1: idle = 0xfe; for (chan = 1; chan < 32; chan++) if (sp->chans[chan] == ch) for (boff = 0; boff < X400P_EBUFNO; boff++) *(base + (boff << 10) + (xp_t1_chan_map[chan] << 2)) = idle; break; default: case SDL_GTYPE_E1: idle = 0xff; for (chan = 1; chan < 32; chan++) if (sp->chans[chan] == ch) for (boff = 0; boff < X400P_EBUFNO; boff++) *(base + (boff << 10) + (xp_e1_chan_map[chan] << 2)) = idle; break; } /* stop transmitters and receivers */ ch->sdl.config.ifflags = 0; ch->sdl.statem.tx_state = SDL_STATE_IDLE; ch->sdl.statem.rx_state = SDL_STATE_IDLE; /* stop daedr and daedt */ ch->sdt.statem.daedt_state = SDT_STATE_IDLE; ch->sdt.statem.daedr_state = SDT_STATE_IDLE; /* stop aerm */ ch->sdt.statem.aerm_state = SDT_STATE_IDLE; ch->sdt.statem.Ti = ch->sdt.config.Tin; /* stop eim */ ch->sdt.statem.eim_state = SDT_STATE_IDLE; xp_timer_stop(ch, t8); /* stop suerm */ ch->sdt.statem.suerm_state = SDT_STATE_IDLE; /* reset transmitter and receiver state */ if (ch->tx.msg && ch->tx.msg != ch->tx.cmp) freemsg(xchg(&ch->tx.msg, NULL)); if (ch->tx.cmp) freemsg(xchg(&ch->tx.cmp, NULL)); if (ch->rx.msg) freemsg(xchg(&ch->rx.msg, NULL)); if (ch->rx.nxt) freemsg(xchg(&ch->rx.nxt, NULL)); if (ch->rx.cmp) freemsg(xchg(&ch->rx.cmp, NULL)); bzero(&ch->tx, sizeof(ch->tx)); bzero(&ch->rx, sizeof(ch->tx)); if (ch->xp == xp) ch->xp = NULL; } spin_unlock_irqrestore(&cd->lock, flags); } else swerr(); /* perform disable */ lmi_disable_con(xp, q, mp); return (0); lmi_outstate: return (-EPROTO); } /** lmi_optmgmt_req: - process LMI_OPTMGMT_REQ primitive * @xp: private structure (locked) * @q: active queue (write queue) * @mp: the LMI_OPTMGMT_REQ primitive */ noinline fastcall __unlikely int lmi_optmgmt_req(struct xp *xp, queue_t *q, mblk_t *mp) { fixme(("FIXME: must check for options change\n")); return (-EOPNOTSUPP); } /* * ------------------------------------------------------------------------- * * DLPI PRIMITIVES * * ------------------------------------------------------------------------- */ /** dl_info_req: - process DL_INFO_REQ primtive * @xp: private structure (locked) * @q: active queue (write queue) * @mp: the DL_INFO_REQ primitive */ noinline fastcall __unlikely int dl_info_req(struct xp *xp, queue_t *q, mblk_t *mp) { dl_info_req_t *p; if (!MBLKIN(mp, 0, sizeof(*p))) goto badprim; return dl_info_ack(xp, q, mp); badprim: return (-EMSGSIZE); } /** dl_attach_req: - process DL_ATTACH_REQ primtive * @xp: private structure (locked) * @q: active queue (write queue) * @mp: the DL_ATTACH_REQ primitive * * This is not quite the same as the LMI. When we attach, we do not do anything more than * validate the PPA. While LMI binds to the ch structure at this point, we do not bind to the ch * until the DL_BIND_REQ. That is because there are a couple of ways of specifying that * monitoring is to be performed (dl_sap == 0, dl_service_mode of DL_HP_RAWDLS with a * dl_max_conind of 1), etc. */ noinline fastcall __unlikely int dl_attach_req(struct xp *xp, queue_t *q, mblk_t *mp) { dl_attach_req_t *p; prefetchw(xp); if (!MBLKIN(mp, 0, sizeof(*p))) goto badprim; p = (typeof(p)) mp->b_rptr; if (dl_get_state(xp) != DL_UNATTACHED) goto outstate; dl_set_state(xp, DL_ATTACH_PENDING); xp->ppa = p->dl_ppa; if (xp->ppa == 0) { /* Just want to attach to everything, that's ok. This is a global attach. */ xp->card = -1; xp->span = -1; xp->chan = -1; } else { /* check card */ if ((xp->card = (xp->ppa >> 12) & 0x0f) == 0x0f) { /* want to attach to all cards, same as ppa == 0 */ xp->ppa = 0; xp->card = -1; xp->span = -1; xp->chan = -1; } else { struct cd *cd; if (0 > xp->card || xp->card > X400_CARDS - 1) goto badppa; if (!(cd = x400p_cards[xp->card])) goto badppa; /* check span */ if ((xp->span = (xp->ppa >> 8) & 0x0f) == 0x0f) { /* want to attach to all spans on this card */ xp->span = -1; xp->chan = -1; } else { struct sp *sp; struct ch *ch; if (0 > xp->span || xp->span > cd->ports - 1) goto badppa; if (!(sp = cd->spans[xp->span])) goto badppa; /* check chan */ if ((xp->chan = (xp->ppa >> 0) & 0xff) == 0xff) { /* want all channels in this span */ xp->chan = -1; } else { switch (sp->config.ifgtype) { case SDL_GTYPE_E1: if (xp->chan < 0 || xp->chan > 31) goto badppa; break; case SDL_GTYPE_T1: case SDL_GTYPE_J1: if (xp->chan < 0 || xp->chan > 24) goto badppa; break; default: goto badppa; } if (!(ch = sp->chans[xp->chan])) goto badppa; } } } } dl_set_state(xp, DL_ATTACH_PENDING); dl_ok_ack(xp, q, mp, DL_UNBOUND, DL_ATTACH_REQ); return (0); badprim: return (-EMSGSIZE); outstate: return (-EPROTO); badppa: return (-EADDRNOTAVAIL); } /** dl_detach_req: - process DL_DETACH_REQ primtive * @xp: private structure (locked) * @q: active queue (write queue) * @mp: the DL_DETACH_REQ primitive * * This is largely a state transition: when we are attached (but unbound) to an interface, we * simply have the card, span, chan and slot numbers set to what was a valid interface at the time * of the attach. (Because, in general, interfaces do not disappear while the driver is loaded, an * interface, once validated, is persistently valid.) */ noinline fastcall __unlikely int dl_detach_req(struct xp *xp, queue_t *q, mblk_t *mp) { dl_detach_req_t *p; prefetchw(xp); if (!MBLKIN(mp, 0, sizeof(*p))) goto badprim; p = (typeof(p)) mp->b_rptr; if (dl_get_state(xp) != DL_UNBOUND) goto outstate; dl_set_state(xp, DL_DETACH_PENDING); xp->card = -1; xp->span = -1; xp->chan = -1; dl_ok_ack(xp, q, mp, DL_UNATTACHED, DL_DETACH_REQ); return (0); outstate: return (-EPROTO); badprim: return (-EMSGSIZE); } /** dl_bind_req: - process DL_BIND_REQ primtive * @xp: private structure (locked) * @q: active queue (write queue) * @mp: the DL_BIND_REQ primitive * * This is where we actually bind the xp structure to the appropriate ch structure (if any). */ noinline fastcall __unlikely int dl_bind_req(struct xp *xp, queue_t *q, mblk_t *mp) { dl_bind_req_t *p; struct cd *cd = NULL; struct sp *sp = NULL; struct ch *ch = NULL; int card, span; ulong reason = 0; ulong errno = 0; psw_t flags; prefetchw(xp); if (!MBLKIN(mp, 0, sizeof(*p))) goto badprim; p = (typeof(p)) mp->b_rptr; if (dl_get_state(xp) != DL_IDLE) goto outstate; dl_set_state(xp, DL_BIND_PENDING); /* the layout of these structures is static so no locks are required */ xp->monitor = XP_MONITOR_NONE; if (xp->card == -1) { /* driver level bind - always monitoring */ xp->monitor = XP_MONITOR_GLOB; goto monitoring; } cd = x400p_cards[xp->card]; if (!cd) /* card structure disappeared */ goto badbad; if (xp->span == -1) { /* card level bind - always monitoring */ xp->monitor = XP_MONITOR_CARD; goto monitoring; } sp = cd->spans[xp->span]; if (!sp) /* span structure disappeared */ goto badbad; if (xp->chan == -1) { /* span level bind - always monitoring */ xp->monitor = XP_MONITOR_SPAN; goto monitoring; } ch = sp->chans[xp->chan]; if (!ch) /* chan structure disappeared */ goto badbad; monitoring: /* we are attached to a timeslot and are not necessarily monitoring, need some more info from the DL_BIND_REQ to determine what to do. */ switch (p->dl_service_mode) { #ifdef _HPUX_SOURCE case DL_HP_RAWDLS: if (p->dl_max_conind == 1) { /* this is how HP does it */ if (xp->monitor == XP_MONITOR_NONE) xp->monitor = XP_MONITOR_CHAN; } break; #endif /* _HPUX_SOURCE */ case DL_CLDLS: /* When it asks for connection-less data link service on this interface, always assume that the application wants monitoring at the chan level. */ if (xp->monitor == XP_MONITOR_NONE) xp->monitor = XP_MONITOR_CHAN; break; case DL_CODLS: /* When it asks for connection-oriented data link service on this interface, always assume that the application wants active connection at the chan level. If a monitoring PPA was attached, this is an error. */ if (xp->monitor != XP_MONITOR_NONE) goto badserv; break; case DL_ACLDLS: default: goto badserv; } switch ((xp->level = p->dl_sap)) { case XP_LEVEL_MON_SDT: /* base SDT monitoring SAP */ case XP_LEVEL_MON_SL: /* base SL monitoring SAP */ if (xp->monitor == XP_MONITOR_NONE) xp->monitor = XP_MONITOR_CHAN; break; case XP_LEVEL_ACT_SDT: /* SDT non-monitoring SAP */ case XP_LEVEL_ACT_SL: /* SL non-monitoring SAP */ case XP_LEVEL_ACT_SDL: /* SDL non-monitoring SAP */ if (xp->monitor != XP_MONITOR_NONE) goto badsap; break; case XP_LEVEL_MON_SDL: /* base SDL monitoring SAP */ default: goto badsap; } switch (xp->monitor) { int chan; case XP_MONITOR_NONE: /* not monitoring, active link */ /* we are doing what lmi_attach and lmi_enable would do */ if (sp->config.iftxlevel < 8) { spin_lock_bh(&ch->lock); if (ch->xp == NULL) { ch->xp = xp; xp->ch = ch_get(ch); ch->sdl.statem.rx_state = SDL_STATE_IDLE; ch->sdl.statem.tx_state = SDL_STATE_IDLE; ch->sdl.config.ifflags = 0; ch->sdt.statem.daedr_state = SDT_STATE_IDLE; ch->sdt.statem.daedt_state = SDT_STATE_IDLE; } else { reason = DL_BUSY; errno = EADDRNOTAVAIL; } spin_unlock_bh(&ch->lock); if (reason != 0) goto addrnotavail; #if 0 /* FIXME FIXME FIXME: we need to convert timers back to being independent of a STREAMS queue. Just use regular linux timers. */ /* remember to free timers on unbind */ if (xp_alloc_timers(ch, xp->oq)) { spin_lock_bh(&ch->lock); ch->xp = NULL; ch_put(xchg(&xp->ch, NULL)); spin_unlock_bh(&ch->lock); reason = DL_SYSERR; reason = ENOMEM; } #endif } if (reason != 0) goto addrnotavail; ch->sdl.config.ifflags |= SDL_IF_UP; startup_span(sp); break; case XP_MONITOR_GLOB: /* monitoring at the driver level */ switch (xp->level) { case XP_LEVEL_MON_SDT: /* monitoring SDT */ xp->xray.flags = XP_XRAY_SDT_GLOB; break; case XP_LEVEL_MON_SL: /* monitoring SL */ xp->xray.flags = XP_XRAY_SL_GLOB; break; case XP_LEVEL_MON_SDL: /* monitoring SDL */ xp->xray.flags = XP_XRAY_SDL_GLOB; break; } read_lock_irqsave(&x400p_lock, flags); if ((xp->xray.next = x400p_xrays)) xp->xray.next->xray.prev = &xp->xray.next; xp->xray.prev = &x400p_xrays; x400p_xrays = xp; read_unlock_irqrestore(&x400p_lock, flags); for (card = 0; card < X400_CARDS; card++) { if (!(cd = x400p_cards[card])) continue; for (span = 0; span < cd->ports; span++) { int chan; if (!(sp = cd->spans[span])) continue; if (xp->level == XP_LEVEL_MON_SDT && sp->config.iftxlevel > 7) startup_span(sp); for (chan = 0; chan < 32; chan++) { if (!(ch = sp->chans[chan])) continue; spin_lock_bh(&ch->lock); ch->xray.flags |= xp->xray.flags; if (xp->level == XP_LEVEL_MON_SDT && sp->config.iftxlevel > 7) { sl_daedt_start(ch); sl_daedr_start(ch); } spin_unlock_bh(&ch->lock); } } } break; case XP_MONITOR_CARD: /* monitoring at the card level */ switch (xp->level) { case XP_LEVEL_MON_SDT: /* monitoring SDT */ xp->xray.flags = XP_XRAY_SDT_CARD; break; case XP_LEVEL_MON_SL: /* monitoring SL */ xp->xray.flags = XP_XRAY_SL_CARD; break; case XP_LEVEL_MON_SDL: /* monitoring SDL */ xp->xray.flags = XP_XRAY_SDL_CARD; break; } spin_lock_irqsave(&cd->lock, flags); if ((xp->xray.next = cd->xray)) xp->xray.next->xray.prev = &xp->xray.next; xp->xray.prev = &cd->xray; cd->xray = xp; spin_unlock_irqrestore(&cd->lock, flags); for (span = 0; span < 4; span++) { int chan; if (!(sp = cd->spans[span])) continue; for (chan = 0; chan < 32; chan++) { if (!(ch = sp->chans[chan])) continue; spin_lock_bh(&ch->lock); ch->xray.flags |= xp->xray.flags; if (xp->level == XP_LEVEL_MON_SDT && sp->config.iftxlevel > 7) { sl_daedt_start(ch); sl_daedr_start(ch); } spin_unlock_bh(&ch->lock); } if (xp->level == XP_LEVEL_MON_SDT && sp->config.iftxlevel > 7) startup_span(sp); } break; case XP_MONITOR_SPAN: /* monitoring at the span level */ switch (xp->level) { case XP_LEVEL_MON_SDT: /* monitoring SDT */ xp->xray.flags = XP_XRAY_SDT_SPAN; break; case XP_LEVEL_MON_SL: /* monitoring SL */ xp->xray.flags = XP_XRAY_SL_SPAN; break; case XP_LEVEL_MON_SDL: /* monitoring SDL */ xp->xray.flags = XP_XRAY_SDL_SPAN; break; } spin_lock_irqsave(&sp->lock, flags); if ((xp->xray.next = sp->xray)) xp->xray.next->xray.prev = &xp->xray.next; xp->xray.prev = &sp->xray; sp->xray = xp; spin_unlock_irqrestore(&sp->lock, flags); for (chan = 0; chan < 32; chan++) { if (!(ch = sp->chans[chan])) continue; spin_lock_bh(&ch->lock); ch->xray.flags |= xp->xray.flags; if (xp->level == XP_LEVEL_MON_SDT && sp->config.iftxlevel > 7) { sl_daedt_start(ch); sl_daedr_start(ch); } spin_unlock_bh(&ch->lock); } if (xp->level == XP_LEVEL_MON_SDT && sp->config.iftxlevel > 7) startup_span(sp); break; case XP_MONITOR_CHAN: /* monitoring at the chan level */ switch (xp->level) { case XP_LEVEL_MON_SDT: /* monitoring SDT */ xp->xray.flags = XP_XRAY_SDT_CHAN; break; case XP_LEVEL_MON_SL: /* monitoring SL */ xp->xray.flags = XP_XRAY_SL_CHAN; break; case XP_LEVEL_MON_SDL: /* monitoring SDL */ xp->xray.flags = XP_XRAY_SDL_CHAN; break; } spin_lock_bh(&ch->lock); if ((xp->xray.next = ch->xray.list)) xp->xray.next->xray.prev = &xp->xray.next; xp->xray.prev = &ch->xray.list; ch->xray.list = xp; ch->xray.flags |= xp->xray.flags; if (xp->level == XP_LEVEL_MON_SDT && sp->config.iftxlevel > 7) { sl_daedt_start(ch); sl_daedr_start(ch); } spin_unlock_bh(&ch->lock); if (xp->level == XP_LEVEL_MON_SDT && sp->config.iftxlevel > 7) startup_span(sp); break; } dl_bind_ack(xp, q, mp, xp->level, xp->monitor ? 0 : 1); return (0); addrnotavail: return (-EADDRNOTAVAIL); badprim: return (-EMSGSIZE); outstate: return (-EPROTO); badbad: return (-EFAULT); badserv: return (-EPROTONOSUPPORT); badsap: return (-EAFNOSUPPORT); } /** dl_unbind_req: - process DL_UNBIND_REQ primtive * @xp: private structure (locked) * @q: active queue (write queue) * @mp: the DL_UNBIND_REQ primitive */ noinline fastcall __unlikely int dl_unbind_req(struct xp *xp, queue_t *q, mblk_t *mp) { struct ch *ch = xp->ch; dl_unbind_req_t *p; psw_t flags; if (!MBLKIN(mp, 0, sizeof(*p))) goto badprim; if (dl_get_state(xp) != DL_IDLE || ch == NULL) goto outstate; dl_set_state(xp, DL_UNBIND_PENDING); switch (xp->monitor) { case XP_MONITOR_NONE: /* not monitoring */ switch (xp->level) { case XP_LEVEL_ACT_SL: /* SL level */ spin_lock_bh(&ch->lock); sl_lsc_stop(ch); spin_unlock_bh(&ch->lock); break; case XP_LEVEL_ACT_SDT: /* SDT level */ spin_lock_bh(&ch->lock); ch->sdt.statem.daedr_state = SDT_STATE_IDLE; ch->sdt.statem.daedt_state = SDT_STATE_IDLE; ch->sdl.config.ifflags &= ~SDL_IF_RX_RUNNING; ch->sdl.config.ifflags &= ~SDL_IF_TX_RUNNING; spin_unlock_bh(&ch->lock); break; case XP_LEVEL_ACT_SDL: /* SDL level */ spin_lock_bh(&ch->lock); ch->sdl.config.ifflags &= ~SDL_IF_RX_RUNNING; ch->sdl.config.ifflags &= ~SDL_IF_TX_RUNNING; spin_unlock_bh(&ch->lock); break; } break; case XP_MONITOR_GLOB: /* monitoring at driver level */ xp->xray.flags &= ~XP_XRAY_GLOB; /* ch will fix their own xray flags */ read_lock_irqsave(&x400p_lock, flags); if (((*xp->xray.prev) = xp->xray.next)) xp->xray.next->xray.prev = xp->xray.prev; xp->xray.next = NULL; xp->xray.prev = &xp->xray.next; read_unlock_irqrestore(&x400p_lock, flags); break; case XP_MONITOR_CARD: /* monitoring at card level */ { struct cd *cd = cd_find(xp->card); if (!cd) goto efault; xp->xray.flags &= ~XP_XRAY_CARD; /* ch will fix their own xray flags */ spin_lock_irqsave(&cd->lock, flags); if (((*xp->xray.prev) = xp->xray.next)) xp->xray.next->xray.prev = xp->xray.prev; xp->xray.next = NULL; xp->xray.prev = &xp->xray.next; spin_unlock_irqrestore(&cd->lock, flags); break; } case XP_MONITOR_SPAN: /* monitoring at span level */ { struct cd *cd = cd_find(xp->card); struct sp *sp; if (!cd) goto efault; sp = cd->spans[xp->span]; if (!sp) goto efault; xp->xray.flags &= ~XP_XRAY_SPAN; /* ch will fix their own xray flags */ spin_lock_irqsave(&sp->lock, flags); if (((*xp->xray.prev) = xp->xray.next)) xp->xray.next->xray.prev = xp->xray.prev; xp->xray.next = NULL; xp->xray.prev = &xp->xray.next; spin_unlock_irqrestore(&sp->lock, flags); break; } case XP_MONITOR_CHAN: /* monitoring at chan level */ xp->xray.flags &= ~XP_XRAY_CHAN; /* ch will fix their own xray flags */ spin_lock_bh(&ch->lock); if (((*xp->xray.prev) = xp->xray.next)) xp->xray.next->xray.prev = xp->xray.prev; xp->xray.next = NULL; xp->xray.prev = &xp->xray.next; spin_unlock_bh(&ch->lock); break; } dl_ok_ack(xp, q, mp, DL_UNBOUND, DL_UNBIND_REQ); return (0); efault: return (-EFAULT); outstate: return (-EPROTO); badprim: return (-EMSGSIZE); } /** dl_subs_bind_req: - process DL_SUBS_BIND_REQ primtive * @xp: private structure (locked) * @q: active queue (write queue) * @mp: the DL_SUBS_BIND_REQ primitive */ static inline fastcall __unlikely int dl_subs_bind_req(struct xp *xp, queue_t *q, mblk_t *mp) { return (-EOPNOTSUPP); } /** dl_subs_unbind_req: - process DL_SUBS_UNBIND_REQ primtive * @xp: private structure (locked) * @q: active queue (write queue) * @mp: the DL_SUBS_UNBIND_REQ primitive */ static inline fastcall __unlikely int dl_subs_unbind_req(struct xp *xp, queue_t *q, mblk_t *mp) { /* can never be in the right state */ return (-EPROTO); } /** dl_unitdata_req: - process DL_UNITDATA_REQ primtive * @xp: private structure (locked) * @q: active queue (write queue) * @mp: the DL_UNITDATA_REQ primitive */ static inline fastcall __unlikely int dl_unitdata_req(struct xp *xp, queue_t *q, mblk_t *mp) { return (-EOPNOTSUPP); } /** dl_udqos_req: - process DL_UDQOS_REQ primtive * @xp: private structure (locked) * @q: active queue (write queue) * @mp: the DL_UDQOS_REQ primitive */ static inline fastcall __unlikely int dl_udqos_req(struct xp *xp, queue_t *q, mblk_t *mp) { return (-EOPNOTSUPP); } /** dl_connect_req: - process DL_CONNECT_REQ primtive * @xp: private structure (locked) * @q: active queue (write queue) * @mp: the DL_CONNECT_REQ primitive */ noinline fastcall __unlikely int dl_connect_req(struct xp *xp, queue_t *q, mblk_t *mp) { struct ch *ch = xp->ch; if (dl_get_state(xp) != DL_IDLE || ch == NULL) goto outstate; if (xp->monitor) return (-EOPNOTSUPP); switch (xp->level) { case XP_LEVEL_ACT_SDL: /* SDL connection */ spin_lock_bh(&ch->lock); ch->sdl.config.ifflags |= SDL_IF_TX_RUNNING; ch->sdl.statem.tx_state = SDL_STATE_IN_SERVICE; ch->sdl.config.ifflags |= SDL_IF_RX_RUNNING; ch->sdl.statem.rx_state = SDL_STATE_IN_SERVICE; ch->sdl.config.ifflags |= SDL_IF_UP; spin_unlock_bh(&ch->lock); break; case XP_LEVEL_ACT_SDT: /* SDT connection */ spin_lock_bh(&ch->lock); sl_daedt_start(ch); sl_daedr_start(ch); spin_unlock_bh(&ch->lock); break; case XP_LEVEL_ACT_SL: /* SL connection */ spin_lock_bh(&ch->lock); sl_lsc_start(ch); spin_unlock_bh(&ch->lock); break; } return (-EOPNOTSUPP); outstate: return (-EPROTO); } /** dl_connect_res: - process DL_CONNECT_RES primtive * @xp: private structure (locked) * @q: active queue (write queue) * @mp: the DL_CONNECT_RES primitive */ static inline fastcall __unlikely int dl_connect_res(struct xp *xp, queue_t *q, mblk_t *mp) { /* can never be in correct state */ return (-EPROTO); } /** dl_token_req: - process DL_TOKEN_REQ primtive * @xp: private structure (locked) * @q: active queue (write queue) * @mp: the DL_TOKEN_REQ primitive */ noinline fastcall __unlikely int dl_token_req(struct xp *xp, queue_t *q, mblk_t *mp) { dl_token_ack(xp, q, mp); return (0); } /** dl_disconnect_req: - process DL_DISCONNECT_REQ primtive * @xp: private structure (locked) * @q: active queue (write queue) * @mp: the DL_DISCONNECT_REQ primitive */ noinline fastcall __unlikely int dl_disconnect_req(struct xp *xp, queue_t *q, mblk_t *mp) { struct ch *ch = xp->ch; if (dl_get_state(xp) != DL_DATAXFER || ch == NULL) goto outstate; if (xp->monitor) return (-EOPNOTSUPP); switch (xp->level) { case XP_LEVEL_ACT_SDL: /* SDL connection */ spin_lock_bh(&ch->lock); ch->sdl.config.ifflags &= ~(SDL_IF_TX_RUNNING | SDL_IF_RX_RUNNING | SDL_IF_UP); ch->sdl.statem.rx_state = SDL_STATE_IDLE; ch->sdl.statem.tx_state = SDL_STATE_IDLE; spin_unlock_bh(&ch->lock); break; case XP_LEVEL_ACT_SDT: /* SDT connection */ spin_lock_bh(&ch->lock); ch->sdt.statem.daedr_state = SDT_STATE_IDLE; ch->sdl.statem.rx_state = SDL_STATE_IDLE; ch->sdt.statem.daedt_state = SDT_STATE_IDLE; ch->sdl.statem.tx_state = SDL_STATE_IDLE; ch->sdl.config.ifflags &= ~(SDL_IF_TX_RUNNING | SDL_IF_RX_RUNNING | SDL_IF_UP); spin_unlock_bh(&ch->lock); break; case XP_LEVEL_ACT_SL: /* SL connection */ spin_lock_bh(&ch->lock); sl_lsc_stop(ch); spin_unlock_bh(&ch->lock); } return (0); outstate: return (-EPROTO); } /** dl_reset_req: - process DL_RESET_REQ primtive * @xp: private structure (locked) * @q: active queue (write queue) * @mp: the DL_RESET_REQ primitive */ static inline fastcall __unlikely int dl_reset_req(struct xp *xp, queue_t *q, mblk_t *mp) { return (-EOPNOTSUPP); } /** dl_reset_res: - process DL_RESET_RES primtive * @xp: private structure (locked) * @q: active queue (write queue) * @mp: the DL_RESET_RES primitive */ static inline fastcall __unlikely int dl_reset_res(struct xp *xp, queue_t *q, mblk_t *mp) { return (-EPROTO); } /** dl_xid_req: - process DL_XID_REQ primtive * @xp: private structure (locked) * @q: active queue (write queue) * @mp: the DL_XID_REQ primitive */ static inline fastcall __unlikely int dl_xid_req(struct xp *xp, queue_t *q, mblk_t *mp) { return (-EOPNOTSUPP); } /** dl_xid_res: - process DL_XID_RES primtive * @xp: private structure (locked) * @q: active queue (write queue) * @mp: the DL_XID_RES primitive */ static inline fastcall __unlikely int dl_xid_res(struct xp *xp, queue_t *q, mblk_t *mp) { return (-EPROTO); } /** dl_test_req: - process DL_TEST_REQ primtive * @xp: private structure (locked) * @q: active queue (write queue) * @mp: the DL_TEST_REQ primitive */ static inline fastcall __unlikely int dl_test_req(struct xp *xp, queue_t *q, mblk_t *mp) { return (-EOPNOTSUPP); } /** dl_test_res: - process DL_TEST_RES primtive * @xp: private structure (locked) * @q: active queue (write queue) * @mp: the DL_TEST_RES primitive */ static inline fastcall __unlikely int dl_test_res(struct xp *xp, queue_t *q, mblk_t *mp) { return (-EPROTO); } /** dl_enabmulti_req: - process DL_ENABMULTI_REQ primtive * @xp: private structure (locked) * @q: active queue (write queue) * @mp: the DL_ENABMULTI_REQ primitive */ static inline fastcall __unlikely int dl_enabmulti_req(struct xp *xp, queue_t *q, mblk_t *mp) { return (-EOPNOTSUPP); } /** dl_disabmulti_req: - process DL_DISABMULTI_REQ primtive * @xp: private structure (locked) * @q: active queue (write queue) * @mp: the DL_DISABMULTI_REQ primitive */ static inline fastcall __unlikely int dl_disabmulti_req(struct xp *xp, queue_t *q, mblk_t *mp) { return (-ENOENT); } /** dl_promsicon_req: - process DL_PROMISCON_REQ primtive * @xp: private structure (locked) * @q: active queue (write queue) * @mp: the DL_PROMISCON_REQ primitive */ static inline fastcall __unlikely int dl_promiscon_req(struct xp *xp, queue_t *q, mblk_t *mp) { return (-EOPNOTSUPP); } /** dl_promiscoff_req: - process DL_PROMISCOFF_REQ primtive * @xp: private structure (locked) * @q: active queue (write queue) * @mp: the DL_PROMISCOFF_REQ primitive */ static inline fastcall __unlikely int dl_promiscoff_req(struct xp *xp, queue_t *q, mblk_t *mp) { return (-EOPNOTSUPP); } /** dl_phys_addr_req: - process DL_PHYS_ADDR_REQ primtive * @xp: private structure (locked) * @q: active queue (write queue) * @mp: the DL_PHYS_ADDR_REQ primitive * * TODO: There is no reason why we shouldn't deliver the signalling datalink/terminal identifier in * response to this message. */ static inline fastcall __unlikely int dl_phys_addr_req(struct xp *xp, queue_t *q, mblk_t *mp) { return (-EOPNOTSUPP); } /** dl_set_phys_addr_req: - process DL_SET_PHYS_ADDR_REQ primtive * @xp: private structure (locked) * @q: active queue (write queue) * @mp: the DL_SET_PHYS_ADDR_REQ primitive * * TODO: There is no reason why we shouldn't set the signalling datalink/terminal identifier in * response to this message. */ static inline fastcall __unlikely int dl_set_phys_addr_req(struct xp *xp, queue_t *q, mblk_t *mp) { return (-EOPNOTSUPP); } /** dl_get_statistics_req: - process DL_GET_STATISTICS_REQ primtive * @xp: private structure (locked) * @q: active queue (write queue) * @mp: the DL_GET_STATISTICS_REQ primitive * * TODO: There is no reason why we should not provide the current link statistics in response to * this primitive. */ static inline fastcall __unlikely int dl_get_statistics_req(struct xp *xp, queue_t *q, mblk_t *mp) { return (-EOPNOTSUPP); } /** dl_monitor_link_layer: - process DL_MONITOR_LINK_LAYER primtive * @xp: private structure (locked) * @q: active queue (write queue) * @mp: the DL_MONITOR_LINK_LAYER primitive * * This primitive is a Spider extension that we support with Linux Fast-STREAMS as well. It * requests that link layer monitoring be performed. I have no idea what the contents of the * primitive are, but I assume that it is empty other than the primitve type itself. We want the * stream to be attached to an interface, but not yet bound to it. I assume that the response to * the message is a DL_OK_ACK primtive. * * TODO: Implement this primitive. */ static inline fastcall __unlikely int dl_monitor_link_layer(struct xp *xp, queue_t *q, mblk_t *mp) { return (-EOPNOTSUPP); } #ifdef _SUN_SOURCE #ifdef DL_NOTIFY_REQ /** dl_notify_req: - process DL_NOTIFY_REQ primtive * @xp: private structure (locked) * @q: active queue (write queue) * @mp: the DL_NOTIFY_REQ primitive * * There are several notifications that are pertinent to SS7 signalling links: DL_NOTE_LINK_DOWN, * DL_NOTE_LINK_UP, DL_NOTE_SDU_SIZE, DL_NOTE_PHYS_ADDR, DL_NOTE_PROMISC_ON_PHYS, * DL_NOTE_PROMISC_OFF_PHYS, DL_NOTE_CAPAB_RENEG. * * TODO: Implement this primitive. */ static inline fastcall __unlikely int dl_notify_req(struct xp *xp, queue_t *q, mblk_t *mp) { return (-EOPNOTSUPP); } #endif /* DL_NOTIFY_REQ */ #ifdef DL_AGGR_REQ /** dl_aggr_req: - process DL_AGGR_REQ primtive * @xp: private structure (locked) * @q: active queue (write queue) * @mp: the DL_AGGR_REQ primitive * * This primitive is unsupported as it has no equivalent for SS7. */ static inline fastcall __unlikely int dl_aggr_req(struct xp *xp, queue_t *q, mblk_t *mp) { return (-EOPNOTSUPP); } #endif /* DL_AGGR_REQ */ #ifdef DL_UNAGGR_REQ /** dl_unaggr_req: - process DL_UNAGGR_REQ primtive * @xp: private structure (locked) * @q: active queue (write queue) * @mp: the DL_UNAGGR_REQ primitive * * This primitive is unsupported as it has no equivalent for SS7. */ static inline fastcall __unlikely int dl_unaggr_req(struct xp *xp, queue_t *q, mblk_t *mp) { return (-EOPNOTSUPP); } #endif /* DL_UNAGGR_REQ */ #ifdef DL_CAPABILITY_REQ /** dl_capability_req: - process DL_CAPABILITY_REQ primtive * @xp: private structure (locked) * @q: active queue (write queue) * @mp: the DL_CAPABILITY_REQ primitive * * This primitive is unsupported as it has no equivalent for SS7. */ static inline fastcall __unlikely int dl_capability_req(struct xp *xp, queue_t *q, mblk_t *mp) { return (-EOPNOTSUPP); } #endif /* DL_CAPABILITY_REQ */ #ifdef DL_CONTROL_REQ /** dl_control_req: - process DL_CONTROL_REQ primtive * @xp: private structure (locked) * @q: active queue (write queue) * @mp: the DL_CONTROL_REQ primitive * * This primitive is unsupported as it has no equivalent for SS7. */ static inline fastcall __unlikely int dl_control_req(struct xp *xp, queue_t *q, mblk_t *mp) { return (-EOPNOTSUPP); } #endif /* DL_CONTROL_REQ */ #ifdef DL_PASSIVE_REQ /** dl_passive_req: - process DL_PASSIVE_REQ primtive * @xp: private structure (locked) * @q: active queue (write queue) * @mp: the DL_PASSIVE_REQ primitive * * This primitive is unsupported as it has no equivalent for SS7. */ static inline fastcall __unlikely int dl_passive_req(struct xp *xp, queue_t *q, mblk_t *mp) { return (-EOPNOTSUPP); } #endif /* DL_PASSIVE_REQ */ #ifdef DL_INTR_MODE_REQ /** dl_intr_mode_req: - process DL_INTR_MODE_REQ primtive * @xp: private structure (locked) * @q: active queue (write queue) * @mp: the DL_INTR_MODE_REQ primitive * * This primitive is unsupported as it has no equivalent for SS7. */ static inline fastcall __unlikely int dl_intr_mode_req(struct xp *xp, queue_t *q, mblk_t *mp) { return (-EOPNOTSUPP); } #endif /* DL_INTR_MODE_REQ */ #endif /* SUN_SOURCE */ #ifdef _HPUX_SOURCE #ifdef DL_HP_PPA_REQ /** dl_hp_ppa_req: - process DL_HP_PPA_REQ primtive * @xp: private structure (locked) * @q: active queue (write queue) * @mp: the DL_HP_PPA_REQ primitive * * See DL_HP_PPA_REQ(7). The DL_HP_PPA_REQ primitive is used to obtain a list of all of the valid * Physical Points of Attachment (PPA) currently installed in the system and known to the DLS * provider. The primitive requests that the DLS provider assemble a list of all PPA known to the * provider and acknowledge the successful receipt of the primitive by issuing a DL_HP_PPA_ACK(7) * primitive containing the list of PPA and PPA associated information. * * TODO: Implement this primitive. */ static inline fastcall __unlikely int dl_hp_ppa_req(struct xp *xp, queue_t *q, mblk_t *mp) { return (-EOPNOTSUPP); } #endif /* DL_HP_PPA_REQ */ #ifdef DL_HP_MULTICAST_LIST_REQ /** dl_hp_multicast_list_req: - process DL_HP_MULTICAST_LIST_REQ primtive * @xp: private structure (locked) * @q: active queue (write queue) * @mp: the DL_HP_MULTICAST_LIST_REQ primitive * * This primitive is unsupported as it has no equivalent for SS7. */ static inline fastcall __unlikely int dl_hp_multicast_list_req(struct xp *xp, queue_t *q, mblk_t *mp) { return (-EOPNOTSUPP); } #endif /* DL_HP_MULTICAST_LIST_REQ */ #ifdef DL_HP_RAWDATA_REQ /** dl_hp_rawdata_req: - process DL_HP_RAWDATA_REQ primtive * @xp: private structure (locked) * @q: active queue (write queue) * @mp: the DL_HP_RAWDATA_REQ primitive * * TODO: Implement this primitive. */ static inline fastcall __unlikely int dl_hp_rawdata_req(struct xp *xp, queue_t *q, mblk_t *mp) { return (-EOPNOTSUPP); } #endif /* DL_HP_RAWDATA_REQ */ #ifdef DL_HP_HW_RESET_REQ /** dl_hp_hw_reset_req: - process DL_HP_HW_RESET_REQ primtive * @xp: private structure (locked) * @q: active queue (write queue) * @mp: the DL_HP_HW_RESET_REQ primitive * * TODO: Implement this primitive. */ static inline fastcall __unlikely int dl_hp_hw_reset_req(struct xp *xp, queue_t *q, mblk_t *mp) { return (-EOPNOTSUPP); } #endif /* DL_HP_HW_RESET_REQ */ #endif /* _HPUX_SOURCE */ /* * ========================================================================= * * IO Controls * * ========================================================================= */ STATIC __unlikely int dsx_info_size(dsx_info_t * arg) { int size = sizeof(*arg); switch (arg->type) { case DSX_OBJ_TYPE_DFLT: size += sizeof(arg->info->dflt); break; case DSX_OBJ_TYPE_SPAN: size += sizeof(arg->info->span); break; case DSX_OBJ_TYPE_CHAN: size += sizeof(arg->info->chan); break; case DSX_OBJ_TYPE_FRAC: size += sizeof(arg->info->frac); break; default: return (-EINVAL); } return (size); } noinline __unlikely int dsx_iocginfo_dflt(dsx_info_t * arg) { return (0); } noinline __unlikely int dsx_iocginfo_span(struct sp *sp, dsx_info_t * arg) { return (0); } noinline __unlikely int dsx_iocginfo_chan(struct sp *sp, struct ch *ch, dsx_info_t * arg) { return (0); } noinline __unlikely int dsx_iocginfo_frac(struct sp *sp, struct ch *ch, dsx_info_t * arg) { return (0); } noinline __unlikely int dsx_iocginfo(queue_t *q, mblk_t *mp, mblk_t *dp) { dsx_info_t *hdr, *arg = (typeof(arg)) dp->b_rptr; int ret; mblk_t *db; if ((ret = dsx_info_size(arg)) < 0) return (ret); if (!(db = mi_copyout_alloc(q, mp, 0, ret, 0))) return (-ENOSR); *(hdr = (typeof(hdr)) db->b_rptr) = *arg; switch (arg->type) { struct sp *sp; struct ch *ch; case DSX_OBJ_TYPE_DFLT: if (arg->id != 0) return (-ESRCH); if ((ret = dsx_iocginfo_dflt(hdr)) < 0) return (ret); break; case DSX_OBJ_TYPE_SPAN: if (!(sp = sp_find(arg->id))) return (-ESRCH); if ((ret = dsx_iocginfo_span(sp, hdr)) < 0) return (ret); break; case DSX_OBJ_TYPE_CHAN: if (!(sp = sp_find(arg->id))) return (-ESRCH); if (IS_ERR((ch = ch_find(arg->id)))) return (-ESRCH); if ((ret = dsx_iocginfo_chan(sp, ch, hdr)) < 0) return (ret); break; case DSX_OBJ_TYPE_FRAC: if (!(sp = sp_find(arg->id))) return (-ESRCH); if (IS_ERR((ch = ch_find(arg->id)))) return (-ESRCH); if ((ret = dsx_iocginfo_frac(sp, ch, hdr)) < 0) return (ret); break; default: return (-EINVAL); } mi_copyout(q, mp); return (0); } STATIC __unlikely int dsx_option_size(dsx_option_t * arg) { int size = sizeof(*arg); switch (arg->type) { case DSX_OBJ_TYPE_DFLT: size += sizeof(arg->option->dflt); break; case DSX_OBJ_TYPE_SPAN: size += sizeof(arg->option->span); break; case DSX_OBJ_TYPE_CHAN: size += sizeof(arg->option->chan); break; case DSX_OBJ_TYPE_FRAC: size += sizeof(arg->option->frac); break; default: return (-EINVAL); } return (size); } noinline __unlikely int dsx_iocgoption_dflt(dsx_option_t * arg) { return (0); } noinline __unlikely int dsx_iocgoption_span(struct sp *sp, dsx_option_t * arg) { struct dsx_opt_conf_span *val = (typeof(val)) (arg + 1); val->dsx1SendCode = DSX1SENDCODE_DSX1SENDNOCODE; val->dsx1LoopbackConfig = DSX1LOOPBACKCONFIG_DSX1NOLOOP; switch (sp->config.ifclock) { case SDL_CLOCK_INT: case SDL_CLOCK_EXT: case SDL_CLOCK_MASTER: val->dsx1TransmitClockSource = DSX1TRANSMITCLOCKSOURCE_LOCALTIMING; break; case SDL_CLOCK_LOOP: val->dsx1TransmitClockSource = DSX1TRANSMITCLOCKSOURCE_LOOPTIMING; break; case SDL_CLOCK_SLAVE: val->dsx1TransmitClockSource = DSX1TRANSMITCLOCKSOURCE_THROUGHTIMING; break; default: case SDL_CLOCK_DPLL: case SDL_CLOCK_ABR: case SDL_CLOCK_SHAPER: case SDL_CLOCK_TICK: case SDL_CLOCK_NONE: val->dsx1TransmitClockSource = DSX1TRANSMITCLOCKSOURCE_ADAPTIVE; break; } val->dsx1Fdl = 0; val->dsx1Fdl |= (1 << DSX1FDL_OTHER); val->dsx1Fdl |= (1 << DSX1FDL_DSX1ANSIT1403); val->dsx1Fdl |= (1 << DSX1FDL_DSX1ATT54016); val->dsx1Fdl |= (1 << DSX1FDL_DSX1FDLNONE); val->dsx1LineStatusChangeTrapEnable = DSX1LINESTATUSCHANGETRAPENABLE_DISABLED; if (sp->config.iftxlevel & ~0x7) { val->dsx1LineMode = DSX1LINEMODE_DSU; val->dsx1LineLength = 0; val->dsx1LineBuildOut = DSX1LINEBUILDOUT_NOTAPPLICABLE; val->dsx1LineImpedance = DSX1LINEIMPEDANCE_NOTAPPLICABLE; } else if (0 < sp->config.iftxlevel && sp->config.iftxlevel < 5) { val->dsx1LineMode = DSX1LINEMODE_DSU; val->dsx1LineBuildOut = DSX1LINEBUILDOUT_NOTAPPLICABLE; if (sp->config.ifgtype != SDL_GTYPE_E1) { val->dsx1LineImpedance = DSX1LINEIMPEDANCE_BALANCED100OHMS; switch (sp->config.iftxlevel) { case 0: val->dsx1LineLength = 40; /* 40 meters: 133ft */ break; case 1: val->dsx1LineLength = 80; /* 80 meters: 266ft */ break; case 2: val->dsx1LineLength = 120; /* 120 meters: 399ft */ break; case 3: val->dsx1LineLength = 160; /* 160 meters: 533ft */ break; case 4: val->dsx1LineLength = 200; /* 200 meters: 666ft */ break; } } else { switch (sp->config.iftxlevel) { case 1: case 3: val->dsx1LineImpedance = DSX1LINEIMPEDANCE_UNBALANCED75OHMS; break; case 2: case 4: val->dsx1LineImpedance = DSX1LINEIMPEDANCE_BALANCED120OHMS; break; } } } else { val->dsx1LineLength = 0; val->dsx1LineMode = DSX1LINEMODE_CSU; if (sp->config.ifgtype != SDL_GTYPE_E1) { val->dsx1LineImpedance = DSX1LINEIMPEDANCE_BALANCED100OHMS; switch (sp->config.iftxlevel) { case 0: val->dsx1LineBuildOut = DSX1LINEBUILDOUT_ZERODB; break; case 5: val->dsx1LineBuildOut = DSX1LINEBUILDOUT_NEG75DB; break; case 6: val->dsx1LineBuildOut = DSX1LINEBUILDOUT_NEG15DB; break; case 7: val->dsx1LineBuildOut = DSX1LINEBUILDOUT_NEG225DB; break; } } else { switch (sp->config.iftxlevel) { case 0: case 7: val->dsx1LineImpedance = DSX1LINEIMPEDANCE_NOTAPPLICABLE; break; case 5: val->dsx1LineImpedance = DSX1LINEIMPEDANCE_UNBALANCED75OHMS; break; case 6: val->dsx1LineImpedance = DSX1LINEIMPEDANCE_BALANCED120OHMS; break; } } } return (0); } noinline __unlikely int dsx_iocgoption_chan(struct sp *sp, struct ch *ch, dsx_option_t * arg) { struct dsx_opt_conf_chan *val = (typeof(val)) (arg + 1); val->dsx0TransmitCodesEnable = DSX0TRANSMITCODESENABLE_FALSE; return (0); } noinline __unlikely int dsx_iocgoption_frac(struct sp *sp, struct ch *ch, dsx_option_t * arg) { return (0); } noinline __unlikely int dsx_iocgoption(queue_t *q, mblk_t *mp, mblk_t *dp) { dsx_option_t *hdr, *arg = (typeof(arg)) dp->b_rptr; int ret; mblk_t *db; if ((ret = dsx_option_size(arg)) < 0) return (ret); if (!(db = mi_copyout_alloc(q, mp, 0, ret, 0))) return (-ENOSR); *(hdr = (typeof(hdr)) db->b_rptr) = *arg; switch (arg->id) { struct sp *sp; struct ch *ch; case DSX_OBJ_TYPE_DFLT: if (arg->id != 0) return (-ESRCH); if ((ret = dsx_iocgoption_dflt(hdr)) < 0) return (ret); break; case DSX_OBJ_TYPE_SPAN: if (!(sp = sp_find(arg->id))) return (-ESRCH); if ((ret = dsx_iocgoption_span(sp, hdr)) < 0) return (ret); break; case DSX_OBJ_TYPE_CHAN: if (!(sp = sp_find(arg->id))) return (-ESRCH); if (IS_ERR((ch = ch_find(arg->id)))) return (-ESRCH); if ((ret = dsx_iocgoption_chan(sp, ch, hdr)) < 0) return (ret); break; case DSX_OBJ_TYPE_FRAC: if (!(sp = sp_find(arg->id))) return (-ESRCH); if (IS_ERR((ch = ch_find(arg->id)))) return (-ESRCH); if ((ret = dsx_iocgoption_frac(sp, ch, hdr)) < 0) return (ret); break; default: return (-EINVAL); } mi_copyout(q, mp); return (0); } noinline __unlikely int dsx_test_options_dflt(dsx_option_t * arg) { return (0); } noinline __unlikely int dsx_test_options_span(struct sp *sp, dsx_option_t * arg) { struct dsx_opt_conf_span *val = (typeof(val)) (arg + 1); switch (val->dsx1SendCode) { case DSX1SENDCODE_DSX1SENDNOCODE: break; case DSX1SENDCODE_DSX1SENDLINECODE: case DSX1SENDCODE_DSX1SENDPAYLOADCODE: case DSX1SENDCODE_DSX1SENDRESETCODE: case DSX1SENDCODE_DSX1SENDQRS: case DSX1SENDCODE_DSX1SEND511PATTERN: case DSX1SENDCODE_DSX1SEND3IN24PATTERN: case DSX1SENDCODE_DSX1SENDOTHERTESTPATTERN: goto eopnotsupp; default: goto einval; } switch (val->dsx1LoopbackConfig) { case DSX1LOOPBACKCONFIG_DSX1NOLOOP: break; case DSX1LOOPBACKCONFIG_DSX1PAYLOADLOOP: case DSX1LOOPBACKCONFIG_DSX1LINELOOP: case DSX1LOOPBACKCONFIG_DSX1OTHERLOOP: case DSX1LOOPBACKCONFIG_DSX1INWARDLOOP: case DSX1LOOPBACKCONFIG_DSX1DUALLOOP: goto eopnotsupp; default: goto einval; } switch (val->dsx1TransmitClockSource) { case DSX1TRANSMITCLOCKSOURCE_LOOPTIMING: case DSX1TRANSMITCLOCKSOURCE_LOCALTIMING: case DSX1TRANSMITCLOCKSOURCE_THROUGHTIMING: break; case DSX1TRANSMITCLOCKSOURCE_ADAPTIVE: goto eopnotsupp; default: goto einval; } if (val->dsx1Fdl & (1 << DSX1FDL_OTHER)) goto eopnotsupp; if (val->dsx1Fdl & (1 << DSX1FDL_DSX1ANSIT1403)) goto eopnotsupp; if (val->dsx1Fdl & (1 << DSX1FDL_DSX1ATT54016)) goto eopnotsupp; if (val->dsx1Fdl & (1 << DSX1FDL_DSX1FDLNONE)) goto eopnotsupp; if (sp->config.ifgtype != SDL_GTYPE_E1) { if (0 > val->dsx1LineLength || val->dsx1LineLength > 200) goto einval; } switch (val->dsx1LineStatusChangeTrapEnable) { case DSX1LINESTATUSCHANGETRAPENABLE_ENABLED: case DSX1LINESTATUSCHANGETRAPENABLE_DISABLED: break; default: goto einval; } switch (val->dsx1LineMode) { case DSX1LINEMODE_CSU: case DSX1LINEMODE_DSU: break; default: goto einval; } switch (val->dsx1LineBuildOut) { case DSX1LINEBUILDOUT_NOTAPPLICABLE: if (val->dsx1LineMode == DSX1LINEMODE_CSU && sp->config.ifgtype != SDL_GTYPE_E1) goto einval; break; case DSX1LINEBUILDOUT_NEG75DB: case DSX1LINEBUILDOUT_NEG15DB: case DSX1LINEBUILDOUT_NEG225DB: case DSX1LINEBUILDOUT_ZERODB: if (val->dsx1LineMode != DSX1LINEMODE_CSU || sp->config.ifgtype == SDL_GTYPE_E1) goto einval; break; default: goto einval; } switch (val->dsx1LineImpedance) { case DSX1LINEIMPEDANCE_NOTAPPLICABLE: if (sp->config.iftxlevel <= 8) goto einval; break; case DSX1LINEIMPEDANCE_BALANCED100OHMS: if (sp->config.ifgtype == SDL_GTYPE_E1) goto einval; break; case DSX1LINEIMPEDANCE_UNBALANCED75OHMS: case DSX1LINEIMPEDANCE_BALANCED120OHMS: if (sp->config.ifgtype != SDL_GTYPE_E1) goto einval; break; default: goto einval; } return (0); eopnotsupp: return (-EOPNOTSUPP); einval: return (-EINVAL); } noinline __unlikely int dsx_test_options_chan(struct sp *sp, struct ch *ch, dsx_option_t * arg) { struct dsx_opt_conf_chan *val = (typeof(val)) (arg + 1); switch (val->dsx0TransmitCodesEnable) { case DSX0TRANSMITCODESENABLE_FALSE: break; case DSX0TRANSMITCODESENABLE_TRUE: goto eopnotsupp; default: goto einval; } return (0); eopnotsupp: return (-EOPNOTSUPP); einval: return (-EINVAL); } noinline __unlikely int dsx_test_options_frac(struct sp *sp, struct ch *ch, dsx_option_t * arg) { return (0); } noinline __unlikely int dsx_test_options(queue_t *q, mblk_t *mp, dsx_option_t * arg) { int ret; switch (arg->type) { struct sp *sp; struct ch *ch; case DSX_OBJ_TYPE_DFLT: /* defaults */ if (arg->id != 0) return (-ESRCH); if ((ret = dsx_test_options_dflt(arg)) < 0) return (ret); break; case DSX_OBJ_TYPE_SPAN: /* span */ if (!(sp = sp_find(arg->id))) return (-ESRCH); if ((ret = dsx_test_options_span(sp, arg)) < 0) return (ret); break; case DSX_OBJ_TYPE_CHAN: /* channel */ if (!(sp = sp_find(arg->id))) return (-ESRCH); if (IS_ERR((ch = ch_find(arg->id)))) return (-ESRCH); if ((ret = dsx_test_options_chan(sp, ch, arg)) < 0) return (ret); break; case DSX_OBJ_TYPE_FRAC: /* fractional */ if (!(sp = sp_find(arg->id))) return (-ESRCH); if (IS_ERR((ch = ch_find(arg->id)))) return (-ESRCH); if ((ret = dsx_test_options_frac(sp, ch, arg)) < 0) return (ret); break; default: return (-EINVAL); } return (0); } noinline __unlikely int dsx_set_options_dflt(dsx_option_t * arg) { if (arg->id != 0) goto esrch; return (0); esrch: return (-ESRCH); } noinline __unlikely int dsx_set_options_span(dsx_option_t * arg) { struct sp *sp; struct dsx_opt_conf_span *val = (typeof(val)) (arg + 1); uint txlevel = 0, span_reconfig = 0; if (!(sp = sp_find(arg->id))) goto esrch; switch (val->dsx1LoopbackConfig) { case DSX1LOOPBACKCONFIG_DSX1NOLOOP: if (sp->config.ifgmode & SDL_GMODE_LOC_LB) { span_reconfig = 1; sp->config.ifgmode &= ~SDL_GMODE_LOC_LB; } if (sp->config.ifgmode & SDL_GMODE_REM_LB) { span_reconfig = 1; sp->config.ifgmode &= ~SDL_GMODE_REM_LB; } break; } switch (val->dsx1TransmitClockSource) { case DSX1TRANSMITCLOCKSOURCE_LOOPTIMING: if (sp->config.ifclock != SDL_CLOCK_LOOP) { span_reconfig = 1; sp->config.ifclock = SDL_CLOCK_LOOP; } break; case DSX1TRANSMITCLOCKSOURCE_LOCALTIMING: if (sp->config.ifclock != SDL_CLOCK_EXT) { span_reconfig = 1; sp->config.ifclock = SDL_CLOCK_EXT; } break; case DSX1TRANSMITCLOCKSOURCE_THROUGHTIMING: if (sp->config.ifclock != SDL_CLOCK_INT) { span_reconfig = 1; sp->config.ifclock = SDL_CLOCK_INT; } break; } if (sp->config.ifgtype == SDL_GTYPE_E1) { switch (val->dsx1LineImpedance) { case DSX1LINEIMPEDANCE_UNBALANCED75OHMS: txlevel = 1; break; case DSX1LINEIMPEDANCE_BALANCED120OHMS: txlevel = 2; break; } } else { val->dsx1LineImpedance = DSX1LINEIMPEDANCE_BALANCED100OHMS; switch (val->dsx1LineMode) { case DSX1LINEMODE_DSU: if (0 <= val->dsx1LineLength && val->dsx1LineLength < 40) { txlevel = 0; } else if (40 <= val->dsx1LineLength && val->dsx1LineLength < 80) { txlevel = 1; } else if (80 <= val->dsx1LineLength && val->dsx1LineLength < 120) { txlevel = 2; } else if (120 <= val->dsx1LineLength && val->dsx1LineLength < 160) { txlevel = 3; } else if (160 <= val->dsx1LineLength && val->dsx1LineLength <= 200) { txlevel = 4; } break; case DSX1LINEMODE_CSU: switch (val->dsx1LineBuildOut) { case DSX1LINEBUILDOUT_NOTAPPLICABLE: case DSX1LINEBUILDOUT_ZERODB: txlevel = 0; break; case DSX1LINEBUILDOUT_NEG75DB: txlevel = 5; break; case DSX1LINEBUILDOUT_NEG15DB: txlevel = 6; break; case DSX1LINEBUILDOUT_NEG225DB: txlevel = 7; break; } break; } } if (sp->config.iftxlevel != txlevel) { span_reconfig = 1; sp->config.iftxlevel = txlevel; } if (span_reconfig && (sp->config.ifflags & SDL_IF_UP)) xp_span_reconfig(sp); return (0); esrch: return (-ESRCH); } noinline __unlikely int dsx_set_options_chan(dsx_option_t * arg) { return (0); } noinline __unlikely int dsx_set_options_frac(dsx_option_t * arg) { return (0); } noinline __unlikely int dsx_set_options(queue_t *q, mblk_t *mp, dsx_option_t * arg) { switch (arg->type) { case DSX_OBJ_TYPE_DFLT: return dsx_set_options_dflt(arg); case DSX_OBJ_TYPE_SPAN: return dsx_set_options_span(arg); case DSX_OBJ_TYPE_CHAN: return dsx_set_options_chan(arg); case DSX_OBJ_TYPE_FRAC: return dsx_set_options_frac(arg); } return (-EINVAL); } noinline __unlikely int dsx_iocsoption(queue_t *q, mblk_t *mp, mblk_t *dp) { dsx_option_t *arg = (typeof(arg)) dp->b_rptr; int ret; if ((ret = dsx_test_options(q, mp, arg))) return (ret); return dsx_set_options(q, mp, arg); } STATIC __unlikely int dsx_lconfig_size(dsx_config_t * arg) { int size = sizeof(*arg); switch (arg->type) { struct cd *cd; struct sp *sp; uint card, span; case DSX_OBJ_TYPE_DFLT: size += sizeof(uint); break; case DSX_OBJ_TYPE_SPAN: for (card = 0; card < X400_CARDS; card++) { if (!(cd = x400p_cards[card])) continue; for (span = 0; span < cd->ports; span++) size += sizeof(uint); } break; case DSX_OBJ_TYPE_CHAN: for (card = 0; card < X400_CARDS; card++) { if (!(cd = x400p_cards[card])) continue; for (span = 0; span < cd->ports; span++) if ((sp = cd->spans[span])) { switch (sp->config.ifgtype) { case SDL_GTYPE_E1: size += sizeof(uint) * 31; break; case SDL_GTYPE_J1: case SDL_GTYPE_T1: size += sizeof(uint) * 24; break; } } } break; case DSX_OBJ_TYPE_FRAC: break; default: return (-EINVAL); } return (size); } /** * dsx_ioclconfig: - list configuration input-output control * @q: active queue (management stream write queue) * @mp: the input-output control * * Lists as a number of unsigned integers the identifiers of all of the elements of a type that will * fit into the buffer area. When successful, returns the number of elements (whether they would * fit into the buffer or not). */ noinline __unlikely int dsx_ioclconfig(queue_t *q, mblk_t *mp, mblk_t *dp) { dsx_config_t *hdr, *arg = (typeof(arg)) dp->b_rptr; int ret; mblk_t *db; uint num = 0, *val = (typeof(val)) (arg + 1); if ((ret = dsx_lconfig_size(arg)) < 0) return (ret); if (!(db = mi_copyout_alloc(q, mp, 0, ret, 0))) return (-ENOSR); *(hdr = (typeof(hdr)) db->b_rptr) = *arg; switch (arg->type) { struct cd *cd; struct sp *sp; uint card, span, chan; case DSX_OBJ_TYPE_DFLT: if ((unsigned char *) (val + 1) <= mp->b_cont->b_wptr) *val = 0; val++; num++; break; case DSX_OBJ_TYPE_SPAN: for (card = 0; card < X400_CARDS; card++) { if (!(cd = x400p_cards[card])) continue; for (span = 0; span < cd->ports; span++, val++, num++) if ((unsigned char *) (val + 1) <= mp->b_cont->b_wptr) *val = (DRV_ID << 16) | (cd->card << 12) | (span << 8); } break; case DSX_OBJ_TYPE_CHAN: for (card = 0; card < X400_CARDS; card++) { if (!(cd = x400p_cards[card])) continue; for (span = 0; span < cd->ports; span++) { if (!(sp = cd->spans[span])) continue; switch (sp->config.ifgtype) { case SDL_GTYPE_E1: for (chan = 1; chan <= 31; chan++, val++, num++) if ((unsigned char *) (val + 1) <= mp->b_cont->b_wptr) *val = (DRV_ID << 16) | (cd-> card << 12) | (span << 8) | (chan << 0); break; case SDL_GTYPE_T1: case SDL_GTYPE_J1: for (chan = 1; chan <= 24; chan++, val++, num++) if ((unsigned char *) (val + 1) <= mp->b_cont->b_wptr) *val = (DRV_ID << 16) | (cd-> card << 12) | (span << 8) | (chan << 0); break; } } } break; case DSX_OBJ_TYPE_FRAC: break; default: return (-EINVAL); } mp->b_cont->b_wptr = (unsigned char *) val; return (num); } STATIC __unlikely int dsx_config_size(dsx_config_t * arg) { int size = sizeof(*arg); switch (arg->type) { case DSX_OBJ_TYPE_DFLT: size += sizeof(arg->config->dflt); break; case DSX_OBJ_TYPE_SPAN: size += sizeof(arg->config->span); break; case DSX_OBJ_TYPE_CHAN: size += sizeof(arg->config->chan); break; case DSX_OBJ_TYPE_FRAC: size += sizeof(arg->config->frac); break; default: return (-EINVAL); } return (size); } noinline __unlikely int dsx_iocgconfig_dflt(dsx_config_t * arg) { return (0); } noinline __unlikely int dsx_iocgconfig_span(struct sp *sp, dsx_config_t * arg) { struct dsx_conf_span *val = (typeof(val)) (arg + 1); val->dsx1LineIndex = (DRV_ID << 16) | (sp->cd->card << 12); val->dsx1IfIndex = (DRV_ID << 16) | (sp->cd->card << 12) | (sp->span << 8); val->dsx1Ds1ChannelNumber = 0; val->dsx1CircuitIdentifier[0] = '\0'; switch (sp->config.ifgtype) { case SDL_GTYPE_E2: val->dsx1LineType = DSX1LINETYPE_DSX1E2; val->dsx1LineCoding = DSX1LINECODING_OTHER; break; case SDL_GTYPE_T2: case SDL_GTYPE_T3: val->dsx1LineType = DSX1LINETYPE_DSX1DS2M12; val->dsx1LineCoding = DSX1LINECODING_DSX1B6ZS; break; case SDL_GTYPE_E1: switch (sp->config.ifframing) { case SDL_FRAMING_CAS: switch (sp->config.ifgcrc) { case SDL_GCRC_CRC4: val->dsx1LineType = DSX1LINETYPE_DSX1E1CRCMF; break; case SDL_GCRC_CRC5: val->dsx1LineType = DSX1LINETYPE_DSX1E1MF; break; } break; case SDL_FRAMING_CCS: switch (sp->config.ifgcrc) { case SDL_GCRC_CRC4: val->dsx1LineType = DSX1LINETYPE_DSX1E1CRC; break; case SDL_GCRC_CRC5: val->dsx1LineType = DSX1LINETYPE_DSX1E1; break; } break; } switch (sp->config.ifcoding) { case SDL_CODING_HDB3: val->dsx1LineCoding = DSX1LINECODING_DSX1HDB3; break; case SDL_CODING_AMI: val->dsx1LineCoding = DSX1LINECODING_DSX1AMI; break; } break; case SDL_GTYPE_T1: switch (sp->config.ifframing) { case SDL_FRAMING_D4: val->dsx1LineType = DSX1LINETYPE_DSX1D4; break; case SDL_FRAMING_ESF: val->dsx1LineType = DSX1LINETYPE_DSX1ESF; break; } switch (sp->config.ifcoding) { case SDL_CODING_AMI: val->dsx1LineCoding = DSX1LINECODING_DSX1AMI; val->dsx1SignalMode = DSX1SIGNALMODE_ROBBEDBIT; break; case SDL_CODING_B8ZS: val->dsx1LineCoding = DSX1LINECODING_DSX1B8ZS; val->dsx1SignalMode = DSX1SIGNALMODE_NONE; break; case SDL_CODING_B6ZS: val->dsx1LineCoding = DSX1LINECODING_DSX1B6ZS; val->dsx1SignalMode = DSX1SIGNALMODE_NONE; break; } break; case SDL_GTYPE_J1: val->dsx1LineType = DSX1LINETYPE_DSX1J1ESF; switch (sp->config.ifcoding) { case SDL_CODING_AMI: val->dsx1LineCoding = DSX1LINECODING_DSX1AMI; break; case SDL_CODING_B8ZS: val->dsx1LineCoding = DSX1LINECODING_DSX1B8ZS; break; case SDL_CODING_B6ZS: val->dsx1LineCoding = DSX1LINECODING_DSX1B6ZS; break; } break; } val->dsx1Channelization = DSX1CHANNELIZATION_ENABLEDDS0; return (0); } noinline __unlikely int dsx_iocgconfig_chan(struct sp *sp, struct ch *ch, dsx_config_t * arg) { struct dsx_conf_chan *val = (typeof(val)) (arg + 1); uint iftype; val->ifIndex = arg->id; val->dsx1IfIndex = (DRV_ID << 16) | (sp->cd->card << 12) | (sp->span << 8); val->dsx0Ds0ChannelNumber = arg->id & 0x1f; val->dsx0CircuitIdentifier[0] = '\0'; iftype = ch ? ch->sdl.config.iftype : sp->config.iftype; switch (iftype) { case SDL_TYPE_DS0: val->dsx0RobbedBitSignalling = DSX0ROBBEDBITSIGNALLING_FALSE; break; case SDL_TYPE_DS0A: val->dsx0RobbedBitSignalling = DSX0ROBBEDBITSIGNALLING_TRUE; break; } val->dsx0IdleCode = 0x00; val->dsx0SeizedCode = 0x0f; return (0); } noinline __unlikely int dsx_iocgconfig_frac(struct sp *sp, struct ch *ch, dsx_config_t * arg) { return (-ESRCH); } /** * dsx_iocgconfig: - get configuration information for an object * @q: active queue (management stream write queue) * @mp: the input-output control * @arg; the configuration structure */ noinline __unlikely int dsx_iocgconfig(queue_t *q, mblk_t *mp, mblk_t *dp) { dsx_config_t *hdr, *arg = (typeof(arg)) dp->b_rptr; int ret; mblk_t *db; arg->cmd = DSX_GET; if ((ret = dsx_config_size(arg)) < 0) return (ret); if (!(db = mi_copyout_alloc(q, mp, 0, ret, 0))) return (-ENOSR); *(hdr = (typeof(hdr)) db->b_rptr) = *arg; switch (arg->type) { struct sp *sp; struct ch *ch; case DSX_OBJ_TYPE_DFLT: if (arg->id != 0) return (-ESRCH); if ((ret = dsx_iocgconfig_dflt(hdr)) < 0) return (ret); break; case DSX_OBJ_TYPE_SPAN: if (!(sp = sp_find(arg->id))) return (-ESRCH); if ((ret = dsx_iocgconfig_span(sp, hdr)) < 0) return (ret); break; case DSX_OBJ_TYPE_CHAN: if (!(sp = sp_find(arg->id))) return (-ESRCH); if (IS_ERR((ch = ch_find(arg->id)))) return (-ESRCH); if ((ret = dsx_iocgconfig_chan(sp, ch, hdr)) < 0) return (ret); break; case DSX_OBJ_TYPE_FRAC: if (!(sp = sp_find(arg->id))) return (-ESRCH); if (IS_ERR((ch = ch_find(arg->id)))) return (-ESRCH); if ((ret = dsx_iocgconfig_frac(sp, ch, hdr)) < 0) return (ret); break; default: return (-EINVAL); } mi_copyout(q, mp); return (0); } noinline __unlikely int dsx_iocsconfig(queue_t *q, mblk_t *mp, mblk_t *dp) { return (-EOPNOTSUPP); } noinline __unlikely int dsx_ioctconfig(queue_t *q, mblk_t *mp, mblk_t *dp) { return (-EOPNOTSUPP); } noinline __unlikely int dsx_ioccconfig(queue_t *q, mblk_t *mp, mblk_t *dp) { return (-EOPNOTSUPP); } STATIC __unlikely int dsx_statem_size(dsx_statem_t * arg) { int size = sizeof(*arg); switch (arg->type) { case DSX_OBJ_TYPE_DFLT: size += sizeof(arg->statem->dflt); break; case DSX_OBJ_TYPE_SPAN: size += sizeof(arg->statem->span); break; case DSX_OBJ_TYPE_CHAN: size += sizeof(arg->statem->chan); break; case DSX_OBJ_TYPE_FRAC: size += sizeof(arg->statem->frac); break; default: return (-EINVAL); } return (size); } noinline __unlikely int dsx_iocgstatem(queue_t *q, mblk_t *mp, mblk_t *dp) { return (-EOPNOTSUPP); } noinline __unlikely int dsx_ioccmreset(queue_t *q, mblk_t *mp, mblk_t *dp) { return (-EOPNOTSUPP); } STATIC __unlikely int dsx_status_size(dsx_status_t * arg) { int size = sizeof(*arg); switch (arg->type) { case DSX_OBJ_TYPE_DFLT: size += sizeof(arg->status->dflt); break; case DSX_OBJ_TYPE_SPAN: size += sizeof(arg->status->span); break; case DSX_OBJ_TYPE_CHAN: size += sizeof(arg->status->chan); break; case DSX_OBJ_TYPE_FRAC: size += sizeof(arg->status->frac); break; default: return (-EINVAL); } return (size); } noinline __unlikely int dsx_iocgstatus(queue_t *q, mblk_t *mp, mblk_t *dp) { return (-EOPNOTSUPP); } noinline __unlikely int dsx_iocsstatus(queue_t *q, mblk_t *mp, mblk_t *dp) { return (-EOPNOTSUPP); } noinline __unlikely int dsx_ioccstatus(queue_t *q, mblk_t *mp, mblk_t *dp) { return (-EOPNOTSUPP); } STATIC __unlikely int dsx_stats_size(dsx_stats_t * arg) { int size = sizeof(*arg); switch (arg->type) { case DSX_OBJ_TYPE_DFLT: size += sizeof(arg->stats->dflt); break; case DSX_OBJ_TYPE_SPAN: size += sizeof(arg->stats->span); break; case DSX_OBJ_TYPE_CHAN: size += sizeof(arg->stats->chan); break; case DSX_OBJ_TYPE_FRAC: size += sizeof(arg->stats->frac); break; default: return (-EINVAL); } return (size); } noinline __unlikely int dsx_iocgstatsp(queue_t *q, mblk_t *mp, mblk_t *dp) { return (-EOPNOTSUPP); } noinline __unlikely int dsx_iocsstatsp(queue_t *q, mblk_t *mp, mblk_t *dp) { return (-EOPNOTSUPP); } noinline __unlikely int dsx_iocgstats_dflt(dsx_stats_t * arg) { struct dsx_stats_dflt *val = (typeof(val)) (arg + 1); /* there are no default dsx stats */ bzero(val, sizeof(*val)); return (0); } noinline __unlikely int dsx_iocgstats_span(struct sp *sp, dsx_stats_t * arg) { struct dsx_stats_span *val = (typeof(val)) (arg + 1); /* FIXME: get these */ bzero(val, sizeof(*val)); switch (arg->subtype) { case DSX_SUBTYPE_NEAREND: { uint interval, valid, invalid; struct st *st, total; for (valid = 0, invalid = 0, interval = 0; interval < 96; interval++) { st = &sp->hist[interval]; if (st->ValidData) valid++; else invalid++; } val->NearEnd.dsx1ValidIntervals = valid; val->NearEnd.dsx1InvalidIntervals = invalid; if (arg->interval == 0) st = &sp->stats[2]; else if (arg->interval > 96 && arg->interval != 0xffffffff) return (-EINVAL); else if (sp->hist == NULL) return (-EINVAL); else if (arg->interval == 0xffffffff) { bzero(&total, sizeof(total)); for (interval = 0; interval < 96; interval++) { st = &sp->hist[interval]; if (st->ValidData) { total.ESs += st->ESs; total.SESs += st->SESs; total.SEFSs += st->SEFSs; total.UASs += st->UASs; total.CSSs += st->CSSs; total.PCVs += st->PCVs; total.LESs += st->LESs; total.BESs += st->BESs; total.DMs += st->DMs; total.LCVs += st->LCVs; } } if (valid) total.ValidData = DSX1FARENDINTERVALVALIDDATA_TRUE; else total.ValidData = DSX1FARENDINTERVALVALIDDATA_FALSE; st = &total; } else st = &sp->hist[(sp->curr + (arg->interval - 1)) % 96]; val->NearEnd.dsx1ESs = st->ESs; val->NearEnd.dsx1SESs = st->SESs; val->NearEnd.dsx1SEFSs = st->SEFSs; val->NearEnd.dsx1UASs = st->UASs; val->NearEnd.dsx1CSSs = st->CSSs; val->NearEnd.dsx1PCVs = st->PCVs; val->NearEnd.dsx1LESs = st->LESs; val->NearEnd.dsx1BESs = st->BESs; val->NearEnd.dsx1DMs = st->DMs; val->NearEnd.dsx1LCVs = st->LCVs; val->NearEnd.dsx1ValidData = st->ValidData; break; } case DSX_SUBTYPE_FAREND: { val->FarEnd.dsx1ValidIntervals = 0; val->FarEnd.dsx1InvalidIntervals = 0; val->FarEnd.dsx1ESs = 0; val->FarEnd.dsx1SESs = 0; val->FarEnd.dsx1SEFSs = 0; val->FarEnd.dsx1UASs = 0; val->FarEnd.dsx1CSSs = 0; val->FarEnd.dsx1PCVs = 0; val->FarEnd.dsx1LESs = 0; val->FarEnd.dsx1BESs = 0; val->FarEnd.dsx1DMs = 0; val->FarEnd.dsx1ValidData = DSX1FARENDINTERVALVALIDDATA_FALSE; break; } default: return (-EINVAL); } return (0); } noinline __unlikely int dsx_iocgstats_chan(struct sp *sp, struct ch *ch, dsx_stats_t * arg) { struct dsx_stats_chan *val = (typeof(val)) (arg + 1); /* there are no channel dsx stats */ bzero(val, sizeof(*val)); return (0); } noinline __unlikely int dsx_iocgstats_frac(struct sp *sp, struct ch *ch, dsx_stats_t * arg) { struct dsx_stats_frac *val = (typeof(val)) (arg + 1); /* there are no fractional dsx stats */ bzero(val, sizeof(*val)); return (0); } noinline __unlikely int dsx_iocgstats(queue_t *q, mblk_t *mp, mblk_t *dp) { dsx_stats_t *hdr, *arg = (typeof(arg)) dp->b_rptr; int ret; mblk_t *db; if ((ret = dsx_stats_size(arg)) < 0) return (ret); if (!(db = mi_copyout_alloc(q, mp, 0, ret, 0))) return (-ENOSR); *(hdr = (typeof(hdr)) db->b_rptr) = *arg; switch (arg->type) { struct sp *sp; struct ch *ch; case DSX_OBJ_TYPE_DFLT: if (arg->id != 0) return (-ESRCH); if ((ret = dsx_iocgstats_dflt(hdr)) < 0) return (ret); break; case DSX_OBJ_TYPE_SPAN: if (!(sp = sp_find(arg->id))) return (-ESRCH); if ((ret = dsx_iocgstats_span(sp, hdr)) < 0) return (ret); break; case DSX_OBJ_TYPE_CHAN: if (!(sp = sp_find(arg->id))) return (-ESRCH); if (IS_ERR((ch = ch_find(arg->id)))) return (-ESRCH); if ((ret = dsx_iocgstats_chan(sp, ch, hdr)) < 0) return (ret); break; case DSX_OBJ_TYPE_FRAC: if (!(sp = sp_find(arg->id))) return (-ESRCH); if (IS_ERR((ch = ch_find(arg->id)))) return (-ESRCH); if ((ret = dsx_iocgstats_frac(sp, ch, hdr)) < 0) return (ret); break; default: return (-EINVAL); } mi_copyout(q, mp); return (0); } noinline __unlikely int dsx_ioccstats(queue_t *q, mblk_t *mp, mblk_t *dp) { return (-EOPNOTSUPP); } STATIC __unlikely int dsx_notify_size(dsx_notify_t * arg) { int size = sizeof(*arg); switch (arg->type) { case DSX_OBJ_TYPE_DFLT: size += sizeof(arg->events->dflt); break; case DSX_OBJ_TYPE_SPAN: size += sizeof(arg->events->span); break; case DSX_OBJ_TYPE_CHAN: size += sizeof(arg->events->chan); break; case DSX_OBJ_TYPE_FRAC: size += sizeof(arg->events->frac); break; default: return (-EINVAL); } return (size); } noinline __unlikely int dsx_iocgnotify(queue_t *q, mblk_t *mp, mblk_t *dp) { return (-EOPNOTSUPP); } noinline __unlikely int dsx_iocsnotify(queue_t *q, mblk_t *mp, mblk_t *dp) { return (-EOPNOTSUPP); } noinline __unlikely int dsx_ioccnotify(queue_t *q, mblk_t *mp, mblk_t *dp) { return (-EOPNOTSUPP); } STATIC __unlikely int dsx_attr_size(int type) { dsx_attr_t *arg; int size = sizeof(*arg); switch (type) { case DSX_OBJ_TYPE_DFLT: size += sizeof(arg->attrs->dflt); break; case DSX_OBJ_TYPE_SPAN: size += sizeof(arg->attrs->span); break; case DSX_OBJ_TYPE_CHAN: size += sizeof(arg->attrs->chan); break; case DSX_OBJ_TYPE_FRAC: size += sizeof(arg->attrs->frac); break; default: return (-EINVAL); } return (size); } noinline __unlikely int dsx_iocgattr(queue_t *q, mblk_t *mp, mblk_t *dp) { (void) &dsx_attr_size; return (-EOPNOTSUPP); } STATIC __unlikely int dsx_mgmt_size(dsx_mgmt_t * arg) { int size = sizeof(*arg); switch (arg->type) { case DSX_OBJ_TYPE_DFLT: size += sizeof(arg->action->dflt); break; case DSX_OBJ_TYPE_SPAN: size += sizeof(arg->action->span); break; case DSX_OBJ_TYPE_CHAN: size += sizeof(arg->action->chan); break; case DSX_OBJ_TYPE_FRAC: size += sizeof(arg->action->frac); break; default: return (-EINVAL); } return (size); } noinline __unlikely int dsx_ioccmgmt(queue_t *q, mblk_t *mp, mblk_t *dp) { return (-EOPNOTSUPP); } STATIC __unlikely int dsx_pass_size(dsx_pass_t * arg) { int size = sizeof(*arg); size += arg->ctl_length; size += arg->dat_length; return (size); } noinline __unlikely int dsx_ioccpass(queue_t *q, mblk_t *mp, mblk_t *dp) { return (-EOPNOTSUPP); } /* * ========================================================================= * * MX INPUT-OUTPUT CONTROL COMMAND ACTIONS * * ========================================================================= */ STATIC __unlikely int mx_info_size(mx_info_t * arg) { int size = sizeof(*arg); switch (arg->type) { case MX_OBJ_TYPE_DFLT: size += sizeof(arg->info->dflt); break; case MX_OBJ_TYPE_SYNC: size += sizeof(arg->info->sync); break; case MX_OBJ_TYPE_CARD: size += sizeof(arg->info->card); break; case MX_OBJ_TYPE_SPAN: size += sizeof(arg->info->span); break; case MX_OBJ_TYPE_CHAN: size += sizeof(arg->info->chan); break; case MX_OBJ_TYPE_FRAC: size += sizeof(arg->info->frac); break; case MX_OBJ_TYPE_XCON: size += sizeof(arg->info->xcon); break; case MX_OBJ_TYPE_BERT: size += sizeof(arg->info->bert); break; default: return (-EINVAL); } return (size); } noinline __unlikely int mx_iocginfo_dflt(mx_info_t * arg) { struct mx_info_dflt *val = (typeof(val)) (arg + 1); val->mxDrivIdnum = DRV_ID; val->mxDrivMajor = CMAJOR_0; strncpy(val->mxDrivDescription, SL_X400P_DESCRIP, sizeof(val->mxDrivDescription)); strncpy(val->mxDrivRevision, SL_X400P_REVISION, sizeof(val->mxDrivRevision)); strncpy(val->mxDrivCopyright, SL_X400P_COPYRIGHT, sizeof(val->mxDrivCopyright)); strncpy(val->mxDrivSupportedDevice, SL_X400P_DEVICE, sizeof(val->mxDrivSupportedDevice)); strncpy(val->mxDrivContact, SL_X400P_CONTACT, sizeof(val->mxDrivContact)); val->mxDrivLicense = MXDRIVLICENSE_GPL; memcpy(val->mxDrivDate, "\x07\xd9\x01\x0e\x0c\x21\x08\x00\x00\x00\x00\x00", 12); return (0); } noinline __unlikely int mx_iocginfo_sync(struct sg *sg, mx_info_t * arg) { return (-EOPNOTSUPP); } noinline __unlikely int mx_iocginfo_card(struct cd *cd, mx_info_t * arg) { struct mx_info_card *val; val = (typeof(val)) (arg + 1); /* FIXME: complete this */ switch (cd->board) { case PLX9030: val->mxCardType = X400PCARDTYPE_PLX9030; break; case PLXDEVBRD: val->mxCardType = X400PCARDTYPE_PLXDEVBRD; break; case X400P: val->mxCardType = X400PCARDTYPE_X400P; break; case E400P: val->mxCardType = X400PCARDTYPE_E400P; break; case T400P: val->mxCardType = X400PCARDTYPE_T400P; break; case X400PSS7: val->mxCardType = X400PCARDTYPE_X400PSS7; break; case E400PSS7: val->mxCardType = X400PCARDTYPE_E400PSS7; break; case T400PSS7: val->mxCardType = X400PCARDTYPE_T400PSS7; break; case V400P: val->mxCardType = X400PCARDTYPE_V400P; break; case V400PE: val->mxCardType = X400PCARDTYPE_V400PE; break; case V400PT: val->mxCardType = X400PCARDTYPE_V400PT; break; case V401PE: val->mxCardType = X400PCARDTYPE_V401PE; break; case V401PT: val->mxCardType = X400PCARDTYPE_V401PT; break; case A400P: val->mxCardType = X400PCARDTYPE_A400P; break; case AE400P: val->mxCardType = X400PCARDTYPE_AE400P; break; case AT400P: val->mxCardType = X400PCARDTYPE_AT400P; break; case A400PE: val->mxCardType = X400PCARDTYPE_A400PE; break; case A400PT: val->mxCardType = X400PCARDTYPE_A400PT; break; case CP100: val->mxCardType = X400PCARDTYPE_CP100; break; case CP100P: val->mxCardType = X400PCARDTYPE_CP100P; break; case CP100E: val->mxCardType = X400PCARDTYPE_CP100E; break; case CP200: val->mxCardType = X400PCARDTYPE_CP200; break; case CP200P: val->mxCardType = X400PCARDTYPE_CP200P; break; case CP200E: val->mxCardType = X400PCARDTYPE_CP200E; break; case CP400: val->mxCardType = X400PCARDTYPE_CP400; break; case CP400P: val->mxCardType = X400PCARDTYPE_CP400P; break; case CP400E: val->mxCardType = X400PCARDTYPE_CP400E; break; default: val->mxCardType = X400PCARDTYPE_NONE; break; } /* this driver does not support board indexes yet */ val->mxCardIdentifier = 0; /* this driver does not support board revision yet */ val->mxCardRevision = 0; switch (cd->device) { case XP_DEV_DS2152: val->mxCardChipType = X400PCARDCHIPTYPE_DS2152; break; case XP_DEV_DS21352: val->mxCardChipType = X400PCARDCHIPTYPE_DS21352; break; case XP_DEV_DS21552: val->mxCardChipType = X400PCARDCHIPTYPE_DS21552; break; case XP_DEV_DS2154: val->mxCardChipType = X400PCARDCHIPTYPE_DS2154; break; case XP_DEV_DS21354: val->mxCardChipType = X400PCARDCHIPTYPE_DS21354; break; case XP_DEV_DS21554: val->mxCardChipType = X400PCARDCHIPTYPE_DS21554; break; case XP_DEV_DS2155: val->mxCardChipType = X400PCARDCHIPTYPE_DS2155; break; case XP_DEV_DS21455: val->mxCardChipType = X400PCARDCHIPTYPE_DS21455; break; case XP_DEV_DS21458: val->mxCardChipType = X400PCARDCHIPTYPE_DS21458; break; case XP_DEV_DS2156: val->mxCardChipType = X400PCARDCHIPTYPE_DS2156; break; default: val->mxCardChipType = X400PCARDCHIPTYPE_NONE; break; } val->mxCardChipRevision = cd->devrev; val->mxCardPciBus = cd->bus; val->mxCardPciSlot = cd->slot; val->mxCardPciIrq = cd->irq; strncpy(val->mxCardName,xp_board_info[cd->board].name,sizeof(val->mxCardName)); return (0); } noinline __unlikely int mx_iocginfo_span(struct sp *sp, mx_info_t * arg) { /* there is no span information */ return (0); } noinline __unlikely int mx_iocginfo_chan(struct sp *sp, struct ch *ch, mx_info_t * arg) { /* there is no channel information */ return (0); } noinline __unlikely int mx_iocginfo(queue_t *q, mblk_t *mp, mblk_t *dp) { mx_info_t *hdr, *arg = (typeof(arg)) dp->b_rptr; int ret; mblk_t *db; psw_t flags; if ((ret = mx_info_size(arg)) < 0) return (ret); if (!(db = mi_copyout_alloc(q, mp, 0, ret, 0))) return (-ENOSR); *(hdr = (typeof(hdr)) db->b_rptr) = *arg; ret = -ESRCH; switch (arg->type) { struct cd *cd; struct sp *sp; struct ch *ch; struct sg *sg; case MX_OBJ_TYPE_DFLT: /* defaults */ if (arg->id != 0) break; ret = mx_iocginfo_dflt(hdr); break; case MX_OBJ_TYPE_SYNC: /* synchronization group */ if (!(sg = sg_find(arg->id))) break; spin_lock_irqsave(&sg->lock, flags); ret = mx_iocginfo_sync(sg, hdr); spin_unlock_irqrestore(&sg->lock, flags); break; case MX_OBJ_TYPE_CARD: /* card */ if (!(cd = cd_find(arg->id))) break; spin_lock_irqsave(&cd->lock, flags); ret = mx_iocginfo_card(cd, hdr); spin_unlock_irqrestore(&cd->lock, flags); break; case MX_OBJ_TYPE_SPAN: /* span */ if (!(sp = sp_find(arg->id))) break; spin_lock_irqsave(&sp->lock, flags); ret = mx_iocginfo_span(sp, hdr); spin_unlock_irqrestore(&sp->lock, flags); break; case MX_OBJ_TYPE_CHAN: /* channel */ if (!(sp = sp_find(arg->id))) break; if (IS_ERR((ch = ch_find(arg->id)))) break; spin_lock_bh(&ch->lock); ret = mx_iocginfo_chan(sp, ch, hdr); spin_unlock_bh(&ch->lock); break; case MX_OBJ_TYPE_FRAC: /* fractional */ /* this driver does not support fractionals */ break; case MX_OBJ_TYPE_XCON: /* cross connect */ /* this driver does not support cross-connects */ break; case MX_OBJ_TYPE_BERT: /* bit error rate test */ /* this driver does not support bert */ break; default: ret = -EINVAL; break; } if (ret >= 0) mi_copyout(q, mp); return (ret); } STATIC __unlikely int mx_option_size(mx_option_t * arg) { int size = sizeof(*arg); switch (arg->type) { case MX_OBJ_TYPE_DFLT: size += sizeof(arg->option->dflt); break; case MX_OBJ_TYPE_SYNC: size += sizeof(arg->option->sync); break; case MX_OBJ_TYPE_CARD: size += sizeof(arg->option->card); break; case MX_OBJ_TYPE_SPAN: size += sizeof(arg->option->span); break; case MX_OBJ_TYPE_CHAN: size += sizeof(arg->option->chan); break; case MX_OBJ_TYPE_FRAC: size += sizeof(arg->option->frac); break; case MX_OBJ_TYPE_XCON: size += sizeof(arg->option->xcon); break; case MX_OBJ_TYPE_BERT: size += sizeof(arg->option->bert); break; default: return (-EINVAL); } return (size); } noinline __unlikely int mx_iocgoption_dflt(mx_option_t * arg) { /* this is no default options */ return (0); } noinline __unlikely int mx_iocgoption_sync(struct sg *sg, mx_option_t * arg) { return (-EOPNOTSUPP); } noinline __unlikely int mx_iocgoption_card(struct cd *cd, mx_option_t * arg) { struct mx_opt_conf_card *val = (typeof(val)) (arg + 1); val->mxCardMode = 0; if (cd->config.ifgmode & SDL_GMODE_LOC_LB) val->mxCardMode |= (1 << MXCARDMODE_LOCALLOOPBACK); if (cd->config.ifgmode & SDL_GMODE_REM_LB) val->mxCardMode |= (1 << MXCARDMODE_REMOTELOOPBACK); if (cd->config.ifclock == SDL_CLOCK_MASTER) val->mxCardSyncMaster = MXCARDSYNCMASTER_MASTER; else val->mxCardSyncMaster = MXCARDSYNCMASTER_SLAVE; switch (cd->config.ifsync) { default: case SYNCSELF: val->mxCardSyncSource = MXCARDSYNCSOURCE_SYNCSELF; break; case SYNC1: val->mxCardSyncSource = MXCARDSYNCSOURCE_SYNC1; break; case SYNC2: val->mxCardSyncSource = MXCARDSYNCSOURCE_SYNC2; break; case SYNC3: val->mxCardSyncSource = MXCARDSYNCSOURCE_SYNC3; break; case SYNC4: val->mxCardSyncSource = MXCARDSYNCSOURCE_SYNC4; break; case SYNCEXTERN: val->mxCardSyncSource = MXCARDSYNCSOURCE_SYNCEXTERN; break; case SYNCAUTO: val->mxCardSyncSource = MXCARDSYNCSOURCE_SYNCAUTO; break; } return (0); } noinline __unlikely int mx_iocgoption_span(struct sp *sp, mx_option_t * arg) { struct mx_opt_conf_span *val = (typeof(val)) (arg + 1); switch (sp->config.ifgmode) { case SDL_GMODE_LOC_LB: val->mxSpanMode = (1 << MXSPANMODE_LOCAL); break; case SDL_GMODE_REM_LB: val->mxSpanMode = (1 << MXSPANMODE_REMOTE); break; case SDL_GMODE_BOTH_LB: val->mxSpanMode = (1 << MXSPANMODE_LOCAL) | (1 << MXSPANMODE_REMOTE); default: case SDL_GMODE_NONE: val->mxSpanMode = 0; break; } switch (sp->config.ifclock) { case SDL_CLOCK_INT: val->mxSpanClocking = MXSPANCLOCKING_INTERNAL; break; case SDL_CLOCK_EXT: val->mxSpanClocking = MXSPANCLOCKING_EXTERNAL; break; case SDL_CLOCK_LOOP: val->mxSpanClocking = MXSPANCLOCKING_LOOP; break; case SDL_CLOCK_MASTER: val->mxSpanClocking = MXSPANCLOCKING_INTERNAL; break; case SDL_CLOCK_SLAVE: val->mxSpanClocking = MXSPANCLOCKING_EXTERNAL; break; default: case SDL_CLOCK_DPLL: case SDL_CLOCK_ABR: case SDL_CLOCK_SHAPER: case SDL_CLOCK_TICK: case SDL_CLOCK_NONE: val->mxSpanClocking = MXSPANCLOCKING_NONE; break; } if (sp->config.iftxlevel & ~0x7) { /* monitoring mode */ val->mxSpanLineMode = MXSPANLINEMODE_MONITOR; val->mxSpanLineLength = MXSPANLINELENGTH_NONE; val->mxSpanLineAttenuation = MXSPANLINEATTENUATION_NONE; val->mxSpanLineImpedance = MXSPANLINEIMPEDANCE_BALANCED120OHM; switch (sp->cd->device) { case XP_DEV_DS2155: case XP_DEV_DS21455: case XP_DEV_DS21458: case XP_DEV_DS2156: default: switch (sp->config.iftxlevel & 0x3) { case 0: /* 0 */ val->mxSpanLineGain = MXSPANLINEGAIN_MON0DB; break; case 1: /* 20 dB */ val->mxSpanLineGain = MXSPANLINEGAIN_MON20DB; break; case 2: /* 26 dB */ val->mxSpanLineGain = MXSPANLINEGAIN_MON26DB; break; case 3: /* 32 dB */ val->mxSpanLineGain = MXSPANLINEGAIN_MON32DB; break; } break; case XP_DEV_DS2152: case XP_DEV_DS21352: case XP_DEV_DS21552: switch (sp->config.iftxlevel & 0x3) { case 0: /* 0 */ val->mxSpanLineGain = MXSPANLINEGAIN_MON0DB; break; case 1: /* 12 dB */ val->mxSpanLineGain = MXSPANLINEGAIN_MON12DB; break; case 2: case 3: /* 20 dB */ val->mxSpanLineGain = MXSPANLINEGAIN_MON20DB; break; } break; case XP_DEV_DS2154: case XP_DEV_DS21354: case XP_DEV_DS21554: switch (sp->config.iftxlevel & 0x3) { case 0: /* 0 */ val->mxSpanLineGain = MXSPANLINEGAIN_MON0DB; break; case 1: /* 12 dB */ val->mxSpanLineGain = MXSPANLINEGAIN_MON12DB; break; case 2: case 3: /* 30 dB */ val->mxSpanLineGain = MXSPANLINEGAIN_MON30DB; break; } break; } } else { /* normal DSU/CSU mode */ val->mxSpanLineGain = MXSPANLINEGAIN_NONE; if (sp->config.ifgtype == SDL_GTYPE_E1) { val->mxSpanLineLength = MXSPANLINELENGTH_NONE; val->mxSpanLineAttenuation = MXSPANLINEATTENUATION_NONE; switch (sp->config.iftxlevel & 0x7) { case SDL_TXLEVEL_75OHM_NM: /* 1 */ val->mxSpanLineMode = MXSPANLINEMODE_DSU; val->mxSpanLineImpedance = MXSPANLINEIMPEDANCE_UNBALANCED75OHM; break; case SDL_TXLEVEL_75OHM_PR: /* 3 */ case SDL_TXLEVEL_75OHM_HRL: /* 5 */ case 7: val->mxSpanLineMode = MXSPANLINEMODE_CSU; val->mxSpanLineImpedance = MXSPANLINEIMPEDANCE_UNBALANCED75OHM; break; case 0: case SDL_TXLEVEL_120OHM_NM: /* 2 */ val->mxSpanLineMode = MXSPANLINEMODE_DSU; val->mxSpanLineImpedance = MXSPANLINEIMPEDANCE_BALANCED120OHM; break; case SDL_TXLEVEL_120OHM_PR: /* 4 */ case SDL_TXLEVEL_120OHM_HRL: /* 6 */ val->mxSpanLineMode = MXSPANLINEMODE_CSU; val->mxSpanLineImpedance = MXSPANLINEIMPEDANCE_BALANCED120OHM; break; } } else { val->mxSpanLineImpedance = MXSPANLINEIMPEDANCE_BALANCED100OHM; switch (sp->config.iftxlevel & 0x7) { case 0: val->mxSpanLineMode = MXSPANLINEMODE_CSU; val->mxSpanLineLength = MXSPANLINELENGTH_DSX133FT; val->mxSpanLineAttenuation = MXSPANLINEATTENUATION_CSU0DB; break; case 1: val->mxSpanLineMode = MXSPANLINEMODE_DSU; val->mxSpanLineLength = MXSPANLINELENGTH_DSX266FT; val->mxSpanLineAttenuation = MXSPANLINEATTENUATION_CSU0DB; break; case 2: val->mxSpanLineMode = MXSPANLINEMODE_DSU; val->mxSpanLineLength = MXSPANLINELENGTH_DSX399FT; val->mxSpanLineAttenuation = MXSPANLINEATTENUATION_CSU0DB; break; case 3: val->mxSpanLineMode = MXSPANLINEMODE_DSU; val->mxSpanLineLength = MXSPANLINELENGTH_DSX533FT; val->mxSpanLineAttenuation = MXSPANLINEATTENUATION_CSU0DB; break; case 4: val->mxSpanLineMode = MXSPANLINEMODE_DSU; val->mxSpanLineLength = MXSPANLINELENGTH_DSX666FT; val->mxSpanLineAttenuation = MXSPANLINEATTENUATION_CSU0DB; break; case 5: val->mxSpanLineMode = MXSPANLINEMODE_CSU; val->mxSpanLineLength = MXSPANLINELENGTH_NONE; val->mxSpanLineAttenuation = MXSPANLINEATTENUATION_CSU8DB; break; case 6: val->mxSpanLineMode = MXSPANLINEMODE_CSU; val->mxSpanLineLength = MXSPANLINELENGTH_NONE; val->mxSpanLineAttenuation = MXSPANLINEATTENUATION_CSU15DB; break; case 7: val->mxSpanLineMode = MXSPANLINEMODE_CSU; val->mxSpanLineLength = MXSPANLINELENGTH_NONE; val->mxSpanLineAttenuation = MXSPANLINEATTENUATION_CSU23DB; break; } } } val->mxSpanLineDelay = 0; /* not measured this driver */ val->mxSpanTxLevel = MXSPANTXLEVEL_ON; val->mxSpanRxLevel = MXSPANRXLEVEL_ON; val->mxSpanAlarmSettleTime = 5000; /* always 5 seconds for this driver */ val->mxSpanLineCodeTime = 5000; /* always 5 seconds for this driver */ val->mxSpanLineCode = MXSPANLINECODE_NOCODE; /* not supported this driver */ val->mxSpanReceiveThreshold = 0; /* not supported this driver */ return (0); } noinline __unlikely int mx_iocgoption_chan(struct sp *sp, struct ch *ch, mx_option_t * arg) { struct mx_opt_conf_chan *val; sdl_config_t *config; val = (typeof(val)) (arg + 1); config = ch ? &ch->sdl.config : &sp->config; switch (config->iftype) { case SDL_TYPE_DS0: /* DS0 channel */ val->mxChanType = (config->ifframing == SDL_FRAMING_CAS) ? MXCHANTYPE_CAS : MXCHANTYPE_CCS; val->mxChanFormat = MXCHANFORMAT_DS0; val->mxChanRate = MXCHANRATE_KBITS64; val->mxChanMode = 0; /* no loopback supported */ break; case SDL_TYPE_DS0A: /* DS0A channel */ val->mxChanType = (config->ifgtype == SDL_GTYPE_E1 && config->ifframing != MXCHANTYPE_CAS) ? MXCHANTYPE_CCS : MXCHANTYPE_CAS; val->mxChanFormat = MXCHANFORMAT_DS0A; val->mxChanRate = MXCHANRATE_KBITS56; val->mxChanMode = 0; /* no loopback supported */ break; case SDL_TYPE_E1: /* full E1 span */ val->mxChanType = (config->ifframing == SDL_FRAMING_CAS) ? MXCHANTYPE_CAS : MXCHANTYPE_CCS; val->mxChanFormat = MXCHANFORMAT_E1; val->mxChanRate = MXCHANRATE_KBITS1984; val->mxChanMode = 0; /* no loopback supported */ break; case SDL_TYPE_T1: /* full T1 span */ val->mxChanType = MXCHANTYPE_CCS; val->mxChanFormat = MXCHANFORMAT_T1; val->mxChanRate = MXCHANRATE_KBITS1536; val->mxChanMode = 0; /* no loopback supported */ break; case SDL_TYPE_J1: /* full J1 span */ val->mxChanType = MXCHANTYPE_CCS; val->mxChanFormat = MXCHANFORMAT_J1; val->mxChanRate = MXCHANRATE_KBITS1536; val->mxChanMode = 0; /* no loopback supported */ break; default: val->mxChanType = MXCHANTYPE_NONE; val->mxChanFormat = MXCHANFORMAT_NONE; val->mxChanRate = MXCHANRATE_VARIABLE; val->mxChanMode = 0; /* no loopback supported */ break; } return (0); } noinline __unlikely int mx_iocgoption(queue_t *q, mblk_t *mp, mblk_t *dp) { mx_option_t *hdr, *arg = (typeof(arg)) dp->b_rptr; int ret; mblk_t *db; psw_t flags; if ((ret = mx_option_size(arg)) < 0) return (ret); if (!(db = mi_copyout_alloc(q, mp, 0, ret, 0))) return (-ENOSR); *(hdr = (typeof(hdr)) db->b_rptr) = *arg; ret = -ESRCH; switch (arg->type) { struct cd *cd; struct sp *sp; struct ch *ch; struct sg *sg; case MX_OBJ_TYPE_DFLT: /* defaults */ if (arg->id != 0) break; ret = mx_iocgoption_dflt(hdr); break; case MX_OBJ_TYPE_SYNC: /* synchronization group */ if (!(sg = sg_find(arg->id))) break; spin_lock_irqsave(&sg->lock, flags); ret = mx_iocgoption_sync(sg, hdr); spin_unlock_irqrestore(&sg->lock, flags); break; case MX_OBJ_TYPE_CARD: /* card */ if (!(cd = cd_find(arg->id))) break; spin_lock_irqsave(&cd->lock, flags); ret = mx_iocgoption_card(cd, hdr); spin_unlock_irqrestore(&cd->lock, flags); break; case MX_OBJ_TYPE_SPAN: /* span */ if (!(sp = sp_find(arg->id))) break; spin_lock_irqsave(&sp->lock, flags); ret = mx_iocgoption_span(sp, hdr); spin_unlock_irqrestore(&sp->lock, flags); break; case MX_OBJ_TYPE_CHAN: /* channel */ if (!(sp = sp_find(arg->id))) break; if (IS_ERR((ch = ch_find(arg->id)))) break; spin_lock_bh(&ch->lock); ret = mx_iocgoption_chan(sp, ch, hdr); spin_unlock_bh(&ch->lock); break; case MX_OBJ_TYPE_FRAC: /* fractional */ break; case MX_OBJ_TYPE_XCON: /* cross connect */ break; case MX_OBJ_TYPE_BERT: /* bit error rate test */ break; default: ret = -EINVAL; break; } if (ret >= 0) mi_copyout(q, mp); return (ret); } noinline __unlikely int mx_test_options_dflt(mx_option_t * arg) { if (arg->id != 0) goto esrch; /* there are no default options yet */ return (0); esrch: return (-ESRCH); } noinline __unlikely int mx_test_options_card(mx_option_t * arg) { struct cd *cd; struct mx_opt_conf_card *val = (typeof(val)) (arg + 1); if (!(cd = cd_find(arg->id))) goto esrch; /* check validity of arguments */ if (val->mxCardMode & ~((1 << MXCARDMODE_LOCALLOOPBACK) | (1 << MXCARDMODE_REMOTELOOPBACK))) goto einval; switch (val->mxCardSyncMaster) { case MXCARDSYNCMASTER_MASTER: case MXCARDSYNCMASTER_SLAVE: break; default: goto einval; } switch (val->mxCardSyncSource) { case MXCARDSYNCSOURCE_SYNCSELF: case MXCARDSYNCSOURCE_SYNC1: case MXCARDSYNCSOURCE_SYNC2: case MXCARDSYNCSOURCE_SYNC3: case MXCARDSYNCSOURCE_SYNC4: break; default: case MXCARDSYNCSOURCE_SYNCEXTERN: case MXCARDSYNCSOURCE_SYNCAUTO: goto einval; } return (0); esrch: return (-ESRCH); einval: return (-EINVAL); } noinline __unlikely int mx_test_options_span(mx_option_t * arg) { struct sp *sp; struct mx_opt_conf_span *val = (typeof(val)) (arg + 1); if (!(sp = sp_find(arg->id))) goto esrch; /* check validity of values */ if (val->mxSpanMode & ~((1 << MXSPANMODE_LOCAL) | (1 << MXSPANMODE_REMOTE))) goto einval; switch (val->mxSpanClocking) { case MXSPANCLOCKING_INTERNAL: case MXSPANCLOCKING_EXTERNAL: case MXSPANCLOCKING_LOOP: break; default: goto einval; } switch (val->mxSpanLineMode) { case MXSPANLINEMODE_NONE: /* set to whatever it is */ if (sp->config.iftxlevel & ~0x7) { val->mxSpanLineMode = MXSPANLINEMODE_MONITOR; } else if (sp->config.ifgtype == SDL_GTYPE_E1) { if (sp->config.iftxlevel & 0x6) val->mxSpanLineMode = MXSPANLINEMODE_CSU; else val->mxSpanLineMode = MXSPANLINEMODE_DSU; } else { if (sp->config.iftxlevel == 0 || sp->config.iftxlevel > 4) val->mxSpanLineMode = MXSPANLINEMODE_CSU; else val->mxSpanLineMode = MXSPANLINEMODE_DSU; } break; case MXSPANLINEMODE_DSU: case MXSPANLINEMODE_CSU: case MXSPANLINEMODE_MONITOR: break; default: goto einval; } switch (val->mxSpanLineLength) { case MXSPANLINELENGTH_NONE: /* set to whatever it is */ if (sp->config.ifgtype != SDL_GTYPE_E1 && sp->config.iftxlevel < 5) { switch (sp->config.iftxlevel) { case 0: val->mxSpanLineLength = MXSPANLINELENGTH_DSX133FT; break; case 1: val->mxSpanLineLength = MXSPANLINELENGTH_DSX266FT; break; case 2: val->mxSpanLineLength = MXSPANLINELENGTH_DSX399FT; break; case 3: val->mxSpanLineLength = MXSPANLINELENGTH_DSX533FT; break; case 4: val->mxSpanLineLength = MXSPANLINELENGTH_DSX666FT; break; } } break; case MXSPANLINELENGTH_DSX133FT: case MXSPANLINELENGTH_DSX266FT: case MXSPANLINELENGTH_DSX399FT: case MXSPANLINELENGTH_DSX533FT: case MXSPANLINELENGTH_DSX666FT: break; default: goto einval; } switch (val->mxSpanLineAttenuation) { case MXSPANLINEATTENUATION_NONE: /* set it to whatever it is */ if (sp->config.ifgtype != SDL_GTYPE_E1 && sp->config.iftxlevel < 8) { switch (sp->config.iftxlevel) { case 0: case 1: case 2: case 3: case 4: val->mxSpanLineAttenuation = MXSPANLINEATTENUATION_CSU0DB; break; case 5: val->mxSpanLineAttenuation = MXSPANLINEATTENUATION_CSU8DB; break; case 6: val->mxSpanLineAttenuation = MXSPANLINEATTENUATION_CSU15DB; break; case 7: val->mxSpanLineAttenuation = MXSPANLINEATTENUATION_CSU23DB; break; } } break; case MXSPANLINEATTENUATION_CSU0DB: case MXSPANLINEATTENUATION_CSU8DB: case MXSPANLINEATTENUATION_CSU15DB: case MXSPANLINEATTENUATION_CSU23DB: break; default: goto einval; } switch (val->mxSpanLineGain) { case MXSPANLINEGAIN_NONE: /* set it to whatever it is */ if (sp->config.iftxlevel >= 8) { switch (sp->cd->device) { case XP_DEV_DS2155: case XP_DEV_DS21455: case XP_DEV_DS21458: case XP_DEV_DS2156: default: switch (sp->config.iftxlevel & 0x3) { case 0: /* 0 */ val->mxSpanLineGain = MXSPANLINEGAIN_MON0DB; break; case 1: /* 20 dB */ val->mxSpanLineGain = MXSPANLINEGAIN_MON20DB; break; case 2: /* 26 dB */ val->mxSpanLineGain = MXSPANLINEGAIN_MON26DB; break; case 3: /* 32 dB */ val->mxSpanLineGain = MXSPANLINEGAIN_MON32DB; break; } break; case XP_DEV_DS2152: case XP_DEV_DS21352: case XP_DEV_DS21552: switch (sp->config.iftxlevel & 0x3) { case 0: /* 0 */ val->mxSpanLineGain = MXSPANLINEGAIN_MON0DB; break; case 1: /* 12 dB */ val->mxSpanLineGain = MXSPANLINEGAIN_MON12DB; break; case 2: case 3: /* 20 dB */ val->mxSpanLineGain = MXSPANLINEGAIN_MON20DB; break; } break; case XP_DEV_DS2154: case XP_DEV_DS21354: case XP_DEV_DS21554: switch (sp->config.iftxlevel & 0x3) { case 0: /* 0 */ val->mxSpanLineGain = MXSPANLINEGAIN_MON0DB; break; case 1: /* 12 dB */ val->mxSpanLineGain = MXSPANLINEGAIN_MON12DB; break; case 2: case 3: /* 30 dB */ val->mxSpanLineGain = MXSPANLINEGAIN_MON30DB; break; } break; } } break; case MXSPANLINEGAIN_MON0DB: case MXSPANLINEGAIN_MON12DB: case MXSPANLINEGAIN_MON20DB: case MXSPANLINEGAIN_MON26DB: case MXSPANLINEGAIN_MON30DB: case MXSPANLINEGAIN_MON32DB: break; default: goto einval; } switch (val->mxSpanLineImpedance) { case MXSPANLINEIMPEDANCE_NONE: /* set it to whatever it is */ if (sp->config.ifgtype == SDL_GTYPE_E1) { if (sp->config.iftxlevel & 0x1) val->mxSpanLineImpedance = MXSPANLINEIMPEDANCE_UNBALANCED75OHM; else val->mxSpanLineImpedance = MXSPANLINEIMPEDANCE_BALANCED120OHM; } else { val->mxSpanLineImpedance = MXSPANLINEIMPEDANCE_BALANCED100OHM; } break; case MXSPANLINEIMPEDANCE_UNBALANCED75OHM: case MXSPANLINEIMPEDANCE_BALANCED100OHM: case MXSPANLINEIMPEDANCE_BALANCED120OHM: break; default: goto einval; } if (val->mxSpanLineDelay != 0) goto einval; switch (val->mxSpanTxLevel) { case MXSPANTXLEVEL_OFF: case MXSPANTXLEVEL_ON: break; default: goto einval; } switch (val->mxSpanRxLevel) { case MXSPANRXLEVEL_OFF: case MXSPANRXLEVEL_ON: break; default: goto einval; } if (val->mxSpanAlarmSettleTime != 5000) val->mxSpanAlarmSettleTime = 5000; if (val->mxSpanLineCodeTime != 5000) val->mxSpanLineCodeTime = 5000; switch (val->mxSpanLineCode) { case MXSPANLINECODE_NOCODE: break; default: case MXSPANLINECODE_LINECODE: case MXSPANLINECODE_PAYLOADCODE: case MXSPANLINECODE_RESETCODE: case MXSPANLINECODE_TESTCODE: case MXSPANLINECODE_UNFRAMEDALLONES: case MXSPANLINECODE_UNFRAMEDONEANDZERO: goto einval; } if (val->mxSpanReceiveThreshold != 0) goto einval; return (0); esrch: return (-ESRCH); einval: return (-EINVAL); } noinline __unlikely int mx_test_options_chan(mx_option_t * arg) { struct ch *ch; struct mx_opt_conf_chan *val = (typeof(val)) (arg + 1); if (IS_ERR((ch = ch_find(arg->id))) || ch == NULL) goto esrch; /* check validity of values */ switch (val->mxChanType) { case MXCHANTYPE_NONE: val->mxChanType = MXCHANTYPE_CCS; case MXCHANTYPE_CCS: break; case MXCHANTYPE_CAS: default: goto einval; } switch (val->mxChanFormat) { case MXCHANFORMAT_NONE: /* set to what it is */ switch (ch->sdl.config.iftype) { case SDL_TYPE_DS0: val->mxChanFormat = MXCHANFORMAT_DS0; break; case SDL_TYPE_DS0A: val->mxChanFormat = MXCHANFORMAT_DS0A; break; case SDL_TYPE_E1: val->mxChanFormat = MXCHANFORMAT_E1; break; case SDL_TYPE_T1: val->mxChanFormat = MXCHANFORMAT_T1; break; case SDL_TYPE_J1: val->mxChanFormat = MXCHANFORMAT_J1; break; } break; case MXCHANFORMAT_DS0: case MXCHANFORMAT_DS0A: break; case MXCHANFORMAT_E1: if (ch->sdl.config.ifgtype != SDL_GTYPE_E1) goto einval; break; case MXCHANFORMAT_T1: if (ch->sdl.config.ifgtype != SDL_GTYPE_T1) goto einval; break; case MXCHANFORMAT_J1: if (ch->sdl.config.ifgtype != SDL_GTYPE_J1) goto einval; break; default: goto einval; } switch (val->mxChanRate) { case MXCHANRATE_VARIABLE: /* set it to what it will be */ switch (val->mxChanFormat) { case MXCHANFORMAT_DS0: val->mxChanRate = MXCHANRATE_KBITS64; break; case MXCHANFORMAT_DS0A: val->mxChanRate = MXCHANRATE_KBITS56; break; case MXCHANFORMAT_E1: val->mxChanRate = MXCHANRATE_KBITS1984; break; case MXCHANFORMAT_T1: val->mxChanRate = MXCHANRATE_KBITS1536; break; case MXCHANFORMAT_J1: val->mxChanRate = MXCHANRATE_KBITS1536; break; } break; case MXCHANRATE_KBITS56: case MXCHANRATE_KBITS64: break; case MXCHANRATE_KBITS1536: if (ch->sdl.config.ifgtype == SDL_GTYPE_E1) goto einval; break; case MXCHANRATE_KBITS1984: if (ch->sdl.config.ifgtype != SDL_GTYPE_E1) goto einval; break; default: goto einval; } switch (val->mxChanMode) { case (1 << MXCHANMODE_REMOTELOOPBACK): case (1 << MXCHANMODE_LOCALLOOPBACK): case (1 << MXCHANMODE_TEST): case (1 << MXCHANMODE_LOOPBACKECHO): break; default: goto einval; } return (0); esrch: return (-ESRCH); einval: return (-EINVAL); } noinline __unlikely int mx_test_options(queue_t *q, mblk_t *mp, mx_option_t * arg) { int ret; switch (arg->type) { case MX_OBJ_TYPE_DFLT: /* defaults */ if ((unsigned char *) (&arg->option->dflt + 1) > mp->b_cont->b_wptr) goto emsgsize; if ((ret = mx_test_options_dflt(arg)) >= 0) mp->b_cont->b_wptr = (unsigned char *) (&arg->option->dflt + 1); break; case MX_OBJ_TYPE_SYNC: /* synchronization group */ goto esrch; case MX_OBJ_TYPE_CARD: /* card */ if ((unsigned char *) (&arg->option->card + 1) > mp->b_cont->b_wptr) goto emsgsize; if ((ret = mx_test_options_card(arg)) >= 0) mp->b_cont->b_wptr = (unsigned char *) (&arg->option->card + 1); break; case MX_OBJ_TYPE_SPAN: /* span */ if ((unsigned char *) (&arg->option->span + 1) > mp->b_cont->b_wptr) goto emsgsize; if ((ret = mx_test_options_span(arg)) >= 0) mp->b_cont->b_wptr = (unsigned char *) (&arg->option->span + 1); break; case MX_OBJ_TYPE_CHAN: /* channel */ if ((unsigned char *) (&arg->option->chan + 1) > mp->b_cont->b_wptr) goto emsgsize; if ((ret = mx_test_options_chan(arg)) >= 0) mp->b_cont->b_wptr = (unsigned char *) (&arg->option->chan + 1); break; case MX_OBJ_TYPE_FRAC: /* fractional */ goto esrch; case MX_OBJ_TYPE_XCON: /* cross connect */ goto esrch; case MX_OBJ_TYPE_BERT: /* bit error rate test */ goto esrch; default: goto einval; } return (ret); emsgsize: return (-EMSGSIZE); esrch: return (-ESRCH); einval: return (-EINVAL); } noinline __unlikely int mx_set_options_dflt(mx_option_t * arg) { /* there are no default options yet */ return (0); } noinline __unlikely int mx_set_options_sync(struct sg *sg, mx_option_t * arg) { return (0); } noinline __unlikely int mx_set_options_card(struct cd *cd, mx_option_t * arg) { struct mx_opt_conf_card *val = (typeof(val)) (arg + 1); uint card_reconfig = 0; /* validity of options already checked */ if (val->mxCardMode & (1 << MXCARDMODE_LOCALLOOPBACK)) { if (!(cd->config.ifgmode & SDL_GMODE_LOC_LB)) { card_reconfig = 1; cd->config.ifgmode |= SDL_GMODE_LOC_LB; } } if (val->mxCardMode & (1 << MXCARDMODE_REMOTELOOPBACK)) { if (!(cd->config.ifgmode & SDL_GMODE_REM_LB)) { card_reconfig = 1; cd->config.ifgmode |= SDL_GMODE_REM_LB; } } switch (val->mxCardSyncMaster) { case MXCARDSYNCMASTER_MASTER: if (cd->config.ifclock != SDL_CLOCK_MASTER) { card_reconfig = 1; cd->config.ifclock = SDL_CLOCK_MASTER; } break; case MXCARDSYNCMASTER_SLAVE: if (cd->config.ifclock != SDL_CLOCK_SLAVE) { card_reconfig = 1; cd->config.ifclock = SDL_CLOCK_SLAVE; } break; } switch (val->mxCardSyncSource) { case MXCARDSYNCSOURCE_SYNCSELF: if (cd->config.ifsync != SYNCSELF) { card_reconfig = 1; cd->config.ifsync = SYNCSELF; } break; case MXCARDSYNCSOURCE_SYNC1: if (cd->config.ifsync != SYNC1) { card_reconfig = 1; cd->config.ifsync = SYNC1; } break; case MXCARDSYNCSOURCE_SYNC2: if (cd->config.ifsync != SYNC2) { card_reconfig = 1; cd->config.ifsync = SYNC2; } break; case MXCARDSYNCSOURCE_SYNC3: if (cd->config.ifsync != SYNC3) { card_reconfig = 1; cd->config.ifsync = SYNC3; } break; case MXCARDSYNCSOURCE_SYNC4: if (cd->config.ifsync != SYNC4) { card_reconfig = 1; cd->config.ifsync = SYNC4; } break; case MXCARDSYNCSOURCE_SYNCEXTERN: if (cd->config.ifsync != SYNCEXTERN) { card_reconfig = 1; cd->config.ifsync = SYNCEXTERN; } break; case MXCARDSYNCSOURCE_SYNCAUTO: if (cd->config.ifsync != SYNCAUTO) { card_reconfig = 1; cd->config.ifsync = SYNCAUTO; } break; } if (card_reconfig && (cd->config.ifflags & SDL_IF_UP)) xp_card_reconfig(cd, 0); return (0); } noinline __unlikely int mx_set_options_span(struct sp *sp, mx_option_t * arg) { struct mx_opt_conf_span *val = (typeof(val)) (arg + 1); uint txlevel = 0, span_reconfig = 0; /* mxSpanMode */ if (val->mxSpanMode & (1 << MXSPANMODE_LOCAL)) { if (!(sp->config.ifgmode & SDL_GMODE_LOC_LB)) { span_reconfig = 1; sp->config.ifgmode |= SDL_GMODE_LOC_LB; } } else { if (sp->config.ifgmode & SDL_GMODE_LOC_LB) { span_reconfig = 1; sp->config.ifgmode &= ~SDL_GMODE_LOC_LB; } } if (val->mxSpanMode & (1 << MXSPANMODE_REMOTE)) { if (!(sp->config.ifgmode & SDL_GMODE_REM_LB)) { span_reconfig = 1; sp->config.ifgmode |= SDL_GMODE_REM_LB; } } else { if (sp->config.ifgmode & SDL_GMODE_REM_LB) { span_reconfig = 1; sp->config.ifgmode &= ~SDL_GMODE_REM_LB; } } /* mxSpanClocking */ switch (val->mxSpanClocking) { case MXSPANCLOCKING_INTERNAL: if (sp->config.ifclock != SDL_CLOCK_INT) { span_reconfig = 1; sp->config.ifclock = SDL_CLOCK_INT; } break; case MXSPANCLOCKING_EXTERNAL: if (sp->config.ifclock != SDL_CLOCK_EXT) { span_reconfig = 1; sp->config.ifclock = SDL_CLOCK_EXT; } break; case MXSPANCLOCKING_LOOP: if (sp->config.ifclock != SDL_CLOCK_LOOP) { span_reconfig = 1; sp->config.ifclock = SDL_CLOCK_LOOP; } break; } /* mxSpanLineMode */ /* mxSpanLineImpedance */ /* mxSpanLineLength */ /* mxSpanLineAttenuation */ /* mxSpanLineGain */ switch (val->mxSpanLineMode) { case MXSPANLINEMODE_MONITOR: val->mxSpanLineLength = MXSPANLINELENGTH_NONE; val->mxSpanLineImpedance = MXSPANLINEIMPEDANCE_NONE; val->mxSpanLineAttenuation = MXSPANLINEATTENUATION_NONE; txlevel = 8; switch (val->mxSpanLineGain) { case MXSPANLINEGAIN_NONE: case MXSPANLINEGAIN_MON0DB: break; case MXSPANLINEGAIN_MON12DB: switch (sp->cd->device) { case XP_DEV_DS2155: case XP_DEV_DS21455: case XP_DEV_DS21458: case XP_DEV_DS2156: txlevel += 0; /* nearest lower */ val->mxSpanLineGain = MXSPANLINEGAIN_MON0DB; break; default: txlevel += 1; break; } break; case MXSPANLINEGAIN_MON20DB: switch (sp->cd->device) { case XP_DEV_DS2155: case XP_DEV_DS21455: case XP_DEV_DS21458: case XP_DEV_DS2156: txlevel += 1; break; case XP_DEV_DS2152: case XP_DEV_DS21352: case XP_DEV_DS21552: txlevel += 2; break; case XP_DEV_DS2154: case XP_DEV_DS21354: case XP_DEV_DS21554: txlevel += 1; /* nearest lower */ val->mxSpanLineGain = MXSPANLINEGAIN_MON12DB; break; } break; case MXSPANLINEGAIN_MON26DB: switch (sp->cd->device) { case XP_DEV_DS2155: case XP_DEV_DS21455: case XP_DEV_DS21458: case XP_DEV_DS2156: txlevel += 2; break; case XP_DEV_DS2152: case XP_DEV_DS21352: case XP_DEV_DS21552: txlevel += 2; /* nearest lower */ val->mxSpanLineGain = MXSPANLINEGAIN_MON20DB; break; case XP_DEV_DS2154: case XP_DEV_DS21354: case XP_DEV_DS21554: txlevel += 1; /* nearest lower */ val->mxSpanLineGain = MXSPANLINEGAIN_MON12DB; break; } break; case MXSPANLINEGAIN_MON30DB: switch (sp->cd->device) { case XP_DEV_DS2155: case XP_DEV_DS21455: case XP_DEV_DS21458: case XP_DEV_DS2156: txlevel += 2; /* nearest lower */ val->mxSpanLineGain = MXSPANLINEGAIN_MON26DB; break; case XP_DEV_DS2152: case XP_DEV_DS21352: case XP_DEV_DS21552: txlevel += 2; /* nearest lower */ val->mxSpanLineGain = MXSPANLINEGAIN_MON20DB; break; case XP_DEV_DS2154: case XP_DEV_DS21354: case XP_DEV_DS21554: txlevel += 2; break; } break; case MXSPANLINEGAIN_MON32DB: switch (sp->cd->device) { case XP_DEV_DS2155: case XP_DEV_DS21455: case XP_DEV_DS21458: case XP_DEV_DS2156: txlevel += 3; break; case XP_DEV_DS2152: case XP_DEV_DS21352: case XP_DEV_DS21552: txlevel += 2; /* nearest lower */ val->mxSpanLineGain = MXSPANLINEGAIN_MON20DB; break; case XP_DEV_DS2154: case XP_DEV_DS21354: case XP_DEV_DS21554: txlevel += 2; /* nearest lower */ val->mxSpanLineGain = MXSPANLINEGAIN_MON30DB; break; } break; } break; case MXSPANLINEMODE_DSU: val->mxSpanLineGain = MXSPANLINEGAIN_NONE; val->mxSpanLineAttenuation = MXSPANLINEATTENUATION_NONE; if (sp->config.ifgtype == SDL_GTYPE_E1) { val->mxSpanLineLength = MXSPANLINELENGTH_NONE; val->mxSpanLineImpedance = MXSPANLINEIMPEDANCE_UNBALANCED75OHM; txlevel = 1; } else { val->mxSpanLineImpedance = MXSPANLINEIMPEDANCE_BALANCED100OHM; switch (val->mxSpanLineLength) { case MXSPANLINELENGTH_NONE: val->mxSpanLineLength = MXSPANLINELENGTH_DSX133FT; /* fall through */ case MXSPANLINELENGTH_DSX133FT: txlevel = 0; break; case MXSPANLINELENGTH_DSX266FT: txlevel = 1; break; case MXSPANLINELENGTH_DSX399FT: txlevel = 2; break; case MXSPANLINELENGTH_DSX533FT: txlevel = 3; break; case MXSPANLINELENGTH_DSX666FT: txlevel = 4; break; } } break; case MXSPANLINEMODE_CSU: val->mxSpanLineGain = MXSPANLINEGAIN_NONE; val->mxSpanLineLength = MXSPANLINELENGTH_NONE; if (sp->config.ifgtype == SDL_GTYPE_E1) { val->mxSpanLineImpedance = MXSPANLINEIMPEDANCE_BALANCED120OHM; val->mxSpanLineAttenuation = MXSPANLINEATTENUATION_NONE; txlevel = 1; } else { val->mxSpanLineImpedance = MXSPANLINEIMPEDANCE_BALANCED100OHM; switch (val->mxSpanLineAttenuation) { case MXSPANLINEATTENUATION_NONE: val->mxSpanLineAttenuation = MXSPANLINEATTENUATION_CSU0DB; /* fall through */ case MXSPANLINEATTENUATION_CSU0DB: txlevel = 0; break; case MXSPANLINEATTENUATION_CSU8DB: txlevel = 5; break; case MXSPANLINEATTENUATION_CSU15DB: txlevel = 6; break; case MXSPANLINEATTENUATION_CSU23DB: txlevel = 7; break; } } break; } if (sp->config.iftxlevel != txlevel) { span_reconfig = 1; sp->config.iftxlevel = txlevel; } /* mxSpanLineDelay */ /* mxSpanTxLevel */ switch (val->mxSpanTxLevel) { case MXSPANTXLEVEL_ON: if (!(sp->config.ifflags & SDL_IF_TX_RUNNING)) { span_reconfig = 1; sp->config.ifflags |= SDL_IF_TX_RUNNING; } break; case MXSPANTXLEVEL_OFF: case MXSPANTXLEVEL_OPEN: if (sp->config.ifflags & SDL_IF_TX_RUNNING) { span_reconfig = 1; sp->config.ifflags &= ~SDL_IF_TX_RUNNING; } break; } /* mxSpanRxLevel */ switch (val->mxSpanRxLevel) { case MXSPANRXLEVEL_ON: if (!(sp->config.ifflags & SDL_IF_RX_RUNNING)) { span_reconfig = 1; sp->config.ifflags |= SDL_IF_RX_RUNNING; } break; case MXSPANRXLEVEL_OFF: case MXSPANRXLEVEL_OPEN: if (sp->config.ifflags & SDL_IF_RX_RUNNING) { span_reconfig = 1; sp->config.ifflags &= ~SDL_IF_RX_RUNNING; } break; } /* mxSpanLineAlarmSettleTime */ /* mxSpanLineCodeTime */ /* mxSpanLineCode */ /* mxSpanReceiveThreshold */ if (span_reconfig && (sp->config.ifflags & SDL_IF_UP)) xp_span_reconfig(sp); return (0); } noinline __unlikely int mx_set_options_chan(struct ch *ch, mx_option_t * arg) { struct mx_opt_conf_chan *val = (typeof(val)) (arg + 1); uint chan_reconfig = 0; /* mxChanType */ /* always MXCHANTYPE_CCS for this driver */ /* mxChanFormat */ switch (val->mxChanFormat) { case MXCHANFORMAT_DS0A: if (ch->sdl.config.iftype != SDL_TYPE_DS0A) { chan_reconfig = 1; ch->sdl.config.iftype = SDL_TYPE_DS0A; } break; case MXCHANFORMAT_DS0: if (ch->sdl.config.iftype != SDL_TYPE_DS0) { chan_reconfig = 1; ch->sdl.config.iftype = SDL_TYPE_DS0; } break; case MXCHANFORMAT_E1: if (ch->sdl.config.iftype != SDL_TYPE_E1) { chan_reconfig = 1; ch->sdl.config.iftype = SDL_TYPE_E1; } break; case MXCHANFORMAT_T1: if (ch->sdl.config.iftype != SDL_TYPE_T1) { chan_reconfig = 1; ch->sdl.config.iftype = SDL_TYPE_T1; } break; case MXCHANFORMAT_J1: if (ch->sdl.config.iftype != SDL_TYPE_J1) { chan_reconfig = 1; ch->sdl.config.iftype = SDL_TYPE_J1; } break; } switch (val->mxChanRate) { case MXCHANRATE_KBITS56: if (ch->sdl.config.ifrate != SDL_RATE_DS0A) { chan_reconfig = 1; ch->sdl.config.ifrate = SDL_RATE_DS0A; } break; case MXCHANRATE_KBITS64: if (ch->sdl.config.ifrate != SDL_RATE_DS0) { chan_reconfig = 1; ch->sdl.config.ifrate = SDL_RATE_DS0; } break; case MXCHANRATE_KBITS1536: if (ch->sdl.config.ifrate != SDL_RATE_T1) { chan_reconfig = 1; ch->sdl.config.ifrate = SDL_RATE_T1; } break; case MXCHANRATE_KBITS1984: if (ch->sdl.config.ifrate != SDL_RATE_E1) { chan_reconfig = 1; ch->sdl.config.ifrate = SDL_RATE_E1; } break; } switch (val->mxChanMode) { case (1 << MXCHANMODE_REMOTELOOPBACK): if (ch->sdl.config.ifmode != SDL_MODE_REM_LB) { chan_reconfig = 1; ch->sdl.config.ifmode = SDL_MODE_REM_LB; } break; case (1 << MXCHANMODE_LOCALLOOPBACK): if (ch->sdl.config.ifmode != SDL_MODE_LOC_LB) { chan_reconfig = 1; ch->sdl.config.ifmode = SDL_MODE_LOC_LB; } break; case (1 << MXCHANMODE_TEST): if (ch->sdl.config.ifmode != SDL_MODE_TEST) { chan_reconfig = 1; ch->sdl.config.ifmode = SDL_MODE_TEST; } break; case (1 << MXCHANMODE_LOOPBACKECHO): if (ch->sdl.config.ifmode != SDL_MODE_LB_ECHO) { chan_reconfig = 1; ch->sdl.config.ifmode = SDL_MODE_LB_ECHO; } break; } if (chan_reconfig && (ch->sdl.config.ifflags & SDL_IF_UP)) /* FIXME */ ; return (0); } /** mx_iocsoption: - set options * @q: active queue (management stream write queue) * @mp: the input-output control */ noinline __unlikely int mx_iocsoption(queue_t *q, mblk_t *mp, mblk_t *dp) { mx_option_t *arg = (typeof(arg)) dp->b_rptr; int ret; ret = -ESRCH; switch (arg->type) { struct sg *sg; struct cd *cd; struct sp *sp; struct ch *ch; psw_t flags; case MX_OBJ_TYPE_DFLT: /* defaults */ if (arg->id != 0) break; ret = mx_set_options_dflt(arg); break; case MX_OBJ_TYPE_SYNC: /* synchronization group */ if (!(sg = sg_find(arg->id))) break; spin_lock_irqsave(&sg->lock, flags); ret = mx_set_options_sync(sg, arg); spin_unlock_irqrestore(&sg->lock, flags); break; case MX_OBJ_TYPE_CARD: /* card */ if (!(cd = cd_find(arg->id))) break; spin_lock_irqsave(&cd->lock, flags); ret = mx_set_options_card(cd, arg); spin_unlock_irqrestore(&cd->lock, flags); break; case MX_OBJ_TYPE_SPAN: /* span */ if (!(sp = sp_find(arg->id))) break; spin_lock_irqsave(&sp->lock, flags); ret = mx_set_options_span(sp, arg); spin_unlock_irqrestore(&sp->lock, flags); break; case MX_OBJ_TYPE_CHAN: /* channel */ if (IS_ERR((ch = ch_find(arg->id)))) break; spin_lock_bh(&ch->lock); ret = mx_set_options_chan(ch, arg); spin_unlock_bh(&ch->lock); break; case MX_OBJ_TYPE_FRAC: /* fractional */ break; case MX_OBJ_TYPE_XCON: /* cross connect */ break; case MX_OBJ_TYPE_BERT: /* bit error rate test */ break; default: ret = -EINVAL; break; } return (ret); } /** mx_ioclconfig: - list configuration input-output control * @q: active queue (management stream write queue) * @mp: the input-output control * * Lists as a number of unsigned integers the identifiers of all of the elements of a type that * will fit into the buffer area. When successful, returns the number of elements (whether they * would fit into the buffer or not). */ noinline __unlikely int mx_ioclconfig(queue_t *q, mblk_t *mp, mblk_t *dp) { mx_config_t *hdr, *arg = (typeof(arg)) dp->b_rptr; uint num = 0, *val, can = arg->id; struct cd *cd; struct sp *sp; uint card, span, chan; mblk_t *db; if (!(db = mi_copyout_alloc(q, mp, 0, sizeof(*hdr) + can * sizeof(*val), 0))) return (-ENOSR); *(hdr = (typeof(hdr)) db->b_rptr) = *arg; val = (typeof(val)) (hdr + 1); switch (arg->type) { case MX_OBJ_TYPE_DFLT: /* defaults */ /* list all default objects: there is always only one */ if ((unsigned char *) (val + 1) <= db->b_wptr) *val = 0; val++; num++; break; case MX_OBJ_TYPE_SYNC: /* synchronization group */ /* list all existing syncrhonization groups: this driver does not support syncrhonization groups, so the list is always empty? XXX */ break; case MX_OBJ_TYPE_CARD: /* card */ /* list all equipped card ids */ for (card = 0; card < X400_CARDS; card++) { if (!(cd = x400p_cards[card])) continue; if ((unsigned char *) (val + 1) <= db->b_wptr) *val = (cd->card << 12); val++; num++; } break; case MX_OBJ_TYPE_SPAN: /* span */ /* list all equipped span ids */ for (card = 0; card < X400_CARDS; card++) { if (!(cd = x400p_cards[card])) continue; for (span = 0; span < cd->ports; span++, val++, num++) if ((unsigned char *) (val + 1) <= db->b_wptr) *val = (cd->card << 12) | (span << 8); } break; case MX_OBJ_TYPE_CHAN: /* channel */ /* list all equipped channel ids */ for (card = 0; card < X400_CARDS; card++) { if (!(cd = x400p_cards[card])) continue; for (span = 0; span < cd->ports; span++) { if (!(sp = cd->spans[span])) continue; switch (sp->config.ifgtype) { case SDL_GTYPE_E1: for (chan = 1; chan <= 31; chan++, val++, num++) if ((unsigned char *) (val + 1) <= db->b_wptr) *val = (cd->card << 12) | (span << 8) | (chan << 0); break; case SDL_GTYPE_T1: for (chan = 1; chan <= 24; chan++, val++, num++) if ((unsigned char *) (val + 1) <= db->b_wptr) *val = (cd->card << 12) | (span << 8) | (chan << 0); break; case SDL_GTYPE_J1: for (chan = 1; chan <= 24; chan++, val++, num++) if ((unsigned char *) (val + 1) <= db->b_wptr) *val = (cd->card << 12) | (span << 8) | (chan << 0); break; } } } break; case MX_OBJ_TYPE_FRAC: /* fractional */ /* list all existing fractional ids: this driver does not support fractional, so the list is always empty */ break; case MX_OBJ_TYPE_XCON: /* cross connect */ /* list all existing cross connects: this driver does not support cross-connect, so the list is always empty */ break; case MX_OBJ_TYPE_BERT: /* bit error rate test */ /* list all equipped span ids capable of bert testing: this driver does not support bert, so the list is always empty */ break; default: goto einval; } if (db->b_wptr > (unsigned char *) val) db->b_wptr = (unsigned char *) val; hdr->id = num > can ? can : num; mi_copy_set_rval(mp, num); return (0); einval: return (-EINVAL); } STATIC __unlikely int mx_config_size(mx_config_t * arg) { int size = sizeof(*arg); switch (arg->type) { case MX_OBJ_TYPE_DFLT: size += sizeof(arg->config->dflt); break; case MX_OBJ_TYPE_SYNC: size += sizeof(arg->config->sync); break; case MX_OBJ_TYPE_CARD: size += sizeof(arg->config->card); break; case MX_OBJ_TYPE_SPAN: size += sizeof(arg->config->span); break; case MX_OBJ_TYPE_CHAN: size += sizeof(arg->config->chan); break; case MX_OBJ_TYPE_FRAC: size += sizeof(arg->config->frac); break; case MX_OBJ_TYPE_XCON: size += sizeof(arg->config->xcon); break; case MX_OBJ_TYPE_BERT: size += sizeof(arg->config->bert); break; default: return (-EINVAL); } return (size); } noinline __unlikely int mx_iocgconfig_dflt(mx_config_t * arg) { /* there is no configuration for default */ return (0); } noinline __unlikely int mx_iocgconfig_sync(struct sg *sg, mx_config_t * arg) { return (-EOPNOTSUPP); } /** mx_iocgconfig_card: - get configuration information for a card * @cd: card structure * @arg; the configuration structure */ noinline __unlikely int mx_iocgconfig_card(struct cd *cd, mx_config_t * arg) { struct mx_conf_card *val = (typeof(val)) (arg + 1); val->mxCardIndex = cd->card; switch (cd->config.ifgtype) { case SDL_GTYPE_E1: val->mxCardSpanType = MXCARDSPANTYPE_E1; break; case SDL_GTYPE_T1: val->mxCardSpanType = MXCARDSPANTYPE_T1; break; case SDL_GTYPE_J1: val->mxCardSpanType = MXCARDSPANTYPE_J1; break; default: val->mxCardSpanType = MXCARDSPANTYPE_NONE; break; } val->mxCardSyncGroup = 0; return (0); } /** mx_iocgconfig_span: - get configuration information for a span * @sp: span structure * @arg; the configuration structure */ noinline __unlikely int mx_iocgconfig_span(struct sp *sp, mx_config_t * arg) { struct mx_conf_span *val; val = (typeof(val)) (arg + 1); val->mxCardIndex = (arg->id >> 12) & 0xf; val->mxSpanIndex = (arg->id >> 8) & 0xf; val->mxSpanName[0] = '\0'; switch (sp->config.ifgtype) { case SDL_GTYPE_E1: val->mxSpanType = MXSPANTYPE_E1; break; case SDL_GTYPE_T1: val->mxSpanType = MXSPANTYPE_T1; break; case SDL_GTYPE_J1: val->mxSpanType = MXSPANTYPE_J1; break; case SDL_GTYPE_E2: val->mxSpanType = MXSPANTYPE_E2; break; case SDL_GTYPE_E3: val->mxSpanType = MXSPANTYPE_E3; break; case SDL_GTYPE_T3: val->mxSpanType = MXSPANTYPE_T3; break; default: val->mxSpanType = MXSPANTYPE_NONE; break; } switch (sp->config.ifgcrc) { case SDL_GCRC_CRC4: val->mxSpanCrc = MXSPANCRC_CRC4; break; case SDL_GCRC_CRC5: val->mxSpanCrc = MXSPANCRC_CRC5; break; case SDL_GCRC_CRC6: val->mxSpanCrc = MXSPANCRC_CRC6; break; case SDL_GCRC_CRC6J: val->mxSpanCrc = MXSPANCRC_CRC6J; break; default: case SDL_GCRC_NONE: val->mxSpanCrc = MXSPANCRC_NONE; break; } switch (sp->config.ifcoding) { case SDL_CODING_AMI: val->mxSpanCoding = MXSPANCODING_AMI; break; case SDL_CODING_B6ZS: val->mxSpanCoding = MXSPANCODING_B6ZS; break; case SDL_CODING_B8ZS: val->mxSpanCoding = MXSPANCODING_B8ZS; break; case SDL_CODING_HDB3: val->mxSpanCoding = MXSPANCODING_HDB3; break; default: case SDL_CODING_NONE: case SDL_CODING_NRZ: case SDL_CODING_NRZI: case SDL_CODING_AAL1: case SDL_CODING_AAL2: case SDL_CODING_AAL5: val->mxSpanCoding = MXSPANCODING_NONE; break; } switch (sp->config.ifframing) { case SDL_FRAMING_CCS: val->mxSpanFraming = MXSPANFRAMING_CCS; break; case SDL_FRAMING_CAS: val->mxSpanFraming = MXSPANFRAMING_CAS; break; case SDL_FRAMING_SF: /* Same as D4 */ val->mxSpanFraming = MXSPANFRAMING_SF; break; case SDL_FRAMING_ESF: val->mxSpanFraming = MXSPANFRAMING_ESF; break; default: case SDL_FRAMING_NONE: val->mxSpanFraming = MXSPANFRAMING_NONE; break; } switch (sp->config.ifgtype) { case SDL_GTYPE_E1: val->mxSpanDataLink = MXSPANDATALINK_OTHER; break; case SDL_GTYPE_T1: val->mxSpanDataLink = MXSPANDATALINK_ANSIT1403; break; case SDL_GTYPE_J1: val->mxSpanDataLink = MXSPANDATALINK_OTHER; break; } val->mxSpanPriority = 0; val->mxSpanPrimary = 0; return (0); } /** mx_iocgconfig_chan: - get configuration information for a channel * @sp: span structure * @ch: channel structure * @arg; the configuration structure */ noinline __unlikely int mx_iocgconfig_chan(struct sp *sp, struct ch *ch, mx_config_t * arg) { struct mx_conf_chan *val; val = (typeof(val)) (arg + 1); val->mxCardIndex = (arg->id >> 12) & 0x0f; val->mxSpanIndex = (arg->id >> 8) & 0x0f; val->mxChanIndex = (arg->id >> 0) & 0xff; return (0); } /** mx_iocgconfig: - get configuration information for an object * @q: active queue (management stream write queue) * @mp: the input-output control * @arg; the configuration structure */ noinline __unlikely int mx_iocgconfig(queue_t *q, mblk_t *mp, mblk_t *dp) { mx_config_t *hdr, *arg = (typeof(arg)) dp->b_rptr; int ret; mblk_t *db; psw_t flags; arg->cmd = MX_GET; if ((ret = mx_config_size(arg)) < 0) return (ret); if (!(db = mi_copyout_alloc(q, mp, 0, ret, 0))) return (-ENOSR); *(hdr = (typeof(hdr)) db->b_rptr) = *arg; ret = -ESRCH; switch (arg->type) { struct cd *cd; struct sp *sp; struct ch *ch; struct sg *sg; case MX_OBJ_TYPE_DFLT: /* defaults */ if (arg->id != 0) break; ret = mx_iocgconfig_dflt(hdr); break; case MX_OBJ_TYPE_SYNC: /* synchronization group */ if (!(sg = sg_find(arg->id))) break; spin_lock_irqsave(&sg->lock, flags); ret = mx_iocgconfig_sync(sg, hdr); spin_unlock_irqrestore(&sg->lock, flags); break; case MX_OBJ_TYPE_CARD: /* card */ if (!(cd = cd_find(arg->id))) break; spin_lock_irqsave(&cd->lock, flags); ret = mx_iocgconfig_card(cd, hdr); spin_unlock_irqrestore(&cd->lock, flags); break; case MX_OBJ_TYPE_SPAN: /* span */ if (!(sp = sp_find(arg->id))) break; spin_lock_irqsave(&sp->lock, flags); ret = mx_iocgconfig_span(sp, hdr); spin_unlock_irqrestore(&sp->lock, flags); break; case MX_OBJ_TYPE_CHAN: /* channel */ if (!(sp = sp_find(arg->id))) break; if (IS_ERR((ch = ch_find(arg->id)))) break; spin_lock_bh(&ch->lock); ret = mx_iocgconfig_chan(sp, ch, hdr); spin_unlock_bh(&ch->lock); break; case MX_OBJ_TYPE_FRAC: /* fractional */ break; case MX_OBJ_TYPE_XCON: /* cross connect */ break; case MX_OBJ_TYPE_BERT: /* bit error rate test */ break; default: ret = -EINVAL; break; } if (ret >= 0) mi_copyout(q, mp); return (ret); } noinline __unlikely int mx_test_config_dflt(mx_config_t * arg) { return (0); } noinline __unlikely int mx_test_config_sync(struct sg *sg, mx_config_t * arg) { return (0); } noinline __unlikely int mx_test_config_card(struct cd *cd, mx_config_t * arg) { struct mx_conf_card *val = (typeof(val)) (arg + 1); if (val->mxCardIndex != cd->card) goto einval; switch (val->mxCardSpanType) { case MXSPANTYPE_E1: switch (cd->device) { case XP_DEV_DS2152: case XP_DEV_DS21352: case XP_DEV_DS21552: /* These chips do not support E1. */ goto einval; } switch (cd->board) { case PLX9030: case PLXDEVBRD: case T400P: case T400PSS7: case V400PT: default: /* These cards do not support E1. */ goto einval; case A400P: case V401PT: case A400PT: /* These cards actually suport E1. */ break; case CP100: case CP100P: case CP100E: case CP200: case CP200P: case CP200E: case CP400: case CP400P: case CP400E: /* These cards suport E1. */ break; } break; case MXSPANTYPE_T1: case MXSPANTYPE_J1: switch (cd->device) { case XP_DEV_DS2152: /* This chip does not support J1. */ if (val->mxCardSpanType == MXSPANTYPE_J1) goto einval; break; case XP_DEV_DS2154: case XP_DEV_DS21354: case XP_DEV_DS21554: /* These chips do not support T1 or J1. */ goto einval; } switch (cd->board) { case E400P: case E400PSS7: case V400PE: /* These cards do not support T1 or J1. */ goto einval; case A400P: case V401PE: case A400PE: /* These cards actually support T1 or J1. */ break; case CP100: case CP100P: case CP100E: case CP200: case CP200P: case CP200E: case CP400: case CP400P: case CP400E: /* These cards suport T1 or J1. */ break; } break; break; default: case MXSPANTYPE_E2: case MXSPANTYPE_E3: case MXSPANTYPE_T3: /* these are not applicable */ goto einval; case MXSPANTYPE_NONE: /* don't change modes at all */ switch (cd->config.ifgtype) { case SDL_GTYPE_E1: val->mxCardSpanType = MXCARDSPANTYPE_E1; break; case SDL_GTYPE_T1: val->mxCardSpanType = MXCARDSPANTYPE_T1; break; case SDL_GTYPE_J1: val->mxCardSpanType = MXCARDSPANTYPE_J1; break; case SDL_GTYPE_E2: val->mxCardSpanType = MXCARDSPANTYPE_E1; break; case SDL_GTYPE_E3: val->mxCardSpanType = MXCARDSPANTYPE_E1; break; case SDL_GTYPE_T3: val->mxCardSpanType = MXCARDSPANTYPE_T1; break; default: val->mxCardSpanType = MXCARDSPANTYPE_NONE; break; } break; } /* the driver only supports one large default synchronization group */ if (val->mxCardSyncGroup != 0) goto einval; return (0); einval: return (-EINVAL); } noinline __unlikely int mx_test_config_span(struct sp *sp, mx_config_t * arg) { struct cd *cd; struct mx_conf_span *val = (typeof(val)) (arg + 1); cd = sp->cd; if (val->mxCardIndex != cd->card) goto einval; if (val->mxSpanIndex != sp->span) goto einval; switch (val->mxSpanType) { /* affects configuration of channels */ case MXSPANTYPE_NONE: /* leave it at whatever it is already set to */ switch (sp->config.ifgtype) { case SDL_GTYPE_E1: val->mxSpanType = MXSPANTYPE_E1; break; case SDL_GTYPE_T1: val->mxSpanType = MXSPANTYPE_T1; break; case SDL_GTYPE_J1: val->mxSpanType = MXSPANTYPE_J1; break; } break; case MXSPANTYPE_T1: case MXSPANTYPE_J1: /* span cannot be different from board mode unless it is just the difference between T1 and J1: is this really true? I think that the card's internal clock and external bus clock is either E1 or T1 rate, however, there is nothing really stopping using self timing. There is even a way of using the jitter attenuator to run T1 off of an E1 clock, but simplify things for now. */ if (cd->config.ifgtype == SDL_GTYPE_E1) goto einval; break; case MXSPANTYPE_E1: /* span cannot be different from board mode unless it is just the difference between T1 and J1: is this really true? I think that the card's internal clock and external bus clock is either E1 or T1 rate, however, there is nothing really stopping using self timing. There is even a way of using the jitter attenuator to run T1 off of an E1 clock, but simplify things for now. */ if (cd->config.ifgtype != SDL_GTYPE_E1) goto einval; break; default: case MXSPANTYPE_E2: case MXSPANTYPE_E3: case MXSPANTYPE_T3: goto einval; } if (val->mxSpanCrc == MXSPANCRC_NONE) { switch (sp->config.ifgcrc) { case SDL_GCRC_CRC4: val->mxSpanCrc = MXSPANCRC_CRC4; break; case SDL_GCRC_CRC5: val->mxSpanCrc = MXSPANCRC_CRC5; break; case SDL_GCRC_CRC6: val->mxSpanCrc = MXSPANCRC_CRC6; break; case SDL_GCRC_CRC6J: val->mxSpanCrc = MXSPANCRC_CRC6J; break; } } if (val->mxSpanCoding == MXSPANCODING_NONE) { switch (sp->config.ifcoding) { case SDL_CODING_AMI: val->mxSpanCoding = MXSPANCODING_AMI; break; case SDL_CODING_B6ZS: val->mxSpanCoding = MXSPANCODING_B6ZS; break; case SDL_CODING_B8ZS: val->mxSpanCoding = MXSPANCODING_B8ZS; break; case SDL_CODING_HDB3: val->mxSpanCoding = MXSPANCODING_HDB3; break; } } if (val->mxSpanFraming == MXSPANFRAMING_NONE) { switch (sp->config.ifframing) { case SDL_FRAMING_CCS: val->mxSpanFraming = MXSPANFRAMING_CCS; break; case SDL_FRAMING_CAS: val->mxSpanFraming = MXSPANFRAMING_CAS; break; case SDL_FRAMING_SF: /* SDL_FRAMING_D4 is the same */ val->mxSpanFraming = MXSPANFRAMING_SF; break; case SDL_FRAMING_ESF: val->mxSpanFraming = MXSPANFRAMING_ESF; break; } } /* the setting of CRC must be consistent with mode and framing */ switch (val->mxSpanCrc) { case MXSPANCRC_NONE: break; case MXSPANCRC_CRC4: /* E1 CAS */ if (val->mxSpanType != MXSPANTYPE_E1) goto einval; if (val->mxSpanFraming != MXSPANFRAMING_CAS) goto einval; break; case MXSPANCRC_CRC5: /* E1 CCS */ if (val->mxSpanType != MXSPANTYPE_E1) goto einval; if (val->mxSpanFraming != MXSPANFRAMING_CCS) goto einval; break; case MXSPANCRC_CRC6: /* T1 */ if (val->mxSpanType != MXSPANTYPE_T1) goto einval; break; case MXSPANCRC_CRC6J: /* J1 */ if (val->mxSpanType != MXSPANTYPE_J1) goto einval; break; default: goto einval; } switch (val->mxSpanCoding) { case MXSPANCODING_NONE: break; case MXSPANCODING_AMI: /* ok for all modes and framing */ break; case MXSPANCODING_B6ZS: case MXSPANCODING_B8ZS: if (val->mxSpanType == MXSPANTYPE_E1) goto einval; break; case MXSPANCODING_HDB3: if (val->mxSpanType != MXSPANTYPE_E1) goto einval; break; case MXSPANCODING_JBZS: case MXSPANCODING_ZBTSI: /* not supported by driver */ goto einval; default: goto einval; } switch (val->mxSpanFraming) { case MXSPANFRAMING_NONE: break; case MXSPANFRAMING_CCS: if (val->mxSpanType != MXSPANTYPE_E1) goto einval; if (val->mxSpanCrc != MXSPANCRC_CRC5) goto einval; break; case MXSPANFRAMING_CAS: if (val->mxSpanType != MXSPANTYPE_E1) goto einval; if (val->mxSpanCrc != MXSPANCRC_CRC4) goto einval; break; case MXSPANFRAMING_SF: if (val->mxSpanType != MXSPANTYPE_T1) goto einval; if (val->mxSpanCrc != MXSPANCRC_CRC6) goto einval; break; case MXSPANFRAMING_D4: if (val->mxSpanType != MXSPANTYPE_T1) goto einval; if (val->mxSpanCrc != MXSPANCRC_CRC6) goto einval; break; case MXSPANFRAMING_ESF: if (val->mxSpanType != MXSPANTYPE_T1 && val->mxSpanType != MXSPANTYPE_J1) goto einval; if (val->mxSpanCrc != MXSPANCRC_CRC6 && val->mxSpanCrc != MXSPANCRC_CRC6J) goto einval; break; default: goto einval; } switch (val->mxSpanDataLink) { case MXSPANDATALINK_ANSIT1403: if (val->mxSpanType != MXSPANTYPE_T1 && val->mxSpanType != MXSPANTYPE_J1) goto einval; break; case MXSPANDATALINK_ATT54016: if (val->mxSpanType != MXSPANTYPE_T1) goto einval; break; case MXSPANDATALINK_OTHER: break; default: goto einval; } if (val->mxSpanPriority != 0) { if (1 > val->mxSpanPriority || val->mxSpanPriority > 4) goto einval; } /* this driver does not support primary backup */ if (val->mxSpanPrimary != 0) goto einval; return (0); einval: return (-EINVAL); } noinline __unlikely int mx_test_config_chan(struct sp *sp, struct ch *ch, mx_config_t * arg) { struct cd *cd; struct mx_conf_chan *val = (typeof(val)) (arg + 1); uint chan; cd = sp->cd; chan = (arg->id >> 0) & 0xff; if (val->mxCardIndex != cd->card) goto einval; if (val->mxSpanIndex != sp->span) goto einval; switch (sp->config.ifgtype) { default: case SDL_GTYPE_E1: if (1 > chan || chan > 31) goto einval; break; case SDL_GTYPE_T1: case SDL_GTYPE_J1: if (1 > chan || chan > 24) goto einval; break; } return (0); einval: return (-EINVAL); } static noinline __unlikely int mx_commit_config_dflt(mx_config_t * arg) { /* not configuration to commit */ return (0); } static noinline __unlikely int mx_commit_config_sync(struct sg *sg, mx_config_t * arg) { return (0); } static noinline __unlikely int mx_commit_config_card(struct cd *cd, mx_config_t * arg) { struct sp *sp; struct ch *ch; struct mx_conf_card *val = (typeof(val)) (arg + 1); uint span, chan; uint card_reconfig = 0, span_reconfig = 0, chan_reconfig = 0; switch (val->mxCardSpanType) { case MXCARDSPANTYPE_NONE: break; case MXCARDSPANTYPE_E1: if (cd->config.ifgtype == SDL_GTYPE_E1) break; card_reconfig |= (1 << cd->card); cd->config.ifgtype = SDL_GTYPE_E1; for (span = 0; span < cd->ports; span++) { if ((sp = cd->spans[span]) == NULL) continue; if (sp->config.ifgtype == SDL_GTYPE_E1) continue; span_reconfig |= (1 << sp->span); sp->config.ifgtype = SDL_GTYPE_E1; sp->config.ifgcrc = SDL_GCRC_CRC4; sp->config.ifcoding = SDL_CODING_HDB3; sp->config.ifframing = SDL_FRAMING_CCS; for (chan = 1; chan < 32; chan++) { if (!(ch = sp->chans[chan])) continue; chan_reconfig |= (1 << (chan - 1)); ch->sdl.config.ifgtype = SDL_GTYPE_E1; ch->sdl.config.ifgcrc = SDL_GCRC_CRC4; ch->sdl.config.ifcoding = SDL_CODING_HDB3; ch->sdl.config.ifframing = SDL_FRAMING_CCS; switch (ch->sdl.config.iftype) { case SDL_TYPE_T1: case SDL_TYPE_J1: ch->sdl.config.iftype = SDL_TYPE_E1; } } } break; case MXCARDSPANTYPE_T1: if (cd->config.ifgtype == SDL_GTYPE_T1) break; card_reconfig |= (1 << cd->card); cd->config.ifgtype = SDL_GTYPE_T1; for (span = 0; span < cd->ports; span++) { if ((sp = cd->spans[span]) == NULL) continue; if (sp->config.ifgtype == SDL_GTYPE_T1) continue; span_reconfig |= (1 << sp->span); switch (sp->config.ifgtype) { case SDL_GTYPE_J1: sp->config.ifgtype = SDL_GTYPE_T1; sp->config.ifgcrc = SDL_GCRC_CRC6; for (chan = 1; chan <= 24; chan++) { if (!(ch = sp->chans[chan])) continue; chan_reconfig |= (1 << (chan - 1)); ch->sdl.config.ifgtype = SDL_GTYPE_T1; ch->sdl.config.ifgcrc = SDL_GCRC_CRC6; switch (ch->sdl.config.iftype) { case SDL_TYPE_J1: ch->sdl.config.iftype = SDL_TYPE_T1; } } break; case SDL_GTYPE_E1: sp->config.ifgtype = SDL_GTYPE_T1; sp->config.ifgcrc = SDL_GCRC_CRC6; sp->config.ifcoding = SDL_CODING_B8ZS; sp->config.ifframing = SDL_FRAMING_ESF; for (chan = 1; chan <= 24; chan++) { if ((ch = sp->chans[chan]) == NULL) continue; chan_reconfig |= (1 << (chan - 1)); ch->sdl.config.ifgtype = SDL_GTYPE_T1; ch->sdl.config.ifgcrc = SDL_GCRC_CRC6; ch->sdl.config.ifcoding = SDL_CODING_B8ZS; ch->sdl.config.ifframing = SDL_FRAMING_ESF; switch (ch->sdl.config.iftype) { case SDL_TYPE_E1: ch->sdl.config.iftype = SDL_TYPE_T1; } } break; } } break; case MXCARDSPANTYPE_J1: if (cd->config.ifgtype == SDL_GTYPE_J1) break; card_reconfig |= (1 << cd->card); cd->config.ifgtype = SDL_GTYPE_J1; for (span = 0; span < cd->ports; span++) { if ((sp = cd->spans[span]) == NULL) continue; if (sp->config.ifgtype == SDL_GTYPE_J1) continue; span_reconfig |= (1 << sp->span); switch (sp->config.ifgtype) { case SDL_GTYPE_T1: sp->config.ifgtype = SDL_GTYPE_J1; sp->config.ifgcrc = SDL_GCRC_CRC6J; for (chan = 1; chan <= 24; chan++) { if ((ch = sp->chans[chan]) == NULL) continue; chan_reconfig |= (1 << (chan - 1)); ch->sdl.config.ifgtype = SDL_GTYPE_J1; ch->sdl.config.ifgcrc = SDL_GCRC_CRC6J; switch (ch->sdl.config.iftype) { case SDL_TYPE_T1: ch->sdl.config.iftype = SDL_TYPE_J1; } } break; case SDL_GTYPE_E1: sp->config.ifgtype = SDL_GTYPE_J1; sp->config.ifgcrc = SDL_GCRC_CRC6J; sp->config.ifcoding = SDL_CODING_B8ZS; sp->config.ifframing = SDL_FRAMING_ESF; for (chan = 1; chan <= 24; chan++) { if ((ch = sp->chans[chan]) == NULL) continue; chan_reconfig |= (1 << (chan - 1)); ch->sdl.config.ifgtype = SDL_GTYPE_J1; ch->sdl.config.ifgcrc = SDL_GCRC_CRC6J; ch->sdl.config.ifcoding = SDL_CODING_B8ZS; ch->sdl.config.ifframing = SDL_FRAMING_ESF; switch (ch->sdl.config.iftype) { case SDL_TYPE_E1: ch->sdl.config.iftype = SDL_TYPE_J1; } } break; } } break; } if (!card_reconfig || !(cd->config.ifflags & SDL_IF_UP)) return (0); xp_card_reconfig(cd, 0); for (span = 0; span < cd->ports; span++) { if ((sp = cd->spans[span]) == NULL) continue; if (!(span_reconfig & (1 << span)) || !(sp->config.ifflags & SDL_IF_UP)) continue; xp_span_reconfig(sp); switch (sp->config.ifgtype) { case SDL_GTYPE_E1: for (chan = 1; chan <= 31; chan++) { if (!(ch = sp->chans[chan])) continue; if ((chan_reconfig & (1 << (chan - 1))) && (ch->sdl.config.ifflags & SDL_IF_UP)) { /* xp_chan_reconfig(ch); */ } } break; case SDL_GTYPE_T1: case SDL_GTYPE_J1: for (chan = 1; chan <= 24; chan++) { if (!(ch = sp->chans[chan])) continue; if ((chan_reconfig & (1 << (chan - 1))) && (ch->sdl.config.ifflags & SDL_IF_UP)) { /* xp_chan_reconfig(ch); */ } } break; } } return (0); } static noinline __unlikely int mx_commit_config_span(struct sp *sp, mx_config_t * arg) { return (0); } static noinline __unlikely int mx_commit_config_chan(struct ch *ch, mx_config_t * arg) { return (0); } noinline __unlikely int mx_iocsconfig(queue_t *q, mblk_t *mp, mblk_t *dp) { mx_config_t *arg = (typeof(arg)) dp->b_rptr; int ret; switch (arg->cmd) { case MX_CHA: break; case MX_ADD: case MX_DEL: /* cannot insert or delete entries */ return (-EOPNOTSUPP); default: return (-EINVAL); } ret = -ESRCH; switch (arg->type) { struct sg *sg; struct cd *cd; struct sp *sp; struct ch *ch; psw_t flags; case MX_OBJ_TYPE_DFLT: /* defaults */ if (arg->id != 0) break; if ((ret = mx_test_config_dflt(arg)) >= 0) ret = mx_commit_config_dflt(arg); break; case MX_OBJ_TYPE_SYNC: /* synchronization group */ /* syncrhonization groups not supported by driver */ if (!(sg = sg_find(arg->id))) break; spin_lock_irqsave(&sg->lock, flags); if ((ret = mx_test_config_sync(sg, arg)) >= 0) ret = mx_commit_config_sync(sg, arg); spin_unlock_irqrestore(&sg->lock, flags); break; case MX_OBJ_TYPE_CARD: /* card */ if (!(cd = cd_find(arg->id))) break; spin_lock_irqsave(&cd->lock, flags); if ((ret = mx_test_config_card(cd, arg)) >= 0) ret = mx_commit_config_card(cd, arg); spin_unlock_irqrestore(&cd->lock, flags); break; case MX_OBJ_TYPE_SPAN: /* span */ if (!(sp = sp_find(arg->id))) break; spin_lock_irqsave(&sp->lock, flags); if ((ret = mx_test_config_span(sp, arg)) >= 0) ret = mx_commit_config_span(sp, arg); spin_unlock_irqrestore(&sp->lock, flags); break; case MX_OBJ_TYPE_CHAN: /* channel */ if (!(sp = sp_find(arg->id))) break; if (IS_ERR((ch = ch_find(arg->id)))) break; spin_lock_bh(&ch->lock); if ((ret = mx_test_config_chan(sp, ch, arg)) >= 0) ret = mx_commit_config_chan(ch, arg); spin_unlock_bh(&ch->lock); break; case MX_OBJ_TYPE_FRAC: /* fractional */ /* fractionals not supported by driver */ break; case MX_OBJ_TYPE_XCON: /* cross connect */ /* cross-connect not supported by driver */ break; case MX_OBJ_TYPE_BERT: /* bit error rate test */ /* bert not supported by driver */ break; } return (ret); } noinline __unlikely int mx_ioctconfig(queue_t *q, mblk_t *mp, mblk_t *dp) { mx_config_t *arg = (typeof(arg)) dp->b_rptr; int ret; arg->cmd = MX_TST; ret = -ESRCH; switch (arg->type) { struct sg *sg; struct cd *cd; struct sp *sp; struct ch *ch; psw_t flags; case MX_OBJ_TYPE_DFLT: /* defaults */ if (arg->id != 0) break; ret = mx_test_config_dflt(arg); break; case MX_OBJ_TYPE_SYNC: /* synchronization group */ /* syncrhonization groups not supported by driver */ if (!(sg = sg_find(arg->id))) break; spin_lock_irqsave(&sg->lock, flags); ret = mx_test_config_sync(sg, arg); spin_unlock_irqrestore(&sg->lock, flags); break; case MX_OBJ_TYPE_CARD: /* card */ if (!(cd = cd_find(arg->id))) break; spin_lock_irqsave(&cd->lock, flags); ret = mx_test_config_card(cd, arg); spin_unlock_irqrestore(&cd->lock, flags); break; case MX_OBJ_TYPE_SPAN: /* span */ if (!(sp = sp_find(arg->id))) break; spin_lock_irqsave(&sp->lock, flags); ret = mx_test_config_span(sp, arg); spin_unlock_irqrestore(&sp->lock, flags); break; case MX_OBJ_TYPE_CHAN: /* channel */ if (!(sp = sp_find(arg->id))) break; if (IS_ERR((ch = ch_find(arg->id)))) break; spin_lock_bh(&ch->lock); ret = mx_test_config_chan(sp, ch, arg); spin_unlock_bh(&ch->lock); break; case MX_OBJ_TYPE_FRAC: /* fractional */ /* fractionals not supported by driver */ break; case MX_OBJ_TYPE_XCON: /* cross connect */ /* cross-connect not supported by driver */ break; case MX_OBJ_TYPE_BERT: /* bit error rate test */ /* bert not supported by driver */ break; } return (ret); } noinline __unlikely int mx_ioccconfig(queue_t *q, mblk_t *mp, mblk_t *dp) { mx_config_t *arg = (typeof(arg)) dp->b_rptr; int ret; arg->cmd = MX_COM; ret = -ESRCH; switch (arg->type) { struct sg *sg; struct cd *cd; struct sp *sp; struct ch *ch; psw_t flags; case MX_OBJ_TYPE_DFLT: /* defaults */ if (arg->id != 0) break; ret = mx_commit_config_dflt(arg); break; case MX_OBJ_TYPE_SYNC: /* synchronization group */ /* syncrhonization groups not supported by driver */ if (!(sg = sg_find(arg->id))) break; spin_lock_irqsave(&sg->lock, flags); ret = mx_commit_config_sync(sg, arg); spin_unlock_irqrestore(&sg->lock, flags); break; case MX_OBJ_TYPE_CARD: /* card */ if (!(cd = cd_find(arg->id))) break; spin_lock_irqsave(&cd->lock, flags); ret = mx_commit_config_card(cd, arg); spin_unlock_irqrestore(&cd->lock, flags); break; case MX_OBJ_TYPE_SPAN: /* span */ if (!(sp = sp_find(arg->id))) break; spin_lock_irqsave(&sp->lock, flags); ret = mx_commit_config_span(sp, arg); spin_unlock_irqrestore(&sp->lock, flags); break; case MX_OBJ_TYPE_CHAN: /* channel */ if (!(sp = sp_find(arg->id))) break; if (IS_ERR((ch = ch_find(arg->id)))) break; spin_lock_bh(&ch->lock); ret = mx_commit_config_chan(ch, arg); spin_unlock_bh(&ch->lock); break; case MX_OBJ_TYPE_FRAC: /* fractional */ /* fractionals not supported by driver */ break; case MX_OBJ_TYPE_XCON: /* cross connect */ /* cross-connect not supported by driver */ break; case MX_OBJ_TYPE_BERT: /* bit error rate test */ /* bert not supported by driver */ break; } return (ret); } STATIC __unlikely int mx_statem_size(mx_statem_t * arg) { int size = sizeof(*arg); switch (arg->type) { case MX_OBJ_TYPE_DFLT: size += sizeof(arg->statem->dflt); break; case MX_OBJ_TYPE_SYNC: size += sizeof(arg->statem->sync); break; case MX_OBJ_TYPE_CARD: size += sizeof(arg->statem->card); break; case MX_OBJ_TYPE_SPAN: size += sizeof(arg->statem->span); break; case MX_OBJ_TYPE_CHAN: size += sizeof(arg->statem->chan); break; case MX_OBJ_TYPE_FRAC: size += sizeof(arg->statem->frac); break; case MX_OBJ_TYPE_XCON: size += sizeof(arg->statem->xcon); break; case MX_OBJ_TYPE_BERT: size += sizeof(arg->statem->bert); break; default: return (-EINVAL); } return (size); } noinline __unlikely int mx_iocgstatem_dflt(mx_statem_t * arg) { /* no state information for default */ return (0); } noinline __unlikely int mx_iocgstatem_sync(struct sg *sg, mx_statem_t * arg) { return (-EOPNOTSUPP); } noinline __unlikely int mx_iocgstatem_card(struct cd *cd, mx_statem_t * arg) { /* no state information for cards */ return (0); } noinline __unlikely int mx_iocgstatem_span(struct sp *sp, mx_statem_t * arg) { /* no state information for spans */ return (0); } noinline __unlikely int mx_iocgstatem_chan(struct sp *sp, struct ch *ch, mx_statem_t * arg) { uint chan; chan = arg->id & 0xff; switch (sp->config.ifgtype) { case SDL_GTYPE_E1: if (1 > chan || chan > 31) goto esrch; break; case SDL_GTYPE_T1: case SDL_GTYPE_J1: if (1 > chan || chan > 24) goto esrch; break; default: goto esrch; } /* no state information for channels */ return (0); esrch: return (-ESRCH); } noinline __unlikely int mx_iocgstatem(queue_t *q, mblk_t *mp, mblk_t *dp) { mx_statem_t *hdr, *arg = (typeof(arg)) dp->b_rptr; int ret; mblk_t *db; if ((ret = mx_statem_size(arg)) < 0) return (ret); if (!(db = mi_copyout_alloc(q, mp, 0, ret, 0))) return (-ENOSR); *(hdr = (typeof(hdr)) db->b_rptr) = *arg; ret = -ESRCH; switch (arg->type) { struct cd *cd; struct sp *sp; struct ch *ch; struct sg *sg; psw_t flags; case MX_OBJ_TYPE_DFLT: /* defaults */ if (arg->id != 0) break; ret = mx_iocgstatem_dflt(hdr); break; case MX_OBJ_TYPE_SYNC: /* synchronization group */ if (!(sg = sg_find(arg->id))) break; spin_lock_irqsave(&sg->lock, flags); ret = mx_iocgstatem_sync(sg, hdr); spin_unlock_irqrestore(&sg->lock, flags); break; case MX_OBJ_TYPE_CARD: /* card */ if (!(cd = cd_find(arg->id))) break; spin_lock_irqsave(&cd->lock, flags); ret = mx_iocgstatem_card(cd, hdr); spin_unlock_irqrestore(&cd->lock, flags); break; case MX_OBJ_TYPE_SPAN: /* span */ if (!(sp = sp_find(arg->id))) break; spin_lock_irqsave(&sp->lock, flags); ret = mx_iocgstatem_span(sp, hdr); spin_unlock_irqrestore(&sp->lock, flags); break; case MX_OBJ_TYPE_CHAN: /* channel */ if (!(sp = sp_find(arg->id))) break; if (IS_ERR((ch = ch_find(arg->id)))) break; spin_lock_bh(&ch->lock); ret = mx_iocgstatem_chan(sp, ch, hdr); spin_unlock_bh(&ch->lock); break; case MX_OBJ_TYPE_FRAC: /* fractional */ break; case MX_OBJ_TYPE_XCON: /* cross connect */ break; case MX_OBJ_TYPE_BERT: /* bit error rate test */ break; default: ret = -EINVAL; break; } if (ret >= 0) mi_copyout(q, mp); return (ret); } noinline __unlikely int mx_ioccmreset(queue_t *q, mblk_t *mp, mblk_t *dp) { mx_statem_t *arg = (typeof(arg)) dp->b_rptr; switch (arg->type) { case MX_OBJ_TYPE_DFLT: /* defaults */ case MX_OBJ_TYPE_SYNC: /* synchronization group */ case MX_OBJ_TYPE_CARD: /* card */ case MX_OBJ_TYPE_SPAN: /* span */ case MX_OBJ_TYPE_CHAN: /* channel */ case MX_OBJ_TYPE_FRAC: /* fractional */ case MX_OBJ_TYPE_XCON: /* cross connect */ case MX_OBJ_TYPE_BERT: /* bit error rate test */ return (0); default: goto einval; } einval: return (-EINVAL); } STATIC __unlikely int mx_status_size(mx_status_t * arg) { int size = sizeof(*arg); switch (arg->type) { case MX_OBJ_TYPE_DFLT: size += sizeof(arg->status->dflt); break; case MX_OBJ_TYPE_SYNC: size += sizeof(arg->status->sync); break; case MX_OBJ_TYPE_CARD: size += sizeof(arg->status->card); break; case MX_OBJ_TYPE_SPAN: size += sizeof(arg->status->span); break; case MX_OBJ_TYPE_CHAN: size += sizeof(arg->status->chan); break; case MX_OBJ_TYPE_FRAC: size += sizeof(arg->status->frac); break; case MX_OBJ_TYPE_XCON: size += sizeof(arg->status->xcon); break; case MX_OBJ_TYPE_BERT: size += sizeof(arg->status->bert); break; default: return (-EINVAL); } return (size); } noinline __unlikely int mx_iocgstatus_dflt(mx_status_t * arg) { /* there are no defined status fields for the default object */ return (0); } noinline __unlikely int mx_iocgstatus_sync(struct sg *sg, mx_status_t * arg) { /* there are no defined status fields for the synchronization object */ return (0); } /** mx_iocgstatus_card: - get the card MX status * @cd: card structure pointer * @arg: place to put status */ noinline __unlikely int mx_iocgstatus_card(struct cd *cd, mx_status_t * arg) { struct mx_status_card *val = (typeof(val)) (arg + 1); /* mxCardAdministrativeState */ if (cd->config.ifflags & SDL_IF_UP) val->mxCardAdministrativeState = X721_ADMINISTRATIVESTATE_UNLOCKED; else val->mxCardAdministrativeState = X721_ADMINISTRATIVESTATE_LOCKED; /* mxCardOperationalState */ /* mxCardUsageState */ if (!(cd->config.ifflags & SDL_IF_UP)) { val->mxCardOperationalState = X721_OPERATIONALSTATE_DISABLED; val->mxCardUsageState = X721_USAGESTATE_IDLE; val->mxCardAvailabilityStatus = 0; val->mxCardAlarmStatus = 0; } else { uint span, used = 0, busy = 1, depend = 0, alarms = 0; val->mxCardOperationalState = X721_OPERATIONALSTATE_ENABLED; for (span = 0; span < cd->ports; span++) { struct sp *sp; if ((sp = cd->spans[span]) && (sp->config.ifflags & SDL_IF_UP)) { uint chan; struct ch *ch; if (sp->config.ifgtype == SDL_GTYPE_E1) { for (chan = 1; chan <= 31; chan++) if ((ch = sp->chans[chan])) used = 1; else busy = 0; } else { for (chan = 1; chan <= 24; chan++) if ((ch = sp->chans[chan])) used = 1; else busy = 0; } alarms |= sp->config.ifalarms; } else { depend = 1; } } if (busy) val->mxCardUsageState = X721_USAGESTATE_BUSY; else if (used) val->mxCardUsageState = X721_USAGESTATE_ACTIVE; else val->mxCardUsageState = X721_USAGESTATE_IDLE; if (depend) val->mxCardAvailabilityStatus = (1 << X721_AVAILABILITYSTATUS_DEPENDENCY); else val->mxCardAvailabilityStatus = 0; val->mxCardAlarmStatus = 0; if (alarms & SDL_ALARM_YEL) { val->mxCardAlarmStatus |= (1 << X721_ALARMSTATUS_MINOR); val->mxCardAvailabilityStatus |= (1 << X721_AVAILABILITYSTATUS_DEGRADED); } if (alarms & SDL_ALARM_RED) { val->mxCardAlarmStatus |= (1 << X721_ALARMSTATUS_MAJOR); val->mxCardAvailabilityStatus |= (1 << X721_AVAILABILITYSTATUS_FAILED); } if (alarms & SDL_ALARM_BLU) { val->mxCardAlarmStatus |= (1 << X721_ALARMSTATUS_ALARMOUTSTANDING); val->mxCardAvailabilityStatus |= (1 << X721_AVAILABILITYSTATUS_DEPENDENCY); } } /* mxCardAlarmStatus */ /* mxCardProceduralStatus */ val->mxCardProceduralStatus = 0; if (!(cd->config.ifflags & SDL_IF_UP)) val->mxCardProceduralStatus |= (1 << X721_PROCEDURALSTATUS_INITIALIZATIONREQUIRED); if (!(cd->config.ifflags & (SDL_IF_TX_RUNNING | SDL_IF_RX_RUNNING))) val->mxCardProceduralStatus |= (1 << X721_PROCEDURALSTATUS_NOTINITIALIZED); /* mxCardAvailabilityStatus */ /* mxCardControlStatus */ val->mxCardControlStatus = 0; if (!(cd->config.ifflags & (SDL_IF_TX_RUNNING | SDL_IF_RX_RUNNING)) && (val->mxCardUsageState != X721_USAGESTATE_IDLE)) val->mxCardControlStatus |= (1 << X721_CONTROLSTATUS_SUSPENDED); /* mxCardUnknownStatus */ val->mxCardUnknownStatus = X721_UNKNOWNSTATUS_FALSE; /* mxCardStandbyStatus */ val->mxCardStandbyStatus = X721_STANDBYSTATUS_PROVIDINGSERVICE; return (0); } /** mx_iocgstatus_span: - get the status of a span * @sp: span structure pointer * @arg: place to put status */ noinline __unlikely int mx_iocgstatus_span(struct sp *sp, mx_status_t * arg) { struct mx_status_span *val = (typeof(val)) (arg + 1); /* mxSpanAdministrativeState */ if (sp->config.ifflags & (SDL_IF_TX_RUNNING | SDL_IF_RX_RUNNING)) val->mxSpanAdministrativeState = X721_ADMINISTRATIVESTATE_UNLOCKED; else val->mxSpanAdministrativeState = X721_ADMINISTRATIVESTATE_LOCKED; /* mxSpanOperationalState */ if (!(sp->config.ifflags & SDL_IF_UP)) { val->mxSpanOperationalState = X721_OPERATIONALSTATE_DISABLED; val->mxSpanUsageState = X721_USAGESTATE_IDLE; val->mxSpanAvailabilityStatus = 0; val->mxSpanAlarmStatus = 0; val->mxSpanAlarms = 0; } else { uint used = 0, busy = 1, chan; struct ch *ch; val->mxSpanOperationalState = X721_OPERATIONALSTATE_ENABLED; if (sp->config.ifgtype == SDL_GTYPE_E1) { for (chan = 1; chan <= 31; chan++) if ((ch = sp->chans[chan])) used = 1; else busy = 0; } else { for (chan = 1; chan <= 24; chan++) if ((ch = sp->chans[chan])) used = 1; else busy = 0; } if (busy) val->mxSpanUsageState = X721_USAGESTATE_BUSY; else if (used) val->mxSpanUsageState = X721_USAGESTATE_ACTIVE; else val->mxSpanUsageState = X721_USAGESTATE_IDLE; if (!(sp->cd->config.ifflags & SDL_IF_UP) || !(sp->cd->config.ifflags & (SDL_IF_TX_RUNNING | SDL_IF_RX_RUNNING))) val->mxSpanAvailabilityStatus |= (1 << X721_AVAILABILITYSTATUS_DEPENDENCY); else val->mxSpanAvailabilityStatus = 0; /* mxSpanAlarms */ val->mxSpanAlarms = 0; if (sp->config.ifalarms & SDL_ALARM_YEL) { val->mxSpanAlarms |= (1 << MXSPANALARMS_YELLOW); val->mxSpanAlarmStatus |= (1 << X721_ALARMSTATUS_MINOR); val->mxSpanAvailabilityStatus |= (1 << X721_AVAILABILITYSTATUS_DEGRADED); } if (sp->config.ifalarms & SDL_ALARM_RED) { val->mxSpanAlarms |= (1 << MXSPANALARMS_RED); val->mxSpanAlarmStatus |= (1 << X721_ALARMSTATUS_MAJOR); val->mxSpanAvailabilityStatus |= (1 << X721_AVAILABILITYSTATUS_FAILED); } if (sp->config.ifalarms & SDL_ALARM_BLU) { val->mxSpanAlarms |= (1 << MXSPANALARMS_BLUE); val->mxSpanAlarmStatus |= (1 << X721_ALARMSTATUS_ALARMOUTSTANDING); val->mxSpanAvailabilityStatus |= (1 << X721_AVAILABILITYSTATUS_DEPENDENCY); } if (sp->config.ifalarms & SDL_ALARM_REC) val->mxSpanAlarms |= (1 << MXSPANALARMS_RECOVERY); if (sp->config.ifalarms & SDL_ALARM_DMF) val->mxSpanAlarms |= (1 << MXSPANALARMS_DISTMF); } /* mxSpanUsageState */ /* mxSpanAlarmStatus */ /* mxSpanProceduralStatus */ val->mxSpanProceduralStatus = 0; if (!(sp->config.ifflags & SDL_IF_UP)) val->mxSpanProceduralStatus |= (1 << X721_PROCEDURALSTATUS_INITIALIZATIONREQUIRED); if (!(sp->config.ifflags & (SDL_IF_TX_RUNNING | SDL_IF_RX_RUNNING))) val->mxSpanProceduralStatus |= (1 << X721_PROCEDURALSTATUS_NOTINITIALIZED); /* mxSpanAvailabilityStatus */ /* mxSpanControlStatus */ val->mxSpanControlStatus = 0; if (!(sp->config.ifflags & (SDL_IF_TX_RUNNING | SDL_IF_RX_RUNNING)) && (val->mxSpanUsageState != X721_USAGESTATE_IDLE)) val->mxSpanControlStatus |= (1 << X721_CONTROLSTATUS_SUSPENDED); /* mxSpanStandbyStatus */ val->mxSpanStandbyStatus = X721_STANDBYSTATUS_PROVIDINGSERVICE; /* mxSpanUnknownStatus */ val->mxSpanUnknownStatus = X721_UNKNOWNSTATUS_FALSE; /* mxSpanLoopbackStatus */ val->mxSpanLoopbackStatus = 0; /* for now */ /* mxSpanLineStatus */ val->mxSpanLineStatus = (1 << MXSPANLINESTATUS_NONE); /* for now */ /* mxSpanEvents */ val->mxSpanEvents = 0; if (sp->status.flags & (XP_STATE_RLOS)) val->mxSpanEvents |= (1 << MXSPANEVENTS_RLOS); if (sp->status.flags & (XP_STATE_FRCL)) val->mxSpanEvents |= (1 << MXSPANEVENTS_FRCL); if (sp->status.flags & (XP_STATE_RUA1)) val->mxSpanEvents |= (1 << MXSPANEVENTS_RUAL); if (sp->status.flags & (XP_STATE_RYEL)) val->mxSpanEvents |= (1 << MXSPANEVENTS_RYEL); if (sp->status.flags & (XP_STATE_RRA)) val->mxSpanEvents |= (1 << MXSPANEVENTS_RRA); if (sp->status.flags & (XP_STATE_RDMA)) val->mxSpanEvents |= (1 << MXSPANEVENTS_RDMA); #if 0 if (sp->status.flags & (XP_STATE_V52LNK)) val->mxSpanEvents |= (1 << MXSPANEVENTS_V52LNK); #endif if (sp->status.flags & (XP_STATE_LORC)) val->mxSpanEvents |= (1 << MXSPANEVENTS_LORC); if (sp->status.flags & (XP_STATE_LOTC)) val->mxSpanEvents |= (1 << MXSPANEVENTS_LOTC); if (sp->status.flags & (XP_STATE_LUP)) val->mxSpanEvents |= (1 << MXSPANEVENTS_LUP); if (sp->status.flags & (XP_STATE_LDN)) val->mxSpanEvents |= (1 << MXSPANEVENTS_LDN); if (sp->status.flags & (XP_STATE_SPARE)) val->mxSpanEvents |= (1 << MXSPANEVENTS_LSPARE); if (sp->status.flags & (XP_STATE_TOCD)) val->mxSpanEvents |= (1 << MXSPANEVENTS_TOCD); if (sp->status.flags & (XP_STATE_TSCD)) val->mxSpanEvents |= (1 << MXSPANEVENTS_TCLE); return (0); } noinline __unlikely int mx_iocgstatus_chan(struct sp *sp, struct ch *ch, mx_status_t * arg) { struct mx_status_chan *val = (typeof(val)) (arg + 1); /* mxChanAdministrativeState */ if (!ch || ch->sdl.config.ifflags & (SDL_IF_TX_RUNNING | SDL_IF_RX_RUNNING)) val->mxChanAdministrativeState = X721_ADMINISTRATIVESTATE_UNLOCKED; else val->mxChanAdministrativeState = X721_ADMINISTRATIVESTATE_LOCKED; val->mxChanAlarmStatus = 0; /* mxChanOperationalState */ if (!ch || !(ch->sdl.config.ifflags & SDL_IF_UP)) { val->mxChanOperationalState = X721_OPERATIONALSTATE_DISABLED; val->mxChanUsageState = X721_USAGESTATE_IDLE; val->mxChanAvailabilityStatus = 0; } else { val->mxChanOperationalState = X721_OPERATIONALSTATE_ENABLED; val->mxChanUsageState = X721_USAGESTATE_BUSY; if (!ch || !(ch->sp->config.ifflags & SDL_IF_UP) || !(ch->sp->config.ifflags & (SDL_IF_TX_RUNNING | SDL_IF_RX_RUNNING))) val->mxChanAvailabilityStatus = (1 << X721_AVAILABILITYSTATUS_DEPENDENCY); else val->mxChanAvailabilityStatus = 0; if (ch) { if (ch->sp->config.ifalarms & SDL_ALARM_YEL) { val->mxChanAlarmStatus |= (1 << X721_ALARMSTATUS_MINOR); val->mxChanAvailabilityStatus |= (1 << X721_AVAILABILITYSTATUS_DEGRADED); } if (ch->sp->config.ifalarms & SDL_ALARM_RED) { val->mxChanAlarmStatus |= (1 << X721_ALARMSTATUS_MAJOR); val->mxChanAvailabilityStatus |= (1 << X721_AVAILABILITYSTATUS_FAILED); } if (ch->sp->config.ifalarms & SDL_ALARM_BLU) { val->mxChanAlarmStatus |= (1 << X721_ALARMSTATUS_ALARMOUTSTANDING); val->mxChanAvailabilityStatus |= (1 << X721_AVAILABILITYSTATUS_DEPENDENCY); } } } /* mxChanUsageState */ /* mxChanAvailabilityStatus */ /* mxChanControlStatus */ val->mxChanControlStatus = 0; if (!(ch->sdl.config.ifflags & (SDL_IF_TX_RUNNING | SDL_IF_RX_RUNNING)) && (val->mxChanUsageState != X721_USAGESTATE_IDLE)) val->mxChanControlStatus |= (1 << X721_CONTROLSTATUS_SUSPENDED); /* mxChanProceduralStatus */ val->mxChanProceduralStatus = 0; if (!(ch->sdl.config.ifflags & SDL_IF_UP)) val->mxChanProceduralStatus |= (1 << X721_PROCEDURALSTATUS_INITIALIZATIONREQUIRED); if (!(ch->sdl.config.ifflags & (SDL_IF_TX_RUNNING | SDL_IF_RX_RUNNING))) val->mxChanProceduralStatus |= (1 << X721_PROCEDURALSTATUS_NOTINITIALIZED); /* mxChanAlarmStatus */ /* mxChanStandbyStatus */ val->mxChanStandbyStatus = X721_STANDBYSTATUS_PROVIDINGSERVICE; return (0); } noinline __unlikely int mx_iocgstatus(queue_t *q, mblk_t *mp, mblk_t *dp) { mx_status_t *hdr, *arg = (typeof(arg)) dp->b_rptr; int ret; mblk_t *db; if ((ret = mx_status_size(arg)) < 0) return (ret); if (!(db = mi_copyout_alloc(q, mp, 0, ret, 0))) return (-ENOSR); *(hdr = (typeof(hdr)) db->b_rptr) = *arg; ret = -ESRCH; switch (arg->type) { struct cd *cd; struct sp *sp; struct ch *ch; struct sg *sg; psw_t flags; case MX_OBJ_TYPE_DFLT: /* defaults */ if (arg->id != 0) break; ret = mx_iocgstatus_dflt(hdr); break; case MX_OBJ_TYPE_SYNC: /* synchronization group */ if (!(sg = sg_find(arg->id))) break; spin_lock_irqsave(&sg->lock, flags); ret = mx_iocgstatus_sync(sg, hdr); spin_unlock_irqrestore(&sg->lock, flags); break; case MX_OBJ_TYPE_CARD: /* card */ if (!(cd = cd_find(arg->id))) break; spin_lock_irqsave(&cd->lock, flags); ret = mx_iocgstatus_card(cd, hdr); spin_unlock_irqrestore(&cd->lock, flags); break; case MX_OBJ_TYPE_SPAN: /* span */ if (!(sp = sp_find(arg->id))) break; spin_lock_irqsave(&sp->lock, flags); ret = mx_iocgstatus_span(sp, hdr); spin_unlock_irqrestore(&sp->lock, flags); break; case MX_OBJ_TYPE_CHAN: /* channel */ if (!(sp = sp_find(arg->id))) break; if (IS_ERR((ch = ch_find(arg->id)))) break; spin_lock_bh(&ch->lock); ret = mx_iocgstatus_chan(sp, ch, hdr); spin_unlock_bh(&ch->lock); break; case MX_OBJ_TYPE_FRAC: /* fractional */ break; case MX_OBJ_TYPE_XCON: /* cross connect */ break; case MX_OBJ_TYPE_BERT: /* bit error rate test */ break; default: ret = -EINVAL; break; } mi_copyout(q, mp); return (0); } noinline __unlikely int mx_iocsstatus(queue_t *q, mblk_t *mp, mblk_t *dp) { mx_status_t *arg = (typeof(arg)) dp->b_rptr; switch (arg->type) { case MX_OBJ_TYPE_DFLT: /* defaults */ return (0); case MX_OBJ_TYPE_SYNC: /* synchronization group */ return (0); case MX_OBJ_TYPE_CARD: /* card */ /* FIXME: complete this */ return (-EOPNOTSUPP); case MX_OBJ_TYPE_SPAN: /* span */ /* FIXME: complete this */ return (-EOPNOTSUPP); case MX_OBJ_TYPE_CHAN: /* channel */ /* FIXME: complete this */ return (-EOPNOTSUPP); case MX_OBJ_TYPE_FRAC: /* fractional */ return (0); case MX_OBJ_TYPE_XCON: /* cross connect */ return (0); case MX_OBJ_TYPE_BERT: /* bit error rate test */ /* FIXME: complete this */ return (-EOPNOTSUPP); default: goto einval; } einval: return (-EINVAL); } noinline __unlikely int mx_ioccstatus(queue_t *q, mblk_t *mp, mblk_t *dp) { mx_status_t *arg = (typeof(arg)) dp->b_rptr; switch (arg->type) { case MX_OBJ_TYPE_DFLT: /* defaults */ return (0); case MX_OBJ_TYPE_SYNC: /* synchronization group */ return (0); case MX_OBJ_TYPE_CARD: /* card */ /* FIXME: complete this */ return (-EOPNOTSUPP); case MX_OBJ_TYPE_SPAN: /* span */ /* FIXME: complete this */ return (-EOPNOTSUPP); case MX_OBJ_TYPE_CHAN: /* channel */ /* FIXME: complete this */ return (-EOPNOTSUPP); case MX_OBJ_TYPE_FRAC: /* fractional */ return (0); case MX_OBJ_TYPE_XCON: /* cross connect */ return (0); case MX_OBJ_TYPE_BERT: /* bit error rate test */ /* FIXME: complete this */ return (-EOPNOTSUPP); default: goto einval; } einval: return (-EINVAL); } STATIC __unlikely int mx_stats_size(mx_stats_t * arg) { int size = sizeof(*arg); switch (arg->type) { case MX_OBJ_TYPE_DFLT: size += sizeof(arg->stats->dflt); break; case MX_OBJ_TYPE_SYNC: size += sizeof(arg->stats->sync); break; case MX_OBJ_TYPE_CARD: size += sizeof(arg->stats->card); break; case MX_OBJ_TYPE_SPAN: size += sizeof(arg->stats->span); break; case MX_OBJ_TYPE_CHAN: size += sizeof(arg->stats->chan); break; case MX_OBJ_TYPE_FRAC: size += sizeof(arg->stats->frac); break; case MX_OBJ_TYPE_XCON: size += sizeof(arg->stats->xcon); break; case MX_OBJ_TYPE_BERT: size += sizeof(arg->stats->bert); break; default: return (-EINVAL); } return (size); } noinline __unlikely int mx_iocgstatsp(queue_t *q, mblk_t *mp, mblk_t *dp) { mx_stats_t *arg = (typeof(arg)) dp->b_rptr; switch (arg->type) { case MX_OBJ_TYPE_DFLT: /* defaults */ return (0); case MX_OBJ_TYPE_SYNC: /* synchronization group */ return (0); case MX_OBJ_TYPE_CARD: /* card */ /* FIXME: complete this */ return (-EOPNOTSUPP); case MX_OBJ_TYPE_SPAN: /* span */ /* FIXME: complete this */ return (-EOPNOTSUPP); case MX_OBJ_TYPE_CHAN: /* channel */ return (0); case MX_OBJ_TYPE_FRAC: /* fractional */ return (0); case MX_OBJ_TYPE_XCON: /* cross connect */ return (0); case MX_OBJ_TYPE_BERT: /* bit error rate test */ /* FIXME: complete this */ return (-EOPNOTSUPP); default: goto einval; } einval: return (-EINVAL); } noinline __unlikely int mx_iocsstatsp(queue_t *q, mblk_t *mp, mblk_t *dp) { mx_stats_t *arg = (typeof(arg)) dp->b_rptr; switch (arg->type) { case MX_OBJ_TYPE_DFLT: /* defaults */ return (0); case MX_OBJ_TYPE_SYNC: /* synchronization group */ return (0); case MX_OBJ_TYPE_CARD: /* card */ /* FIXME: complete this */ return (-EOPNOTSUPP); case MX_OBJ_TYPE_SPAN: /* span */ /* FIXME: complete this */ return (-EOPNOTSUPP); case MX_OBJ_TYPE_CHAN: /* channel */ return (0); case MX_OBJ_TYPE_FRAC: /* fractional */ return (0); case MX_OBJ_TYPE_XCON: /* cross connect */ return (0); case MX_OBJ_TYPE_BERT: /* bit error rate test */ /* FIXME: complete this */ return (-EOPNOTSUPP); default: goto einval; } einval: return (-EINVAL); } noinline __unlikely int mx_iocgstats_dflt(mx_stats_t * arg) { struct mx_stats_dflt *val = (typeof(val)) (arg + 1); /* FIXME: get these */ bzero(val, sizeof(*val)); return (0); } noinline __unlikely int mx_iocgstats_sync(struct sg *sg, mx_stats_t * arg) { struct mx_stats_sync *val = (typeof(val)) (arg + 1); /* FIXME: get these */ bzero(val, sizeof(*val)); return (0); } noinline __unlikely int mx_iocgstats_card(struct cd *cd, mx_stats_t * arg) { struct mx_stats_card *val = (typeof(val)) (arg + 1); /* FIXME: get these */ bzero(val, sizeof(*val)); return (0); } noinline __unlikely int mx_iocgstats_span(struct sp *sp, mx_stats_t * arg) { struct mx_stats_span *val = (typeof(val)) (arg + 1); uint interval, valid, invalid; struct st *st, total; /* FIXME: get these */ bzero(val, sizeof(*val)); for (valid = 0, invalid = 0, interval = 0; interval < 96; interval++) { st = &sp->hist[interval]; if (st->ValidData) valid++; else invalid++; } val->mxValidIntervals = valid; val->mxInvalidIntervals = invalid; if (arg->interval == 0) st = &sp->stats[2]; else if (arg->interval > 96 && arg->interval != 0xffffffff) return (-EINVAL); else if (sp->hist == NULL) return (-EINVAL); else if (arg->interval == 0xffffffff) { bzero(&total, sizeof(total)); for (interval = 0; interval < 96; interval++) { st = &sp->hist[interval]; if (st->ValidData) { total.ESs += st->ESs; total.SESs += st->SESs; total.UASs += st->UASs; total.CSSs += st->CSSs; total.PCVs += st->PCVs; total.LESs += st->LESs; total.BESs += st->BESs; total.DMs += st->DMs; total.LCVs += st->LCVs; total.FASEs += st->FASEs; total.FABEs += st->FABEs; total.FEBEs += st->FEBEs; } } if (valid) total.ValidData = 2; /* true(2) */ else total.ValidData = 1; /* false(1) */ st = &total; } else st = &sp->hist[(sp->curr + (arg->interval - 1)) % 96]; val->mxNearEndESs = st->ESs; val->mxNearEndSESs = st->SESs; val->mxNearEndUASs = st->UASs; val->mxNearEndCSSs = st->CSSs; val->mxNearEndPCVs = st->PCVs; val->mxNearEndLESs = st->LESs; val->mxNearEndBESs = st->BESs; val->mxNearEndDMs = st->DMs; val->mxNearEndLCVs = st->LCVs; val->mxNearEndFASEs = st->FASEs; val->mxNearEndFABEs = st->FABEs; val->mxNearEndFEBEs = st->FEBEs; val->mxNearEndValidData = st->ValidData; /* FIXME: don't support far-end collection yet... */ val->mxFarEndESs = 0; val->mxFarEndSESs = 0; val->mxFarEndUASs = 0; val->mxFarEndCSSs = 0; val->mxFarEndPCVs = 0; val->mxFarEndLESs = 0; val->mxFarEndBESs = 0; val->mxFarEndDMs = 0; val->mxFarEndValidData = 1; /* false(1) */ return (0); } noinline __unlikely int mx_iocgstats_chan(struct sp *sp, struct ch *ch, mx_stats_t * arg) { struct mx_stats_chan *val = (typeof(val)) (arg + 1); /* FIXME: get these */ bzero(val, sizeof(*val)); return (0); } noinline __unlikely int mx_iocgstats(queue_t *q, mblk_t *mp, mblk_t *dp) { mx_stats_t *hdr, *arg = (typeof(arg)) dp->b_rptr; int ret; mblk_t *db; if ((ret = mx_stats_size(arg)) < 0) return (ret); if (!(db = mi_copyout_alloc(q, mp, 0, ret, 0))) return (-ENOSR); *(hdr = (typeof(hdr)) db->b_rptr) = *arg; ret = -ESRCH; switch (arg->type) { struct cd *cd; struct sp *sp; struct ch *ch; struct sg *sg; psw_t flags; case MX_OBJ_TYPE_DFLT: /* defaults */ if (arg->id != 0) break; ret = mx_iocgstats_dflt(hdr); break; case MX_OBJ_TYPE_SYNC: /* synchronization group */ if (!(sg = sg_find(arg->id))) break; spin_lock_irqsave(&sg->lock, flags); ret = mx_iocgstats_sync(sg, hdr); spin_unlock_irqrestore(&sg->lock, flags); break; case MX_OBJ_TYPE_CARD: /* card */ if (!(cd = cd_find(arg->id))) break; spin_lock_irqsave(&cd->lock, flags); ret = mx_iocgstats_card(cd, hdr); spin_unlock_irqrestore(&cd->lock, flags); break; case MX_OBJ_TYPE_SPAN: /* span */ if (!(sp = sp_find(arg->id))) break; spin_lock_irqsave(&sp->lock, flags); ret = mx_iocgstats_span(sp, hdr); spin_unlock_irqrestore(&sp->lock, flags); break; case MX_OBJ_TYPE_CHAN: /* channel */ if (!(sp = sp_find(arg->id))) break; if (IS_ERR((ch = ch_find(arg->id)))) break; spin_lock_bh(&ch->lock); ret = mx_iocgstats_chan(sp, ch, hdr); spin_unlock_bh(&ch->lock); break; case MX_OBJ_TYPE_FRAC: /* fractional */ break; case MX_OBJ_TYPE_XCON: /* cross connect */ break; case MX_OBJ_TYPE_BERT: /* bit error rate test */ break; default: ret = -EINVAL; break; } if (ret >= 0) mi_copyout(q, mp); return (ret); } noinline __unlikely int mx_ioccstats(queue_t *q, mblk_t *mp, mblk_t *dp) { mx_stats_t *arg = (typeof(arg)) dp->b_rptr; switch (arg->type) { case MX_OBJ_TYPE_DFLT: /* defaults */ return (0); case MX_OBJ_TYPE_SYNC: /* synchronization group */ return (0); case MX_OBJ_TYPE_CARD: /* card */ /* FIXME: complete this */ return (-EOPNOTSUPP); case MX_OBJ_TYPE_SPAN: /* span */ /* FIXME: complete this */ return (-EOPNOTSUPP); case MX_OBJ_TYPE_CHAN: /* channel */ return (0); case MX_OBJ_TYPE_FRAC: /* fractional */ return (0); case MX_OBJ_TYPE_XCON: /* cross connect */ return (0); case MX_OBJ_TYPE_BERT: /* bit error rate test */ /* FIXME: complete this */ return (-EOPNOTSUPP); default: goto einval; } einval: return (-EINVAL); } STATIC __unlikely int mx_notify_size(mx_notify_t * arg) { int size = sizeof(*arg); switch (arg->type) { case MX_OBJ_TYPE_DFLT: size += sizeof(arg->events->dflt); break; case MX_OBJ_TYPE_SYNC: size += sizeof(arg->events->sync); break; case MX_OBJ_TYPE_CARD: size += sizeof(arg->events->card); break; case MX_OBJ_TYPE_SPAN: size += sizeof(arg->events->span); break; case MX_OBJ_TYPE_CHAN: size += sizeof(arg->events->chan); break; case MX_OBJ_TYPE_FRAC: size += sizeof(arg->events->frac); break; case MX_OBJ_TYPE_XCON: size += sizeof(arg->events->xcon); break; case MX_OBJ_TYPE_BERT: size += sizeof(arg->events->bert); break; default: return (-EINVAL); } return (size); } noinline __unlikely int mx_iocgnotify_dflt(mx_notify_t * arg) { /* FIXME: complete this */ return (0); } noinline __unlikely int mx_iocgnotify_sync(struct sg *sg, mx_notify_t * arg) { /* FIXME: complete this */ return (-EOPNOTSUPP); } noinline __unlikely int mx_iocgnotify_card(struct cd *cd, mx_notify_t * arg) { /* FIXME: complete this */ return (0); } noinline __unlikely int mx_iocgnotify_span(struct sp *sp, mx_notify_t * arg) { /* FIXME: complete this */ return (0); } noinline __unlikely int mx_iocgnotify_chan(struct sp *sp, struct ch *ch, mx_notify_t * arg) { /* FIXME: complete this */ return (0); } noinline __unlikely int mx_iocgnotify(queue_t *q, mblk_t *mp, mblk_t *dp) { mx_notify_t *hdr, *arg = (typeof(arg)) dp->b_rptr; int ret; mblk_t *db; if ((ret = mx_notify_size(arg)) < 0) return (ret); if (!(db = mi_copyout_alloc(q, mp, 0, ret, 0))) return (-ENOSR); *(hdr = (typeof(hdr)) db->b_rptr) = *arg; ret = -ESRCH; switch (arg->type) { struct cd *cd; struct sp *sp; struct ch *ch; struct sg *sg; psw_t flags; case MX_OBJ_TYPE_DFLT: /* defaults */ if (arg->id != 0) break; ret = mx_iocgnotify_dflt(hdr); break; case MX_OBJ_TYPE_SYNC: /* synchronization group */ if (!(sg = sg_find(arg->id))) break; spin_lock_irqsave(&sg->lock, flags); ret = mx_iocgnotify_sync(sg, hdr); spin_unlock_irqrestore(&sg->lock, flags); break; case MX_OBJ_TYPE_CARD: /* card */ if (!(cd = cd_find(arg->id))) break; spin_lock_irqsave(&cd->lock, flags); ret = mx_iocgnotify_card(cd, hdr); spin_unlock_irqrestore(&cd->lock, flags); break; case MX_OBJ_TYPE_SPAN: /* span */ if (!(sp = sp_find(arg->id))) break; spin_lock_irqsave(&sp->lock, flags); ret = mx_iocgnotify_span(sp, hdr); spin_unlock_irqrestore(&sp->lock, flags); break; case MX_OBJ_TYPE_CHAN: /* channel */ if (!(sp = sp_find(arg->id))) break; if (IS_ERR((ch = ch_find(arg->id)))) break; spin_lock_bh(&ch->lock); ret = mx_iocgnotify_chan(sp, ch, hdr); spin_unlock_bh(&ch->lock); break; case MX_OBJ_TYPE_FRAC: /* fractional */ break; case MX_OBJ_TYPE_XCON: /* cross connect */ break; case MX_OBJ_TYPE_BERT: /* bit error rate test */ break; default: ret = -EINVAL; break; } if (ret >= 0) mi_copyout(q, mp); return (ret); } noinline __unlikely int mx_iocsnotify(queue_t *q, mblk_t *mp, mblk_t *dp) { mx_notify_t *arg = (typeof(arg)) dp->b_rptr; switch (arg->type) { case MX_OBJ_TYPE_DFLT: /* defaults */ /* FIXME: complete this */ return (-EOPNOTSUPP); case MX_OBJ_TYPE_SYNC: /* synchronization group */ /* FIXME: complete this */ return (-EOPNOTSUPP); case MX_OBJ_TYPE_CARD: /* card */ /* FIXME: complete this */ return (-EOPNOTSUPP); case MX_OBJ_TYPE_SPAN: /* span */ /* FIXME: complete this */ return (-EOPNOTSUPP); case MX_OBJ_TYPE_CHAN: /* channel */ /* FIXME: complete this */ return (-EOPNOTSUPP); case MX_OBJ_TYPE_FRAC: /* fractional */ /* FIXME: complete this */ return (-EOPNOTSUPP); case MX_OBJ_TYPE_XCON: /* cross connect */ /* FIXME: complete this */ return (-EOPNOTSUPP); case MX_OBJ_TYPE_BERT: /* bit error rate test */ /* FIXME: complete this */ return (-EOPNOTSUPP); default: goto einval; } einval: return (-EINVAL); } noinline __unlikely int mx_ioccnotify(queue_t *q, mblk_t *mp, mblk_t *dp) { mx_notify_t *arg = (typeof(arg)) dp->b_rptr; switch (arg->type) { case MX_OBJ_TYPE_DFLT: /* defaults */ /* FIXME: complete this */ return (-EOPNOTSUPP); case MX_OBJ_TYPE_SYNC: /* synchronization group */ /* FIXME: complete this */ return (-EOPNOTSUPP); case MX_OBJ_TYPE_CARD: /* card */ /* FIXME: complete this */ return (-EOPNOTSUPP); case MX_OBJ_TYPE_SPAN: /* span */ /* FIXME: complete this */ return (-EOPNOTSUPP); case MX_OBJ_TYPE_CHAN: /* channel */ /* FIXME: complete this */ return (-EOPNOTSUPP); case MX_OBJ_TYPE_FRAC: /* fractional */ /* FIXME: complete this */ return (-EOPNOTSUPP); case MX_OBJ_TYPE_XCON: /* cross connect */ /* FIXME: complete this */ return (-EOPNOTSUPP); case MX_OBJ_TYPE_BERT: /* bit error rate test */ /* FIXME: complete this */ return (-EOPNOTSUPP); default: goto einval; } einval: return (-EINVAL); } STATIC __unlikely int mx_attr_size(mx_attr_t * arg) { int size = sizeof(*arg); switch (arg->type) { case MX_OBJ_TYPE_DFLT: size += sizeof(arg->attrs->dflt); break; case MX_OBJ_TYPE_SYNC: size += sizeof(arg->attrs->sync); break; case MX_OBJ_TYPE_CARD: size += sizeof(arg->attrs->card); break; case MX_OBJ_TYPE_SPAN: size += sizeof(arg->attrs->span); break; case MX_OBJ_TYPE_CHAN: size += sizeof(arg->attrs->chan); break; case MX_OBJ_TYPE_FRAC: size += sizeof(arg->attrs->frac); break; case MX_OBJ_TYPE_XCON: size += sizeof(arg->attrs->xcon); break; case MX_OBJ_TYPE_BERT: size += sizeof(arg->attrs->bert); break; default: return (-EINVAL); } return (size); } noinline __unlikely int mx_iocgattr_dflt(mx_attr_t * arg) { int ret; if ((ret = mx_iocgconfig_dflt((mx_config_t *) & arg->attrs->dflt.config)) < 0) goto error; if ((ret = mx_iocgoption_dflt((mx_option_t *) & arg->attrs->dflt.option)) < 0) goto error; if ((ret = mx_iocginfo_dflt((mx_info_t *) & arg->attrs->dflt.inform)) < 0) goto error; if ((ret = mx_iocgstatem_dflt((mx_statem_t *) & arg->attrs->dflt.statem)) < 0) goto error; if ((ret = mx_iocgstatus_dflt((mx_status_t *) & arg->attrs->dflt.status)) < 0) goto error; if ((ret = mx_iocgstats_dflt((mx_stats_t *) & arg->attrs->dflt.stats)) < 0) goto error; if ((ret = mx_iocgnotify_dflt((mx_notify_t *) & arg->attrs->dflt.events)) < 0) goto error; return (0); error: return (ret); } noinline __unlikely int mx_iocgattr_sync(struct sg *sg, mx_attr_t * arg) { return (-EOPNOTSUPP); } noinline __unlikely int mx_iocgattr_card(struct cd *cd, mx_attr_t * arg) { int ret; if ((ret = mx_iocgconfig_card(cd, (mx_config_t *) & arg->attrs->card.config)) < 0) goto error; if ((ret = mx_iocgoption_card(cd, (mx_option_t *) & arg->attrs->card.option)) < 0) goto error; if ((ret = mx_iocginfo_card(cd, (mx_info_t *) & arg->attrs->card.inform)) < 0) goto error; if ((ret = mx_iocgstatem_card(cd, (mx_statem_t *) & arg->attrs->card.statem)) < 0) goto error; if ((ret = mx_iocgstatus_card(cd, (mx_status_t *) & arg->attrs->card.status)) < 0) goto error; if ((ret = mx_iocgstats_card(cd, (mx_stats_t *) & arg->attrs->card.stats)) < 0) goto error; if ((ret = mx_iocgnotify_card(cd, (mx_notify_t *) & arg->attrs->card.events)) < 0) goto error; return (0); error: return (ret); } noinline __unlikely int mx_iocgattr_span(struct sp *sp, mx_attr_t * arg) { int ret; if ((ret = mx_iocgconfig_span(sp, (mx_config_t *) & arg->attrs->span.config)) < 0) goto error; if ((ret = mx_iocgoption_span(sp, (mx_option_t *) & arg->attrs->span.option)) < 0) goto error; if ((ret = mx_iocginfo_span(sp, (mx_info_t *) & arg->attrs->span.inform)) < 0) goto error; if ((ret = mx_iocgstatem_span(sp, (mx_statem_t *) & arg->attrs->span.statem)) < 0) goto error; if ((ret = mx_iocgstatus_span(sp, (mx_status_t *) & arg->attrs->span.status)) < 0) goto error; if ((ret = mx_iocgstats_span(sp, (mx_stats_t *) & arg->attrs->span.stats)) < 0) goto error; if ((ret = mx_iocgnotify_span(sp, (mx_notify_t *) & arg->attrs->span.events)) < 0) goto error; return (0); error: return (ret); } noinline __unlikely int mx_iocgattr_chan(struct sp *sp, struct ch *ch, mx_attr_t * arg) { int ret; if ((ret = mx_iocgconfig_chan(sp, ch, (mx_config_t *) & arg->attrs->chan.config)) < 0) goto error; if ((ret = mx_iocgoption_chan(sp, ch, (mx_option_t *) & arg->attrs->chan.option)) < 0) goto error; if ((ret = mx_iocginfo_chan(sp, ch, (mx_info_t *) & arg->attrs->chan.inform)) < 0) goto error; if ((ret = mx_iocgstatem_chan(sp, ch, (mx_statem_t *) & arg->attrs->chan.statem)) < 0) goto error; if ((ret = mx_iocgstatus_chan(sp, ch, (mx_status_t *) & arg->attrs->chan.status)) < 0) goto error; if ((ret = mx_iocgstats_chan(sp, ch, (mx_stats_t *) & arg->attrs->chan.stats)) < 0) goto error; if ((ret = mx_iocgnotify_chan(sp, ch, (mx_notify_t *) & arg->attrs->chan.events)) < 0) goto error; return (0); error: return (ret); } noinline __unlikely int mx_iocgattr(queue_t *q, mblk_t *mp, mblk_t *dp) { mx_attr_t *hdr, *arg = (typeof(arg)) dp->b_rptr; int ret; mblk_t *db; if ((ret = mx_attr_size(arg)) < 0) return (ret); if (!(db = mi_copyout_alloc(q, mp, 0, ret, 0))) return (-ENOSR); *(hdr = (typeof(hdr)) db->b_rptr) = *arg; ret = -ESRCH; switch (arg->type) { struct cd *cd; struct sp *sp; struct ch *ch; struct sg *sg; psw_t flags; case MX_OBJ_TYPE_DFLT: /* defaults */ if (arg->id != 0) break; ret = mx_iocgattr_dflt(hdr); break; case MX_OBJ_TYPE_SYNC: /* synchronization group */ if (!(sg = sg_find(arg->id))) break; spin_lock_irqsave(&sg->lock, flags); ret = mx_iocgattr_sync(sg, hdr); spin_unlock_irqrestore(&sg->lock, flags); break; case MX_OBJ_TYPE_CARD: /* card */ if (!(cd = cd_find(arg->id))) break; spin_lock_irqsave(&cd->lock, flags); ret = mx_iocgattr_card(cd, hdr); spin_unlock_irqrestore(&cd->lock, flags); break; case MX_OBJ_TYPE_SPAN: /* span */ if (!(sp = sp_find(arg->id))) break; spin_lock_irqsave(&sp->lock, flags); ret = mx_iocgattr_span(sp, hdr); spin_unlock_irqrestore(&sp->lock, flags); break; case MX_OBJ_TYPE_CHAN: /* channel */ if (!(sp = sp_find(arg->id))) break; if (IS_ERR((ch = ch_find(arg->id)))) break; spin_lock_bh(&ch->lock); ret = mx_iocgattr_chan(sp, ch, hdr); spin_unlock_bh(&ch->lock); break; case MX_OBJ_TYPE_FRAC: /* fractional */ break; case MX_OBJ_TYPE_XCON: /* cross connect */ break; case MX_OBJ_TYPE_BERT: /* bit error rate test */ break; default: ret = -EINVAL; break; } if (ret >= 0) mi_copyout(q, mp); return (0); } STATIC __unlikely int mx_mgmt_size(mx_mgmt_t * arg) { int size = sizeof(*arg); switch (arg->type) { case MX_OBJ_TYPE_DFLT: size += sizeof(arg->action->dflt); break; case MX_OBJ_TYPE_SYNC: size += sizeof(arg->action->sync); break; case MX_OBJ_TYPE_CARD: size += sizeof(arg->action->card); break; case MX_OBJ_TYPE_SPAN: size += sizeof(arg->action->span); break; case MX_OBJ_TYPE_CHAN: size += sizeof(arg->action->chan); break; case MX_OBJ_TYPE_FRAC: size += sizeof(arg->action->frac); break; case MX_OBJ_TYPE_XCON: size += sizeof(arg->action->xcon); break; case MX_OBJ_TYPE_BERT: size += sizeof(arg->action->bert); break; default: return (-EINVAL); } return (size); } noinline __unlikely int mx_ioccmgmt(queue_t *q, mblk_t *mp, mblk_t *dp) { mx_mgmt_t *arg = (typeof(arg)) dp->b_rptr; switch (arg->type) { case MX_OBJ_TYPE_DFLT: /* defaults */ /* FIXME: complete this */ return (-EOPNOTSUPP); case MX_OBJ_TYPE_SYNC: /* synchronization group */ /* FIXME: complete this */ return (-EOPNOTSUPP); case MX_OBJ_TYPE_CARD: /* card */ /* FIXME: complete this */ return (-EOPNOTSUPP); case MX_OBJ_TYPE_SPAN: /* span */ /* FIXME: complete this */ return (-EOPNOTSUPP); case MX_OBJ_TYPE_CHAN: /* channel */ /* FIXME: complete this */ return (-EOPNOTSUPP); case MX_OBJ_TYPE_FRAC: /* fractional */ /* FIXME: complete this */ return (-EOPNOTSUPP); case MX_OBJ_TYPE_XCON: /* cross connect */ /* FIXME: complete this */ return (-EOPNOTSUPP); case MX_OBJ_TYPE_BERT: /* bit error rate test */ /* FIXME: complete this */ return (-EOPNOTSUPP); default: goto einval; } einval: return (-EINVAL); } STATIC __unlikely int mx_pass_size(mx_pass_t * arg) { int size = sizeof(*arg); size += arg->ctl_length; size += arg->dat_length; return (size); } noinline __unlikely int mx_ioccpass(queue_t *q, mblk_t *mp, mblk_t *dp) { return (-EOPNOTSUPP); } /* * ------------------------------------------------------------------------- * * Test and Commit SL configuration settings * * ------------------------------------------------------------------------- */ #if 0 noinline __unlikely int sl_test_config(struct xp *xp, sl_config_t * arg) { return (-EOPNOTSUPP); } noinline __unlikely int sl_commit_config(struct xp *xp, sl_config_t * arg) { return (-EOPNOTSUPP); } #endif noinline __unlikely void sl_iocgoptions(struct ch *ch, mblk_t *dp) { lmi_option_t *arg = (typeof(arg)) dp->b_rptr; *arg = ch->option; } noinline __unlikely int sl_iocsoptions(struct ch *ch, mblk_t *dp) { lmi_option_t *arg = (typeof(arg)) dp->b_rptr; ch->option = *arg; return (0); } noinline __unlikely void sl_iocgconfig(struct ch *ch, mblk_t *dp) { sl_config_t *arg = (typeof(arg)) dp->b_rptr; *arg = ch->sl.config; #if 1 arg->t1 = drv_hztomsec(arg->t1); arg->t2 = drv_hztomsec(arg->t2); arg->t2l = drv_hztomsec(arg->t2l); arg->t2h = drv_hztomsec(arg->t2h); arg->t3 = drv_hztomsec(arg->t3); arg->t4n = drv_hztomsec(arg->t4n); arg->t4e = drv_hztomsec(arg->t4e); arg->t5 = drv_hztomsec(arg->t5); arg->t6 = drv_hztomsec(arg->t6); arg->t7 = drv_hztomsec(arg->t7); #endif } noinline __unlikely int sl_iocsconfig(struct ch *ch, mblk_t *dp) { sl_config_t *arg = (typeof(arg)) dp->b_rptr; #if 1 arg->t1 = drv_msectohz(arg->t1); arg->t2 = drv_msectohz(arg->t2); arg->t2l = drv_msectohz(arg->t2l); arg->t2h = drv_msectohz(arg->t2h); arg->t3 = drv_msectohz(arg->t3); arg->t4n = drv_msectohz(arg->t4n); arg->t4e = drv_msectohz(arg->t4e); arg->t5 = drv_msectohz(arg->t5); arg->t6 = drv_msectohz(arg->t6); arg->t7 = drv_msectohz(arg->t7); #endif ch->sl.config = *arg; return (0); } noinline __unlikely int sl_ioctconfig(struct ch *ch, mblk_t *dp) { sl_config_t *arg = (typeof(arg)) dp->b_rptr; (void) arg; return (-EOPNOTSUPP); } noinline __unlikely int sl_ioccconfig(struct ch *ch, mblk_t *dp) { sl_config_t *arg = (typeof(arg)) dp->b_rptr; (void) arg; return (-EOPNOTSUPP); } noinline __unlikely void sl_iocgstatem(struct ch *ch, mblk_t *dp) { sl_statem_t *arg = (typeof(arg)) dp->b_rptr; *arg = ch->sl.statem; } noinline __unlikely int sl_ioccmreset(struct ch *ch, mblk_t *dp) { sl_statem_t *arg = (typeof(arg)) dp->b_rptr; ch->sl.statem = *arg; return (0); } noinline __unlikely void sl_iocgstatsp(struct ch *ch, mblk_t *dp) { sl_stats_t *arg = (typeof(arg)) dp->b_rptr; *arg = ch->sl.statsp; } noinline __unlikely int sl_iocsstatsp(struct ch *ch, mblk_t *dp) { sl_stats_t *arg = (typeof(arg)) dp->b_rptr; ch->sl.statsp = *arg; return (0); } noinline __unlikely void sl_iocgstats(struct ch *ch, mblk_t *dp) { sl_stats_t *arg = (typeof(arg)) dp->b_rptr; *arg = ch->sl.stats; } noinline __unlikely int sl_ioccstats(struct ch *ch, mblk_t *dp) { sl_stats_t *arg = (typeof(arg)) dp->b_rptr; bzero(&ch->sl.stats, sizeof(ch->sl.stats)); return (0); } noinline __unlikely void sl_iocgnotify(struct ch *ch, mblk_t *dp) { sl_notify_t *arg = (typeof(arg)) dp->b_rptr; *arg = ch->sl.notify; } noinline __unlikely int sl_iocsnotify(struct ch *ch, mblk_t *dp) { sl_notify_t *arg = (typeof(arg)) dp->b_rptr; ch->sl.notify.events |= arg->events; return (0); } noinline __unlikely int sl_ioccnotify(struct ch *ch, mblk_t *dp) { sl_notify_t *arg = (typeof(arg)) dp->b_rptr; ch->sl.notify.events &= ~(arg->events); return (0); } /* * ------------------------------------------------------------------------- * * Test and Commit SDT configuration settings * * ------------------------------------------------------------------------- */ noinline __unlikely int sdt_test_config(struct ch *ch, sdt_config_t * arg) { if (!arg->t8) arg->t8 = ch->sdt.config.t8; if (!arg->Tin) arg->Tin = ch->sdt.config.Tin; if (!arg->Tie) arg->Tie = ch->sdt.config.Tie; if (!arg->T) arg->T = ch->sdt.config.T; if (!arg->D) arg->D = ch->sdt.config.D; if (!arg->Te) arg->Te = ch->sdt.config.Te; if (!arg->De) arg->De = ch->sdt.config.De; if (!arg->Ue) arg->Ue = ch->sdt.config.Ue; if (!arg->N) arg->N = ch->sdt.config.N; if (!arg->m) arg->m = ch->sdt.config.m; if (!arg->b) arg->b = ch->sdt.config.b; else if (arg->b != ch->sdt.config.b) return (-EINVAL); return (0); } noinline __unlikely void sdt_iocgoptions(struct ch *ch, mblk_t *dp) { lmi_option_t *arg = (typeof(arg)) dp->b_rptr; *arg = ch->option; } noinline __unlikely int sdt_iocsoptions(struct ch *ch, mblk_t *dp) { lmi_option_t *arg = (typeof(arg)) dp->b_rptr; ch->option = *arg; return (0); } noinline __unlikely void sdt_iocgconfig(struct ch *ch, mblk_t *dp) { sdt_config_t *arg = (typeof(arg)) dp->b_rptr; *arg = ch->sdt.config; #if 1 arg->t8 = drv_hztomsec(arg->t8); #endif } noinline __unlikely int sdt_iocsconfig(struct ch *ch, mblk_t *dp) { sdt_config_t *arg = (typeof(arg)) dp->b_rptr; #if 1 arg->t8 = drv_msectohz(arg->t8); #endif ch->sdt.config = *arg; return (0); } noinline __unlikely int sdt_ioctconfig(struct ch *ch, mblk_t *dp) { sdt_config_t *arg = (typeof(arg)) dp->b_rptr; return sdt_test_config(ch, arg); } noinline __unlikely int sdt_ioccconfig(struct ch *ch, mblk_t *dp) { sdt_config_t *arg = (typeof(arg)) dp->b_rptr; ch->sdt.config = *arg; return (0); } noinline __unlikely void sdt_iocgstatem(struct ch *ch, mblk_t *dp) { sdt_statem_t *arg = (typeof(arg)) dp->b_rptr; *arg = ch->sdt.statem; } noinline __unlikely int sdt_ioccmreset(struct ch *ch, mblk_t *dp) { fixme(("Master reset\n")); return (-EOPNOTSUPP); } noinline __unlikely void sdt_iocgstatsp(struct ch *ch, mblk_t *dp) { sdt_stats_t *arg = (typeof(arg)) dp->b_rptr; *arg = ch->sdt.statsp; } noinline __unlikely int sdt_iocsstatsp(struct ch *ch, mblk_t *dp) { sdt_stats_t *arg = (typeof(arg)) dp->b_rptr; ch->sdt.statsp = *arg; return (0); } noinline __unlikely void sdt_iocgstats(struct ch *ch, mblk_t *dp) { sdt_stats_t *arg = (typeof(arg)) dp->b_rptr; *arg = ch->sdt.stats; } noinline __unlikely int sdt_ioccstats(struct ch *ch, mblk_t *dp) { sdt_stats_t *arg = (typeof(arg)) dp->b_rptr; bzero(&ch->sdt.stats, sizeof(ch->sdt.stats)); return (0); } noinline __unlikely void sdt_iocgnotify(struct ch *ch, mblk_t *dp) { sdt_notify_t *arg = (typeof(arg)) dp->b_rptr; *arg = ch->sdt.notify; } noinline __unlikely int sdt_iocsnotify(struct ch *ch, mblk_t *dp) { sdt_notify_t *arg = (typeof(arg)) dp->b_rptr; ch->sdt.notify = *arg; return (0); } noinline __unlikely int sdt_ioccnotify(struct ch *ch, mblk_t *dp) { sdt_notify_t *arg = (typeof(arg)) dp->b_rptr; ch->sdt.notify.events &= ~arg->events; return (0); } noinline __unlikely void sdt_ioccabort(struct ch *ch) { ch->tx.residue |= 0x7f << ch->tx.rbits; ch->tx.rbits += 7; } /* * ------------------------------------------------------------------------- * * Test SDL configuration settings * * ------------------------------------------------------------------------- */ noinline __unlikely int sdl_test_config(struct ch *ch, sdl_config_t * arg) { if (arg->ifflags) { return (-EINVAL); } switch (arg->iftype) { case SDL_TYPE_NONE: /* unknown/unspecified */ arg->iftype = ch->sdl.config.iftype; break; case SDL_TYPE_DS0: /* DS0 channel */ case SDL_TYPE_DS0A: /* DS0A channel */ /* yes we allow DS0A on E1 */ break; case SDL_TYPE_E1: /* full E1 span */ if (ch->sp->config.ifgtype != SDL_GTYPE_E1) { return (-EINVAL); } break; case SDL_TYPE_T1: /* full T1 span */ if (ch->sp->config.ifgtype != SDL_GTYPE_T1) { return (-EINVAL); } break; case SDL_TYPE_J1: /* full J1 span */ if (ch->sp->config.ifgtype != SDL_GTYPE_T1 && ch->sp->config.ifgtype != SDL_GTYPE_J1) { return (-EINVAL); } break; default: return (-EINVAL); } switch (arg->ifmode) { case SDL_MODE_NONE: /* */ arg->ifmode = ch->sdl.config.ifmode; break; case SDL_MODE_PEER: /* */ break; case SDL_MODE_ECHO: /* */ case SDL_MODE_REM_LB: /* */ case SDL_MODE_LOC_LB: /* */ case SDL_MODE_LB_ECHO: /* */ case SDL_MODE_TEST: /* */ break; default: return (-EINVAL); } switch (arg->ifgmode) { case SDL_GMODE_NONE: case SDL_GMODE_LOC_LB: break; case SDL_GMODE_REM_LB: default: return (-EINVAL); } if (ch->sp) { switch (arg->ifgtype) { case SDL_GTYPE_NONE: /* */ arg->ifgtype = ch->sp->config.ifgtype; break; case SDL_GTYPE_E1: /* */ case SDL_GTYPE_T1: /* */ case SDL_GTYPE_J1: /* */ if (arg->ifgtype != ch->sp->config.ifgtype) { return (-EINVAL); } break; default: return (-EINVAL); } switch (arg->ifgcrc) { case SDL_GCRC_NONE: /* */ switch (arg->ifgtype) { case SDL_GTYPE_E1: arg->ifgcrc = SDL_GCRC_CRC4; break; case SDL_GTYPE_T1: arg->ifgcrc = SDL_GCRC_CRC6; break; case SDL_GTYPE_J1: arg->ifgcrc = SDL_GCRC_CRC6J; break; default: return (-EINVAL); } break; case SDL_GCRC_CRC4: /* */ if (arg->ifgtype != SDL_GTYPE_E1) { return (-EINVAL); } break; case SDL_GCRC_CRC5: /* */ if (arg->ifgtype != SDL_GTYPE_E1) { return (-EINVAL); } break; case SDL_GCRC_CRC6: /* */ if (arg->ifgtype != SDL_GTYPE_T1) { return (-EINVAL); } break; case SDL_GCRC_CRC6J: if (arg->ifgtype != SDL_GTYPE_J1) { return (-EINVAL); } break; default: return (-EINVAL); } switch (arg->ifclock) { case SDL_CLOCK_NONE: /* */ arg->ifclock = ch->sp->config.ifclock; break; case SDL_CLOCK_INT: /* */ case SDL_CLOCK_MASTER: /* */ case SDL_CLOCK_EXT: /* */ case SDL_CLOCK_SLAVE: /* */ case SDL_CLOCK_LOOP: /* */ break; default: return (-EINVAL); } switch (arg->ifcoding) { case SDL_CODING_NONE: /* */ arg->ifcoding = ch->sp->config.ifcoding; break; case SDL_CODING_AMI: /* */ break; case SDL_CODING_B8ZS: /* */ if (arg->ifgtype != SDL_GTYPE_T1 && arg->ifgtype != SDL_GTYPE_J1) { return (-EINVAL); } break; case SDL_CODING_HDB3: /* */ if (arg->ifgtype != SDL_GTYPE_E1) { return (-EINVAL); } break; default: case SDL_CODING_B6ZS: /* */ return (-EINVAL); } switch (arg->ifframing) { case SDL_FRAMING_NONE: /* */ arg->ifframing = ch->sp->config.ifframing; break; case SDL_FRAMING_CCS: /* */ case SDL_FRAMING_CAS: /* */ if (arg->ifgtype != SDL_GTYPE_E1) { return (-EINVAL); } break; case SDL_FRAMING_SF: /* */ case SDL_FRAMING_ESF: /* */ if (arg->ifgtype != SDL_GTYPE_T1 && arg->ifgtype != SDL_GTYPE_J1) { return (-EINVAL); } break; default: return (-EINVAL); } if (arg->iftxlevel == 0) arg->iftxlevel = ch->sp->config.iftxlevel; else if (arg->iftxlevel <= 16) arg->iftxlevel--; else { return (-EINVAL); } if (ch->sp->cd) { int src; for (src = 0; src < SDL_SYNCS; src++) if (arg->ifsyncsrc[src] < 0 || arg->ifsyncsrc[src] > 4) { return (-EINVAL); } } else { return (-EINVAL); } } else { return (-EINVAL); } return (0); } /* * ------------------------------------------------------------------------- * * Commit SDL configuration settings * * ------------------------------------------------------------------------- */ noinline __unlikely void sdl_commit_config(struct ch *ch, sdl_config_t * arg) { int chan_reconfig = 0, span_reconfig = 0, card_reconfig = 0; struct sp *sp; struct cd *cd = NULL; if (ch->sdl.config.iftype != arg->iftype) { ch->sdl.config.iftype = arg->iftype; chan_reconfig = 1; } switch (arg->iftype) { case SDL_TYPE_DS0A: ch->sdl.config.ifrate = 56000; break; case SDL_TYPE_DS0: ch->sdl.config.ifrate = 64000; break; case SDL_TYPE_J1: ch->sdl.config.ifrate = 1544000; break; case SDL_TYPE_T1: ch->sdl.config.ifrate = 1544000; break; case SDL_TYPE_E1: ch->sdl.config.ifrate = 2048000; break; } if (ch->sdl.config.ifrate != arg->ifrate) { ch->sdl.config.ifrate = arg->ifrate; chan_reconfig = 1; } if (ch->sdl.config.ifmode != arg->ifmode) { ch->sdl.config.ifmode = arg->ifmode; chan_reconfig = 1; } if ((sp = ch->sp)) { int chan; struct ch *c; if (sp->config.ifgcrc != arg->ifgcrc) { for (chan = 0; chan < 32; chan++) if ((c = sp->chans[chan])) c->sdl.config.ifgcrc = arg->ifgcrc; sp->config.ifgcrc = arg->ifgcrc; span_reconfig = 1; } if (sp->config.ifgmode != arg->ifgmode) { for (chan = 0; chan < 32; chan++) if ((c = sp->chans[chan])) c->sdl.config.ifgmode = arg->ifgmode; sp->config.ifgmode = arg->ifgmode; span_reconfig = 1; } if (sp->config.ifclock != arg->ifclock) { for (chan = 0; chan < 32; chan++) if ((c = sp->chans[chan])) c->sdl.config.ifclock = arg->ifclock; sp->config.ifclock = arg->ifclock; span_reconfig = 1; } if (sp->config.ifcoding != arg->ifcoding) { for (chan = 0; chan < 32; chan++) if ((c = sp->chans[chan])) c->sdl.config.ifcoding = arg->ifcoding; sp->config.ifcoding = arg->ifcoding; span_reconfig = 1; } if (sp->config.ifframing != arg->ifframing) { for (chan = 0; chan < 32; chan++) if ((c = sp->chans[chan])) c->sdl.config.ifframing = arg->ifframing; sp->config.ifframing = arg->ifframing; span_reconfig = 1; } if (sp->config.iftxlevel != arg->iftxlevel) { for (chan = 0; chan < 32; chan++) if ((c = sp->chans[chan])) c->sdl.config.iftxlevel = arg->iftxlevel; sp->config.iftxlevel = arg->iftxlevel; span_reconfig = 1; } if ((cd = sp->cd)) { int src, span, chan; struct sp *s; struct ch *c; for (src = 0; src < SDL_SYNCS; src++) { if (cd->config.ifsyncsrc[src] == arg->ifsyncsrc[src]) continue; for (span = 0; span < cd->ports; span++) { if (!(s = cd->spans[span])) continue; for (chan = 0; chan < 32; chan++) { if (!(c = s->chans[chan])) continue; c->sdl.config.ifsyncsrc[src] = arg->ifsyncsrc[src]; } } cd->config.ifsyncsrc[src] = arg->ifsyncsrc[src]; card_reconfig = 1; } } } if (sp && span_reconfig && (sp->config.ifflags & SDL_IF_UP) && cd) { /* need to bring up span */ switch (cd->config.ifgtype) { case SDL_GTYPE_E1: { printd(("%s: performing reconfiguration of E1 span %d\n", DRV_NAME, sp->span)); /* Tell ISR to re-evaluate the sync source */ cd->eval_syncsrc = 1; xp_span_reconfig(sp); break; } case SDL_GTYPE_T1: { printd(("%s: performing reconfiguration of T1 span %d\n", DRV_NAME, sp->span)); /* Tell ISR to re-evaluate the sync source */ cd->eval_syncsrc = 1; xp_span_reconfig(sp); break; } case SDL_GTYPE_J1: { printd(("%s: performing reconfiguration of J1 span %d\n", DRV_NAME, sp->span)); /* Tell ISR to re-evaluate the sync source */ cd->eval_syncsrc = 1; xp_span_reconfig(sp); break; } default: swerr(); break; } } if (cd && card_reconfig && (cd->config.ifflags & SDL_IF_UP)) { cd->eval_syncsrc = 1; } } /* * SDL_IOCGOPTIONS: lmi_option_t * ----------------------------------- */ noinline __unlikely void sdl_iocgoptions(struct ch *ch, mblk_t *dp) { lmi_option_t *arg = (lmi_option_t *) dp->b_rptr; *arg = ch->option; } /* * SDL_IOCSOPTIONS: lmi_option_t * ----------------------------------- */ noinline __unlikely int sdl_iocsoptions(struct ch *ch, mblk_t *dp) { lmi_option_t *arg = (typeof(arg)) dp->b_rptr; ch->option = *arg; return (0); } /* * SDL_IOCGCONFIG: sdl_config_t * ----------------------------------- */ noinline __unlikely void sdl_iocgconfig(struct ch *ch, mblk_t *dp) { struct cd *cd; struct sp *sp; int src; sdl_config_t *arg = (typeof(arg)) dp->b_rptr; bzero(arg, sizeof(*arg)); arg->ifflags = ch->sdl.config.ifflags; arg->iftype = ch->sdl.config.iftype; arg->ifrate = ch->sdl.config.ifrate; arg->ifmode = ch->sdl.config.ifmode; arg->ifblksize = ch->sdl.config.ifblksize; if ((sp = ch->sp)) { arg->ifgtype = sp->config.ifgtype; arg->ifgrate = sp->config.ifgrate; arg->ifgmode = sp->config.ifgmode; arg->ifgcrc = sp->config.ifgcrc; arg->ifclock = sp->config.ifclock; arg->ifcoding = sp->config.ifcoding; arg->ifframing = sp->config.ifframing; arg->ifalarms = sp->config.ifalarms; arg->ifrxlevel = sp->config.ifrxlevel; arg->iftxlevel = sp->config.iftxlevel + 1; if ((cd = sp->cd)) { for (src = 0; src < SDL_SYNCS; src++) arg->ifsyncsrc[src] = cd->config.ifsyncsrc[src]; arg->ifsync = cd->config.ifsync; } } } /* * SDL_IOCSCONFIG: sdl_config_t * ----------------------------------- */ noinline __unlikely int sdl_iocsconfig(struct ch *ch, mblk_t *dp) { sdl_config_t *arg = (typeof(arg)) dp->b_rptr; int ret; if ((ret = sdl_test_config(ch, arg))) return (ret); sdl_commit_config(ch, arg); return (0); } /* * SDL_IOCTCONFIG: sdl_config_t * ----------------------------------- */ noinline __unlikely int sdl_ioctconfig(struct ch *ch, mblk_t *dp) { sdl_config_t *arg = (typeof(arg)) dp->b_rptr; return sdl_test_config(ch, arg); } /* * SDL_IOCCCONFIG: sdl_config_t * ----------------------------------- */ noinline __unlikely int sdl_ioccconfig(struct ch *ch, mblk_t *dp) { sdl_config_t *arg = (typeof(arg)) dp->b_rptr; sdl_commit_config(ch, arg); return (0); } /* * SDL_IOCGSTATEM: sdl_statem_t * ----------------------------------- */ noinline __unlikely void sdl_iocgstatem(struct ch *ch, mblk_t *dp) { sdl_statem_t *arg = (typeof(arg)) dp->b_rptr; *arg = ch->sdl.statem; } /* * SDL_IOCCMRESET: sdl_statem_t * ----------------------------------- */ noinline __unlikely int sdl_ioccmreset(struct ch *ch, mblk_t *dp) { (void) ch; (void) dp; fixme(("FIXME: Support master reset\n")); return (-EOPNOTSUPP); } /* * SDL_IOCGSTATSP: sdl_stats_t * ----------------------------------- */ noinline __unlikely void sdl_iocgstatsp(struct ch *ch, mblk_t *dp) { sdl_stats_t *arg = (typeof(arg)) dp->b_rptr; *arg = ch->sdl.statsp; } /* * SDL_IOCSSTATSP: sdl_stats_t * ----------------------------------- */ noinline __unlikely int sdl_iocsstatsp(struct ch *ch, mblk_t *dp) { sdl_stats_t *arg = (typeof(arg)) dp->b_rptr; fixme(("FIXME: check these settings\n")); ch->sdl.statsp = *arg; return (0); } /* * SDL_IOCGSTATS: sdl_stats_t * ----------------------------------- */ noinline __unlikely void sdl_iocgstats(struct ch *ch, mblk_t *dp) { sdl_stats_t *arg = (typeof(arg)) dp->b_rptr; *arg = ch->sdl.stats; } /* * SDL_IOCCSTATS: sdl_stats_t * ----------------------------------- */ noinline __unlikely int sdl_ioccstats(struct ch *ch, mblk_t *dp) { sdl_stats_t *arg = (typeof(arg)) dp->b_rptr; bzero(&ch->sdl.stats, sizeof(ch->sdl.stats)); return (0); } /* * SDL_IOCGNOTIFY: sdl_notify_t * ----------------------------------- */ noinline __unlikely void sdl_iocgnotify(struct ch *ch, mblk_t *dp) { sdl_notify_t *arg = (typeof(arg)) dp->b_rptr; *arg = ch->sdl.notify; } /* * SDL_IOCSNOTIFY: sdl_notify_t * ----------------------------------- */ noinline __unlikely int sdl_iocsnotify(struct ch *ch, mblk_t *dp) { sdl_notify_t *arg = (typeof(arg)) dp->b_rptr; ch->sdl.notify.events |= arg->events; return (0); } /* * SDL_IOCCNOTIFY: sdl_notify_t * ----------------------------------- */ noinline __unlikely int sdl_ioccnotify(struct ch *ch, mblk_t *dp) { sdl_notify_t *arg = (typeof(arg)) dp->b_rptr; ch->sdl.notify.events &= ~arg->events; return (0); } /* * SDL_IOCCDISCTX: * ----------------------------------- */ noinline __unlikely void sdl_ioccdisctx(struct ch *ch) { ch->sdl.config.ifflags &= ~SDL_IF_TX_RUNNING; } /* * SDL_IOCCONNTX: * ----------------------------------- */ noinline __unlikely void sdl_ioccconntx(struct ch *ch) { ch->sdl.config.ifflags |= SDL_IF_TX_RUNNING; } /* * NIT input-output controls * ------------------------------------------------------------------------- */ /* Parse out the interface name and place the card, span and chan in the xp structure. Return 0 on * success, negative error code on error. */ int parse_interface(struct xp *xp, char *p, size_t len) { struct cd *cd; struct sp *sp; struct ch *ch; char *e = p + len; xp->card = -1; xp->span = -1; xp->chan = -1; xp->monitor = XP_MONITOR_NONE; xp->level = XP_LEVEL_MON_SDT; if (p + strlen(DRV_NAME) > e) return (-EINVAL); if (strstr(p, DRV_NAME) != p) return (-EINVAL); p += strlen(DRV_NAME); if (p >= e || *p == '\0') { xp->monitor = XP_MONITOR_GLOB; xp->level = XP_LEVEL_MON_SDT; xp->xray.flags = XP_XRAY_SDT_GLOB; return (0); } xp->card = 0; while (p < e && '0' <= *p && *p <= '9') { xp->card *= 10; xp->card += *p - '0'; p++; } xp->ppa = ((0xff << 0) | (0x0f << 8) | ((xp->card & 0x0f) << 12)); if (xp->card >= 0x0f || (cd = cd_find(xp->ppa)) == NULL) return (-ENXIO); if (p >= e || *p == '\0') { xp->monitor = XP_MONITOR_CARD; xp->level = XP_LEVEL_MON_SDT; xp->xray.flags = XP_XRAY_SDT_CARD; return (0); } if (*p != '.') return (-EINVAL); p++; xp->span = 0; while (p < e && '0' <= *p && *p <= '9') { xp->span *= 10; xp->span += *p - '0'; p++; } xp->ppa = ((0xff << 0) | ((xp->span & 0x0f) << 8) | ((xp->card & 0x0f) << 12)); if (xp->span >= cd->ports || (sp = sp_find(xp->ppa)) != NULL) return (-ENXIO); if (p >= e || *p == '\0') { xp->monitor = XP_MONITOR_SPAN; xp->level = XP_LEVEL_MON_SDT; xp->xray.flags = XP_XRAY_SDT_SPAN; return (0); } if (*p != ':') return (-EINVAL); p++; xp->chan = 0; while (p < e && '0' <= *p && *p <= '9') { xp->chan *= 10; xp->chan += *p - '0'; p++; } xp->ppa = ((xp->chan & 0xff) | ((xp->span & 0x0f) << 8) | ((xp->card & 0x0f) << 12)); if (xp->chan >= 32 || IS_ERR(ch = ch_find(xp->ppa))) return (-ENXIO); if (p >= e || *p == '\0') { xp->monitor = XP_MONITOR_CHAN; xp->level = XP_LEVEL_MON_SDT; xp->xray.flags = XP_XRAY_SDT_CHAN; return (0); } return (-EINVAL); } /** nit_niocbind: - process NIOCBIND ioctl * @xp: private structure * @dp: M_IOCTL/M_IOCDATA data block * * See nit_if(4). The NIOCBIND input-output control command will attach the stream represented by * its first argument to the network interface designated by its third argument, which should be a * pointer to an ifreq structure whose ifr_name field names the desired interface. See <net/if.h> * for the definition of this structure. */ noinline __unlikely int nit_niocbind(struct xp *xp, mblk_t *dp) { struct ifreq *ifr = (typeof(ifr)) dp->b_rptr; int ret; if ((ret = parse_interface(xp, ifr->ifr_name, IFNAMSIZ)) == 0) { /* FIXME: initialize all capture variables */ xp->xray.bpf.dlt = DLT_MTP2; } return (ret); } /** nit_niocssnap: - process NIOCSSNAP ioctl * @xp: private structure * @dp: M_IOCTL/M_IOCDATA data block * * See nit_if(4). The NIOCSSNAP input-output control command sets the current snapshot length to * the value given in the u_long pointed to by the input-output control command's final argument. * nit_if(4) interprets a snapshot length of zero as meaning infinity, so that it will copy all * selected packets in their entirety. It constrains positive snapshot lengths to be at least the * length of an Ethernet header, so that it will pass at least the link-level header of all * selected packets to its upstream neighbor. */ noinline __unlikely int nit_niocssnap(struct xp *xp, mblk_t *dp) { ulong snap = *(ulong *) dp->b_rptr; if (snap != 0) { struct ch *ch; if ((ch = xp->ch) != NULL) { if (snap < ch->sdt.config.m + 1) return (-ERANGE); } else { if (snap < 7) return (-ERANGE); } } xp->xray.nit.snap = snap; return (0); } #ifdef __LP64__ /** nit_niocssnap32: - process 32-bit NIOCSSNAP ioctl * @xp: private structure * @dp: M_IOCTL/M_IOCDATA data block * * See nit_if(4). The NIOCSSNAP input-output control command sets the current snapshot length to * the value given in the u_long pointed to by the input-output control command's final argument. * nit_if(4) interprets a snapshot length of zero as meaning infinity, so that it will copy all * selected packets in their entirety. It constrains positive snapshot lengths to be at least the * length of an Ethernet header, so that it will pass at least the link-level header of all * selected packets to its upstream neighbor. */ noinline __unlikely int nit_niocssnap32(struct xp *xp, mblk_t *dp) { ulong snap = *(uint32_t *) dp->b_rptr; if (snap != 0) { struct ch *ch; if ((ch = xp->ch) != NULL) { if (snap < ch->sdt.config.m + 1) return (-ERANGE); } else { if (snap < 7) return (-ERANGE); } } xp->xray.nit.snap = snap; return (0); } #endif /* __LP64__ */ /** nit_niocgsnap: - process NIOCGSNAP ioctl * @q: write queue * @mp: M_IOCTL/M_IOCDDATA message * @xp: private structure * * See nit_if(4). The NIOCGSNAP input-output control command returns the snapshot length for this * device instance in the u_lonog pointed to by the input-output control command's final argument. */ noinline __unlikely int nit_niocgsnap(queue_t *q, mblk_t *mp, struct xp *xp) { mblk_t *db; if (!(db = mi_copyout_alloc(q, mp, 0, sizeof(ulong), 0))) return (-ENOSR); *(ulong *)db->b_rptr = xp->xray.nit.snap; return (0); } #ifdef __LP64__ /** nit_niocgsnap32: - process 32-bit NIOCGSNAP ioctl * @q: write queue * @mp: M_IOCTL/M_IOCDDATA message * @xp: private structure * * See nit_if(4). The NIOCGSNAP input-output control command returns the snapshot length for this * device instance in the u_lonog pointed to by the input-output control command's final argument. */ noinline __unlikely int nit_niocgsnap32(queue_t *q, mblk_t *mp, struct xp *xp) { mblk_t *db; if (!(db = mi_copyout_alloc(q, mp, 0, sizeof(uint32_t), 0))) return (-ENOSR); *(uint32_t *)db->b_rptr = xp->xray.nit.snap; return (0); } #endif /* __LP64__ */ /** nit_niocsflags: - process NIOCSFLAGS ioctl * @xp: private structure * @dp: M_IOCTL/M_IOCDATA data block * * See nit_if(4). THe NIOCSFLAGS input-output control command recognizes the following flag bits, * which must be given in the u_long pointed to by the input-output control command's final * argument. This set may be augmented in future releases (hah!). All but the NI_PROMISC bit * control the addition of headers that precede the packet body. These headers appear in the order * given below, with the last-mentioned enabled header adjacent to the packet body. * * NI_PROMISC * Requets that the underlying interface be set into promiscuous mode and that all packets that * the interface receives be passed up through the stream. nit only honors this it for the * super-user. * NI_TIMESTAMP * Prepend to each selected packet a header containing the packet arrival time expressed as a * struct timeval. * NI_DROPS * Prepend to each selected packet a header containing the cumulative number of packets that * this instance of nit has dropped because of flow control requirements or resource * exhaustion. The header value is expressed as u_long. Note: it accounts only for events * ocurring within nit, and does not count packets dropped at the network interface level or by * upstream modules. * NI_LEN * Prepend to each selected packet a headere containing the packet's original length * (includeing link-level header), as it was before being trimmed to the snapshot length. The * header value is expressed as u_long. */ noinline __unlikely int nit_niocsflags(struct xp *xp, mblk_t *dp) { uint val = *(ulong *) dp->b_rptr; /* Note we would check super-user for NI_PROMISC but in this driver NI_PROMISC does nothing. */ if ((val & ~NI_USERBITS)) return (-EINVAL); xp->xray.nit.flags = (xp->xray.nit.flags & ~NI_USERBITS) | val; return (0); } #ifdef __LP64__ /** nit_niocsflags32: - process 32-bit NIOCSFLAGS ioctl * @xp: private structure * @dp: M_IOCTL/M_IOCDATA data block */ noinline __unlikely int nit_niocsflags32(struct xp *xp, mblk_t *dp) { uint val = *(uint32_t *) dp->b_rptr; /* Note we would check super-user for NI_PROMISC but in this driver NI_PROMISC does nothing. */ if ((val & ~NI_USERBITS)) return (-EINVAL); xp->xray.nit.flags = (xp->xray.nit.flags & ~NI_USERBITS) | val; return (0); } #endif /* __LP64__ */ /** nit_niocgflags: - process NIOCGFLAGS ioctl * @q: write queue * @mp: M_IOCTL/M_IOCDATA message * @xp: private structure * * See nit_if(4). Returns the current state of the flag bits for this device instance in the * u_long pointed to by the input-outpu control command's final argument. */ noinline __unlikely int nit_niocgflags(queue_t *q, mblk_t *mp, struct xp *xp) { mblk_t *db; if (!(db = mi_copyout_alloc(q, mp, 0, sizeof(ulong), 0))) return (-ENOSR); *(ulong *)db->b_rptr = xp->xray.nit.flags & NI_USERBITS; return (0); } #ifdef __LP64__ /** nit_niocgflags32: - process 32-bit NIOCGFLAGS ioctl * @q: write queue * @mp: M_IOCTL/M_IOCDATA message * @xp: private structure * * See nit_if(4). Returns the current state of the flag bits for this device instance in the * u_long pointed to by the input-outpu control command's final argument. */ noinline __unlikely int nit_niocgflags32(queue_t *q, mblk_t *mp, struct xp *xp) { mblk_t *db; if (!(db = mi_copyout_alloc(q, mp, 0, sizeof(uint32_t), 0))) return (-ENOSR); *(uint32_t *)db->b_rptr = xp->xray.nit.flags & NI_USERBITS; return (0); } #endif /* __LP64__ */ /* * BPF input-output controls * ------------------------------------------------------------------------- */ /** bpf_biocgdlt: - process BIOCGDLT ioctl * @q: write queue * @mp: M_IOCTL/M_IOCDATA message * @xp: private structure * * See bpfdrv(4). (uint) Returns the type of data link layer underlying the attached interface. * [EINVAL] is returned if no interface has yet been specified with BIOCSETIF or BIOCSETLIF. The * device types, prefixed with "DLT_", are defined in <net/bpf.h>. The (third) argument to * ioctl(2s) is a pointer to an unsigned int into which to place the value of the data link type. * * (4.4BSD) This is one of the original commands from the 4.4BSD implementation set. * * Under Linux Fast-STREAMS, the bpfdrv must support this command so that the capture application * can determine the data link type of the capture. */ noinline __unlikely int bpf_biocgdlt(queue_t *q, mblk_t *mp, struct xp *xp) { mblk_t *db; if (xp->ch == NULL) return (-EINVAL); if (!(db = mi_copyout_alloc(q, mp, 0, sizeof(uint), 0))) return (-ENOSR); *(uint *) db->b_rptr = xp->xray.bpf.dlt; return (0); } /** bpf_biocsdlt: - process BIOCSDLT ioctl * @q: write queue * @mp: M_IOCTL/M_IOCDATA message * @xp: private structure * @dp: M_IOCTL/M_IOCDATA data block * * See bpfdrv(4). (uint) Use to specify the type of data link layer of the interface attached to * the bpf descriptor. If the current interface is not of the given type, then the descriptor will * be reattached to an interface of the given type. If the descriptor has promiscuous mode set, * the new interface will be moved to the promiscuous mode. [EINVAL] is returned if no interface * has been specified with BIOCSETIF or BIOCSETLIF. The device types, prefixed with "DLT_", are * defined in <net/bpf.h>. The (third) argument to ioctl(2s) is a pointer to an unsigned int that * provides the requested data link type. * * (NetBSD, Not in 4.4BSD). This is one of the original commands from the extended 4.4BSD * implementation set and is provided by all recent implementations. * * Under Linux Fast-STREAMS, the bpfdrv must support this command so that the capture application * can select the data link type of the capture. * * There are three data link types that are applicable for SS7 signalling links as follows: * * DLT_MTP2_WITH_PHDR * The full HDLC frame with a link level pseudo-header prepended that provides the * signalling data link identifier and a flag indicating whether this frame is an extended * sequence number (Q.703/Annex A) frame. This should be the default for capturing on * wildcard interfaces for BPF. * * DLT_MTP2 * The full HDLC frame with no link level pseudo-header. It is impossible to tell from * which link each message comes and whether it is Annex A or not. Therefore, maybe this * should not even be offerred for wildcard links but only specific slot interfaces. * * DLT_MTP3 * MSUs only with the MTP Level 2 header (BIB/BSN,FIB/FSN,LI) removed. This is problematic * for Japanese SS7 because the message priority is encodeded in the LI spare bits, which * are discarded. Unfortunately BPF has no idea about this. * * The most useful data link type for wildcard interfaces is DLT_MTP2_WITH_PHDR and it will be the * default for wildcard interfaces. The most useful data link type for individual signalling links * is DLT_MTP2 (because the pseudo-header would be redundant on every frame) or even DLT_MTP3. */ noinline __unlikely int bpf_biocsdlt(queue_t *q, mblk_t *mp, struct xp *xp, mblk_t *dp) { uint dlt; /* Check whether an interface has been set yet. */ if (xp->monitor == XP_MONITOR_NONE) return (-EINVAL); switch ((dlt = *(uint *) dp->b_rptr)) { case DLT_MTP2_WITH_PHDR: case DLT_MTP2: case DLT_MTP3: if (xp->xray.bpf.dlt != dlt) { mblk_t *b; /* header changed, flush queue and clear stats */ if (!(b = allocb(2, BPRI_MED))) return (-ENOSR); DB_TYPE(b) = M_FLUSH; b->b_wptr = b->b_rptr + 2; b->b_rptr[0] = FLUSHR; b->b_rptr[1] = 0; flushq(RD(q), FLUSHDATA); xp->xray.bpf.stats.bs_recv = 0; xp->xray.bpf.stats.bs_drop = 0; xp->xray.bpf.stats.bs_capt = 0; xp->xray.bpf.dlt = dlt; qreply(q, b); } xp->xray.bpf.dlt = dlt; return (0); default: return (-EINVAL); } } /** bpf_biocgdltlist: - process BIOCGDLTLIST ioctl * @q: write queue * @mp: M_IOCTL/M_IOCDATA message * @xp: private structure pointer * @cp: copyresp structure pointer * @dp: M_IOCTL/M_IOCDATA data block * * See bpfdrv(4). (struct bpf_dltlist) Retuns a list of data link types of the given interface. A * user allocated buffer to hold the list and bpf_dltlist structure, defined in <net/bpf.h>. * [EINVAL] is returned if no interface has been specified. The device typyes, prefixed with * "DLT_", are defined in <net/bpf.h>. The (third) argument to ioctl(2s) is a pointer to a * bpf_dltlist structure that will contain the available data link types. The bpf_dltlist * structure is defined as follows: * * struct bpf_dltlist { * uint bfl_len; * uint *bfl_list; * }; * * The bpf_dltlist structure contains the following members: * * bfl_len The unsigned integer number of array elements in the array pointed to by the * bfl_list member. On call, this is the size of the array pointed to by the bfl_list * member. On return, this is the number of elements in the array that where populated * by the driver. * * bfl_list Points to an array of unsigned integers that wil contain the available data link * types. On call, this array must contain at least bfl_len elements. On return, the * array will contain bfl_len valid elements. All other elements in the array will * contain the same values as were provided on call. Because there is no data link * type value of zero (0), the caller should zero the entire array before the call as * another mechanism to detect the number of elements returned. * * (NetBSD, Not in 4.4BSD) This is one of the original commands from the extended 4.4BSD * implementation set and is provided by all recent implementations. * * Under Linux Fast-STREAMS, the bpfdrv must support this command so that capture applications can * determine the possible data link types for capture. * * For SS7 the three levels DLT_MTP2_WITH_PHDR, DLT_MTP2 and DLT_MTP3 are always available. The * default will depend on whether it is a wildcard interface or a specific interface. Wildcard * interfaces default to DLT_MTP2_WITH_PHDR, whereas, specific interfaces might default to DLT_MTP2 * or DLT_MTP3. Nevertheless, the capture application can set whichever DLT it wishes of these * three, so always report the three. */ noinline __unlikely int bpf_biocgdltlist(queue_t *q, mblk_t *mp, struct xp *xp, struct copyresp *cp, mblk_t *dp) { caddr_t uaddr; uint n; #if !defined __LP64__ (void) cp; #else /* defined __LP64__ */ if (cp->cp_flag == IOC_ILP32) { struct bpf_dltlist32 *bfl = (typeof(bfl)) dp->b_rptr; uaddr = (caddr_t) (ulong) bfl->bfl_list; n = bfl->bfl_len; } else #endif /* defined __LP64__ */ { struct bpf_dltlist *bfl = (typeof(bfl)) dp->b_rptr; uaddr = (caddr_t) bfl->bfl_list; n = bfl->bfl_len; } if (n > 0) { mblk_t *db; if (n > 3) n = 3; if (!(db = mi_copyout_alloc(q, mp, 0, sizeof(uint), 0))) return (-ENOSR); *(uint *) db->b_rptr = n; if (!(db = mi_copyout_alloc(q, mp, uaddr, n * sizeof(uint), 0))) return (-ENOSR); db->b_wptr = db->b_rptr; if (n) { *(uint *) db->b_wptr = DLT_MTP2_WITH_PHDR; db->b_wptr += sizeof(uint); n--; } if (n) { *(uint *) db->b_wptr = DLT_MTP2; db->b_wptr += sizeof(uint); n--; } if (n) { *(uint *) db->b_wptr = DLT_MTP3; db->b_wptr += sizeof(uint); n--; } } mi_copy_set_rval(mp, 3); return (0); } /** bpf_biocpromisc: - process the BIOCPROMISC ioctl * @xp: private structure * * See bpfdrv(4). (none) Force the interface into promiscuous mode. All packets, not just those * destined for the local host, are processed. Since more than one file can be listening on a * given interface, a listener that opened its interface non-promiscuously may still receive * packets promiscuously. This problem can be remedied with an appropriate filter. The (third) * argument to ioctl(2s) is ignored. * * (4.4BSD) This is one of the original commands from the 4.4BSD implementation set. Under Linux * Fast-STREAMS, the bpfdrv must support this command if promiscuous captuer is permitted. The * response in the case that promiscuous capture is not permitted is not well documented. * * This driver does not provide for promiscuous modes, so the flag is simply accepted. */ noinline __unlikely int bpf_biocpromisc(struct xp *xp) { xp->xray.bpf.flags |= BPF_PROMISC; return (0); } /** bpf_biocflush: - process the BIOCFLUSH ioctl * @q: write queue * @xp: private structure * * See bpfdrv(4). (none) Flushes the buffer of incoming packets, and resets the statistics that * are returned by BIOCGSTATS and BIOCGSTATSOLD. The equivalent function can be performed using * the I_FLUSH(7) STREAMS command. The (third) argument to ioctl(2s) is ignored. * * (4.4BSD) This is one of the original commands from the 4.4BSD implementaiton set. * * Under Linux Fast-STREAMS, the bpfdrv must support this command. The response to the command is * to flush its own read queue and reset its counts and issue a M_FLUSH(9) message upstream * flushing the read queues so that the equivalent action is performed by the bpfmod(4) module and * the Stream head. bpfmod(4) expects that the driver will issue a M_FLUSH(9) message upstream to * flush the read queue when the driver receives this command. */ noinline __unlikely int bpf_biocflush(queue_t *q, struct xp *xp) { mblk_t *bp; if ((bp = allocb(2, BPRI_MED)) == NULL) return (-ENOSR); DB_TYPE(bp) = M_FLUSH; bp->b_wptr = bp->b_rptr + 2; bp->b_rptr[0] = FLUSHR; bp->b_rptr[1] = 0; flushq(RD(q), FLUSHDATA); /* zero statistics */ xp->xray.bpf.stats.bs_recv = 0; xp->xray.bpf.stats.bs_drop = 0; xp->xray.bpf.stats.bs_capt = 0; qreply(q, bp); return (0); } /** bpf_biocgetif: - process the BIOCGETIF ioctl * @q: write queue * @mp: M_IOCTL/M_IOCDATA message * @xp: private structure * * See bpfdrv(4). (struct ifreq) Returns the name of the hardware interface that the file is * listening on. The name is returned in the ifr_name field of the ifreq structure. All other * fileds are undefined. The (third) argument to ioctl(2s) is a pointer to an ifreq structure. * The ifreq stsructure is defined in <net/if.h> and documented in netdevice(7). Only the ifr_name * field of the structure is used: all other fields are undefined. * * (4.4BSD) This is one of the original commands from the 4.4BSD implementation set. Under Linux * Fast-STREAMS, the bpfdrv may support this command to permit the capture application to determine * the current interface setting. (It is not that important, because it will return [EINVAL] if it * has not already been set by the application.) */ noinline __unlikely int bpf_biocgetif(queue_t *q, mblk_t *mp, struct xp *xp) { struct ifreq *ifr; mblk_t *db; if ((db = mi_copyout_alloc(q, mp, 0, sizeof(*ifr), 0))) { ifr = (typeof(ifr)) db->b_rptr; bzero(ifr, sizeof(*ifr)); switch (xp->monitor) { default: case XP_MONITOR_NONE: return (-ENXIO); case XP_MONITOR_GLOB: snprintf(ifr->ifr_name, IFNAMSIZ, DRV_NAME); break; case XP_MONITOR_CARD: snprintf(ifr->ifr_name, IFNAMSIZ, DRV_NAME "%d", xp->card); break; case XP_MONITOR_SPAN: snprintf(ifr->ifr_name, IFNAMSIZ, DRV_NAME "%d.%d", xp->card, xp->span); break; case XP_MONITOR_CHAN: snprintf(ifr->ifr_name, IFNAMSIZ, DRV_NAME "%d.%d:%d", xp->card, xp->span, xp->chan); break; } return (0); } return (-ENOSR); } /** bpf_biocsetif: - process BIOCSETIF ioctl * @q: write queue * @xp: private structure * @dp: M_IOCTL/M_IOCDATA data block * * See bpfdrv(4). (struct ifreq) Sets the hardware interface associated with the file. This * command must be performed before any packets can be read. The device is indicated by name using * the ifr_name field of the ifreq structure. Additionally, the actions of BIOCFLUSH are * performed. The (third) argument to ioctl(2s) is a pointer to an ifreq structure. The ifreq * structure is defined in <net/if.h> and documented in netdevice(7). Only the ifr_name field of * the structure is used: all other fields are undefined. * * (4.4BSD) This is one of the original commands from the 4.4BSD implementation set. Under Linux * Fast-STREAMS, the bpfdrv must support this command to permit capture to occur at all. When this * command is issued, the driver should attach, bind and enable capture on a valid interface. When * the interface was previously set, the driver should first disable, unbind and detach the old * interface. Whether this normally moves the interface to the IFF_UP or down state is not well * documented. */ noinline __unlikely int bpf_biocsetif(queue_t *q, struct xp *xp, mblk_t *dp) { struct ifreq *ifr = (typeof(ifr)) dp->b_rptr; mblk_t *bp; int err; if ((bp = allocb(2, BPRI_MED)) == NULL) return (-ENOSR); if ((err = parse_interface(xp, ifr->ifr_name, IFNAMSIZ)) != 0) { freeb(bp); return (err); } /* FIXME: initialize all capture variables */ xp->xray.bpf.dlt = DLT_MTP2_WITH_PHDR; DB_TYPE(bp) = M_FLUSH; bp->b_wptr = bp->b_rptr + 2; bp->b_rptr[0] = FLUSHR; bp->b_rptr[1] = 0; flushq(RD(q), FLUSHDATA); /* zero statistics */ xp->xray.bpf.stats.bs_recv = 0; xp->xray.bpf.stats.bs_drop = 0; xp->xray.bpf.stats.bs_capt = 0; qreply(q, bp); return (err); } /** bpf_biocgetlif: - process the BIOCGETLIF ioctl * @q: write queue * @mp: M_IOCTL/M_IOCDATA message * @xp: private structure * * See bpfdrv(4). (struct lifreq) Returns the name of the hardware interface that the file is * listening on. The name is returned in the ifr_name field of the lifreq structure. All other * fileds are undefined. The (third) argument to ioctl(2s) is a pointer to an lifreq structure. * The lifreq stsructure is defined in <net/if.h> and documented in netdevice(7). Only the * ifr_name field of the structure is used: all other fields are undefined. * * (Solaris only.) These are Solaris-only commands (because only Solaris has the lifreq structure). * Under Linux Fast-STREAMS, these commands are implemented by bpfdrv(4) for compatibility and to * allow 32-character instead of 16-character interface names. */ noinline __unlikely int bpf_biocgetlif(queue_t *q, mblk_t *mp, struct xp *xp) { struct lifreq *lifr; mblk_t *db; if ((db = mi_copyout_alloc(q, mp, 0, sizeof(*lifr), 0))) return (-ENOSR); lifr = (typeof(lifr)) db->b_rptr; bzero(lifr, sizeof(*lifr)); switch (xp->monitor) { default: case XP_MONITOR_NONE: return (-ENXIO); case XP_MONITOR_GLOB: snprintf(lifr->lifr_name, LIFNAMSIZ, DRV_NAME); break; case XP_MONITOR_CARD: snprintf(lifr->lifr_name, LIFNAMSIZ, DRV_NAME "%d", xp->card); break; case XP_MONITOR_SPAN: snprintf(lifr->lifr_name, LIFNAMSIZ, DRV_NAME "%d.%d", xp->card, xp->span); break; case XP_MONITOR_CHAN: snprintf(lifr->lifr_name, LIFNAMSIZ, DRV_NAME "%d.%d:%d", xp->card, xp->span, xp->chan); break; } return (0); } /** bpf_biocsetlif: - process BIOCSETLIF ioctl * @q: write queue * @xp: private structure * @dp: M_IOCTL/M_IOCDATA data block * * See bpfdrv(4). (struct lifreq) Sets the hardware interface associated with the file. This * command must be performed before any packets can be read. The device is indicated by name using * the ifr_name field of the lifreq structure. Additionally, the actions of BIOCFLUSH are * performed. The (third) argument to ioctl(2s) is a pointer to an lifreq structure. The lifreq * structure is defined in <net/if.h> and documented in netdevice(7). Only the ifr_name field of * the structure is used: all other fields are undefined. * * (Solaris only.) These are Solaris-only commands (because only Solaris has the lifreq structure). * Under Linux Fast-STREAMS, these commands are implemented by bpfdrv(4) for compatibility and to * allow 32-character instead of 16-character interface names. */ noinline __unlikely int bpf_biocsetlif(queue_t *q, struct xp *xp, mblk_t *dp) { struct lifreq *lifr = (typeof(lifr)) dp->b_rptr; mblk_t *bp; int err; if ((bp = allocb(2, BPRI_MED)) == NULL) return (-ENOSR); if ((err = parse_interface(xp, lifr->lifr_name, LIFNAMSIZ)) != 0) { freeb(bp); return (err); } /* FIXME: initialize all capture variables */ xp->xray.bpf.dlt = DLT_MTP2_WITH_PHDR; DB_TYPE(bp) = M_FLUSH; bp->b_wptr = bp->b_rptr + 2; bp->b_rptr[0] = FLUSHR; bp->b_rptr[1] = 0; flushq(RD(q), FLUSHDATA); /* zero statistics */ xp->xray.bpf.stats.bs_recv = 0; xp->xray.bpf.stats.bs_drop = 0; xp->xray.bpf.stats.bs_capt = 0; qreply(q, bp); return (err); } /** bpf_biocgstats: - process BIOCGSTATS ioctl * @q: write queue * @mp: M_IOCTL/M_IOCDATA message * @xp: private structure * * See bpfdrv(4). (struct bpf_stat) Returns the bpf statistics structure. This is a newer * structure that contains 64-bit counts and also calculates the number of packets captured after * filtering. * * (NetBSD, OpenBSD, Solaris.) Many recent implementations (FreeBSD being the notable exception) * implement the 64-bit extended statistics includeing the bs_capt field. The original 4.4BSD * command is renamed to BIOCGSTATSOLD. Under Linux Fast-STREAMS, this command is implemented by * both bpfdrv(4) and bpfmod(4). bpfmod(4) will intercept the command on its way from the driver * and will add its own counts into the statistics. It adds its drops to those of the driver in * bs_drop, and sets the numer of packets that passed the filter in bs_capt. */ noinline __unlikely int bpf_biocgstats(queue_t *q, mblk_t *mp, struct xp *xp) { struct bpf_stat *bs; mblk_t *db; if (!(db = mi_copyout_alloc(q, mp, 0, sizeof(*bs), 0))) return (-ENOSR); bs = (typeof(bs)) db->b_rptr; bzero(bs, sizeof(*bs)); bs->bs_recv = xp->xray.bpf.stats.bs_recv; bs->bs_drop = xp->xray.bpf.stats.bs_drop; bs->bs_capt = xp->xray.bpf.stats.bs_capt; return (0); } /** bpf_biocgstatsold: - process BIOCGSTATSOLD ioctl * @q: write queue * @mp: M_IOCTL/M_IOCDATA message * @xp: private structure * * See bpfdrv(4). (struct bpf_stat_old) Returns the bpf statistics structure. This is the older * structure that contains 32-bit counts and does not calculate the number of packets captured * after filtering. * * (4.4BSD, FreeBSD, OpenBSD) This is the original 32-bit command from the 4.4BSD basic command * set. It lacks the bs_capt field of the newer structure. Not all implementations use the newer * structure, and in that case this command is named BIOCGSTATS. Under Linux Fast-STREAMS, this * command is implemented by both bpfdrv(4) and bpfmod(4). bpfmod(4) will intercept the command on * its way from the driver and will add its own counts int the statistics. It adds its drops to * those of the driver in bs_drop. */ noinline __unlikely int bpf_biocgstatsold(queue_t *q, mblk_t *mp, struct xp *xp) { struct bpf_stat_old *bs; mblk_t *db; if (!(db = mi_copyout_alloc(q, mp, 0, sizeof(*bs), 0))) return (-ENOSR); bs = (typeof(bs)) db->b_rptr; bzero(bs, sizeof(*bs)); bs->bs_recv = xp->xray.bpf.stats.bs_recv; bs->bs_drop = xp->xray.bpf.stats.bs_drop; return (0); } /** bpf_biocghdrcmplt: - process BIOCGHDRCMPLT ioctl * @q: write queue * @mp: M_IOCTL/M_IOCDATA message * @xp: private structure * * See bpfdrv(4). (uint) Gets the status of the "header complete" flag. Set to zero if the link * level source address should be filled in automatically by the interface output routine. Set to * one of the link level source address will be written, as provided, to the wire. This flag is * initialized to zero by default. * * (4.4BSD) This is on of the original commands from the 4.4BSD implementation set. Under Linux * Fast-STREAMS, this command is not necesarily supported by bpfdrv(4). Support also depends on * whether the driver supports sending packets at all. */ noinline __unlikely int bpf_biocghdrcmplt(queue_t *q, mblk_t *mp, struct xp *xp) { mblk_t *db; if (!(db = mi_copyout_alloc(q, mp, 0, sizeof(uint), 0))) return (-ENOSR); *(uint *) db->b_rptr = ((xp->xray.bpf.flags & BPF_HDRCMPLT) != 0); return (0); } /** bpf_biocshdrcmplt: - process BIOCSHDRCMPLT ioctl * @q: write queue * @mp: M_IOCTL/M_IOCDATA message * @xp: private structure * * See bpfdrv(4). (uint) Sets the status of the "header complete" flag. Set to zero if the link * level source address should be filled in automatically by the interface output routine. Set to * one of the link level source address will be written, as provided, to the wire. This flag is * initialized to zero by default. * * (4.4BSD) This is on of the original commands from the 4.4BSD implementation set. Under Linux * Fast-STREAMS, this command is not necesarily supported by bpfdrv(4). Support also depends on * whether the driver supports sending packets at all. */ noinline __unlikely int bpf_biocshdrcmplt(struct xp *xp, mblk_t *dp) { uint val = *(uint *) dp->b_rptr; if (val) xp->xray.bpf.flags |= BPF_HDRCMPLT; else xp->xray.bpf.flags &= ~BPF_HDRCMPLT; return (0); } /** bpf_biocgseesent: - process BIOCGSEESENT ioctl * @q: write queue * @mp: M_IOCTL/M_IOCDATA message * @xp: private structure * * See bpfdrv(4). (uint) This command is obsolete but left for compatibility. Use BIOCGDIRECTION * instead. Gets the flag determining whether locally generated packets on the interface should be * returned by bpf. Set to zero to see only incoming packets on the interface. Set to one to see * packets originating locally and remotely on the interface. This flag is initialized to one by * default. * * (4.4BSD) This is one of the original commands from the 4.4BSD implementation set. Under Linux * Fast-STREAMS, this command is implemented by bpfdrv(4). */ noinline __unlikely int bpf_biocgseesent(queue_t *q, mblk_t *mp, struct xp *xp) { mblk_t *db; if (!(db = mi_copyout_alloc(q, mp, 0, sizeof(uint), 0))) return (-ENOSR); *(uint *) db->b_rptr = ((xp->xray.bpf.flags & BPF_SEESENT) != 0); return (0); } /** bpf_biocsseesent: - process BIOCSSEESENT ioctl * @xp: private structure * @dp: M_IOCTL/M_IOCDATA data block * * See bpfdrv(4). (uint) This command is obsolete but left for compatibility. Use BIOCSDIRECTION * instead. Sets the flag determining whether locally generated packets on the interface should be * returned by bpf. Set to zero to see only incoming packets on the interface. Set to one to see * packets originating locally and remotely on the interface. This flag is initialized to one by * default. * * (4.4BSD) This is one of the original commands from the 4.4BSD implementation set. Under Linux * Fast-STREAMS, this command is implemented by bpfdrv(4). */ noinline __unlikely int bpf_biocsseesent(struct xp *xp, mblk_t *dp) { uint val = *(uint *) dp->b_rptr; if (val) { xp->xray.bpf.flags |= BPF_SEESENT; xp->xray.bpf.direction = BPF_D_INOUT; } else { xp->xray.bpf.flags &= ~BPF_SEESENT; xp->xray.bpf.direction = BPF_D_IN; } return (0); } #ifdef BIOCGDIRECTION /** bpf_biocgdirection: - process BIOCGDIRECTION ioctl * @q: write queue * @mp: M_IOCTL/M_IOCDATA message * @xp: private structure * * See bpfdrv(4). (uint) Get the setting determining whether incoming, outgoing, or all packets * on the interface should be returned by BPF. Set to BPF_D_IN to see only incoming packets on the * interface. Set to BPF_D_INOUT to see packets originating locally and remotely on the interface. * Set to BPF_D_OUT to see only outgoing packets on the interface. This setting is intialized to * BPF_D_INOUT by default. * * (FreeBSD only.) These are FreeBSD-only commands that further address the security problem * addressed by BIOCLOCK, by restricting the direciton of data. Under Linux Fast-STREAMS, these * commands are implemented by bpfdrv(4). */ noinline __unlikely int bpf_biocgdirection(queue_t *q, mblk_t *mp, struct xp *xp) { mblk_t *db; if (!(db = mi_copyout_alloc(q, mp, 0, sizeof(uint), 0))) return (-ENOSR); *(uint *) db->b_rptr = xp->xray.bpf.direction; return (0); } #endif /* BIOCGDIRECTION */ #ifdef BIOCSDIRECTION /** bpf_biocsdirection: - process BIOCSDIRECTION ioctl * @xp: private structure * @dp: M_IOCTL/M_IOCDATA data block * * See bpfdrv(4). (uint) Set the setting determining whether incoming, outgoing, or all packets * on the interface should be returned by BPF. Set to BPF_D_IN to see only incoming packets on the * interface. Set to BPF_D_INOUT to see packets originating locally and remotely on the interface. * Set to BPF_D_OUT to see only outgoing packets on the interface. This setting is intialized to * BPF_D_INOUT by default. * * (FreeBSD only.) These are FreeBSD-only commands that further address the security problem * addressed by BIOCLOCK, by restricting the direciton of data. Under Linux Fast-STREAMS, these * commands are implemented by bpfdrv(4). */ noinline __unlikely int bpf_biocsdirection(struct xp *xp, mblk_t *dp) { uint direction = *(uint *) dp->b_rptr; switch (direction) { case BPF_D_IN: xp->xray.bpf.flags &= ~BPF_SEESENT; break; case BPF_D_OUT: xp->xray.bpf.flags |= BPF_SEESENT; break; case BPF_D_INOUT: xp->xray.bpf.flags |= BPF_SEESENT; break; default: return (-EINVAL); } xp->xray.bpf.direction = direction; } #endif /* BIOCSDIRECTION */ #ifdef BIOCGDIRFILT /** bpf_biocgdirfilt: - process BIOCGDIRFILT ioctl * @q: write queue * @mp: M_IOCTL/M_IOCDATA message * @xp: private structure * * See bpfdrv(4). (uint) Get the status of the "direction filter" flag. When non-zero, packets * matching the specified direction (either BPF_DIRECTION_IN or BPF_DIRECTION_OUT) will be ignored. * * (OpenBSD only.) The rationale for these commands is that OpenBSD does not support the FreeBSD * BIOCSDIRECTION and BIOCGDIRECTION commands, so these commands perform a similar action. Under * Linux Fast-STREAMS, these commands are implemented by bpfdrv(4). */ noinline __unlikely int bpf_biocgdirfilt(queue_t *q, mblk_t *mp, struct xp *xp) { mblk_t *db; uint dirfilt; if (!(db = mi_copyout_alloc(q, mp, 0, sizeof(uint), 0))) return (-ENOSR); switch (xp->xray.bpf.direction) { case BPF_D_OUT: dirfilt = BPF_DIRECTION_IN; break; case BPF_D_IN: dirfilt = BPF_DIRECTION_OUT; break; default: __swerr(); /* fall through */ case BPF_D_INOUT: dirfilt = BPF_DIRECTION_NONE; break; } *(uint *) db->b_rptr = dirfilt; return (0); } #endif /* BIOCGDIRFILT */ #ifdef BIOCSDIRFILT /** bpf_biocsdirfilt: - process BIOCSDIRFILT ioctl * @xp: private structure * @dp: M_IOCTL/M_IOCDATA data block * * See bpfdrv(4). (uint) Set the status of the "direction filter" flag. When non-zero, packets * matching the specified direction (either BPF_DIRECTION_IN or BPF_DIRECTION_OUT) will be ignored. * * (OpenBSD only.) The rationale for these commands is that OpenBSD does not support the FreeBSD * BIOCSDIRECTION and BIOCGDIRECTION commands, so these commands perform a similar action. Under * Linux Fast-STREAMS, these commands are implemented by bpfdrv(4). */ noinline __unlikely int bpf_biocsdirfilt(struct xp *xp, mblk_t *dp) { uint dirfilt = *(uint *) dp->b_rptr; uint direction; switch (dirfilt) { case BPF_DIRECTION_IN: direction = BPF_D_OUT; xp->xray.bpf.flags |= BPF_SEESENT; break; case BPF_DIRECTION_OUT: direction = BPF_D_IN; xp->xray.bpf.flags &= ~BPF_SEESENT; break; case BPF_DIRECTION_NONE: direction = BPF_D_INOUT; xp->xray.bpf.flags |= BPF_SEESENT; break; default: return (-EINVAL); } xp->xray.bpf.direction = direction; return (0); } #endif /* BIOCSDIRFILT */ #ifdef BIOCFEEDBACK /** bpf_biocfeedback: - process BIOCFEEDBACK ioctl * @xp: private structure * @dp: M_IOCTL/M_IOCDATA data block * * See bpfdrv(4). (uint) Set packet feedback mode. This allows injected packets to be fed back * as input to the interface when output via the interface is successful. When BPF_D_INOUT * direction dis set, injected outgoing packet is not returned by BPF to avoid duplication. This * flag is initialized to zero by default. * * (FreeBSD, NetBSD.) This is the original FreeBSD command implemetned by NetBSD fr compatibility * with FreeBSD. Under Linux Fast-STREAMS, this command is implemented by bpfdrv(4). */ noinline __unlikely int bpf_biocfeedback(struct xp *xp, mblk_t *dp) { uint val = *(uint *) dp->b_rptr; if (val) xp->xray.bpf.flags |= BPF_FEEDBACK; else xp->xray.bpf.flags &= ~BPF_FEEDBACK; return (0); } #endif /* BIOCFEEDBACK */ /** bpf_biocgfeedback: - process BIOCGFEEDBACK ioctl * @q: write queue * @mp: M_IOCTL/M_IOCDATA message * @xp: private structure * * See bpfdrv(4). (uint) Get pacekt feedback mode. This is the OpenBSD versions of the FreeBSD * command BIOCFEEDBACK, which cannot reset feedback mode once set. * * (OpenBSD, NetBSD.) These are the FreeBSD workalikes that also permit examining the setting. * Under Linux Fast-STREAMS, these commands are implemented by bpfdrv(4). */ noinline __unlikely int bpf_biocgfeedback(queue_t *q, mblk_t *mp, struct xp *xp) { mblk_t *db; if (!(db = mi_copyout_alloc(q, mp, 0, sizeof(uint), 0))) return (-ENOSR); *(uint *) db->b_rptr = ((xp->xray.bpf.flags & BPF_FEEDBACK) != 0); return (0); } /** bpf_biocsfeedback: - process BIOCSFEEDBACK ioctl * @xp: private structure * @dp: M_IOCTL/M_IOCDATA data block * * See bpfdrv(4). (uint) Set packet feedback mode. This is the OpenBSD versions of the FreeBSD * command BIOCFEEDBACK, which cannot reset feedback mode once set. * * (OpenBSD, NetBSD.) These are the FreeBSD workalikes that also permit examining the setting. * Under Linux Fast-STREAMS, these commands are implemented by bpfdrv(4). */ noinline __unlikely int bpf_biocsfeedback(struct xp *xp, mblk_t *dp) { uint val = *(uint *) dp->b_rptr; if (val) xp->xray.bpf.flags |= BPF_FEEDBACK; else xp->xray.bpf.flags &= ~BPF_FEEDBACK; return (0); } /* * SOCKIO input-output controls * ------------------------------------------------------------------------- */ #ifdef SIOCGIFNUM /** sio_siocgifnum: - process SIOCGIFNUM ioctl * @q: write queue * @mp: M_IOCTL/M_IOCDATA message * @xp: private structure * * See bpfdrv(4). (int) Get the number of interfaces. This request returns an integer that is * the number of interface descriptions (struct ifreq) that will be returned by the SIOCGIFCONF * ioctl; that is, it gives and indication of how large ifc_len has to be. * * The bpfdrv(4) must support this command so that the capture application is aware of the * necessary sizing of the buffer passed to SIOCGIFCONF. */ noinline __unlikely int sio_siocgifnum(queue_t *q, mblk_t *mp, struct xp *xp) { mblk_t *db; struct cd *cd; struct sp *sp; struct ch *ch; int num, card, span, chan; if ((db = mi_copyout_alloc(q, mp, 0, sizeof(int), 0)) == NULL) return (-ENOSR); for (card = 0; card < X400_CARDS; card++) { if (!(cd = x400p_cards[card])) continue; /* one for the card */ num++; for (span = 0; span < cd->ports; span++) { if (!(sp = cd->spans[span])) continue; /* one for the span */ num++; for (chan = 0; chan < 32; chan++) { if (!(ch = sp->chans[chan])) continue; /* one for the channel */ num++; } } } *(int *) db->b_rptr = num; return (0); } #endif /* SIOCGIFNUM */ /** sio_siocgifconf: - process SIOCGIFCONF ioctl * @q: write queue * @mp: M_IOCTL/M_IOCDATA message * @xp: private structure * @dp: M_IOCTL/M_IOCDATA data block * * See bpfdrv(4). (struct ifconf) Returns a list of interface addresses. This currently means * only addresses of the AF_INET (IPv4) family for compatibility. The user passes an ifconf * structure as the (third) argument to the ioctl(2s) call. It contains a pointer to an array of * ifreq structures in ifc_req and its length in bytes in ifc_len. The driver fills the ifreq * structures with all current L3 interface addresses that are running: ifr_name contains the * interface addresses that are running: ifr_name contains the interface name (eth0:1, etc.), * ifr_addr the address. The driver returns the actual length in ifc_len. If ifc_len is equal to * the original length the buffer probably has overflowed and the caller should retry with a larger * buffer to get all addresses. When no error occurs, the command returns zero (0); otherwise * minus one (1) and errno(3) is set to an appropriate error code. Overflow is not considered an * error. * * This command should be supported by the driver to permit the capture application to obtain a * list of valid interface names for use with the BIOCSETIF command. The addresses returned in * ifr_addr are not important, and could simply be 0.0.0.0. */ noinline __unlikely int sio_siocgifconf(queue_t *q, mblk_t *mp, struct xp *xp, mblk_t *dp) { struct ifconf *ifc = (typeof(ifc)) dp->b_rptr; int max = ifc->ifc_len / sizeof(struct ifreq); caddr_t uaddr = (caddr_t) ifc->ifc_buf; struct ifreq *ifr; struct cd *cd; struct sp *sp; struct ch *ch; int card, num, span, chan; mblk_t *db; if ((db = mi_copyout_alloc(q, mp, 0, sizeof(*ifc), 0)) == NULL) return (-ENOSR); ifc = (typeof(ifc)) db->b_rptr; bcopy(ifc, db->b_rptr, sizeof(*ifc)); if ((db = mi_copyout_alloc(q, mp, uaddr, ifc->ifc_len, 0)) == NULL) return (-ENOSR); ifr = (typeof(ifr)) db->b_rptr; bzero(ifr, sizeof(*ifr)); for (num = 0, card = 0; card < X400_CARDS && num < max; card++) { if (!(cd = x400p_cards[card])) continue; /* one for the card */ snprintf(ifr->ifr_name, IFNAMSIZ, DRV_NAME "%d", card); ifr->ifr_addr.sa_family = AF_UNSPEC; ifr++; num++; for (span = 0; span < cd->ports && num < max; span++) { if (!(sp = cd->spans[span])) continue; /* one for the span */ snprintf(ifr->ifr_name, IFNAMSIZ, DRV_NAME "%d.%d", card, span); ifr->ifr_addr.sa_family = AF_UNSPEC; ifr++; num++; for (chan = 0; chan < 32 && num < max; chan++) { if (!(ch = sp->chans[chan])) continue; /* one for the channel */ snprintf(ifr->ifr_name, IFNAMSIZ, DRV_NAME "%d.%d:%d", card, span, chan); ifr->ifr_addr.sa_family = AF_UNSPEC; ifr++; num++; } } } ifc->ifc_len = num * sizeof(*ifr); return (0); } #ifdef __LP64__ /** sio_siocgifconf32: - process 32-bit SIOCGIFCONF ioctl * @q: write queue * @mp: M_IOCTL/M_IOCDATA message * @xp: private structure * @dp: M_IOCTL/M_IOCDATA data block */ noinline __unlikely int sio_siocgifconf32(queue_t *q, mblk_t *mp, struct xp *xp, mblk_t *dp) { struct ifconf32 *ifc = (typeof(ifc)) dp->b_rptr; int max = ifc->ifc_len / sizeof(struct ifreq); caddr_t uaddr = (caddr_t)(ulong) ifc->ifc_buf; struct ifreq *ifr; struct cd *cd; struct sp *sp; struct ch *ch; int card, num, span, chan; mblk_t *db; if ((db = mi_copyout_alloc(q, mp, 0, sizeof(*ifc), 0)) == NULL) return (-ENOSR); ifc = (typeof(ifc)) db->b_rptr; bcopy(ifc, db->b_rptr, sizeof(*ifc)); if ((db = mi_copyout_alloc(q, mp, uaddr, ifc->ifc_len, 0)) == NULL) return (-ENOSR); ifr = (typeof(ifr)) db->b_rptr; bzero(ifr, sizeof(*ifr)); for (num = 0, card = 0; card < X400_CARDS && num < max; card++) { if (!(cd = x400p_cards[card])) continue; /* one for the card */ snprintf(ifr->ifr_name, IFNAMSIZ, DRV_NAME "%d", card); ifr->ifr_addr.sa_family = AF_UNSPEC; ifr++; num++; for (span = 0; span < cd->ports && num < max; span++) { if (!(sp = cd->spans[span])) continue; /* one for the span */ snprintf(ifr->ifr_name, IFNAMSIZ, DRV_NAME "%d.%d", card, span); ifr->ifr_addr.sa_family = AF_UNSPEC; ifr++; num++; for (chan = 0; chan < 32 && num < max; chan++) { if (!(ch = sp->chans[chan])) continue; /* one for the channel */ snprintf(ifr->ifr_name, IFNAMSIZ, DRV_NAME "%d.%d:%d", card, span, chan); ifr->ifr_addr.sa_family = AF_UNSPEC; ifr++; num++; } } } ifc->ifc_len = num * sizeof(*ifr); return (0); } #endif /* __LP64__ */ noinline fastcall __unlikely struct cd * find_ifname_cd(queue_t *q, mblk_t *mp, const char *name) { /* FIXME */ return (NULL); } noinline fastcall __unlikely struct sp * find_ifname_sp(queue_t *q, mblk_t *mp, const char *name) { /* FIXME */ return (NULL); } noinline fastcall __unlikely struct ch * find_ifname_ch(queue_t *q, mblk_t *mp, const char *name) { /* FIXME */ return (NULL); } /** sio_siocgifflags: - process SIOCGIFFLAGS ioctl * @q: write queue * @mp: M_IOCTL/M_IOCDATA message * @xp: private structure * @dp: M_IOCTL/M_IOCDATA data block * * See bpfdrv(4). (struct ifreq) Get the active flag word of the device * specified by ifr_name. ifr_flags contains a bit mask of the following * values: * * IFF_UP interface is running. * IFF_BROADCAST valid broadcast address set. * IFF_DEBUG internal debugging flag. * IFF_LOOPBACK interface is loopback interface. * IFF_POINTTOPOINT interface is point-to-point link. * IFF_RUNNING interface has resources allocated. * IFF_NOARP no arm, L2 dest. address unset. * IFF_PROMISC interface in promiscuous mode. * IFF_NOTRAILERS avoid use of trailers. * IFF_ALLMULTI receive all multicast packets. * * Seting the active flag word is a privileged operation, but any process may read it. * * The bpfdrv(4) must support the SIOCGIFFLAGS command and the IFF_UP flag. libpcap checks flags * with the SIOCGIFFLAGS command and skips all interfaces without the IFF_UP flag set. The command * can return [ENXIO] which will also cause libpcap to skip the interface. Any other error will * cause libpcap to bork out. */ noinline __unlikely int sio_siocgifflags(queue_t *q, mblk_t *mp, struct xp *xp, mblk_t *dp) { struct ifreq *ifr = (typeof(ifr)) dp->b_rptr; struct cd *cd; struct sp *sp; struct ch *ch; mblk_t *db; if (!(db = mi_copyout_alloc(q, mp, 0, sizeof(*ifr), 0))) return (-ENOSR); bcopy(ifr, db->b_rptr, sizeof(*ifr)); ifr = (typeof(ifr)) db->b_rptr; ifr->ifr_flags = 0; ifr->ifr_flags |= IFF_POINTTOPOINT; ifr->ifr_flags |= IFF_NOARP; if ((cd = find_ifname_cd(q, mp, ifr->ifr_name))) { ifr->ifr_flags |= IFF_UP; ifr->ifr_flags |= IFF_RUNNING; ifr->ifr_flags |= IFF_NOXMIT; ifr->ifr_flags |= IFF_NOLOCAL; // ifr->ifr_ppa = (card << 12); return (0); } if ((sp = find_ifname_sp(q, mp, ifr->ifr_name))) { if (sp->config.ifflags & SDL_IF_UP) ifr->ifr_flags |= IFF_UP; if (sp->config.ifflags & (SDL_IF_RX_RUNNING | SDL_IF_TX_RUNNING)) ifr->ifr_flags |= IFF_RUNNING; // ifr->ifr_ppa = (sp->cd->card << 12) | (sp->span << 8); return (0); } if ((ch = find_ifname_ch(q, mp, ifr->ifr_name))) { if (ch->sdl.config.ifflags & SDL_IF_UP) ifr->ifr_flags |= IFF_UP; if (ch->sdl.config.ifflags & (SDL_IF_RX_RUNNING | SDL_IF_TX_RUNNING)) ifr->ifr_flags |= IFF_RUNNING; // ifr->ifr_ppa = ch->ppa; return (0); } return (-ENXIO); } /** sio_siocsifflags: - process SIOCSIFFLAGS ioctl * @q: write queue * @mp: M_IOCTL/M_IOCDATA message * @xp: private structure * @dp: M_IOCTL/M_IOCDATA data block * * See bpfdrv(4). (struct ifreq) Set the active flag word of the device specified by ifr_name. * ifr_flags contains a bit mask of the following values: * * IFF_UP interface is running. * IFF_BROADCAST valid broadcast address set. * IFF_DEBUG internal debugging flag. * IFF_LOOPBACK interface is loopback interface. * IFF_POINTTOPOINT interface is point-to-point link. * IFF_RUNNING interface has resources allocated. * IFF_NOARP no arm, L2 dest. address unset. * IFF_PROMISC interface in promiscuous mode. * IFF_NOTRAILERS avoid use of trailers. * IFF_ALLMULTI receive all multicast packets. * * Seting the active flag word is a privileged operation, but any process may read it. * * The bpfdrv(4) must support the SIOCGIFFLAGS command and the IFF_UP flag. libpcap checks flags * with the SIOCGIFFLAGS command and skips all interfaces without the IFF_UP flag set. The command * can return [ENXIO] which will also cause libpcap to skip the interface. Any other error will * cause libpcap to bork out. * * Note that the SIOCSIFFLAGS input-output control command also sets the PPA. */ noinline __unlikely int sio_siocsifflags(queue_t *q, mblk_t *mp, struct xp *xp, mblk_t *dp) { struct ifreq *ifr = (typeof(ifr)) dp->b_rptr; struct ch *ch = find_ifname_ch(q, mp, ifr->ifr_name); if (ch == NULL) return (-ENXIO); /* FIXME */ return (-EOPNOTSUPP); } noinline __unlikely int sio_siocgifindex(queue_t *q, mblk_t *mp, struct xp *xp, mblk_t *dp) { /* FIXME */ return (-EOPNOTSUPP); } #ifdef SIOCSIFINDEX noinline __unlikely int sio_siocsifindex(queue_t *q, mblk_t *mp, struct xp *xp, mblk_t *dp) { /* FIXME */ return (-EOPNOTSUPP); } #endif /* SIOCSIFINDEX */ noinline __unlikely int sio_siocgifhwaddr(queue_t *q, mblk_t *mp, struct xp *xp, mblk_t *dp) { /* FIXME */ return (-EOPNOTSUPP); } noinline __unlikely int sio_siocsifhwaddr(queue_t *q, mblk_t *mp, struct xp *xp, mblk_t *dp) { /* FIXME */ return (-EOPNOTSUPP); } #ifdef SIOCGLIFNUM /** sio_siocglifnum: - process SIOCGLIFNUM ioctl * @q: write queue * @mp: M_IOCTL/M_IOCDATA message * @xp: private structure * @dp: M_IOCTL/M_IOCDATA data block * * See bpfdrv(4). (struct lifnum) Get the number of interfaces. This request returns an integer * that is the the number of interface descriptions (struct lifreq) that will be returned by the * SIOCGLIFCONF ioctl; that is, it gives an indication of how large lifc_len has to be. This * request takes an lifnum structure as a value-result parameter. The lifn_family field should be * set to AF_UNSPEC to count both AF_INET and AF_INET6 interfaces. The lifn_flags field should be * initially set to zero. * * The bpfdrv(4) must support this command so that the capture application is aware of the * necessary sizing of the buffer passed to SIOCGLIFCONF. */ noinline __unlikely int sio_siocglifnum(queue_t *q, mblk_t *mp, struct xp *xp, mblk_t *dp) { struct lifnum *lifn = (typeof(lifn)) dp->b_rptr; struct cd *cd; struct sp *sp; struct ch *ch; int card, span, chan; if ((db = mi_copyout_alloc(q, mp, 0, sizeof(*lifn), 0)) == NULL) return (-ENOSR); lifn = (typeof(lifn)) db->b_rptr; bcopy(lifn, db->b_rptr, sizeof(*lifn)); if (lifn->lifn_family != AF_UNSPEC) { lifn->lifn_count = 0; return (0); } lifn->lifn_count = 0; for (card = 0; card < X400_CARDS; card++) { if (!(cd = x400p_cards[card])) continue; lifn->lifn_count++; /* one for the card */ for (span = 0; span < cd->ports; span++) { if (!(sp = cd->spans[span])) continue; if (!(sp->config.ifflags & SDL_IF_UP) && (lifn->lifn_flags & (LIFC_ENABLED | LIFC_EXTERNAL_SOURCE))) continue; lifn->lifn_count++; /* one for the span */ for (chan = 0; chan < 32; chan++) { if (!(ch = sp->chans[chan])) continue; if (!ch->xp && (lifn->lifn_flags & (LIFC_NOXMIT | LIFC_EXTERNAL_SOURCE))) /* no transmit, no external source */ continue; if (!(ch->sdl.config.ifflags & SDL_IF_UP) && (lifn->lifn_flags & (LIFC_ENABLED | LIFC_EXTERNAL_SOURCE))) /* no enabled, no external source */ continue; /* one for the channel */ lifn->lifn_count++; } } } return (0); } #endif /* SIOCGLIFNUM */ #ifdef SIOCGLIFCONF /** sio_siocglifconf: - process SIOCGLIFCONF ioctl * @q: write queue * @mp: M_IOCTL/M_IOCDATA message * @xp: private structure * @dp: M_IOCTL/M_IOCDATA data block * * See bpfdrv(4). (struct lifconf) Get interface configuration list. This request takes an * lifconf structure as a value-result parameter. The lic_family field can be set to AF_UNSPEC to * retrieve both AF_INET and AF_INET6 interfaces. The lifc_flags field should be set to zero. Te * lifc_len field should be set to the size of the buffer pointed to by lifc_buf. Upon success, * lifc_len will contain the length, in bytes, of the array of lifreq structures pointed to by * lifc_req. For eaach lifcreq structure, the lifr_name and lifr_addr fields will be valid. */ noinline __unlikely int sio_siocglifconf(queue_t *q, mblk_t *mp, struct xp *xp, mblk_t *dp) { struct lifconf *lifc = (typeof(lifc)) dp->b_rptr; int max = lifc->lifc_len / sizeof(struct lifreq); caddr_t uaddr = (caddr_t) lifc->lifc_buf; struct lifreq *lifr; struct cd *cd; struct sp *sp; struct ch *ch; int card, num, span, chan; if ((db = mi_copyout_alloc(q, mp, 0, sizeof(*lifc), 0)) == NULL) return (-ENOSR); lifc = (typeof(*lifc)) db->b_rptr; bcopy(lifc, db->b_rptr, sizeof(*lifc)); if ((db = mi_copyout_alloc(q, mp, uaddr, lifc->lifc_len, 0)) == NULL) return (-ENOSR); lifr = (typeof(lifr)) db->b_rptr; if (lifc->lifc_family != AF_UNSPEC) { lifc->lifc_len = 0; return (0); } lifr->lifr_len = 0; for (num = 0, card = 0; card < X400_CARDS && num < max; card++) { if (!(cd = x400p_cards[card])) continue; /* one for the card */ snprintf(lifr->lifr_name, LIFNAMSIZ, DRV_NAME "%d", card); lifr->lifr_addr.sa_familty = AF_UNSPEC; lifr++; num++; for (span = 0; span < cd->ports && num < max; span++) { if (!(sp = cd->spans[span])) continue; if (!(sp->config.ifflags & SDL_IF_UP) && (lifc->lifc_flags & (LIFC_ENABLED | LIFC_EXTERNAL_SOURCE))) continue; /* one for the span */ snprintf(lifr->lifr_name, LIFNAMSIZ, DRV_NAME "%d.%d", card, span); lifr->lifr_addr.sa_family = AF_UNSPEC; lifr++; num++; for (chan = 0; chan < 32; chan++) { if (!(ch = sp->chans[chan])) continue; if (!ch->xp && (lifc->lifc_flags & (LIFC_NOXMIT | LIFC_EXTERNAL_SOURCE))) continue; if (!(ch->sdl.config.ifflags & SDL_IF_UP) && (lifc->lifc_flags & (LIFC_ENABLED | LIFC_EXTERNAL_SOURCE))) continue; snprintf(lifr->lifr_name, LIFNAMSIZ, DRV_NAME "%d.%d:%d", card, span, ch->chan); lifr->lifr_addr.sa_family = AF_UNSPEC; lifr++; num++; } } } lifr->lifr_len = num * sizeof(*lifr); return (0); } #ifdef __LP64__ /** sio_siocglifconf32: - process 32-bit SIOCGLIFCONF ioctl * @q: write queue * @mp: M_IOCTL/M_IOCDATA message * @xp: private structure * @dp: M_IOCTL/M_IOCDATA data block */ noinline __unlikely int sio_siocglifconf32(queue_t *q, mblk_t *mp, struct xp *xp, mblk_t *dp) { struct lifconf32 *lifc = (typeof(lifc)) dp->b_rptr; int max = lifc->lifc_len / sizeof(struct lifreq); caddr_t uaddr = (caddr_t) lifc->lifc_buf; struct lifreq *lifr; struct cd *cd; struct sp *sp; struct ch *ch; int card, num, span, chan; if ((db = mi_copyout_alloc(q, mp, 0, sizeof(*lifc), 0)) == NULL) return (-ENOSR); lifc = (typeof(*lifc)) db->b_rptr; bcopy(lifc, db->b_rptr, sizeof(*lifc)); if ((db = mi_copyout_alloc(q, mp, uaddr, lifc->lifc_len, 0)) == NULL) return (-ENOSR); lifr = (typeof(lifr)) db->b_rptr; if (lifc->lifc_family != AF_UNSPEC) { lifc->lifc_len = 0; return (0); } lifr->lifr_len = 0; for (num = 0, card = 0; card < X400_CARDS && num < max; card++) { if (!(cd = x400p_cards[card])) continue; /* one for the card */ snprintf(lifr->lifr_name, LIFNAMSIZ, DRV_NAME "%d", card); lifr->lifr_addr.sa_familty = AF_UNSPEC; lifr++; num++; for (span = 0; span < cd->ports && num < max; span++) { if (!(sp = cd->spans[span])) continue; if (!(sp->config.ifflags & SDL_IF_UP) && (lifc->lifc_flags & (LIFC_ENABLED | LIFC_EXTERNAL_SOURCE))) continue; /* one for the span */ snprintf(lifr->lifr_name, LIFNAMSIZ, DRV_NAME "%d.%d", card, span); lifr->lifr_addr.sa_family = AF_UNSPEC; lifr++; num++; for (chan = 0; chan < 32; chan++) { if (!(ch = sp->chans[chan])) continue; if (!ch->xp && (lifc->lifc_flags & (LIFC_NOXMIT | LIFC_EXTERNAL_SOURCE))) continue; if (!(ch->sdl.config.ifflags & SDL_IF_UP) && (lifc->lifc_flags & (LIFC_ENABLED | LIFC_EXTERNAL_SOURCE))) continue; snprintf(lifr->lifr_name, LIFNAMSIZ, DRV_NAME "%d.%d:%d", card, span, ch->chan); lifr->lifr_addr.sa_family = AF_UNSPEC; lifr++; num++; } } } lifr->lifr_len = num * sizeof(*lifr); return (0); } #endif /* __LP64__ */ #endif /* SIOCGLIFCONF */ #ifdef SIOCSLIFNAME /** sio_siocslifname: - process SIOCSLIFNAME ioctl * @q: write queue * @mp: M_IOCTL/M_IOCDATA message * @xp: private structure * @dp: M_IOCTL/M_IOCDATA data block * * Note that the SIOCSLIFNAME input-output control command also sets the PPA. */ noinline __unlikely int sio_siocslifname(queue_t *q, mblk_t *mp, struct xp *xp, mblk_t *dp) { struct lifreq *lifr = (typeof(lifr)) dp->b_rptr; /* FIXME */ return (-EOPNOTSUPP); } #endif /* SIOCSLIFNAME */ #ifdef SIOCGLIFFLAGS /** sio_siocglifflags: - process SIOCGLIFFFLAGS ioctl * @q: write queue * @mp: M_IOCTL/M_IOCDATA message * @xp: private structure * @dp: M_IOCTL/M_IOCDATA data block * * See bpfdrv(4). (struct lifreq) Get the active flag word of the device specified by lifr_name. * lifr_flags contains a bit mask of the same values as SIOCGIFFLAGS. * * The bpfdrv(4) must support the SIOCGLIFFLAGS command and the IFF_UP flag. libpcap checks flags * with the SIOCGLIFFLAGS command and skips all interfaces without the IFF_UP flag set. The * command can return [ENXIO] which will also cause libpcap to skip the interface. Any other error * will cause libpcap to bork out. */ noinline __unlikely int sio_siocglifflags(queue_t *q, mblk_t *mp, struct xp *xp, mblk_t *dp) { struct lifreq *lifr = (typeof(lifr)) dp->b_rptr; struct cd *cd; struct sp *sp; struct ch *ch; if (!(db = mi_copyout_alloc(q, mp, 0, sizeof(*lifr), 0))) return (-ENOSR); bcopy(lifr, db->b_rptr, sizeof(*lifr)); lifr = (typeof(lifr)) db->b_rptr; lifr->lifr_flags = 0; lifr->lifr_flags |= IFF_POINTTOPOINT; lifr->lifr_flags |= IFF_NOARP; if ((cd = find_ifname_cd(q, mp, lifr->lifr_name))) { lifr->lifr_flags |= IFF_UP; lifr->lifr_flags |= IFF_RUNNING; lifr->lifr_flags |= IFF_NOXMIT; lifr->lifr_flags |= IFF_NOLOCAL; lifr->lifr_ppa = (card << 12); return (0); } if ((sp = find_ifname_sp(q, mp, lifr->lifr_name))) { if (sp->config.ifflags & SDL_IF_UP) lifr->lifr_flags |= IFF_UP; if (sp->config.ifflags & (SDL_IF_RX_RUNNING | SDL_IF_TX_RUNNING)) lifr->lifr_flags |= IFF_RUNNING; lifr->lifr_ppa = (sp->cd->card << 12) | (sp->span << 8); return (0); } if ((ch = find_ifname_ch(q, mp, lifr->lifr_name))) { if (ch->sdl.config.ifflags & SDL_IF_UP) lifr->lifr_flags |= IFF_UP; if (ch->sdl.config.ifflags & (SDL_IF_RX_RUNNING | SDL_IF_TX_RUNNING)) lifr->lifr_flags |= IFF_RUNNING; lifr->lifr_ppa = ch->ppa; return (0); } return (-ENXIO); } #endif /* SIOCGLIFFLAGS */ #ifdef SIOCSLIFFLAGS /** sio_siocslifflags: - process SIOCSLIFFFLAGS ioctl * @q: write queue * @mp: M_IOCTL/M_IOCDATA message * @xp: private structure * @dp: M_IOCTL/M_IOCDATA data block * * See bpfdrv(4). (struct lifreq) Set the active flag word of the device specified by lifr_name. * lifr_flags contains a bit mask of the same values as SIOCGIFFLAGS. * * The bpfdrv(4) must support the SIOCGLIFFLAGS command and the IFF_UP flag. libpcap checks flags * with the SIOCGLIFFLAGS command and skips all interfaces without the IFF_UP flag set. The * command can return [ENXIO] which will also cause libpcap to skip the interface. Any other error * will cause libpcap to bork out. * * Note that the SIOCSLIFNAME input-output control command could also be used to set the PPA. */ noinline __unlikely int sio_siocslifflags(queue_t *q, mblk_t *mp, struct xp *xp, mblk_t *dp) { struct lifreq *lifr = (typeof(lifr)) dp->b_rptr; struct ch *ch = find_ifname_ch(q, mp, lifr->lifr_name); if (ch == NULL) return (-ENXIO); /* FIXME */ return (-EOPNOTSUPP); } #endif /* SIOCSLIFFLAGS */ #ifdef SIOCGLIFINDEX noinline __unlikely int sio_siocglifindex(queue_t *q, mblk_t *mp, struct xp *xp, mblk_t *dp) { /* FIXME */ return (-EOPNOTSUPP); } #endif /* SIOCGLIFINDEX */ #ifdef SIOCSLIFINDEX noinline __unlikely int sio_siocslifindex(queue_t *q, mblk_t *mp, struct xp *xp, mblk_t *dp) { /* FIXME */ return (-EOPNOTSUPP); } #endif /* SIOCSLIFINDEX */ #ifdef SIOCGLIFHWADDR noinline __unlikely int sio_siocglifhwaddr(queue_t *q, mblk_t *mp, struct xp *xp, mblk_t *dp) { /* FIXME */ return (-EOPNOTSUPP); } #endif /* SIOCGLIFHWADDR */ #ifdef SIOCSLIFHWADDR noinline __unlikely int sio_siocslifhwaddr(queue_t *q, mblk_t *mp, struct xp *xp, mblk_t *dp) { /* FIXME */ return (-EOPNOTSUPP); } #endif /* SIOCSLIFHWADDR */ /* * DLIOC input-output controls * ------------------------------------------------------------------------- */ #ifdef DLIOCRAW noinline __unlikely int dl_dliocraw(queue_t *q, mblk_t *mp, struct xp *xp) { /* DLIOCRAW: see dlpi_ioctl(4). Just uses M_DATA instead of DL_UNITDATA_IND and DL_UNITDATA_REQ. */ /* FIXME: set raw mode */ return (-EINVAL); } #endif /* DLIOCRAW */ #ifdef DLIOCNATIVE noinline __unlikely int dl_dliocnative(queue_t *q, mblk_t *mp, struct xp *xp) { /* DLIOCNATIVE: see dlpi_ioctl(4). Causes a native dl_mac_type instead of the default one. So, DL_HDLC instead of DL_OTHER (for signalling link). */ /* FIXME: set native mode */ mi_copy_set_rval(mp, DL_HDLC); return (0); } #endif /* DLIOCNATIVE */ #ifdef DLIOCMARGININFO noinline __unlikely int dl_dliocmargininfo(queue_t *q, mblk_t *mp, struct xp *xp) { int *arg; struct ch *ch; mblk_t *db; if ((ch = xp->ch) == NULL) return (-EINVAL); if ((db = mi_copyout_alloc(q, mp, 0, sizeof(*arg), 0))) { /* The margin is the amount of room available for a native header. So for SS7 this is the L2 header size, which is different depending on whether it is for Annex A or not. */ arg = (typeof(arg)) db->b_rptr; bzero(arg, sizeof(*arg)); *arg = (ch->option.popt & SS7_POPT_XSN) ? 6 : 3; return (0); } return (-ENOSR); } #endif /* DLIOCMARGININFO */ #ifdef DLIOCHDRINFO noinline __unlikely int dl_dliochdrinfo(struct xp *xp, mblk_t *dp) { dl_unitdata_req_t *arg = (typeof(arg)) dp->b_rptr; if (arg->dl_primitive != DL_UNITDATA_REQ) return (-EINVAL); return (-EINVAL); /* not supported */ } #endif /* DLIOCHDRINFO */ #ifdef DL_IOC_DRIVER_OPTIONS noinline __unlikely int dl_ioc_driver_options(struct xp *xp, mblk_t *dp) { driver_ops_t *arg = (typeof(arg)) dp->b_rptr; if (arg->driver_ops_type != 0) return (-EOPNOTSUPP); if (arg->driver_ops_type_1 != 0) return (-EOPNOTSUPP); if (arg->driver_ops_type_2 != 0) return (-EOPNOTSUPP); /* otherwise ok */ return (0); } #endif /* DL_IOC_DRIVER_OPTIONS */ #ifndef DLIOCHDRINFO #ifdef DL_IOC_HDR_INFO noinline __unlikely int dl_ioc_hdr_info(struct xp *xp, mblk_t *dp) { dl_unitdata_req_t *arg = (typeof(arg)) dp->b_rptr; if (arg->dl_primitive != DL_UNITDATA_REQ) return (-EINVAL); return (-EINVAL); /* not supported */ } #endif /* DL_IOC_HDR_INFO */ #endif /* DLIOCHDRINFO */ #ifdef DL_HP_SET_DRV_PARAM_IOCTL noinline __unlikely int dl_hp_set_drv_param_ioctl(struct xp *xp, mblk_t *dp) { dl_hp_set_drv_param_ioctl_t *arg = (typeof(arg)) dp->b_rptr; struct ch *ch; if ((ch = xp->ch) == NULL) goto einval; if ((arg->dl_request & DL_HP_DRV_SPEED) && (arg->dl_speed != 0)) goto einval; if ((arg->dl_request & DL_HP_DRV_DUPLEX) && (arg->dl_duplex != DL_HP_FULL_DUPLEX)) goto einval; if ((arg->dl_request & DL_HP_DRV_AUTONEG) && (arg->dl_autoneg != DL_HP_AUTONEG_SENSE_ON && arg->dl_autoneg != DL_HP_AUTONEG_SENSE_OFF)) goto einval; if ((arg->dl_request & DL_HP_DRV_MTU) && (arg->dl_mtu != ch->sdt.config.m)) goto einval; if (arg->dl_request & DL_HP_DRV_VALUE1) goto einval; if (arg->dl_request & DL_HP_DRV_VALUE2) goto einval; if (arg->dl_request & DL_HP_DRV_VALUE3) goto einval; if (arg->dl_request & DL_HP_DRV_RESERVED1) goto einval; if (arg->dl_request & DL_HP_DRV_RESERVED2) goto einval; if (arg->dl_request & DL_HP_DRV_RESERVED3) goto einval; if (arg->dl_request & DL_HP_DRV_RESERVED4) goto einval; /* otherwise ok */ if (arg->dl_request & DL_HP_DRV_AUTONEG) { switch (arg->dl_autoneg) { case DL_HP_AUTONEG_SENSE_ON: ch->sdl.config.ifflags |= SDL_IF_AUTOCONFIG; break; case DL_HP_AUTONEG_SENSE_OFF: ch->sdl.config.ifflags &= ~SDL_IF_AUTOCONFIG; break; } } return (0); einval: return (-EINVAL); } #endif /* DL_HP_SET_DRV_PARAM_IOCTL */ #ifdef DL_HP_GET_DRV_PARAM_IOCTL noinline __unlikely int dl_hp_get_drv_param_ioctl(queue_t *q, mblk_t *mp, struct xp *xp) { dl_hp_set_drv_param_ioctl_t *arg; struct ch *ch; mblk_t *db; if ((ch = xp->ch) == NULL) return (-EINVAL); if ((db = mi_copyout_alloc(q, mp, 0, sizeof(*arg), 0))) { arg = (typeof(arg)) db->b_rptr; bzero(arg, sizeof(*arg)); arg->dl_request = 0; arg->dl_speed = 0; arg->dl_request |= DL_HP_DRV_SPEED; arg->dl_duplex = DL_HP_FULL_DUPLEX; arg->dl_request |= DL_HP_DRV_DUPLEX; if (ch->sdl.config.ifflags & SDL_IF_AUTOCONFIG) arg->dl_autoneg = DL_HP_AUTONEG_SENSE_ON; else arg->dl_autoneg = DL_HP_AUTONEG_SENSE_OFF; arg->dl_request |= DL_HP_DRV_AUTONEG; arg->dl_mtu = ch->sdt.config.m; arg->dl_request |= DL_HP_DRV_MTU; #if 0 arg->dl_value1 = 0; arg->dl_request |= DL_HP_DRV_VALUE1; arg->dl_value2 = 0; arg->dl_request |= DL_HP_DRV_VALUE2; arg->dl_value3 = 0; arg->dl_request |= DL_HP_DRV_VALUE3; arg->dl_reserved1[0] = 0; arg->dl_request |= DL_HP_DRV_RESERVED1; arg->dl_reserved1[1] = 0; arg->dl_request |= DL_HP_DRV_RESERVED2; arg->dl_reserved2[0] = 0; arg->dl_request |= DL_HP_DRV_RESERVED3; arg->dl_reserved2[1] = 0; arg->dl_request |= DL_HP_DRV_RESERVED4; #endif return (0); } return (-ENOSR); } #endif /* DL_HP_GET_DRV_PARAM_IOCTL */ #ifdef DLPI_SET_NO_LOOPBACK noinline __unlikely int dl_set_no_loopback(struct xp *xp, mblk_t *dp) { switch (*(uint32_t *) dp->b_rptr) { case 0: case 1: return (0); default: return (-EINVAL); } } #endif /* DLPI_SET_NO_LOOPBACK */ /* * ========================================================================= * * X400P Interrupt Service Routine * * ========================================================================= * We break this out into E1 and T1 versions for speed. No need to check card type in the ISR when * it is static for the board. That is: boards do not change type from E1 to T1 or visa versa. */ /** xp_span_process: - process E1/T1/J1 span * @sp: span structure * @wspan: beg tx block pointer * @rspan: beg rx block pointer * @wend: end tx block pointer * @rend: end rx block pointer * * Process an entire E1/T1/J1 span. Process first as a High-Speed Link where all channels are * concatenated to form a signle link (chan == 0); then process the E1/T1/J1 channelized, one * channel at a time (chan != 0). */ noinline fastcall __hot void xp_span_process(struct sp *sp, uchar *wspan, uchar *rspan, uchar *wend, uchar *rend) { const int chanmax = (sp->config.ifgtype == SDL_GTYPE_E1) ? 31 : 24; int chan; for (chan = 0; chan <= chanmax; chan++) { struct ch *ch; if (likely((ch = sp->chans[chan]) != NULL)) { size_t coff; sdl_ulong ifflags; sdl_ulong iftype; prefetch(ch); coff = ((sp->config.ifgtype == SDL_GTYPE_E1) ? xp_e1_chan_map[chan] : xp_t1_chan_map[chan]) << 2; ifflags = ch->sdl.config.ifflags; iftype = ch->sdl.config.iftype; if (ifflags & SDL_IF_UP) { sdt_stats_t *stats = &ch->sdt.stats; prefetchw(stats); if (ifflags & SDL_IF_TX_RUNNING) xp_tx_block(ch, wspan + coff, wend, stats, iftype); else xp_tx_idle(wspan + coff, wend, iftype); if (ifflags & SDL_IF_RX_RUNNING) xp_rx_block(ch, rspan + coff, rend, stats, iftype); } else xp_tx_idle(wspan + coff, wend, iftype); } } } /** xp_card_tasklet: - process E1/T1/J1 card * @data: span structure (opaque) * * Process an entire E1/T1/J1 card as a tasklet. Each span is processed in order. Only one tx and * one rx elastic buffer block (8 frames for 4 spans) is processed at a time to avoid latency * issues. * * This tasklet is scheduled before the ISR returns to feed the next buffer of data into the write * buffer and read the buffer of data from the read buffer. This will run the soft-HDLC on each * channel for 8 more bytes, or if full span will run the soft-HDLC for 192 bytes (T1) or 256 bytes * (E1). */ STATIC __hot void xp_card_tasklet(unsigned long data) { struct cd *cd = (struct cd *) data; int uebno, reschedule = 0; psw_t flags; spin_lock_irqsave(&cd->lock, flags); if (likely((uebno = cd->uebno) != cd->lebno)) { if ((cd->uebno = (uebno + 1) & (X400P_EBUFNO - 1)) != cd->lebno) reschedule = 1; spin_unlock_irqrestore(&cd->lock, flags); { size_t boff = uebno << 10; uchar *wbeg = (uchar *) cd->wbuf + boff; uchar *wend = wbeg + 1024; uchar *rbeg = (uchar *) cd->rbuf + boff; uchar *rend = rbeg + 1024; int span; for (span = 0; span < cd->ports; span++) { struct sp *sp; if ((sp = cd->spans[span]) && (sp->config.ifflags & SDL_IF_UP)) { int soff = span_to_byte(span); xp_span_process(sp, wbeg + soff, rbeg + soff, wend, rend); } } } if (reschedule) tasklet_hi_schedule(&cd->tasklet); } else spin_unlock_irqrestore(&cd->lock, flags); } /** xp_overflow:- X400P Overflow * @cd: card structure * * I know that this is rather like kicking them when they are down, we are doing stats in the ISR * when takslets don't have enough time to run, but we are already in dire trouble if this is * happening anyway. It should not take too much time to peg these counts. */ noinline fastcall void xp_overflow(struct cd *cd) { int span; _printd(("%s: card %d elastic buffer overrun!\n", __FUNCTION__, cd->card)); for (span = 0; span < cd->ports; span++) { struct sp *sp; if ((sp = cd->spans[span]) && (sp->config.ifflags & SDL_IF_UP)) { switch (sp->config.iftype) { struct ch *ch; case SDL_TYPE_DS0: case SDL_TYPE_DS0A: { int chan; for (chan = 1; chan < 32; chan++) { if ((ch = sp->chans[chan]) && (ch->sdl.config.ifflags & SDL_IF_UP)) { if (ch->sdl.config.ifflags & SDL_IF_TX_RUNNING) { ch->sdl.stats.tx_underruns += 8; ch->sdt.stats.tx_underruns += 8; } if (ch->sdl.config.ifflags & SDL_IF_RX_RUNNING) { ch->sdl.stats.rx_overruns += 8; ch->sdt.stats.rx_overruns += 8; } } } break; } case SDL_TYPE_T1: case SDL_TYPE_J1: if ((ch = sp->chans[0]) && (ch->sdl.config.ifflags & SDL_IF_UP)) { if (ch->sdl.config.ifflags & SDL_IF_TX_RUNNING) { ch->sdl.stats.tx_underruns += 8 * 24; ch->sdt.stats.tx_underruns += 8 * 24; } if (ch->sdl.config.ifflags & SDL_IF_RX_RUNNING) { ch->sdl.stats.rx_overruns += 8 * 24; ch->sdt.stats.rx_overruns += 8 * 24; } } break; case SDL_TYPE_E1: if ((ch = sp->chans[0]) && (ch->sdl.config.ifflags & SDL_IF_UP)) { if (ch->sdl.config.ifflags & SDL_IF_TX_RUNNING) { ch->sdl.stats.tx_underruns += 8 * 31; ch->sdt.stats.tx_underruns += 8 * 31; } if (ch->sdl.config.ifflags & SDL_IF_RX_RUNNING) { ch->sdl.stats.rx_overruns += 8 * 31; ch->sdt.stats.rx_overruns += 8 * 31; } } break; default: { static unsigned long throttle = 0; if (throttle + 10 <= (volatile unsigned long) jiffies) break; throttle = (volatile unsigned long) jiffies; swerr(); break; } } } } } static noinline fastcall __hot void xp_t1_txrx_burst(struct cd *cd); static noinline fastcall __hot void xp_t1_process_span(struct cd *cd, struct sp *sp); static noinline fastcall __hot void xp_t1_process_timeout(struct cd *cd, struct sp *sp, volatile uint8_t *xlb, register uint flags); static noinline fastcall __hot void xp_t1_process_state(struct cd *cd, struct sp *sp, register volatile uint8_t *xlb, const register uint flags, const register uint errors); static noinline fastcall __hot void xp_t1_process_stats(struct sp *sp, register uint errors); static noinline fastcall __hot void xp_t1_process_alarms(struct cd *cd, struct sp *sp, register volatile uint8_t *xlb, register uint flags, uint timeout); static noinline fastcall __hot void xp_t1_eval_syncsrc(struct cd *cd); static noinline fastcall __unlikely void xp_t1_process_auto(struct cd *cd, struct sp *sp, register volatile uint8_t *xlb, register uint flags, const register uint errors, const uint timeout); noinline __unlikely int xp_t1_change_config(struct sp *sp, register volatile uint8_t *xlb); /** xp_t1_interrupt: - T400P-SS7 Interrupt Service Routine * @irq: interrupt number * @dev_id: card structure pointer (opaque) * @regs: interrupted registers * * The user will always preceed a read of any fo the SR1, SR2, and RIR registers with a write. The * user will write a byte to one of these registers, with a one in the bit positions he or she * wishes to read and a zero in the bit positions he or she does not wish to obtain the latest * information on. When a one is written to a bit location, the read register will be updated with * the latest information. When a zero is written to a bit position, the read register will not be * updated and the previous value will be held. A write to the status and information registers * will be immediated followed by a read of the same register. The read result should be logically * ANDed with the mask byte that was just written and this value should be written back to the same * register to insure that the bit does indeed clear. This second write step is necessary because * the alarms and events in the statue registers occur asyncrhonously in respect to their access * via the parallel port. This write-read-write scheme allows an external controller or * microprocessor to individually poll certain bits without disturbing the other bits in the * register. This operation is key in controlling the DS21354/DS21554 wtih higher-order software * languages. * * Process an interrupt for a T400P card (with a DS21352/DS21552 chip). The spans on this card can * only be E1 span. This is a departure from the previous driver which counted frames to determine * timeout events: here we utilize the Dallas interrupts available on the card for non-frame * events. This function should really be aligned on a page boundary and the functions that it * calls laid out immediately following the function, thus the forward declarations above. */ STATIC __hot irqreturn_t #ifdef HAVE_KTYPE_IRQ_HANDLER_2ARGS xp_t1_interrupt(int irq, void *dev_id) #else xp_t1_interrupt(int irq, void *dev_id, struct pt_regs *regs) #endif { static unsigned long lasttime = 0; struct cd *cd = (struct cd *) dev_id; int safety; /* Keep another processor from entering the interrupt while another is already processing the interrupt. This means that the top half of the driver must disable interrupts when taking the card lock to avoid deadly embrace. */ spin_lock(&cd->lock); /* active interrupt (otherwise spurious or shared) */ if (!(cd->xlb[STAREG] & (INTACTIVE | DINTACT))) { spin_unlock(&cd->lock); return (irqreturn_t) (IRQ_NONE); } if (likely(cd->xlb[STAREG] & INTACTIVE)) { cd->xlb[CTLREG] = cd->ctlreg | (INTENA | OUTBIT | DINTENA | INTACK); xp_t1_txrx_burst(cd); cd->xlb[CTLREG] = cd->ctlreg | (INTENA | DINTENA); } for (safety = 0; unlikely(cd->xlb[STAREG] & DINTACT); safety++) { uint span; struct sp *sp; /* We would like to try to keep this burning a loop here when there is only one span that is responsible for the Dallas interrupt; however, the DS21352/552 chips do not support an interrupt information register like the DS2155/455/458. */ for (span = 0; span < cd->ports; span++) if (likely((sp = cd->spans[span]) != NULL)) xp_t1_process_span(cd, sp); if (unlikely(safety > 8)) { /* throttle software error message */ if (lasttime == 0 || (jiffies - lasttime) > HZ) { lasttime = jiffies; swerr(); } break; } } /* Reevaluate the sync source when necessary. Try to skip the call here whenever possible to keep the ISR tight. */ if (unlikely(xchg((int *) &cd->eval_syncsrc, 0) != 0)) { if (cd->config.ifsyncsrc[0] != 0) xp_t1_eval_syncsrc(cd); } spin_unlock(&cd->lock); return (irqreturn_t) (IRQ_HANDLED); } /** xp_t1_txrx_burst: - burst transfer TX and RX data * @cd: card structure pointer * * This function is responsible for transfering frame data to and from the card. This is being * done with host driven I/O because the PLX9030 is incapable of bus mastering DMA. When the * memory mapped I/O region is properly described, PCI burst transfers will occur. Transfers are * 1024 bytes written and 1024 bytes read. These are interleaved, but might better be performed as * 4 Lword interleaved transfers. * * Note that this transfer is somewhat different form the one used for E1 or E1/T1/J1 cards because * it can skip words that correspond to ILB slots that are not used by T1. */ static noinline fastcall __hot void xp_t1_txrx_burst(struct cd *cd) { int lebno; if ((lebno = (cd->lebno + 1) & (X400P_EBUFNO - 1)) != cd->uebno) { register int slot; register volatile uint32_t *xll; register const uint32_t *wbuf = cd->wbuf + (lebno << 8); register const uint32_t *const wend = wbuf + 256; register uint32_t *rbuf = cd->rbuf + (lebno << 8); cd->lebno = lebno; for (xll = cd->xll; wbuf < wend;) for (wbuf++, rbuf++, xll++, slot = 1; slot < 32; slot++, xll++, wbuf++, rbuf++) if (slot & 0x3) { prefetch(wbuf + 2); prefetchw(rbuf + 2); *xll = *wbuf; *rbuf = *xll; } tasklet_hi_schedule(&cd->tasklet); } else xp_overflow(cd); } /** xp_t1_process_span: - process Dallas interrupts for a single span * @cd: card structure pointer * @sp: span structure pointer * * PERFORMANCE DEFECTS: * * XP_DEF_AIS: Alarm Indication Signal (AIS) Defect: * For D4 and ESF links, the 'all ones' condition is detected at a DS1 line interface upon * observing an unframed signal with a one's density of at least 99.9 percent present for a * time equal to or greater than T, where 3ms is less than or equal to T, which is less than or * equal to 75ms. The AIS is terminated upon observing a signal not meeting the one's density * of the unframed signal criteria for a period equal to or greater than T. For E1 links, the * 'all-ones' condition is detected at the line interface as a string of 512 bits containing * fewer than three zero bits. * * XP_DEF_OOF: Out of Frame (OOF) Defect: * An OOF defect is the occurrence of a particular density of Framing Error events. For T1 * links, an OOF defect is declared when the receiver detects two or more framing errors within * a 3 ms period for ESF signals and 0.75 ms for D4 signals, or two or more errors out of five, * or fewer consecutive framing-bits. For E1 links, an OOF defect is declared when three * consecutive frame alignment signals have been received with an error. When an OOF defect is * declared, the frame starts searching for a correct pattern. The OOF defect ends when the * signal is in-frame. In-frame occurs when there are fewer than two frame bit errors within a * 3 ms period for ESF signals and 0.75 ms for D4 signals. For E1 links, in-frame occurs when * in frame N, the frame alignment signal is correct; and, in frame N+1, the frame alignment * signal is absent (that is, bit 2 in TS0 is set to one); and, in frame N+2, the frame * alignment signal is present and correct. * * FAILURE STATES: The following failure states are received or detected failures that are * reported. The conditions under which a DS1 interface would, if ever, produce the conditions * leading to the failure state are described in the appropriate specification. * * XP_FAIL_AIS: Alarm Indication Signal (AIS) Failure: * The AIS failure is declared when an AIS defect is detected at the input and the AIS defect * still exists after the LOF failure (which is caused by the unframed nature of the all-ones * signal) is detected. The AIS failure is cleared when the LOF failure is cleared. * * XP_FAIL_FEA: Far End Alarm Failure (Yellow Alarm): * The Far End Alarm failure is also known as Yellow Alarm in the T1 cases and Distant Alarm * (or RAI) in the E1 case. For D4 links, the FEA failure is declared when bit 6 of all * channels have been zero for at least 335 ms and is cleared when bit 6 of at least one * channel is non-zero for a period T, where T is usually less than one second and alway less * than five seconds. The FEA failure is not declared for D4 links when LOS is detected. For * ESF links, the FEA failure is declared if the Yellow Alarm signal pattern occurs in a least * seven out of ten contiguous 16-bit-pattern intervals and is cleared if the Yellow Alarm * signal pattern does not occur in ten contiguous 16-bit signal pattern intervals. For E1 * links, the FEA failure is declared when bit 3 of time-slot zero is set to one on two * consecutive occasions. The FEA failure is cleared when bit 3 of time-slot zero is received * set to zero. * * XP_FAIL_FELOM: Far End Loss of Multiframe Failure: * The FELOM failure is declared when bit 2 of TS16 of frame 0 is received set to one on two * consecutive occasions. The FELOM failure is cleared when bit 2 of TS16 of frame 0 is * received set to zero. The FELOM failure can only be declared for E1 links operating in CAS * mode. * * XP_FAIL_LPF: Loopback Pseudo-Failure: * The LPF is declared when the near end equipment has placed a loop-back (of any kind) on the * DS1. This allows a management entity to determine from one object whether the DS1 can be * considered to be in service or not (from the point of view of the near-end equipment). * * XP_FAIL_LOF: Loss of Frame (LOF) Failure: * For T1 links, the LOF failure is declared with an OOF or LOS defect has persisted for T * seconds, where T is greater than or equal to two, but less than or equal to ten. The LOF * failure is cleared when there have been no OOF or LOS defects during a period T is greater * than or equal to two, but less than or equal to twenty. Many systems will perform "hit * integration" with the period T before declaring or clearing the failure. * * XP_FAIL_LOM: Loss of Multiframe (LOM) Failure: * The LOM failure is declared when two consecutive multi-frame alignment signals (bit 4 through 7 of TS16 of * frame 0) have been received wtih an error. The LOM failure is cleared when the first * correct multi-frame alignment signal is received. The LOM failure can only be declared for * E1 links operating with framing (sometimes called CAS mode). * * XP_FAIL_LOS: Loss of Signal (LOS) Failure: * For T1, the Loss of Signal failure is declared upon observing 175 +/- 74 contiguous pulse * position with no pulses of either positive or negative polarity. The LOS failure is cleared * upon observing an average pulse density of at least 12.5 percent over a period of 175 +/- 74 * contiguous pulse positions starting with the receipt of a pulse. * * XP_FAIL_T16AIS: T16 Alarm Indication Signal Failure: * For E1 links, the Ts16 Alarm Indication Signal failure is declared when time-slot 16 is * received as all ones for all frames of two consecutive multi-frames. This condition * is never declared for T1. */ static noinline fastcall __hot void xp_t1_process_span(struct cd *cd, struct sp *sp) { register volatile uint8_t *xlb = (typeof(xlb)) sp->iobase; register uint8_t status, mask; register uint errors = sp->status.errors; register uint flags = sp->status.flags; uint timeout = 0; if ((mask = xlb[0x7f])) { /* IMR1 */ /* write-read-write cycle */ xlb[0x20] = 0xff; status = xlb[0x20] & 0xff; xlb[0x20] = status; /* SR1.7: LUP: Loop Up Code Detected. Set when the loop up code as defined in the RUPCD register is being received. */ if (status & (1 << 7)) { flags |= XP_STATE_LUP; } else if (mask & (1 << 7)) { flags &= ~XP_STATE_LUP; } /* SR1.6: LDN: Loop Down Code Detected. Set when the loop down code as defined in the RDNCD register is being received. */ if (status & (1 << 6)) { flags |= XP_STATE_LDN; } else if (mask & (1 << 6)) { flags &= ~XP_STATE_LDN; } /* SR1.5: LOTC: Loss of Transmit Clock. Set when the TCLK pin has not transitioned for one channel time (or 5.2us). Will force the RLOS/LOTC pin high if enabled via CCR1.6. Also will force transmit side formatter to switch to RCLK if so enabled via TCR1.7. */ if (status & (1 << 5)) { flags |= XP_STATE_LOTC; } else if (mask & (1 << 5)) { flags &= ~XP_STATE_LOTC; } /* SR1.4: RSLIP: Receive Elastic Store Slip Occurrence. Set when the receive elastic store has either repeated or deleted a frame. */ if (status & (1 << 4)) { errors |= XP_ERR_CSS; } /* SR1.3: RBL: Receive Blue Alarm. Set when an unframed all one's code is received at RPOSI and RNEGI. */ if (status & (1 << 3)) { flags |= XP_STATE_RUA1; } else if (mask & (1 << 3)) { flags &= ~XP_STATE_RUA1; } /* SR1.2: RYEL: Receive Yellow Alarm. Set when a yellow alarm is received at RPOSI and RNEGI. */ if (status & (1 << 2)) { flags |= XP_STATE_RYEL; } else if (mask & (1 << 2)) { flags &= ~XP_STATE_RYEL; } /* SR1.1: LRCL: Line Interface Receive Carrier Loss. Set when a red alarm is received at RTIP and RRING. */ if (status & (1 << 1)) { flags |= XP_STATE_LRCL; } else if (mask & (1 << 1)) { flags &= ~XP_STATE_LRCL; } /* SR1.0: RLOS: Receive Loss of Sync. Set when the device is not syncrhonized to the receive T1 stream. */ if (status & (1 << 0)) { flags |= XP_STATE_RLOS; } else if (mask & (1 << 0)) { flags &= ~XP_STATE_RLOS; } } if ((mask = xlb[0x6f])) { /* IMR2 */ /* write-read-write cycle */ xlb[0x21] = 0xff; status = xlb[0x21] & 0xff; xlb[0x21] = status; /* SR2.7: RMF: Receive Multiframe. Set on receive multiframe boundaries. */ if (status & (1 << 7)) { } else if (mask & (1 << 7)) { } /* SR2.6: TMF: Transmit Multiframe. Set on transmit multiframe boundaries. */ if (status & (1 << 6)) { } else if (mask & (1 << 6)) { } /* SR2.5: SEC: One Second Timer. Set on increments of one second based on RCLK; will be set in increments of 999ms, 999ms and 1002ms every 3 seconds. */ if (status & (1 << 5)) { timeout = 1; } /* SR2.4: RFDL: Receive FDL Buffer Full. Set when the receive FDL buffer (RFDL) fills to capacity (8 bits). */ if (status & (1 << 4)) { } else if (mask & (1 << 4)) { } /* SR2.3: TFDL: Transmit FDL Buffer Empty. Set when the transmit FDL bfufer (TFDL) empties. */ if (status & (1 << 3)) { } else if (mask & (1 << 3)) { } /* SR2.2: RMTCH: Receive FDL Match Occurence. Set when the RFDL matches either RFDLM1 or RFDLM2. */ if (status & (1 << 2)) { } else if (mask & (1 << 2)) { } /* SR2.1: RAF: Receive FDL Abort. Set when eight consecutive one's are received in the FDL. */ if (status & (1 << 1)) { } else if (mask & (1 << 1)) { } /* SR2.0: RSC: Receive Signaling Change. Set when the DS21352/DS21552 detects a change of state in any of the robbed-bit signalling bits. */ if (status & (1 << 0)) { } else if (mask & (1 << 0)) { } } /* Note: at this point, any Dallas interrupt should have been cleared by reading the interrupt bits. Dallas interrupts generated by the IMR registers are acknowledged by reading the corresponding bit of the SR registers. */ if (timeout) xp_t1_process_timeout(cd, sp, xlb, flags); /* Note that alarms are processed asyncrhonously whereas interface state is only processed during timeouts. This keeps the interface state from thrashing around and detection mechanisms falsely triggering on transient conditions. */ if ((flags ^ sp->status.flags) != 0) xp_t1_process_alarms(cd, sp, xlb, flags, timeout); } /** xp_t1_process_timeout: - process timeout for a span * @cd: card structure (locked) * @sp: span structure * @xlb: span iobase pointer * @flags: span flags */ static noinline fastcall __hot void xp_t1_process_timeout(struct cd *cd, struct sp *sp, volatile uint8_t *xlb, register uint flags) { register uint mask, status; register uint errors = sp->status.errors; uint count; /* Read information registers and report */ mask = 0xff; /* write-read-write cycle */ xlb[0x22] = mask; status = xlb[0x22] & mask; xlb[0x22] = status; if (status) { /* RIR1.7: COFA: change of Frame Alignment. Set when the last resync resulted in a change of multiframe alignment. */ /* RIR1.0: FBE: Frame Bit Error. Set when a Ft (D4) or FPS (ESF) framing bit is received in error. Note that the count of these errors can be returned in the MOSCR error counter. */ if (status & ((1 << 7) | (1 << 0))) { errors |= XP_ERR_FASE; } /* RIR1.6: 8ZD: Eight Zero Detect. Set when a string of at least eight consecutive zeros (regardless of the length of the string) have been received at RPOSI and RNEGI. Note that the count of these errors can be returned in the LCVCR error counter. */ /* RIR1.5: 16ZD: Sixteen Zero Detect. Set when a string of at least sixteen consecutive zeros (reagardless of the length of the string) have been received at RPOSI and RNEGI. Note that the count of these errors can be returned in the LCVCR error counter. */ if (status & ((1 << 6) | (1 << 5))) { errors |= XP_ERR_LCV; } /* RIR1.4: RESF: Receive Elastic Store Full. Set when the receive elastic store buffer fills and a frame is deleted. */ /* RIR1.3: RESE: Receive Elastic Store Empty. Set when the receive elasitc store buffer emtpies and a frame is repeated. */ if (status & ((1 << 4) | (1 << 3))) { errors |= XP_ERR_CSS; } /* RIR1.2: SEFE: Severely Errorred Framing Event. Set when 2 out of 6 framing bits (Ft or FPS) are received in error. */ if (status & (1 << 2)) { errors |= XP_ERR_SEFS; } /* RIR1.1: B8ZS: B8ZS Code Word Detect. Set when a B8ZS code word is detected at RPOSI and RNEGI independent of whether the B8ZS mode is selected or not via CCR2.6. Useful for automatically setting the line coding. */ if (status & (1 << 1)) { /* A B8ZS codeword was detected. When we are set to T1 AMI and there are no bipolar violations, and a B8ZS codeword is detected, this certainly means that the line coding should be B8ZS instead of AMI. However, SS7 links are always B8ZS. */ if (sp->config.ifcoding == SDL_CODING_AMI) { errors |= XP_ERR_B8ZS; } } } mask = ((1 << 7) | (1 << 6) | (1 << 5) | (1 << 4) | (1 << 3) | (1 << 2) | (1 << 1) | (1 << 0)); /* write-read-write cycle */ xlb[0x31] = mask; status = xlb[0x31] & mask; xlb[0x31] = status; if (status) { /* RIR2.7: RLOSC: Receive Loss of Sync Clear. Set when the framer achieves synchronization; will remain set until read. */ if (status & (1 << 7)) flags &= ~XP_STATE_RLOS; /* RIR2.6: LRCLC: Line Interface Receive Carrier Lost Clear. Set when the carrier signal is restored; will reamin set util read. */ if (status & (1 << 6)) flags &= ~XP_STATE_LRCL; /* RIR2.5: TESF: Transmit Elastic Store Full. Set when the transmit elastic store buffer fills and a frame is deleted. */ /* RIR2.4: TESE: Transmit Elastic Store Empty. Set when the transmit elastic store buffer empties and a frame is repeated. */ /* RIR2.3: TSLIP: Transmit Elastic Store Slip Occurrence. Set when the transmit elastic store has either repeated or deleted a frame. */ if (status & ((1 << 5) | (1 << 4) | (1 << 3))) errors |= XP_ERR_CSS; /* RIR2.2: RBLC: Receive Blue Alarm Clear. Set when the blue alarm (AIS) is no longer detected; will remain set until read. */ if (status & (1 << 2)) flags &= ~XP_STATE_RUA1; /* RIR2.1: RPDV: Receive Pulse Density Violation. Set when the receive data stream does not meet the ANSI T1.403 requirements for pulse density. */ /* RIR2.0: TPDV: Transmit Pulse Density Violation. Set when the transmit data stream does not meet the ANSI T1.403 requirements for pulse density. */ if (status & ((1 << 1) | (1 << 0))) errors |= XP_ERR_PDV; } mask = ((1 << 7) | (1 << 6) | (1 << 5) | (1 << 4) | (1 << 3)); /* write-read-write cycle */ xlb[0x10] = mask; status = xlb[0x10] & mask; xlb[0x10] = status; sp->config.ifrxlevel = ((status & 0xc0) >> 6); if (status) { /* RIR3.5: JALT: Jitter Attenuation Trip Limit. Set when the jitter attenuator FIFO reaches to within 4 bits of its limit; useful for debugging jitter attenuation operation. */ if (status & (1 << 5)) { flags |= XP_STATE_JALT; errors |= XP_STATE_JALT; } /* RIR3.4: LORC: Loss of Receive Clock. Set when the RCLKI pin has not transitioned for at least 2us (4 us max). */ if (status & (1 << 4)) { flags |= XP_STATE_LORC; errors |= XP_STATE_LORC; } else flags &= ~XP_STATE_LORC; /* RIR3.3: FRCL: Framer Receive Carrier Loss. Set when 192 consecutive zeroes have been received at RPOSI and RNEGI pins; allowed to be cleared when 14 or more ones out of 112 possible bit positions are received. */ if (status & (1 << 3)) { flags |= XP_STATE_FRCL; errors |= XP_STATE_FRCL; } else flags &= ~XP_STATE_FRCL; /* RIR3.7-6: RL1-RL0: Receive Level. 00, +2dB to -7.5dB; 01, -7.5dB to -15dB; 10, -15dB to -22.5dB; 11, less than -22.5dB. */ if ((status & ((1 << 7) | (1 << 6))) == ((1 << 7) | (1 << 6))) flags |= XP_STATE_ILUT; else flags &= ~XP_STATE_ILUT; } mask = ((1 << 2) | (1 << 3) | (1 << 4)); /* write-read-write cycle */ xlb[0x22] = mask; /* RIR1 */ status = xlb[0x22] & mask; xlb[0x22] = status; if (status) { /* RIR1.4: RESF: Receive Elastic Store Full. */ /* RIR1.3: RESE: Receive Elastic Store Empty. */ if ((mask & ((1 << 3) | (1 << 4))) && (status & ((1 << 3) | (1 << 4)))) { errors |= XP_ERR_CSS; /* controlled slip */ errors |= XP_ERR_ES; } /* RIR1.2: SEFE: Severely Errorred Framing Event. */ if ((mask & (1 << 2)) && (status & (1 << 2))) { errors |= XP_ERR_SEFS; /* severely errored frame */ } } mask = ((1 << 3) | (1 << 4) | (1 << 5)); /* write-read-write cycle */ xlb[0x31] = mask; status = xlb[0x31] & mask; xlb[0x31] = status; if (status) { /* RIR2.5: TESF: Transmit Elastic Store Full. */ /* RIR2.4: TESE: Transmit Elastic Store Empty. */ /* RIR2.3: TSLIP: Transmit Elastic Store Slip Occurrence. */ if ((mask & ((1 << 3) | (1 << 4) | (1 << 5))) && (status & ((1 << 3) | (1 << 4) | (1 << 5)))) { errors |= XP_ERR_CSS; /* controlled slip */ errors |= XP_ERR_ES; } } /* The number of Line Code Violations (LCVs) in the current interval. An LCV is the occurrence of a Bipolar Violation (BPV) or Excessive Zeros (EXZ) error event. */ /* RCR1.7: LCVCRF: Line Code Violation Count Register Function Select. 0, do not count excessive zeros; 1, count excessive zeros. */ /* The 16-bit line code violation LCV count register reports code violations (CV). CV are defined as Bipolar Violations (BPVs) or excessive zeros. If the B8ZS mode is set for the receive side via CCR2.2, then B8ZS code words are not counted. This counter is always enabled; it is not disabled during receive loss of synchronization (RLOS=1) conditions. */ if ((count = (((uint) xlb[0x23] << 8) + ((uint) xlb[0x24])))) { sp->stats[0].LCVs += count; errors |= XP_ERR_LCV; /* line code violation */ } /* The number of Path Coding Violations (PCVs) in the current interval. A Path Coding Violation is a frame synchronization bit error in the D4 and E1 no-CRC4 formats, or a CRC or frame synchronization bit error in the ESF and E1 CRC4 formats. */ /* RCR2.1: FSBE: PCVCR Fs-Bit Error Report Enable. 0, do not report bit errors in Fs-bit position; only Ft bit position; 1, report bit errors in Fs-bit position as well as Ft-bit position. */ /* The 12-bit path code violation (PCV) counter records errors in the CRC6 code words. When set to operate in the D4 framing mode (CCR2.3=0), PCVCR will automatically count errors in the Ft framing bit position. Via the RCR2.1 bit, a framer can be programmed to also report errors in the Fs framing bit position. The PCVCR will be disabled during receive loss of synchronization (RLOS=1) conditions. */ /* CCR2.3=D4, RCR2.1=no, errors in the Ft pattern. */ /* CCR2.3=D4, RCR2.1=yes, errors in both the Ft and Fs pattern. */ /* CCR2.3=ESF, RCR2.1=don't care, errors in the CRC6 code words. */ /* NOTE: when in the ESF mode, a steady stream of PCVs might indicate that CRC6J should be set instead of CRC6, or vise versa. */ if ((count = (((uint) (xlb[0x25] & 0x0f) << 8) + ((uint) xlb[0x26])))) { sp->stats[0].PCVs += count; errors |= XP_ERR_PCV; /* path code violation */ errors |= XP_ERR_ES; } /* the number of Multi-frames Out Of Sync(LOFs) in the current interval. A Loss of Frame count (LOFs) is the number of multi-frames that the receive synchronizer is out of sync. This may also be a count of errors in the Ft framing pattern in D4 mode, or errors in the FPS framing patter in the ESF mode. */ /* RCR2.0: MOSCRF: Multi-frame Out of Sync Count Register Function Select. 0, count errors in the framing bit position; 1, count the number of multi-frames out of sync. */ if ((count = (((uint) (xlb[0x25] & 0xf0) << 4) + ((uint) xlb[0x27])))) { sp->stats[0].FASEs += count; errors |= XP_ERR_FASE; errors |= XP_ERR_ES; } xp_t1_process_state(cd, sp, xlb, flags, errors); /* CCR3.2: ECUS: 0 = 8000 frames, 1 = 333 frames */ if ((sp->interval += (xlb[0x30] & 0x04) ? 333 : 8000) >= 8000) { sp->interval -= 8000; /* this is a 1 second timeout */ xp_t1_process_stats(sp, errors); sp->status.errors = 0; } else sp->status.errors = errors; return; } /** xp_t1_process_state: - process state transitions for the device. * @cd: card structure pointer * @sp: span structure pointer * @xlb: span iobase * @flags: state flags (read only) * @errors: error flags (read only) * * Process state transitions once a timeout. This is to ensure that the interface state does not * change due to transient conditions of less than 40 ms. Also, any events or errors here have * accumulated for the entire timeout period (more than 40 ms). * * Processing DS21352/552 state transitions is more difficult because there is no transmitter * open-circuit detection capability on the chip, making transmitter state difficult to determine. * Also, receiver input level determination is rather limited in range. Both these deficiencies * make it difficult to automatically determine whether a span is in a monitor configuration or not * and whether linear gain should be applied to the receivers. * * The approach is to take the transmitters offline altogether, and check whether a synced receive * side is indicating a yellow alarm. When the receiver is synced and there is no yellow alarm, * the transmitters are not connected to the line. When the receivers won't sync but there is no * carrier loss, we can use the input level somewhat, and possibly some errors, to determine * whether linear gain should be applied. When there is no carrier for some time, we can go ahead * and try applying linear gain. A new line interface receive carrier loss should start the * process all over again so that when a line is disconnected and then reconnected, it will * autoconfigure again. * * To perform all of these actions, we run a state machine and keep a state variable in * sp->status.state. A state transition is performed at most once every 42/62 ms (short timeout). * The current state and the condition of the state flags and current errors are used to determine * the next state. */ static noinline fastcall __hot void xp_t1_process_state(struct cd *cd, struct sp *sp, register volatile uint8_t *xlb, const register uint flags, const register uint errors) { register uint ifflags = sp->config.ifflags; /* State flags that we set: XP_STATE_LUP, XP_STATE_LDN, XP_STATE_LOTC, XP_STATE_RUA1, XP_STATE_RYEL, XP_STATE_LRCL, XP_STATE_RLOS, XP_STATE_LORC, XP_STATE_FRCL, XP_STATE_ILUT (but not as good as DS2155). */ /* integrate receiver state */ if (flags & (XP_STATE_LRCL | XP_STATE_FRCL)) { ifflags &= ~SDL_IF_RX_UP; ifflags &= ~SDL_IF_RX_RUNNING; } else { ifflags |= SDL_IF_RX_UP; if (flags & (XP_STATE_RLOS | XP_STATE_RUA1 | XP_STATE_LORC)) ifflags &= ~SDL_IF_RX_RUNNING; else ifflags |= SDL_IF_RX_RUNNING; } /* Note the DS21352/552 does not actually provide open-circuit or short-circuit transmitter detection. The flags are there for the DS2155/455/458 chips. To establish that the transmitters are open-circuited we need to transmit unframed all ones and detect the remote AIS indication from the far end. In fact, the only semi-useful flags we have is XP_STATE_LOTC. */ /* integrate transmitter state */ if (flags & (XP_STATE_TOCD | XP_STATE_TSCD)) { ifflags &= ~SDL_IF_TX_UP; ifflags &= ~SDL_IF_TX_RUNNING; } else { ifflags |= SDL_IF_TX_UP; if (flags & (XP_STATE_LOLITC | XP_STATE_LOTC)) ifflags &= ~SDL_IF_TX_RUNNING; else ifflags |= SDL_IF_TX_RUNNING; } if (!(ifflags & SDL_IF_RX_UP)) { ifflags &= ~SDL_IF_TX_UP; ifflags &= ~SDL_IF_TX_RUNNING; } /* integrate interface state */ if (flags & (SDL_IF_RX_UP | SDL_IF_TX_UP)) ifflags |= SDL_IF_UP; else ifflags &= ~SDL_IF_UP; /* detect changes in transmitter state */ if ((ifflags ^ sp->config.ifflags) & (SDL_IF_TX_UP | SDL_IF_TX_RUNNING)) { } /* detect changes in receiver state */ if ((ifflags ^ sp->config.ifflags) & (SDL_IF_RX_UP | SDL_IF_RX_RUNNING)) { } /* detect changes in interface state */ if ((ifflags ^ sp->config. ifflags) & (SDL_IF_UP | SDL_IF_TX_UP | SDL_IF_RX_UP | SDL_IF_TX_RUNNING | SDL_IF_RX_RUNNING)) { } /* perform autoconfiguration when necessary */ if (ifflags & SDL_IF_AUTOCONFIG) { if (likely(sp->status.state == 40)) { if (unlikely((flags & (XP_STATE_LRCL)) != 0)) /* lost carrier, start full autoconfig */ sp->status.state = 0; else if (unlikely((flags & (XP_STATE_FRCL)) != 0)) /* lost signal, start partial autoconfig */ sp->status.state = 20; } if (unlikely(sp->status.state != 40)) /* lost configuration hold, process autoconfig */ xp_t1_process_auto(cd, sp, xlb, flags, errors, 1); } } /** xp_t1_process_auto: - process autoconfiguration state machine * @cd: card structure pointer * @sp: span structure pointer * @xlb: span iobase * @flags: state flags * @errors: error events * @timeout: true when timeout * * Note that we do not even execute this function unless SDL_IF_AUTOCONFIG is set in the interface * flags. The function is executed on regular interrupts as well as timeout interrupts. The * @timeout argument is set when the interrupt was as a result of a timeout, and Unset otherwise. * This permits having the autodetection state machine run very quickly for expected * configurations. * * The DS21352/552 chip can perform linear gain for monitoring applications of 12dB or 20dB. 20dB * corresponds to 432-470 Ohm isolation resistors on a single high-impedance monitoring tap. 12dB * linear gain (corresponding to 150 Ohm isolation resistors) is not useful for monitoring * applications. */ static noinline fastcall __unlikely void xp_t1_process_auto(struct cd *cd, struct sp *sp, register volatile uint8_t *xlb, register uint flags, const register uint errors, const uint timeout) { register uint state = sp->status.state; const uint interval = timeout ? ((xlb[0x30] & 0x04) ? 333 : 8000) : 0; for (;;) { do { if (flags & XP_STATE_LIRST) { /* resetting line interface */ sp->status.count = 0; sp->status.config = 0; state = 0; break; } if ((flags & XP_STATE_LRCL) && (state >= 8)) { /* lost line carrier */ sp->status.count = 0; state = 0; break; } if ((flags & XP_STATE_FRCL) && (state >= 9)) { /* lost framer signal */ sp->status.count = 0; state = 8; break; } if ((flags & XP_STATE_RUA1) && (state >= 10)) { /* lost service */ sp->status.count = 0; state = 9; break; } if ((flags & XP_STATE_RLOS) && (11 <= state && state < 13)) { /* lost sync */ sp->status.count = 0; state = 10; break; } } while (0); switch (state) { default: state = 0; /* fall through */ case 0: /* LIRST subsidance. Wait 125 ms or more when the LIRST condition remains, then clear the condition and move on to line detection. */ if (flags & (XP_STATE_LIRST)) { if ((sp->status.count += interval) < 1000) { /* wait for up to 125 ms */ break; } /* remove LIRST flag */ sp->status.flags &= ~(XP_STATE_LIRST); flags &= ~(XP_STATE_LIRST); /* reset elastic stores */ /* CCR7.5: RESR: Receive Elastic Store Reset. toggle to reset. */ /* CCR7.4: TESR: Transmit Elastic Store Reset. toggle to reset. */ xlb[0x0a] &= ~((1 << 5) | (1 << 4)); xlb[0x0a] |= (1 << 5) | (1 << 4); xlb[0x0a] &= ~((1 << 5) | (1 << 4)); /* realign elastic stores */ /* CCR6.6: RESA: Receive Elastic Store Align. toggle to align. */ /* CCR6.5: TESA: Transmit Elastic Store Align. toggle to align. */ xlb[0x1e] &= ~((1 << 6) | (1 << 5)); xlb[0x1e] |= (1 << 6) | (1 << 5); xlb[0x1e] &= ~((1 << 6) | (1 << 5)); } /* remove linear gain */ xlb[0x09] = 0x00; /* set 0dB CSU */ xlb[0x7c] &= ~((1 << 7) | (1 << 6) | (1 << 5)); /* start transmitter */ /* LICR.0: TPD: Transmit Power Down. 0 = normal; 1 = power-down. */ xlb[0x7c] &= ~(1 << 0); /* send unframed all ones */ /* TCR1.1=0: TBL: Transmit Blue Alarm. 0 = normal; 1 = tx unframed all ones. */ xlb[0x35] |= (1 << 1); /* set count and flags */ sp->status.count = 0; sp->config.ifflags &= ~(SDL_IF_UP | SDL_IF_RX_UP | SDL_IF_TX_UP | SDL_IF_RX_MON); state = 1; /* fall through */ case 1: /* Line carrier detect, 0dB gain. */ if (flags & (XP_STATE_LRCL)) { if ((sp->status.count += interval) >= 1000) { /* try applying linear gain */ /* apply 12dB linear gain */ xlb[0x09] = 0x72; sp->status.count = 0; state = 2; continue; } /* wait for up to 125 ms */ break; } /* start transmitter */ /* LICR.0: TPD: Transmit Power Down. 0 = normal; 1 = power-down. */ xlb[0x7c] &= ~(1 << 0); sp->config.ifflags &= ~SDL_IF_RX_MON; sp->status.count = 0; state = 8; continue; case 2: /* Line carrier detect, monitoring, 12dB gain. No line carrier was detected with 0dB linear gain, try applying 12dB gain. */ if (flags & (XP_STATE_LRCL)) { if ((sp->status.count += interval) >= 1000) { /* try applying more linear gain */ /* apply 20dB linear gain */ xlb[0x09] = 0x70; sp->status.count = 0; state = 3; continue; } /* wait for up to 125 ms */ break; } sp->status.count = 0; state = 5; continue; case 3: /* Line carrier detect, monitoring, 20dB gain. No line carrier was detected with 0dB and 12dB linear gain, try applying 20dB gain. */ if (flags & (XP_STATE_LRCL)) { if ((sp->status.count += interval) >= 1000) { /* try removing gain again */ /* apply 0dB linear gain */ xlb[0x09] = 0x00; sp->status.count = 0; state = 1; continue; } /* wait for up to 125 ms */ break; } /* apply 12dB linear gain */ sp->status.count = 0; state = 4; /* fall through */ case 4: /* Line carrier detected, monitoring, 12dB gain. 20dB gain was applied previously with success, drop back to 12dB gain to test that things were not just connected at a bad time. */ if (flags & (XP_STATE_LRCL)) { if ((sp->status.count += interval) >= 1000) { /* put back to 20dB gain */ /* apply 20dB linear gain */ xlb[0x09] = 0x70; sp->status.count = 0; state = 6; continue; } /* wait for 125 ms */ break; } /* apply 0dB linear gain */ sp->status.count = 0; state = 5; /* fall through */ case 5: /* Line carrier detected, monitoring, 0dB gain. 12dB gain was applied previously with success, drop back to 0dB gain to test that things were not just connected at a bad time. */ if (flags & (XP_STATE_LRCL)) { if ((sp->status.count += interval) >= 1000) { /* put back to 12dB gain */ /* apply 12dB linear gain */ xlb[0x09] = 0x72; sp->status.count = 0; state = 7; continue; } /* wait for 125 ms */ break; } /* start transmitter */ /* LICR.0: TPD: Transmit Power Down. 0 = normal; 1 = power-down. */ xlb[0x7c] &= ~(1 << 0); sp->config.ifflags &= ~SDL_IF_RX_MON; sp->status.count = 0; state = 8; continue; case 6: /* Line carrier detected, monitoring, 20dB gain. 20dB worked, 12dB didn't, go back to 20dB and lock in if successful. */ if (flags & (XP_STATE_LRCL)) { if ((sp->status.count += interval) >= 1000) { /* 20dB worked before but doesn't now, start again */ /* apply 0dB linear gain */ xlb[0x09] = 0x00; sp->status.count = 0; state = 0; continue; } /* wait for 125 ms */ break; } /* stop transmitter */ /* LICR.0: TPD: Transmit Power Down. 0 = normal; 1 = power-down. */ xlb[0x7c] |= (1 << 0); sp->config.ifflags |= SDL_IF_RX_MON; sp->status.count = 0; state = 8; continue; case 7: /* Line carrier detected, monitoring, 12dB gain. 12dB worked, 0dB didn't, go back to 12dB and lock in if successful. */ if (flags & (XP_STATE_LRCL)) { if ((sp->status.count += interval) >= 1000) { /* 12dB worked before but doesn't now, start again */ /* apply 0dB linear gain */ xlb[0x09] = 0x00; sp->status.count = 0; state = 0; continue; } /* wait for 125 ms */ break; } /* stop transmitter */ /* LICR.0: TPD: Transmit Power Down. 0 = normal; 1 = power-down. */ xlb[0x7c] |= (1 << 0); sp->config.ifflags |= SDL_IF_RX_MON; sp->status.count = 0; state = 8; continue; case 8: /* Framer signal detect. Line carrier detected, 0dB, 12dB or 20dB linear gain applied. When other than 0dB linear gain is applied, SDL_IF_RX_MON flag is set. */ if (flags & (XP_STATE_FRCL)) { if ((sp->status.count += interval) >= 1000) { /* no framer signal, start again */ sp->status.count = 0; state = 0; continue; } /* wait for 125 ms */ break; } sp->status.count = 0; state = 9; /* fall through */ case 9: /* Framing detect, sending unframed all ones. If we are in a loop-around mode we will wait here for manual (specific) configuration because we will be both sending and receiving unframed all ones. However, only wait for 10 seconds and then restart in case there is an error in the state machine that locks us here. */ if (flags & (XP_STATE_RUA1)) { if ((sp->status.count += interval) >= 10 * 8000) { /* no service for 10 seconds, start again */ sp->status.count = 0; state = 0; continue; } /* wait up to 10 seconds */ break; } sp->status.count = 0; state = 10; /* fall through */ case 10: /* Frame detect, not receiving unframed all ones. */ if (flags & (XP_STATE_RLOS)) { if ((sp->status.count += interval) >= 3200) { /* no sync after 400 ms */ /* reconfigure and try again */ if (xp_t1_change_config(sp, xlb)) { /* exhausted possibilities, start again */ sp->status.count = 0; state = 0; continue; } sp->status.count = 0; /* wait to test possibility */ break; } /* wait for up to 400 ms */ break; } sp->status.count = 0; state = 11; /* fall through */ case 11: /* Transmitter detection, transmitting unframed all ones. We are transmitting unframed all ones, so when there is no remote alarm after 125 ms the transmitters must be disconnected. */ if (!(flags & (XP_STATE_RYEL | XP_STATE_RRA))) { if ((sp->status.count += interval) >= 1000) { /* No alarm after 125 milliseconds, transmitters must be disconnected. When no linear gain is applied, but transmitters are disconnected: this is a 0dB active monitoring tap. When linear gain applied, already monitoring so this is an expected result. */ /* stop transmitter */ /* LICR.0: TPD: Transmit Power Down. 0 = normal; 1 = power-down. */ xlb[0x7c] |= (1 << 0); sp->config.ifflags |= SDL_IF_RX_MON; sp->config.ifflags &= ~(SDL_IF_TX_UP); sp->config.ifflags |= (SDL_IF_RX_UP | SDL_IF_UP); sp->status.count = 0; state = 13; continue; } /* wait up to 125 ms */ break; } /* transmit normal frames */ /* TCR1.1=0: TBL: Transmit Blue Alarm. 0 = normal; 1 = tx unframed all ones. */ xlb[0x35] &= ~(1 << 1); sp->status.count = 0; state = 12; /* fall through */ case 12: /* Transmitter detection, sending normal frames. We previously had a remote alarm condition when sending unframed all ones. We start sending normal frames and check that the alarm clears within 10 seconds. */ if (flags & (XP_STATE_RYEL | XP_STATE_RRA)) { if ((sp->status.count += interval) < 10 * 8000) { /* wait up to 10 seconds */ break; } /* Alarms did not clear after 10 seconds, but this might just be a sync problem. */ } /* start transmitter */ /* LICR.0: TPD: Transmit Power Down. 0 = normal; 1 = power-down. */ xlb[0x7c] &= ~(1 << 0); sp->config.ifflags &= ~SDL_IF_RX_MON; sp->config.ifflags |= (SDL_IF_TX_UP); sp->config.ifflags |= (SDL_IF_RX_UP | SDL_IF_UP); sp->status.count = 0; state = 13; /* fall through */ case 13: /* Stable state, normal mode, transmitters externally connected, sending normal frames. This is an active connection, not a monitoring tap. Flags have been set accordingly. Stay in this state unless we lose carrier, signal, start receiving unframed all ones, or lose sync for more than 400 ms. */ /* Stable state, monitoring mode, transmitters externally disconnected, sending unframed all ones. This is a monitoring tap (active or passive). Flags have been set accordingly. Stay in this state unless we lose carrier, signal, start receiving unframed all ones, or lose sync for more than 400 ms. */ if (flags & (XP_STATE_RLOS)) { /* lost sync */ if ((sp->status.count += interval) >= 3200) { /* send unframed all ones */ /* TCR1.1=0: TBL: Transmit Blue Alarm. 0 = normal; 1 = tx unframed all ones. */ xlb[0x35] |= (1 << 1); sp->status.count = 0; state = 10; continue; } /* wait for up to 400 ms */ break; } sp->status.count = 0; /* stay in this state */ break; } break; } /* set the new state variable */ sp->status.state = state; } /** xp_t1_change_config: - try changing span configuration for sync * @sp: span structure pointer * @xlb: span iobase * * Diagnose the problem of not acheiving frame synchronization and attempt to change the * configuration accordingly. This is a T1 line so likely difficulties are ESF framing instead of * D4 framing; CRC6 instead of CRC6J; B8ZS instead of AMI. We should simply walk through the * possible configurations until one that works is found or all are exhausted. */ noinline __unlikely int xp_t1_change_config(struct sp *sp, register volatile uint8_t *xlb) { switch (sp->status.config) { case 0: /* ESF, B8ZS, CRC6. */ if (!ansi || japan) { sp->config.ifgtype = SDL_GTYPE_J1; if (sp->config.ifframing != SDL_FRAMING_ESF) { sp->config.ifframing = SDL_FRAMING_ESF; xlb[0x38] |= (1 << 7); /* CCR2.7: 1 = Tx ESF */ xlb[0x38] |= (1 << 3); /* CCR2.3: 1 = Rx ESF */ xlb[0x38] &= ~(1 << 5); /* CCR2.5: 0 = Tx no SLC-96 */ } if (sp->config.ifcoding != SDL_CODING_B8ZS) { sp->config.ifcoding = SDL_CODING_B8ZS; xlb[0x38] |= (1 << 6); /* CCR2.6: 1 = Tx B8ZS */ xlb[0x38] |= (1 << 2); /* CCR2.2: 1 = Rx B8ZS */ } if (sp->config.ifgcrc != SDL_GCRC_CRC6J) { sp->config.ifgcrc = SDL_GCRC_CRC6J; xlb[0x19] |= (1 << 7); /* CCR5.7: 1 = Tx CRC6J */ xlb[0x1e] |= (1 << 7); /* CCR6.7: 1 = Rx CRC6J */ xlb[0x36] |= (1 << 1); /* TCR2.1: 1 = fr 12 */ xlb[0x2c] |= (1 << 2); /* RCR2.2: 1 = fr 12 */ } sp->status.config = 1; break; } /* fall through */ case 1: /* ESF, B8ZS, CRC6J. */ if (ansi || !japan) { sp->config.ifgtype = SDL_GTYPE_T1; if (sp->config.ifframing != SDL_FRAMING_ESF) { sp->config.ifframing = SDL_FRAMING_ESF; xlb[0x38] |= (1 << 7); /* CCR2.7: 1 = Tx ESF */ xlb[0x38] |= (1 << 3); /* CCR2.3: 1 = Rx ESF */ xlb[0x38] &= ~(1 << 5); /* CCR2.5: 0 = Tx no SLC-96 */ } if (sp->config.ifcoding != SDL_CODING_AMI) { sp->config.ifcoding = SDL_CODING_AMI; xlb[0x38] &= ~(1 << 6); /* CCR2.6: 0 = Tx AMI */ xlb[0x38] &= ~(1 << 2); /* CCR2.2: 0 = Rx AMI */ xlb[0x73] = 0x1c; /* Set FDL reg. */ } if (sp->config.ifgcrc != SDL_GCRC_CRC6) { sp->config.ifgcrc = SDL_GCRC_CRC6; xlb[0x19] &= ~(1 << 7); /* CCR5.7: 1 = Tx CRC6 */ xlb[0x1e] &= ~(1 << 7); /* CCR6.7: 1 = Rx CRC6 */ xlb[0x36] &= ~(1 << 1); /* TCR2.1: 0 = bit2 */ xlb[0x2c] &= ~(1 << 2); /* RCR2.2: 0 = bit2 */ } sp->status.config = 2; break; } /* fall through */ case 2: /* ESF, AMI, CRC6. */ if (!ansi || japan) { sp->config.ifgtype = SDL_GTYPE_J1; if (sp->config.ifframing != SDL_FRAMING_ESF) { sp->config.ifframing = SDL_FRAMING_ESF; xlb[0x38] |= (1 << 7); /* CCR2.7: 1 = Tx ESF */ xlb[0x38] |= (1 << 3); /* CCR2.3: 1 = Rx ESF */ xlb[0x38] &= ~(1 << 5); /* CCR2.5: 0 = Tx no SLC-96 */ } if (sp->config.ifcoding != SDL_CODING_AMI) { sp->config.ifcoding = SDL_CODING_AMI; xlb[0x38] &= ~(1 << 6); /* CCR2.6: 0 = Tx AMI */ xlb[0x38] &= ~(1 << 2); /* CCR2.2: 0 = Rx AMI */ xlb[0x73] = 0x1c; /* Set FDL reg. */ } if (sp->config.ifgcrc != SDL_GCRC_CRC6J) { sp->config.ifgcrc = SDL_GCRC_CRC6J; xlb[0x19] |= (1 << 7); /* CCR5.7: 1 = Tx CRC6J */ xlb[0x1e] |= (1 << 7); /* CCR6.7: 1 = Rx CRC6J */ xlb[0x36] |= (1 << 1); /* TCR2.1: 1 = fr 12 */ xlb[0x2c] |= (1 << 2); /* RCR2.2: 1 = fr 12 */ } sp->status.config = 3; break; } /* fall through */ case 3: /* ESF, AMI, CRC6J. */ if (ansi || !japan) { sp->config.ifgtype = SDL_GTYPE_T1; if (sp->config.ifframing != SDL_FRAMING_SF) { sp->config.ifframing = SDL_FRAMING_SF; xlb[0x38] &= ~(1 << 7); /* CCR2.7: 0 = Tx D4 */ xlb[0x38] &= ~(1 << 3); /* CCR2.3: 0 = Rx D4 */ xlb[0x38] |= (1 << 5); /* CCR2.5: 1 = Tx SLC-96 */ } if (sp->config.ifcoding != SDL_CODING_B8ZS) { sp->config.ifcoding = SDL_CODING_B8ZS; xlb[0x38] |= (1 << 6); /* CCR2.6: 1 = Tx B8ZS */ xlb[0x38] |= (1 << 2); /* CCR2.2: 1 = Rx B8ZS */ } if (sp->config.ifgcrc != SDL_GCRC_CRC6) { sp->config.ifgcrc = SDL_GCRC_CRC6; xlb[0x19] &= ~(1 << 7); /* CCR5.7: 1 = Tx CRC6 */ xlb[0x1e] &= ~(1 << 7); /* CCR6.7: 1 = Rx CRC6 */ xlb[0x36] &= ~(1 << 1); /* TCR2.1: 0 = bit2 */ xlb[0x2c] &= ~(1 << 2); /* RCR2.2: 0 = bit2 */ } sp->status.config = 4; break; } /* fall through */ case 4: /* D4, B8ZS, Norm. */ if (!ansi || japan) { sp->config.ifgtype = SDL_GTYPE_J1; if (sp->config.ifframing != SDL_FRAMING_SF) { sp->config.ifframing = SDL_FRAMING_SF; xlb[0x38] &= ~(1 << 7); /* CCR2.7: 0 = Tx D4 */ xlb[0x38] &= ~(1 << 3); /* CCR2.3: 0 = Rx D4 */ xlb[0x38] |= (1 << 5); /* CCR2.5: 1 = Tx SLC-96 */ } if (sp->config.ifcoding != SDL_CODING_B8ZS) { sp->config.ifcoding = SDL_CODING_B8ZS; xlb[0x38] |= (1 << 6); /* CCR2.6: 1 = Tx B8ZS */ xlb[0x38] |= (1 << 2); /* CCR2.2: 1 = Rx B8ZS */ } if (sp->config.ifgcrc != SDL_GCRC_CRC6J) { sp->config.ifgcrc = SDL_GCRC_CRC6J; xlb[0x19] |= (1 << 7); /* CCR5.7: 1 = Tx CRC6J */ xlb[0x1e] |= (1 << 7); /* CCR6.7: 1 = Rx CRC6J */ xlb[0x36] |= (1 << 1); /* TCR2.1: 1 = fr 12 */ xlb[0x2c] |= (1 << 2); /* RCR2.2: 1 = fr 12 */ } sp->status.config = 5; break; } /* fall through */ case 5: /* D4, B8ZS, D4Yel. */ if (ansi || !japan) { sp->config.ifgtype = SDL_GTYPE_T1; if (sp->config.ifframing != SDL_FRAMING_SF) { sp->config.ifframing = SDL_FRAMING_SF; xlb[0x38] &= ~(1 << 7); /* CCR2.7: 0 = Tx D4 */ xlb[0x38] &= ~(1 << 3); /* CCR2.3: 0 = Rx D4 */ xlb[0x38] |= (1 << 5); /* CCR2.5: 1 = Tx SLC-96 */ } if (sp->config.ifcoding != SDL_CODING_AMI) { sp->config.ifcoding = SDL_CODING_AMI; xlb[0x38] &= ~(1 << 6); /* CCR2.6: 0 = Tx AMI */ xlb[0x38] &= ~(1 << 2); /* CCR2.2: 0 = Rx AMI */ xlb[0x73] = 0x1c; /* Set FDL reg. */ } if (sp->config.ifgcrc != SDL_GCRC_CRC6) { sp->config.ifgcrc = SDL_GCRC_CRC6; xlb[0x19] &= ~(1 << 7); /* CCR5.7: 1 = Tx CRC6 */ xlb[0x1e] &= ~(1 << 7); /* CCR6.7: 1 = Rx CRC6 */ xlb[0x36] &= ~(1 << 1); /* TCR2.1: 0 = bit2 */ xlb[0x2c] &= ~(1 << 2); /* RCR2.2: 0 = bit2 */ } sp->status.config = 6; break; } /* fall through */ case 6: /* D4, AMI, Norm. */ if (!ansi || japan) { sp->config.ifgtype = SDL_GTYPE_J1; if (sp->config.ifframing != SDL_FRAMING_SF) { sp->config.ifframing = SDL_FRAMING_SF; xlb[0x38] &= ~(1 << 7); /* CCR2.7: 0 = Tx D4 */ xlb[0x38] &= ~(1 << 3); /* CCR2.3: 0 = Rx D4 */ xlb[0x38] |= (1 << 5); /* CCR2.5: 1 = Tx SLC-96 */ } if (sp->config.ifcoding != SDL_CODING_AMI) { sp->config.ifcoding = SDL_CODING_AMI; xlb[0x38] &= ~(1 << 6); /* CCR2.6: 0 = Tx AMI */ xlb[0x38] &= ~(1 << 2); /* CCR2.2: 0 = Rx AMI */ xlb[0x73] = 0x1c; /* Set FDL reg. */ } if (sp->config.ifgcrc != SDL_GCRC_CRC6J) { sp->config.ifgcrc = SDL_GCRC_CRC6J; xlb[0x19] |= (1 << 7); /* CCR5.7: 1 = Tx CRC6J */ xlb[0x1e] |= (1 << 7); /* CCR6.7: 1 = Rx CRC6J */ xlb[0x36] |= (1 << 1); /* TCR2.1: 1 = fr 12 */ xlb[0x2c] |= (1 << 2); /* RCR2.2: 1 = fr 12 */ } sp->status.config = 7; break; } /* fall through */ case 7: /* D4, AMI, D4Yel. */ /* last configuration failed, go back to default */ if (ansi || !japan) { sp->config.ifgtype = SDL_GTYPE_T1; if (sp->config.ifframing != SDL_FRAMING_ESF) { sp->config.ifframing = SDL_FRAMING_ESF; xlb[0x38] |= (1 << 7); /* CCR2.7: 1 = Tx ESF */ xlb[0x38] |= (1 << 3); /* CCR2.3: 1 = Rx ESF */ xlb[0x38] &= ~(1 << 5); /* CCR2.5: 0 = Tx no SLC-96 */ } if (sp->config.ifcoding != SDL_CODING_B8ZS) { sp->config.ifcoding = SDL_CODING_B8ZS; xlb[0x38] |= (1 << 6); /* CCR2.6: 1 = Tx B8ZS */ xlb[0x38] |= (1 << 2); /* CCR2.2: 1 = Rx B8ZS */ } if (sp->config.ifgcrc != SDL_GCRC_CRC6) { sp->config.ifgcrc = SDL_GCRC_CRC6; xlb[0x19] &= ~(1 << 7); /* CCR5.7: 1 = Tx CRC6 */ xlb[0x1e] &= ~(1 << 7); /* CCR6.7: 1 = Rx CRC6 */ xlb[0x36] &= ~(1 << 1); /* TCR2.1: 0 = bit2 */ xlb[0x2c] &= ~(1 << 2); /* RCR2.2: 0 = bit2 */ } sp->status.config = 0; } else { sp->config.ifgtype = SDL_GTYPE_J1; if (sp->config.ifframing != SDL_FRAMING_ESF) { sp->config.ifframing = SDL_FRAMING_ESF; xlb[0x38] |= (1 << 7); /* CCR2.7: 1 = Tx ESF */ xlb[0x38] |= (1 << 3); /* CCR2.3: 1 = Rx ESF */ xlb[0x38] &= ~(1 << 5); /* CCR2.5: 0 = Tx no SLC-96 */ } if (sp->config.ifcoding != SDL_CODING_B8ZS) { sp->config.ifcoding = SDL_CODING_B8ZS; xlb[0x38] |= (1 << 6); /* CCR2.6: 1 = Tx B8ZS */ xlb[0x38] |= (1 << 2); /* CCR2.2: 1 = Rx B8ZS */ } if (sp->config.ifgcrc != SDL_GCRC_CRC6J) { sp->config.ifgcrc = SDL_GCRC_CRC6J; xlb[0x19] |= (1 << 7); /* CCR5.7: 1 = Tx CRC6J */ xlb[0x1e] |= (1 << 7); /* CCR6.7: 1 = Rx CRC6J */ xlb[0x36] |= (1 << 1); /* TCR2.1: 1 = fr 12 */ xlb[0x2c] |= (1 << 2); /* RCR2.2: 1 = fr 12 */ } sp->status.config = 1; } return (1); } return (0); } /** xp_t1_process_stats: - process statistics (performance measures) for the span * @sp: span structure pointer * @errors: error events accumulated so far. * * ERROR EVENTS: * Bipolar Violation BPV Error Event: A BPV error event for an AMI coded signal is the occurrence * of a pulse of the same polarity as the previous pulse. A BPV error event for a B8ZS or HDB3 * coded signal is the occurrence of a pulse of the same polarity as the previous pulse without * being part of the zero substitution code. * * Controlled Slip (CS) Error Event: A CS is the replication or deletion of the payload bits of a * DS1 frame. A CS may be performed when there is a difference between the timing of a * synchronous receiving terminal an the received signal. A CS does not acuase an Out of Frame * defect. * * Excessive Zeros (EXZ) Error Event: An EXZ error event for an AMI coded signal is the occurence * of more than fifteen contiguous zeros. For a B8ZS coded signal, the defect occurs when more * than seven contiguous zeros are detected. * * Line Coding Violation (LCV) Error Event: An LCV is the occurence of either a Bipolar Violation * or Excessive Zeros (EXZ) error event. * * Path Coding Violation (PCV) Error Event: A PCV error event is a frame synchronization bit error * in the D4 and E1-non-CRC-4 formats, or a CRC error in the ESF and E1-CRC-4 formats. * * PERFORMANCE PARAMETERS: * All performance parameters are accumulated in fifteen minute intervals and up to 96 intervals * (covering a 24-hour period) are kept by an agent. Fewer than 96 intervals of data will be * available if the agent has been restarted within the last 24 hours. In addition, there is a * rolling 24-hour total of each performance parameter. There is no requirement for an agent to * ensure a fixed relationship between the start of a fifteen minute interval and clock time; * however, some agents may align the fifteen minute intervals with quarter hours. * * Severely Errored Seconds (SES): An SES for ESF signals is a second with one of the following: * 320 or more PCV error events; one or more OOF defects; a detected AIS defect. For E1 CRC-4 * signals, an SES is a second with either 832 or more PCV error events or one or more OOF * defects. For E1 non-CRC-4 signals, an SES is a 2048 (LCV ????) PCV or more. For D4 signals, * an SES is a count of one-second intervals with Framing Error events, or an OOF defect, or * 1544 LCV or more. Controlled slips are not included in this parameter. This is not * incremented during an Unavailable Second. * * Severely Errored Framing Seconds (SEFS): An SEFS is a second with either one or more OOF * defects, or a detected AIS defect. * * Unavailable Seconds (UASs): A performance management event that is calculted by counting the * number of seconds for which the interface is unavailable. An interface is said to be * unavailable from the onset of 10 continugous Severely Errored Seconds (SESs), or on the * onset of a condition leading to a failutre. Once unavailable, and if no failure is present, * an interface becomes available at the onset of 10 contiguous seconds with no SESs. * * UAS are calculated by counting the number of seconds that the interface is unavailable. The * DS1 interface is said to be unavailable from the onset of ten contiguous SESs, or the onset * of the condition leadeing to a failure (see Failure States). If the condition leading to * the failure was immediately preceded by one or more continguous SES, then the DS1 interface * unavailability starts from the onset of these SES. Once unavailable, and if no failure is * present, the DS1 interfae becomes available at the onset of 10 contiguous seconds with no * SES. if the failure clearing time is less than or equat to ten seconds. If the failure * clearing time is more than ten seconds, the DS1 interface becoms available at the onset of * tem contiguous seconds with no SES, or the onset period leading to the successful clearing * condition, whichever occurs later. With respect to DS1 error counts, all coutners are * incremented while the DS1 interface is deemed available. While the interface is deemed * unavailable, the only count that is incremented is UAS. A special case exists when the ten * or more second period crosses the 900 second statistic window boundary, as the foregoing * description ipmlies that the SES and UAS counter must be adjusted when the UAS stats is * entered. Successive "gets" of the affectetd dsx1IntervalSESs and dsx1IntervalUASs objects * will return differing values if the first get occurs during the first few seconds of the * window. This is viewed as an unavoidable side-effect of selecting the presently-defined * objects. * * Bursty Errored Secods (BES): A BES (also known as an Errored Second Type B) is a second with * fewer than 320 and more than one PCV, no SEF defects, and no detected incoming AIS defects. * Controlled slips are not incldued in this parameter. * * Errored Seconds (ES): For ESF and E1-CRC links an Errored Second is a second with one of the * followng: one or more PCV; one or more OOF defects; one or more Controlled Slip events; a * detected AIS defect. * * Controlled Slip Seconds (CSS): A cCSS is a one-second interval containing one or more controlled * slips. * * Line Errored Seconds (LES): A LES, according to T1M1.3, is a second in which one or more LCV * error events were detected. While many implementations are currently unable to detect the * zero strings, it is expected that interface manufacturers will add this capability in * deference to ANSI; therefore, it will become available in time. In the T1M1.3 specification, * near end LCV and far end LES are counted. For consistency, we count LES at both ends. * * Degraded Minutes: A DM is one in which the estimated error rate exceeds 1E-06 but does not * exceed 1E-03. DM are determined by collecting all of the Available Seconds, removing any * Severely Errored Seconds grouping the result in 60-second long groups and counting a * 60-second long group (minute) as degraded if the cumulative errors during the seconds * present in the group exceed 1E-6. Available seconds are merely those seconds which are not * unavailable as described below. */ static noinline fastcall __hot void xp_t1_process_stats(struct sp *sp, register uint errors) { /* This is a one second timeout */ /* Calculate severely errored seconds. */ /* Note: when there are a lot of PCV and the span is T1, there is possibility that it should be set to J1 instead. When there are a lot of PCV and the span is J1, there is a possibility that it should be set to T1 instead. */ switch (sp->config.ifframing) { case SDL_FRAMING_ESF: /* A Severely Errored Second for ESF signals is a second with one of the following: 320 or more PCV error events; one or more OOF defects; or a detected AIS defect. */ if (sp->stats[0].PCVs >= 320) errors |= XP_ERR_SES; break; case SDL_FRAMING_D4: /* For D4 signals, an SES is a count of one-second intervals with Framing Error events, or an Out of Frame defect; or 1544 or more LCVs. */ if (sp->stats[0].LCVs >= 1544) errors |= XP_ERR_SES; break; } /* The number of Unavailable Seconds (UASs) in the current interval. */ /* Track the number of consecutive severely errored seconds and the number of consecutive non-severely errored seconds */ if (errors & (XP_ERR_SES)) { sp->status.nses = 0; sp->status.sess++; if (sp->status.sess >= 10) { if (sp->status.sess == 10 && !(errors & XP_ERR_UAS)) { sp->stats[0].UASs += 9; errors |= XP_ERR_UAS; } errors |= XP_ERR_UAS; } } else { sp->status.sess = 0; sp->status.nses++; if (sp->status.nses >= 10) { if (sp->status.nses == 10 && (errors & XP_ERR_UAS)) { sp->stats[0].UASs -= 9; errors &= ~XP_ERR_UAS; } errors &= ~XP_ERR_UAS; } } if (errors & (XP_ERR_UAS)) sp->stats[0].UASs = 1; /* Calculate bursty errored seconds */ switch (sp->config.ifframing) { case SDL_FRAMING_ESF: if (1 < sp->stats[0].PCVs && sp->stats[0].PCVs < 320) if (!(errors & XP_ERR_SEFS)) if (!(errors & XP_FAIL_AIS)) errors |= XP_ERR_BES; break; case SDL_FRAMING_D4: if (1 < sp->stats[0].LCVs && sp->stats[0].LCVs < 1544) if (!(errors & XP_ERR_SEFS)) if (!(errors & XP_FAIL_AIS)) errors |= XP_ERR_BES; break; } /* The number of Errored Seconds (ESs) in the current interval. */ if (sp->stats[0].PCVs > 0) errors |= XP_ERR_ES; if (errors & (XP_ERR_ES)) sp->stats[0].ESs = 1; /* The number of Severely Errored Seconds (SESs) in the current interval. */ if (errors & (XP_ERR_SES)) sp->stats[0].SESs = 1; /* The number of Severely Errored Framing Seconds (SEFSs) in the current interval. */ if (errors & (XP_ERR_SEFS)) sp->stats[0].SEFSs = 1; /* The number of Controlled Slip Seconds (CSSs) in the current interval. */ if (errors & (XP_ERR_CSS)) sp->stats[0].CSSs = 1; /* The number of Line Errored Seconds (LESs) in the current interval. */ if (errors & (XP_ERR_LES)) sp->stats[0].LESs = 1; /* The number of Bursty Errored Seconds (BESs) in the current interval. */ if (errors & (XP_ERR_BES)) sp->stats[0].BESs = 1; /* accumulate the one-second counts */ sp->stats[1].ESs += sp->stats[0].ESs; sp->stats[1].SESs += sp->stats[0].SESs; sp->stats[1].ESs += sp->stats[0].ESs; sp->stats[1].SESs += sp->stats[0].SESs; sp->stats[1].SEFSs += sp->stats[0].SEFSs; sp->stats[1].UASs += sp->stats[0].UASs; sp->stats[1].CSSs += sp->stats[0].CSSs; sp->stats[1].PCVs += sp->stats[0].PCVs; sp->stats[1].LESs += sp->stats[0].LESs; sp->stats[1].BESs += sp->stats[0].BESs; sp->stats[1].DMs += sp->stats[0].DMs; sp->stats[1].LCVs += sp->stats[0].LCVs; sp->stats[1].FASEs += sp->stats[0].FASEs; sp->stats[1].FABEs += sp->stats[0].FABEs; sp->stats[1].FEBEs += sp->stats[0].FEBEs; bzero(&sp->stats[0], sizeof(sp->stats[0])); if ((++sp->stats[1].SECs) == 60) { /* The number of Degraded Minutes (DMs) in the current interval. */ if (errors & (XP_ERR_DM)) sp->stats[1].DMs = 1; /* accumulate one-minute counts */ sp->stats[2].ESs += sp->stats[1].ESs; sp->stats[2].SESs += sp->stats[1].SESs; sp->stats[2].ESs += sp->stats[1].ESs; sp->stats[2].SESs += sp->stats[1].SESs; sp->stats[2].SEFSs += sp->stats[1].SEFSs; sp->stats[2].UASs += sp->stats[1].UASs; sp->stats[2].CSSs += sp->stats[1].CSSs; sp->stats[2].PCVs += sp->stats[1].PCVs; sp->stats[2].LESs += sp->stats[1].LESs; sp->stats[2].BESs += sp->stats[1].BESs; sp->stats[2].DMs += sp->stats[1].DMs; sp->stats[2].LCVs += sp->stats[1].LCVs; sp->stats[2].FASEs += sp->stats[1].FASEs; sp->stats[2].FABEs += sp->stats[1].FABEs; sp->stats[2].FEBEs += sp->stats[1].FEBEs; bzero(&sp->stats[1], sizeof(sp->stats[1])); if ((sp->stats[2].SECs += 60) == 900) { uint index = sp->curr; sp->hist[index] = sp->stats[2]; sp->hist[index].ValidData = 2; /* true(2) */ bzero(&sp->stats[2], sizeof(sp->stats[2])); if (++index == 96) index = 0; sp->curr = index; } } return; } /** xp_t1_process_alarms: - process alarm state and das blinkin' ligths * @cd: card structure pointer * @sp: span structure pointer * @xlb: span register i/o pointer * @flags: state flags * @timeout: true when interrupt is a timeout (for alarm recovery) */ static noinline fastcall __hot void xp_t1_process_alarms(struct cd *cd, struct sp *sp, register volatile uint8_t *xlb, register uint flags, uint timeout) { register uint alarms = sp->config.ifalarms; /* integrate alarms */ if ((flags & XP_STATE_RDMA) && (sp->config.ifframing == SDL_FRAMING_CAS)) alarms |= SDL_ALARM_DMF; else alarms &= ~SDL_ALARM_DMF; if (flags & (XP_STATE_RRA | XP_STATE_RYEL)) alarms |= SDL_ALARM_YEL; else alarms &= ~SDL_ALARM_YEL; if (flags & XP_STATE_RUA1) alarms |= SDL_ALARM_BLU; else alarms &= ~SDL_ALARM_BLU; if (flags & (XP_STATE_RLOS | XP_STATE_FRCL | XP_STATE_LRCL)) alarms |= SDL_ALARM_RED; else alarms &= ~SDL_ALARM_RED; if ((alarms & SDL_ALARM_REC) && (timeout)) { if (alarms & (SDL_ALARM_RED | SDL_ALARM_BLU)) alarms &= ~SDL_ALARM_REC; else { /* recovery time in terms of timeouts (5 seconds) */ if (sp->recovertime && !--sp->recovertime) { xlb[0x35] &= ~(1 << 0); /* TCR1.0: TYEL: 0 = no YEL */ alarms &= ~SDL_ALARM_REC; cd->eval_syncsrc = 1; } } } /* if any of the alarms (or recovery) changed we need to do this */ if ((alarms ^ sp->config.ifalarms) & (SDL_ALARM_RED | SDL_ALARM_BLU | SDL_ALARM_YEL | SDL_ALARM_REC)) { if ((alarms & (SDL_ALARM_RED | SDL_ALARM_BLU)) && !(sp->config.ifalarms & (SDL_ALARM_RED | SDL_ALARM_BLU))) { /* Local alarms have just begun. Signal a yellow (RAI) alarm to the other end. */ if (!(alarms & SDL_ALARM_REC)) { /* local alarms just begun and we were not in recovery */ xlb[0x35] |= (1 << 0); /* TCR1.0: TYEL: 1 = transmit yellow alarm */ if (alarms & SDL_ALARM_RED) cd->eval_syncsrc = 1; } else alarms &= ~SDL_ALARM_REC; } else if ((alarms & SDL_ALARM_RED) && !(sp->config.ifalarms & SDL_ALARM_RED)) { /* red alarm just got added to the set, reevaluate the sync source */ cd->eval_syncsrc = 1; } else if (!(alarms & (SDL_ALARM_RED | SDL_ALARM_BLU)) && (sp->config.ifalarms & (SDL_ALARM_RED | SDL_ALARM_BLU))) { /* Local alarms have just ended. */ alarms |= SDL_ALARM_REC; if (xlb[0x30] & (1 << 2)) /* CCR3.2: ECUS */ sp->recovertime = X400P_SDL_ALARM_SETTLE_T1; else sp->recovertime = X400P_SDL_ALARM_SETTLE_SECONDS; } sp->config.ifalarms &= ~(SDL_ALARM_RED | SDL_ALARM_BLU | SDL_ALARM_YEL | SDL_ALARM_REC); sp->config.ifalarms |= (alarms & (SDL_ALARM_RED | SDL_ALARM_BLU | SDL_ALARM_YEL | SDL_ALARM_REC)); { int leds = 0, all_leds; /* adjust leds */ if (alarms & SDL_ALARM_RED) leds |= LEDRED; else if (alarms & SDL_ALARM_YEL) leds |= LEDYEL; else leds |= LEDGRN; all_leds = cd->ledreg; all_leds &= ~(LEDYEL << (sp->span << 1)); all_leds |= (leds << (sp->span << 1)); if (cd->ledreg != all_leds) { cd->ledreg = all_leds; cd->xlb[LEDREG] = cd->ledreg; } } } } /** xp_t1_eval_syncsrc: - reevaluate synchronization source for card * @cd: card structure pointer * * There is really only one version of this function, it is just laid out in several places for * proper position with respect to the main interrupt service routine. */ static noinline fastcall __hot void xp_t1_eval_syncsrc(struct cd *cd) { /* for safety */ if (cd->config.ifsyncsrc[0] != 0) { int src, synreg = SYNCSELF, ctlreg, clkreg = cd->clkreg; for (src = 0; src < SDL_SYNCS; src++) { struct sp *sp; uint span; if ((span = cd->config.ifsyncsrc[src]) == 0) break; if ((--span < cd->ports && span >= 0) && (sp = cd->spans[span]) && (sp->config.ifflags & SDL_IF_UP) && (sp->config.ifflags & SDL_IF_RX_UP) && (sp->config.ifflags & SDL_IF_RX_RUNNING) && (sp->config.ifclock != SDL_CLOCK_LOOP) && !(sp->config.ifalarms & (SDL_ALARM_BLU | SDL_ALARM_RED))) { synreg = cd->config.ifsyncsrc[src]; if (sp->config.ifgtype == SDL_GTYPE_E1) clkreg |= E1DIV; else clkreg &= ~E1DIV; break; } } if (cd->config.ifsync != synreg) { cd->config.ifsync = synreg; ctlreg = cd->ctlreg & ~E1DIV; ctlreg |= clkreg; /* use divider for span or clock */ cd->xlb[CTLREG] = cd->ctlreg = ctlreg; cd->xlb[SYNREG] = cd->synreg = synreg; } } } static noinline fastcall __hot void xp_e1_txrx_burst(struct cd *cd); static noinline fastcall __hot void xp_e1_process_span(struct cd *cd, struct sp *sp); static noinline fastcall __hot void xp_e1_process_timeout(struct cd *cd, struct sp *sp, volatile uint8_t *xlb, register uint flags); static noinline fastcall __hot void xp_e1_process_state(struct cd *cd, struct sp *sp, register volatile uint8_t *xlb, const register uint flags, const register uint errors); static noinline fastcall __hot void xp_e1_process_stats(struct sp *sp, register uint errors); static noinline fastcall __hot void xp_e1_process_alarms(struct cd *cd, struct sp *sp, register volatile uint8_t *xlb, register uint flags, uint timeout); static noinline fastcall __hot void xp_e1_eval_syncsrc(struct cd *cd); static noinline fastcall __unlikely void xp_e1_process_auto(struct cd *cd, struct sp *sp, register volatile uint8_t *xlb, register uint flags, const register uint errors, const uint timeout); noinline __unlikely int xp_e1_change_config(struct sp *sp, register volatile uint8_t *xlb); /** xp_e1_interrupt: - E400P-SS7 Interrupt Service Routine * @irq: interrupt number * @dev_id: card structure pointer (opaque) * @regs: interrupted registers * * The user will always preceed a read of any fo the SR1, SR2, and RIR registers with a write. The * user will write a byte to one of these registers, with a one in the bit positions he or she * wishes to read and a zero in the bit positions he or she does not wish to obtain the latest * information on. When a one is written to a bit location, the read register will be updated with * the latest information. When a zero is written to a bit position, the read register will not be * updated and the previous value will be held. A write to the status and information registers * will be immediated followed by a read of the same register. The read result should be logically * ANDed with the mask byte that was just written and this value should be written back to the same * register to insure that the bit does indeed clear. This second write step is necessary because * the alarms and events in the status registers occur asyncrhonously in respect to their access * via the parallel port. This write-read-write scheme allows an external controller or * microprocessor to individually poll certain bits without disturbing the other bits in the * register. This operation is key in controlling the DS21354/DS21554 with higher-order software * languages. * * Process an interrupt for a E400P card (with a DS21354/DS21554 chip). The spans on this card can * only be E1 span. This is a departure from the previous driver which counted frames to determine * timeout events: here we utilize the Dallas interrupts available on the card for non-frame * events. This function should really be aligned on a page boundary and the functions that it * calls laid out immediately following the function, thus the forward declarations above. */ STATIC __hot irqreturn_t #ifdef HAVE_KTYPE_IRQ_HANDLER_2ARGS xp_e1_interrupt(int irq, void *dev_id) #else xp_e1_interrupt(int irq, void *dev_id, struct pt_regs *regs) #endif { static unsigned long lasttime = 0; struct cd *cd = (struct cd *) dev_id; int safety; /* Keep another processor from entering the interrupt while another is already processing the interrupt. This means that the top half of the driver must disable interrupts when taking the card lock to avoid deadly embrace. */ spin_lock(&cd->lock); /* active interrupt (otherwise spurious or shared) */ if (!(cd->xlb[STAREG] & (INTACTIVE | DINTACT))) { spin_unlock(&cd->lock); return (irqreturn_t) (IRQ_NONE); } if (likely(cd->xlb[STAREG] & INTACTIVE)) { cd->xlb[CTLREG] = cd->ctlreg | (INTENA | OUTBIT | DINTENA | INTACK); xp_e1_txrx_burst(cd); cd->xlb[CTLREG] = cd->ctlreg | (INTENA | DINTENA); } for (safety = 0; unlikely(cd->xlb[STAREG] & DINTACT); safety++) { uint span; struct sp *sp; /* We would like to try to keep this burning a loop here when there is only one span that is responsible for the Dallas interrupt; however, the DS21354/554 chips do not support an interrupt information register like the DS2155/455/458. */ for (span = 0; span < cd->ports; span++) if (likely((sp = cd->spans[span]) != NULL)) xp_e1_process_span(cd, sp); if (unlikely(safety > 8)) { /* throttle software error message */ if (lasttime == 0 || (jiffies - lasttime) > HZ) { lasttime = jiffies; swerr(); } break; } } /* Reevaluate the sync source when necessary. Try to skip the call here whenever possible to keep the ISR tight. */ if (unlikely(xchg((int *) &cd->eval_syncsrc, 0) != 0)) { if (cd->config.ifsyncsrc[0] != 0) xp_e1_eval_syncsrc(cd); } spin_unlock(&cd->lock); return (irqreturn_t) (IRQ_HANDLED); } /** xp_e1_txrx_burst: - burst transfer TX and RX data * @cd: card structure pointer * * This function is responsible for transfering frame data to and from the card. This is being * done with host driven I/O because the PLX9030 is incapable of bus mastering DMA. When the * memory mapped I/O region is properly described, PCI burst transfers will occur. Transfers are * 1024 bytes written and 1024 bytes read. These are interleaved, but might better be performed as * 4 Lword interleaved transfers. * * This function is identical to xp_x1_txrx_burst(), but is laid out again here so that it is in * the correct location w.r.t. the main interrupt routine. */ static noinline fastcall __hot void xp_e1_txrx_burst(struct cd *cd) { int lebno; if ((lebno = (cd->lebno + 1) & (X400P_EBUFNO - 1)) != cd->uebno) { register int slot; register volatile uint32_t *xll; register const uint32_t *wbuf = cd->wbuf + (lebno << 8); register const uint32_t *const wend = wbuf + 256; register uint32_t *rbuf = cd->rbuf + (lebno << 8); cd->lebno = lebno; for (xll = cd->xll; wbuf < wend;) for (wbuf++, rbuf++, xll++, slot = 1; slot < 32; slot++, xll++, wbuf++, rbuf++) { prefetch(wbuf + 1); prefetchw(rbuf + 1); *xll = *wbuf; *rbuf = *xll; } tasklet_hi_schedule(&cd->tasklet); } else xp_overflow(cd); } /** xp_e1_process_span: - process Dallas interrupts for a single span * @cd: card structure pointer * @sp: span structure pointer * * PERFORMANCE DEFECTS: * * XP_DEF_AIS: Alarm Indication Signal (AIS) Defect: * For D4 and ESF links, the 'all ones' condition is detected at a DS1 line interface upon * observing an unframed signal with a one's density of at least 99.9 percent present for a * time equal to or greater than T, where 3ms is less than or equal to T, which is less than or * equal to 75ms. The AIS is terminated upon observing a signal not meeting the one's density * of the unframed signal criteria for a period equal to or greater than T. For E1 links, the * 'all-ones' condition is detected at the line interface as a string of 512 bits containing * fewer than three zero bits. * * XP_DEF_OOF: Out of Frame (OOF) Defect: * An OOF defect is the occurrence of a particular density of Framing Error events. For T1 * links, an OOF defect is declared when the receiver detects two or more framing errors within * a 3 ms period for ESF signals and 0.75 ms for D4 signals, or two or more errors out of five, * or fewer consecutive framing-bits. For E1 links, an OOF defect is declared when three * consecutive frame alignment signals have been received with an error. When an OOF defect is * declared, the frame starts searching for a correct pattern. The OOF defect ends when the * signal is in-frame. In-frame occurs when there are fewer than two frame bit errors within a * 3 ms period for ESF signals and 0.75 ms for D4 signals. For E1 links, in-frame occurs when * in frame N, the frame alignment signal is correct; and, in frame N+1, the frame alignment * signal is absent (that is, bit 2 in TS0 is set to one); and, in frame N+2, the frame * alignment signal is present and correct. * * FAILURE STATES: The following failure states are received or detected failures that are * reported. The conditions under which a DS1 interface would, if ever, produce the conditions * leading to the failure state are described in the appropriate specification. * * XP_FAIL_AIS: Alarm Indication Signal (AIS) Failure: * The AIS failure is declared when an AIS defect is detected at the input and the AIS defect * still exists after the LOF failure (which is caused by the unframed nature of the all-ones * signal) is detected. The AIS failure is cleared when the LOF failure is cleared. * * XP_FAIL_FEA: Far End Alarm Failure (Yellow Alarm): * The Far End Alarm failure is also known as Yellow Alarm in the T1 cases and Distant Alarm * (or RAI) in the E1 case. For D4 links, the FEA failure is declared when bit 6 of all * channels have been zero for at least 335 ms and is cleared when bit 6 of at least one * channel is non-zero for a period T, where T is usually less than one second and alway less * than five seconds. The FEA failure is not declared for D4 links when LOS is detected. For * ESF links, the FEA failure is declared if the Yellow Alarm signal pattern occurs in a least * seven out of ten contiguous 16-bit-pattern intervals and is cleared if the Yellow Alarm * signal pattern does not occur in ten contiguous 16-bit signal pattern intervals. For E1 * links, the FEA failure is declared when bit 3 of time-slot zero is set to one on two * consecutive occasions. The FEA failure is cleared when bit 3 of time-slot zero is received * set to zero. * * XP_FAIL_FELOM: Far End Loss of Multiframe Failure: * The FELOM failure is declared when bit 2 of TS16 of frame 0 is received set to one on two * consecutive occasions. The FELOM failure is cleared when bit 2 of TS16 of frame 0 is * received set to zero. The FELOM failure can only be declared for E1 links operating in CAS * mode. * * XP_FAIL_LPF: Loopback Pseudo-Failure: * The LPF is declared when the near end equipment has placed a loop-back (of any kind) on the * DS1. This allows a management entity to determine from one object whether the DS1 can be * considered to be in service or not (from the point of view of the near-end equipment). * * XP_FAIL_LOF: Loss of Frame (LOF) Failure: * For T1 links, the LOF failure is declared with an OOF or LOS defect has persisted for T * seconds, where T is greater than or equal to two, but less than or equal to ten. The LOF * failure is cleared when there have been no OOF or LOS defects during a period T is greater * than or equal to two, but less than or equal to twenty. Many systems will perform "hit * integration" with the period T before declaring or clearing the failure. * * XP_FAIL_LOM: Loss of Multiframe (LOM) Failure: * The LOM failure is declared when two consecutive multi-frame alignment signals (bit 4 * through 7 of TS16 of frame 0) have been received wtih an error. The LOM failure is cleared * when the first correct multi-frame alignment signal is received. The LOM failure can only * be declared for E1 links operating with framing (sometimes called CAS mode). * * XP_FAIL_LOS: Loss of Signal (LOS) Failure: * For T1, the Loss of Signal failure is declared upon observing 175 +/- 74 contiguous pulse * position with no pulses of either positive or negative polarity. The LOS failure is * cleared upon observing an average pulse density of at least 12.5 percent over a period of * 175 +/- 74 contiguous pulse positions starting with the receipt of a pulse. * * XP_FAIL_T16AIS: T16 Alarm Indication Signal Failure: * For E1 links, the Ts16 Alarm Indication Signal failure is declared when time-slot 16 is * received as all ones for all frames of two consecutive multi-frames. This condition * is never declared for T1. */ static noinline fastcall __hot void xp_e1_process_span(struct cd *cd, struct sp *sp) { register volatile uint8_t *xlb = (typeof(xlb)) sp->iobase; register uint8_t status, mask; register uint errors = sp->status.errors; register uint flags = sp->status.flags; uint timeout = 0; if ((mask = xlb[0x16])) { /* IMR1 */ /* write-read-write cycle */ xlb[0x06] = mask; /* SR1 */ status = xlb[0x06] & mask; xlb[0x06] = status; /* SR1.7: RSA1: Receive Signalling All Ones/Signalling Change. Set when the contents of time slot 16 contains less than three zeros over 16 consecutive frames. This alarm is not disabled in the CCS signalling mode. Both RSA1 and RSA0 will be set if a change in signalling is detected. */ /* SR1.5: RSA0: Receiv Signalling All Zeros/Signalling Change. Set when over a full MF, time slot 16 contains all zeros. Both RSA1 and RSA0 will be set if a change in signalling is detected. */ if ((mask & (1 << 5)) && (mask & (1 << 7))) { switch (status & ((1 << 5) | (1 << 7))) { case (1 << 5): flags |= XP_STATE_RSAZ; flags &= ~XP_STATE_RSAO; break; case (1 << 7): flags |= XP_STATE_RSAO; flags &= ~XP_STATE_RSAZ; break; case ((1 << 5) | (1 << 7)): /* Change in signalling */ break; case 0: flags &= ~XP_STATE_RSAZ; flags &= ~XP_STATE_RSAO; break; } } /* SR1.6: RDMA: Receive Distant MF Alarm. Set when bit 6 of time slot 16 in frame 0 has been set for two consecutive multiframes. This alarms is not disabled in the CCS signalling mode. */ if (status & (1 << 6)) { flags |= XP_STATE_RDMA; } else if (mask & (1 << 6)) { flags &= ~XP_STATE_RDMA; } /* SR1.4: RSLIP: Receive-Side Elastic Store Slip. Set when the elastic store has either repeated or deleted a frame of data. */ if (status & (1 << 4)) { errors |= XP_ERR_CSS; } /* SR1.3: RUA1: Receive Unframed all Ones. Set when an unframed all ones code is received at RPOSI and RNEGI. */ if (status & (1 << 3)) { flags |= XP_STATE_RUA1; } else if (mask & (1 << 3)) { flags &= ~XP_STATE_RUA1; } /* SR1.2: RRA: Receive Remote Alarm. Set when a remote alarm is received at RPOSI and RNEGI. */ if (status & (1 << 2)) { flags |= XP_STATE_RRA; } else if (mask & (1 << 2)) { flags &= ~XP_STATE_RRA; } /* SR1.1: RCL: Receive Carrier Loss. Set when 255 (or 2048 if CCR3.0 = 1) consecutive zeros have been detected at RTIP and RRING. (Note: a receiver carrier loss based on data received at RPOSI and RNEGI is available in the HSR register). */ if (status & (1 << 1)) { flags |= XP_STATE_LRCL; } else if (mask & (1 << 1)) { flags &= ~XP_STATE_LRCL; } /* SR1.0: RLOS: Receive Loss of Sync. Set then the device is not synchronized to the receive E1 stream. */ if (status & (1 << 0)) { flags |= XP_STATE_RLOS; } else if (mask & (1 << 0)) { flags &= ~XP_STATE_RLOS; } } if ((mask = xlb[0x17])) { /* IMR2 */ /* write-read-write cycle */ xlb[0x07] = mask; /* SR2 */ status = xlb[0x07] & mask; xlb[0x07] = status; /* SR2.7: RMF: Receive CAS Multiframe. Set every 2ms (regardelss if CAS signaling is enabled or not) on receive multiframe boundaries. Used to alert the host that signalling data is available. */ if (status & (1 << 7)) { } else if (mask & (1 << 7)) { } /* SR2.6: RAF: Receive Align Frame. Set every 250ns at the beginning of align frames. Used to alert the host that Si and Sa bits are available in the RAF and RNAF registers. */ if (status & (1 << 6)) { } else if (mask & (1 << 6)) { } /* SR2.5: TMF: Transmit Multiframe. Set every 2ms (regardless if CRC4 is enabled) on transmit mutiframe boundaries. Use to alert the host that signalling data needs to be updated. */ if (status & (1 << 5)) { } else if (mask & (1 << 5)) { } /* SR2.4: SEC: One Second timer. Set on increments of one second based on RCLK. If CCR2.7 = 1, then this bit will be set every 62.5ms instead of once a second. */ if (status & (1 << 4)) { timeout = 1; } /* SR2.3: TAF: Transmit Align Frame. Set every 250ns at the beginning of align frames. Used to alert the host that the TAF and TNAF registers need to be updated. */ if (status & (1 << 3)) { } else if (mask & (1 << 3)) { } /* SR2.2: LOTC: Loss of transmit clock. Set when TCLK pin has not transitioned for one channel time (or 3ns). Will force the LOTC pin high if enabled via TCR2.0. */ if (status & (1 << 2)) { } else if (mask & (1 << 2)) { } /* SR2.1: RCMF: Receive CRC4 Multiframe. Set on CRC4 multiframe boundaries; will continue to be set every 2ms on an arbitrary boundary if CRC4 is disabled. */ if (status & (1 << 1)) { } else if (mask & (1 << 1)) { } /* SR2.0: TSLIP: Transmit Elastic Store Slip. Set when the elastic store has either repeated or deleted a frame of data. */ if (status & (1 << 0)) { } else if (mask & (1 << 0)) { } } /* Note: at this point, any Dallas interrupt should have been cleared by reading the interrupt bits. Dallas interrupts generated by the IMR registers are acknowledged by reading the corresponding bit of the SR registers. */ if (timeout) xp_e1_process_timeout(cd, sp, xlb, flags); /* Note that alarms are processed asyncrhonously whereas interface state is only processed during timeouts. This keeps the interface state from thrashing around and detection mechanisms falsely triggering on transient conditions. */ if ((flags ^ sp->status.flags) != 0) xp_e1_process_alarms(cd, sp, xlb, flags, timeout); } /** xp_e1_process_timeout: - process timeout for a span * @cd: card structure (locked) * @sp: span structure * @xlb: span iobase pointer * @flags: span flags */ static noinline fastcall __hot void xp_e1_process_timeout(struct cd *cd, struct sp *sp, volatile uint8_t *xlb, register uint flags) { register uint mask, status; register uint errors = sp->status.errors; uint count; /* Read information registers and report */ mask = 0xff; /* write-read-write cycle */ xlb[0x08] = mask; /* RIR */ status = xlb[0x08] & mask; xlb[0x08] = status; if (status) { /* RIR.7: TESF: Transmit-side Elastic Store Full. Set when the transmit-side eleastic store buffer fills and a frame is deleted. */ if (status & (1 << 7)) { errors |= XP_ERR_CSS; } /* RIR.6: TESE: Transmit-side Elastic Store Empty. Set when the transmit-side elastic store buffer empties and a frame is repeated. */ if (status & (1 << 6)) { errors |= XP_ERR_CSS; } /* RIR.5: JALT: Jitter Attenuator Limit Trip. Set when the jitter attenuator FIFO reaches to within 4-bits of its limit; useful for debugging jitter attenuation operation. */ if (status & (1 << 5)) { } /* RIR.4: RESF: Receive-side Elastic Store Full. Set when the receive side eleastic store buffer fills and a frame is deleted. */ if (status & (1 << 4)) { errors |= XP_ERR_CSS; } /* RIR.3: RESE: Receive-side Elastic Store Empty. Set when the receive side elastic store buffer empties and a frame is deleted. */ if (status & (1 << 3)) { errors |= XP_ERR_CSS; } /* RIR.2: CRCRC: CRC Resync Criteria Met. Set when 915/1000 codewords are received in error. */ if (status & (1 << 2)) { } /* RIR.1: FASRC: FAS Resync Criteria Met. Set when three consecutive FAS words are received in error. Note: During a CRC resync the FAS synchronizer is brought online to verify the FAS alignment. If during this process a FAS emulator exists, the FAS synchronizer may temporarily align to the emulator. The FASRC will go active indicating a search for a valid FAS has been activated. */ if (status & (1 << 1)) { } /* RIR.0: CASRC: CAS Resync Criteria Met. Set when two consecutive CAS MF alignment words are received in error. */ if (status & (1 << 0)) { } } mask = 0xff; /* write-read-write cycle */ xlb[0x1e] = mask; /* SSR */ status = xlb[0x1e] & mask; xlb[0x1e] = status; /* SSR.7-5: CRC4 Sync Counter Bit 5-2. */ /* SSR.3: CRC4 Sync Counter Bit 0. */ if (status & 0x07) { /* SSR.0: CRC4 MF Sync Active. Set while the synchronizer is searching for the CRC MF alignment word. */ if (status & (1 << 0)) flags &= ~XP_STATE_CRC; else flags |= XP_STATE_CRC; if (status & (1 << 0)) { /* The count of the number of failed 8-ms CRC-4 alignment attempts that have occurred since the last sucessful CRC-4 alignment. This is for G.706 Annex B operation. When the CRC-4 alignment has failed for 400-ms (after achieving basic frame alignment), the CRC-4 capable equipment should assume that the other end is incapable of generating CRC-4 multiframes.A In this case, the transmitter continues transmitting CRC-4 multiframes; however, the E-bits should be set to zero (indicating distant MF alarm). The receiver; however, can be marked as non-CRC-4. */ count = ((status & 0xf0) >> 2) + ((status & 0x08) >> 2); if (count >= 49) { /* Basically we have 488 - 408 = 80 ms to determine that there has been a CRC-4 alignment failure for more than 392 milliseconds. When ECUS is set for 62.5 ms operation, we will detect within 31.25 ms of the event that the CRC-4 has failed for 392 milliseconds or more (i.e. before the CRC-4 counter rolls over). */ /* --1100-0 = 48 = 384 ms */ /* --1100-0 = 50 = 400 ms */ /* --1100-1 = 49 = 392 ms */ /* --1100-1 = 51 = 408 ms */ /* --1101-0 = 52 = 416 ms */ /* --1101-0 = 54 = 432 ms */ /* --1101-1 = 53 = 424 ms */ /* --1101-1 = 55 = 440 ms */ /* --1110-0 = 56 = 448 ms */ /* --1110-0 = 58 = 464 ms */ /* --1110-1 = 57 = 456 ms */ /* --1110-1 = 59 = 472 ms */ /* --1111-0 = 60 = 480 ms */ /* --1111-0 = 62 = 496 ms */ /* --1111-1 = 61 = 488 ms */ /* --1111-1 = 63 = 504 ms */ /* --0000-0 = 64 = 512 ms */ } } /* SSR.1: CASSA: CAS MF Sync Active. Set while the synchronizer is searching for the CAS MF alignment word. */ if (status & (1 << 1)) flags &= ~XP_STATE_CAS; else flags |= XP_STATE_CAS; /* SSR.2: FASSA: FAS Sync Active. Set while the syncrhonizer is searching for alignment at the FAS level. */ if (status & (1 << 2)) flags &= ~XP_STATE_FAS; else if (mask & (1 << 2)) flags |= XP_STATE_FAS; } /* BPV or Code Violation Counter */ /* The 16-bit violation count records either Bipolar Violations (BPVs) or Code Violations (CVs). If CCR2.6 = 0, then the VCR counts bipolar violations. Bipolar violations are defined as consecutive marks of the same polarity. in this mode, if the HDB3 mode is set for the receive side via CCR1.2, then HDB3 codewords are not counted as BPVs. If CCR2.6 = 1, then the VCR counts code violations as defined in ITU O.161. Code violations are defined as consecutive bipolar violations of the same polarity. In most applications, the framer should be set to count BPVs when receiving AMI code and to count CVs when receiving HDB3 code. This counter increments at all times and is not disabled by loss of sync conditions. The counter saturates at 65,535 and will not rollover. The bit error rate on an E1 line would have to be greater than 10E-02 before the VCR would saturate. */ /* NOTE: these are LCVs */ if ((count = ((uint) (xlb[0x00] & 0xff) << 8) | ((uint) (xlb[0x01] & 0xff) >> 0))) { sp->stats[0].LCVs += count; errors |= XP_ERR_LCV; } /* CRC4 Error Counter */ /* The 10-bit CRC4 error counter records word errors in the CRC4. Since the maximum CRC4 count in a one second period is 1000, this counter cannot saturate. The counter is disabled during loss of sync at either the FAS or CRC4 level; it will continue to count if loss of multiframe sync occurs at the CAS level. */ if ((count = ((uint) (xlb[0x02] & 0x03) << 8) | ((uint) (xlb[0x03] & 0xff) >> 0))) { /* NOTE: these are basically PCVs when in the CRC4 mode. */ if (sp->config.ifgcrc == SDL_GCRC_CRC4) { sp->stats[0].PCVs += count; errors |= XP_ERR_PCV; } } /* E-Bit Counter */ /* The 10-bit E-Bit counter records the Far-End Block Errors (FEBE) as reported in the first bit of frames 13 and 15 on E1 lines running with CRC4 multiframe. These count registers will increment once each time the received E-bit is set to zero. Since the maximum E-bit count in a one second period is 1000, this counter cannot saturate. The counter is disabled during loss of sync at either the FAS or CRC4 level; it will continue to count if loss of multiframe sync occurs at the CAS level. */ if ((count = ((uint) (xlb[0x04] & 0x03) << 8) | ((uint) (xlb[0x05] & 0xff) >> 0))) { } /* FAS Error Counter */ /* The 12-bit FAS counter records the word errors in the Frame Alignment Signal in time slot 0. This counter is disabled when RLOS is high. FAS errors will not be counted when the framer is searching for FAS alignment and/or synchronization at either the CAS or CRC4 multiframe level. Since the maximum FAS word error count in a one second period is 4000, this counter cannot saturate. */ if ((count = ((uint) (xlb[0x02] & 0xfc) >> 4) | ((uint) (xlb[0x04] & 0xfc) >> 2))) { /* NOTE: these are basically PCVs when not in the CRC4 mode. */ if (sp->config.ifgcrc != SDL_GCRC_CRC4) { sp->stats[0].PCVs += count; errors |= XP_ERR_PCV; } } xp_e1_process_state(cd, sp, xlb, flags, errors); /* CCR2.7: ECUS: 0 = 8000 frames, 1 = 500 frames */ if ((sp->interval += (xlb[0x1a] & 0x80) ? 500 : 8000) >= 8000) { sp->interval -= 8000; /* this is a 1 second timeout */ xp_e1_process_stats(sp, errors); sp->status.errors = 0; } else sp->status.errors = errors; return; } /** xp_e1_process_state: - process state transitions for the device. * @cd: card structure pointer * @sp: span structure pointer * @xlb: span iobase * @flags: state flags (read only) * @errors: error flags (read only) * * Process state transitions once a timeout. This is to ensure that the interface state does not * change due to transient conditions of less than 40 ms. Also, any events or errors here have * accumulated for the entire timeout period (more than 40 ms). * * Processing DS21354/554 state transitions is more difficult because there is no transmitter * open-circuit detection capability on the chip, making transmitter state difficult to determine. * Also, receiver input level determination is rather limited in range. Both these deficiencies * make it difficult to automatically determine whether a span is in a monitor configuration or not * and whether linear gain should be applied to the receivers. * * The approach is to take the transmitters offline altogether, and check whether a synced receive * side is indicating a yellow alarm. When the receiver is synced and there is no yellow alarm, * the transmitters are not connected to the line. When the receivers won't sync but there is no * carrier loss, we can use the input level somewhat, and possibly some errors, to determine * whether linear gain should be applied. When there is no carrier for some time, we can go ahead * and try applying linear gain. A new line interface receive carrier loss should start the * process all over again so that when a line is disconnected and then reconnected, it will * autoconfigure again. * * To perform all of these actions, we run a state machine and keep a state variable in * sp->status.state. A state transition is performed at most once every 42/62 ms (short timeout). * The current state and the condition of the state flags and current errors are used to determine * the next state. If we are not autoconfiguring anything, we do not run the state machine. */ static noinline fastcall __hot void xp_e1_process_state(struct cd *cd, struct sp *sp, register volatile uint8_t *xlb, const register uint flags, const register uint errors) { register uint ifflags = sp->config.ifflags; /* integrate receiver state */ if (flags & (XP_STATE_LRCL | XP_STATE_FRCL)) { ifflags &= ~SDL_IF_RX_UP; ifflags &= ~SDL_IF_RX_RUNNING; } else { ifflags |= SDL_IF_RX_UP; if (flags & (XP_STATE_RLOS | XP_STATE_RUA1 | XP_STATE_LORC)) ifflags &= ~SDL_IF_RX_RUNNING; else ifflags |= SDL_IF_RX_RUNNING; } /* integrate transmitter state */ if (flags & (XP_STATE_TOCD | XP_STATE_TSCD)) { ifflags &= ~SDL_IF_TX_UP; ifflags &= ~SDL_IF_TX_RUNNING; } else { ifflags |= SDL_IF_TX_UP; if (flags & (XP_STATE_LOLITC | XP_STATE_LOTC)) ifflags &= ~SDL_IF_TX_RUNNING; else ifflags |= SDL_IF_TX_RUNNING; } /* integrate interface state */ if (flags & (SDL_IF_RX_UP | SDL_IF_TX_UP)) ifflags |= SDL_IF_UP; else ifflags &= ~SDL_IF_UP; /* detect changes in transmitter state */ if ((ifflags ^ sp->config.ifflags) & (SDL_IF_TX_UP | SDL_IF_TX_RUNNING)) { } /* detect changes in receiver state */ if ((ifflags ^ sp->config.ifflags) & (SDL_IF_RX_UP | SDL_IF_RX_RUNNING)) { } /* detect changes in interface state */ if ((ifflags ^ sp->config. ifflags) & (SDL_IF_UP | SDL_IF_TX_UP | SDL_IF_RX_UP | SDL_IF_TX_RUNNING | SDL_IF_RX_RUNNING)) { } /* perform autoconfiguration when necessary */ if (ifflags & SDL_IF_AUTOCONFIG) { if (likely(sp->status.state == 40)) { if (unlikely((flags & (XP_STATE_LRCL)) != 0)) /* lost carrier, start full autoconfig */ sp->status.state = 0; else if (unlikely((flags & (XP_STATE_FRCL)) != 0)) /* lost signal, start partial autoconfig */ sp->status.state = 20; } if (unlikely(sp->status.state != 40)) /* lost configuration hold, process autoconfig */ xp_e1_process_auto(cd, sp, xlb, flags, errors, 1); } } /** xp_e1_process_auto: - process autoconfiguration state machine * @cd: card structure pointer * @sp: span structure pointer * @xlb: span iobase * @flags: state flags * @errors: error events * @timeout: true when timeout * * Note that we do not even execute this function unless SDL_IF_AUTOCONFIG is set in the interface * flags. The function is executed on regular interrupts as well as timeout interrupts. The * @timeout argument is set when the interrupt was as a result of a timeout, and Unset otherwise. * This permits having the autodetection state machine run very quickly for expected * configurations. * * The DS21354/554 chip can perform linear gain for monitoring applications of 12dB or 30dB. 30dB * corresponds to 1800 Ohm isolation resistors (or a triple 470 Ohm high-impedance monitoring tap). * 12dB linear gain (corresponding to 180 Ohm isolation resistors) is not useful for monitoring * applications. * */ static noinline fastcall __unlikely void xp_e1_process_auto(struct cd *cd, struct sp *sp, register volatile uint8_t *xlb, register uint flags, const register uint errors, const uint timeout) { register unsigned int state = sp->status.state; const uint interval = timeout ? ((xlb[0x1a] & 0x80) ? 500 : 8000) : 0; for (;;) { do { if (flags & XP_STATE_LIRST) { /* resetting line interface */ sp->status.count = 0; sp->status.config = 0; state = 0; break; } if ((flags & XP_STATE_LRCL) && (8 <= state)) { /* lost carrier */ sp->status.count = 0; state = 0; break; } if ((flags & XP_STATE_FRCL) && (9 <= state)) { /* lost signal */ sp->status.count = 0; state = 8; break; } if ((flags & XP_STATE_RUA1) && (10 <= state)) { /* lost service */ sp->status.count = 0; state = 9; break; } if ((flags & XP_STATE_RLOS) && (11 <= state && state < 13)) { /* lost sync */ sp->status.count = 0; state = 10; break; } } while (0); switch (state) { default: state = 0; /* fall through */ case 0: /* LIRST subsidance. Wait 125 ms or more when the LIRST condition remains, then clear the conditioni and move on to line detection. */ if (flags & (XP_STATE_LIRST)) { if ((sp->status.count += interval) < 1000) { /* wait for up to 125 ms */ break; } /* remove LIRST flag */ sp->status.flags &= ~(XP_STATE_LIRST); flags &= ~(XP_STATE_LIRST); /* reset elastic stores */ /* CCR6.1: 0->1 RES reset */ /* CCR6.0: 0->1 TES reset */ xlb[0x1d] &= ~((1 << 1) | (1 << 0)); xlb[0x1d] |= (1 << 1) | (1 << 0); xlb[0x1d] &= ~((1 << 1) | (1 << 0)); /* realign elastic stores */ /* CCR5.6: 0->1 RES align (not assigned DS2154) */ /* CCR5.5: 0->1 TES align (not assigned DS2154) */ xlb[0xaa] &= ~((1 << 6) | (1 << 5)); xlb[0xaa] |= (1 << 6) | (1 << 5); xlb[0xaa] &= ~((1 << 6) | (1 << 5)); } /* remove linear gain */ /* TEST3: 0x00 = no Rx gain */ xlb[0xac] = 0x00; /* start transmitter, if not already started */ /* LICR.0: transmitters 0 = on; 1 = off */ xlb[0x18] &= ~(1 << 0); /* send unframed all ones if not sending them already */ /* TCR1.4: 0 = normal data, 1 = unframed all ones */ xlb[0x12] |= (1 << 4); sp->status.count = 0; sp->config.ifflags &= ~(SDL_IF_UP | SDL_IF_RX_UP | SDL_IF_TX_UP | SDL_IF_RX_MON); state = 1; /* fall through */ case 1: /* Line carrier detect, 0dB gain. */ if (flags & (XP_STATE_LRCL)) { if ((sp->status.count += interval) >= 1000) { /* try applying linear gain */ /* apply 12dB linear gain */ /* TEST3: 0x72 = 12dB Rx gain */ xlb[0xac] = 0x72; sp->status.count = 0; state = 2; continue; } /* wait for up to 125 ms */ break; } /* start transmitter, if not already started */ /* LICR.0: transmitters 0 = on; 1 = off */ xlb[0x18] &= ~(1 << 0); sp->config.ifflags &= ~SDL_IF_RX_MON; sp->status.count = 0; state = 8; continue; case 2: /* Line carrier detect, monitoring, 12dB gain. No line carrier was detected with 0dB linear gain, try applying 12dB gain. */ if (flags & (XP_STATE_LRCL)) { if ((sp->status.count += interval) >= 1000) { /* try applying more linear gain */ /* apply 30dB linear gain */ /* TEST3: 0x70 = 30dB Rx gain */ xlb[0xac] = 0x70; sp->status.count = 0; state = 3; continue; } /* wait for 125 ms */ break; } sp->status.count = 0; state = 5; continue; case 3: /* Line carrier detect, monitoring, 30dB gain. No line carrier was detected wtih 0dB and 12dB linear gain, try applying 30dB gain. */ if (flags & (XP_STATE_LRCL)) { if ((sp->status.count += interval) >= 1000) { /* try removing gain again */ /* apply 0dB linear gain */ /* TEST3: 0x00 = no Rx gain */ xlb[0xac] = 0x00; sp->status.count = 0; state = 1; continue; } /* wait up to 125 ms */ break; } /* apply 12dB linear gain */ sp->status.count = 0; state = 4; /* fall through */ case 4: /* Line carrier detected, monitoring, 12dB gain. 30dB gain was applied previously with success, drop back to 12dB gain to test that things were not just connected at a bad time. */ if (flags & (XP_STATE_LRCL)) { if ((sp->status.count += interval) >= 1000) { /* put back to 30dB gain */ /* apply 30dB linear gain */ /* TEST3: 0x70 = 30dB Rx gain */ xlb[0xac] = 0x70; sp->status.count = 0; state = 6; continue; } /* wait for 125 ms */ break; } /* apply 0dB linear gain */ sp->status.count = 0; state = 5; /* fall through */ case 5: /* Line carrier detected, monitoring, 0dB gain. 12dB gain was applied perviously wtih success, drop back to 0dB gain to test that things were not just connected at a bad time. */ if (flags & (XP_STATE_LRCL)) { if ((sp->status.count += interval) >= 1000) { /* put back to 12dB gain */ /* apply 12dB linear gain */ /* TEST3: 0x72 = 12dB Rx gain */ xlb[0xac] = 0x72; sp->status.count = 0; state = 7; continue; } /* wait for 125 ms */ break; } /* start transmitter, if not already started */ /* LICR.0: transmitters 0 = on; 1 = off */ xlb[0x18] &= ~(1 << 0); sp->config.ifflags &= ~SDL_IF_RX_MON; sp->status.count = 0; state = 8; continue; case 6: /* Line carrier detected, monitoring, 30dB gain. 30dB worked, 12dB didn't, go back to 30dB an lock in if successful. */ if (flags & (XP_STATE_LRCL)) { if ((sp->status.count += interval) >= 1000) { /* 30dB worked before but doesn't now, start again */ /* apply 0dB linear gain */ /* TEST3: 0x00 = no Rx gain */ xlb[0xac] = 0x00; sp->status.count = 0; state = 0; continue; } /* wait for 125 ms */ break; } /* stop transmitter, if not already stopped */ /* LICR.0: transmitters 0 = on; 1 = off */ xlb[0x18] |= (1 << 0); sp->config.ifflags |= SDL_IF_RX_MON; sp->status.count = 0; state = 8; continue; case 7: /* Line carrier detected, monitoring, 12dB gain. 12dB worked, 0dB didn't, go back to 12dB an lock in if successful. */ if (flags & (XP_STATE_LRCL)) { if ((sp->status.count += interval) >= 1000) { /* 12dB worked before but doesn't now, start again */ /* apply 0dB linear gain */ /* TEST3: 0x00 = no Rx gain */ xlb[0xac] = 0x00; sp->status.count = 0; state = 0; continue; } /* wait for 125 ms */ break; } /* stop transmitter, if not already stopped */ /* LICR.0: transmitters 0 = on; 1 = off */ xlb[0x18] |= (1 << 0); sp->config.ifflags |= SDL_IF_RX_MON; sp->status.count = 0; state = 8; continue; case 8: /* Framer signal detect. Line carrier detected, 0dB, 12dB or 20dB linear gain applied. When other than 0dB linear gain is applied, SDL_IF_RX_MON flag is set. */ if (flags & (XP_STATE_FRCL)) { if ((sp->status.count += interval) >= 1000) { /* no framer signal, start again */ sp->status.count = 0; state = 0; continue; } /* wait for 125 ms */ break; } sp->status.count = 0; state = 9; /* fall through */ case 9: /* Framing detect, sending unframed all ones. If we are in a loop-around mode we will wait here for manual (specific) configuration because we will be both sending and receiving unframed all ones. However, only wait for 10 seconds and then restart in case there is an error in the state machine that locks us here. */ if (flags & (XP_STATE_RUA1)) { if ((sp->status.count += interval) >= 10 * 8000) { /* no service for 10 seconds, start again */ sp->status.count = 0; state = 0; continue; } /* wait up to 10 seconds */ break; } sp->status.count = 0; state = 10; /* fall through */ case 10: /* Frame detect, not receiving unframed all ones. */ if (flags & (XP_STATE_RLOS)) { if ((sp->status.count += interval) >= 3200) { /* no sync after 400 ms */ /* reconfigure and try again */ if (xp_e1_change_config(sp, xlb)) { /* exhausted possiblilities, start again */ sp->status.count = 0; state = 0; continue; } sp->status.count = 0; /* wait to test possibility */ break; } /* wait for up to 400 ms */ break; } sp->status.count = 0; state = 11; /* fall through */ case 11: /* Transmitter detection, transmitting unframed all ones. We are transmitting unframed all ones, so when there is no remote alarm after 125 ms the transmitters must be disconnected. */ if (!(flags & (XP_STATE_RYEL | XP_STATE_RRA))) { if ((sp->status.count += interval) >= 1000) { /* No alarm after 125 milliseconds, transmitters must be disconnected. When no linear gain is applied, but transmitters are disconnected: this is a 0dB active monitoring tap. When linear gain applied, already monitoring so this is an expected result. */ /* stop transmitter, if not already stopped */ /* LICR.0: transmitters 0 = on; 1 = off */ xlb[0x18] |= (1 << 0); sp->config.ifflags |= SDL_IF_RX_MON; sp->config.ifflags &= ~(SDL_IF_TX_UP); sp->config.ifflags |= (SDL_IF_RX_UP | SDL_IF_UP); sp->status.count = 0; state = 13; continue; } /* wait up to 125 ms */ break; } /* transmit normal frames */ /* TCR1.4: 0 = normal data, 1 = unframed all ones */ xlb[0x12] &= ~(1 << 4); sp->status.count = 0; state = 12; /* fall through */ case 12: /* Transmitter detection, sending normal frames. We previously had a remote alarm condition when sending unframed all ones. We start sending normal frames and check that the alarm clears within 10 seconds. */ if (flags & (XP_STATE_RYEL | XP_STATE_RRA)) { if ((sp->status.count += interval) < 10 * 8000) { /* wait up to 10 seconds */ break; } /* Alarms did not clear after 10 seconds, but this might just be a sync problem. */ } /* start transmitter, if not already started */ /* LICR.0: transmitters 0 = on; 1 = off */ xlb[0x18] &= ~(1 << 0); sp->config.ifflags &= ~SDL_IF_RX_MON; sp->config.ifflags |= (SDL_IF_TX_UP); sp->config.ifflags |= (SDL_IF_RX_UP | SDL_IF_UP); sp->status.count = 0; state = 13; /* fall through */ case 13: /* Stable state, normal mode, transmitters externally connected, sending normal frames. This is an active connection, not a monitoring tap. Flags have been set accordingly. Stay in this state unless we lose carrier, signal, start receiving unframed all ones, or lose sync for more than 400 ms. */ /* Stable state, monitoring mode, transmitters externally disconnected, sending unframed all ones. This is a monitoring tap (active or passive). Flags have been set accordingly. Stay in this state unless we lose carrier, signal, start receiving unframed all ones, or lose sync for more than 400 ms. */ if (flags & (XP_STATE_RLOS)) { /* lost sync */ if ((sp->status.count += interval) >= 3200) { /* send unframed all ones */ /* TCR1.4: 0 = normal data, 1 = unframed all ones */ xlb[0x12] |= (1 << 4); sp->status.count = 0; state = 10; continue; } /* wait for up to 400 ms */ break; } sp->status.count = 0; /* stay in this state */ break; } break; } /* set the new state variable */ sp->status.state = state; } /** xp_e1_change_config: - try changing span configuration for sync * @sp: span structure pointer * @xlb: span iobase * * Diagnose the problem and attempt to change the configuration accordingly. This is an E1 line so * likely difficulties are CCS instead of CAS; CRC4 instead of non-CRC4; HDB3 instead of AMI. We * should simply walk through the possible configurations until one that works is found or all are * exhausted. */ noinline __unlikely int xp_e1_change_config(struct sp *sp, register volatile uint8_t *xlb) { switch (sp->status.config) { case 0: /* CCS, HDB3, CRC4 */ sp->config.ifgtype = SDL_GTYPE_E1; if (sp->config.ifframing != SDL_FRAMING_CCS) { sp->config.ifframing = SDL_FRAMING_CCS; xlb[0x14] |= (1 << 3); /* CCR1.3: 1 = Rx CCS */ xlb[0x12] &= ~(1 << 5); /* TCR1.5: 0 = ch 16 data */ } if (sp->config.ifcoding != SDL_CODING_HDB3) { sp->config.ifcoding = SDL_CODING_HDB3; xlb[0x14] |= (1 << 6); /* CCR1.6: 1 = Tx HDB3 */ xlb[0x14] |= (1 << 2); /* CCR1.2: 1 = Rx HDB3 */ xlb[0x1a] |= (1 << 6); /* CCR2.6: 1 = count CVs */ } if (sp->config.ifgcrc != SDL_GCRC_CRC5) { xlb[0x14] |= (1 << 4); /* CCR1.4: 1 = Tx CRC4 */ xlb[0x14] &= ~(1 << 0); /* CCR1.0: 0 = Rx no CRC4 */ } sp->status.config = 1; break; case 1: /* CCS, HDB3, non-CRC4 */ sp->config.ifgtype = SDL_GTYPE_E1; if (sp->config.ifframing != SDL_FRAMING_CCS) { sp->config.ifframing = SDL_FRAMING_CCS; xlb[0x14] |= (1 << 3); /* CCR1.3: 1 = Rx CCS */ xlb[0x12] &= ~(1 << 5); /* TCR1.5: 0 = ch 16 data */ } if (sp->config.ifcoding != SDL_CODING_AMI) { sp->config.ifcoding = SDL_CODING_AMI; xlb[0x14] &= ~(1 << 6); /* CCR1.6: 0 = Tx AMI */ xlb[0x14] &= ~(1 << 2); /* CCR1.2: 0 = Rx AMI */ xlb[0x1a] &= ~(1 << 6); /* CCR2.6: 0 = count BPVs */ } if (sp->config.ifgcrc != SDL_GCRC_CRC4) { xlb[0x14] |= (1 << 4); /* CCR1.4: 1 = Tx CRC4 */ xlb[0x14] |= (1 << 0); /* CCR1.0: 1 = Rx CRC4 */ } sp->status.config = 2; break; case 2: /* CCS, AMI, CRC4 */ sp->config.ifgtype = SDL_GTYPE_E1; if (sp->config.ifframing != SDL_FRAMING_CCS) { sp->config.ifframing = SDL_FRAMING_CCS; xlb[0x14] |= (1 << 3); /* CCR1.3: 1 = Rx CCS */ xlb[0x12] &= ~(1 << 5); /* TCR1.5: 0 = ch 16 data */ } if (sp->config.ifcoding != SDL_CODING_AMI) { sp->config.ifcoding = SDL_CODING_AMI; xlb[0x14] &= ~(1 << 6); /* CCR1.6: 0 = Tx AMI */ xlb[0x14] &= ~(1 << 2); /* CCR1.2: 0 = Rx AMI */ xlb[0x1a] &= ~(1 << 6); /* CCR2.6: 0 = count BPVs */ } if (sp->config.ifgcrc != SDL_GCRC_CRC5) { sp->config.ifgcrc = SDL_GCRC_CRC5; xlb[0x14] |= (1 << 4); /* CCR1.4: 1 = Tx CRC4 */ xlb[0x14] &= ~(1 << 0); /* CCR1.0: 0 = Rx no CRC4 */ } sp->status.config = 3; break; case 3: /* CCS, AMI, non-CRC4 */ sp->config.ifgtype = SDL_GTYPE_E1; if (sp->config.ifframing != SDL_FRAMING_CAS) { sp->config.ifframing = SDL_FRAMING_CAS; xlb[0x14] &= ~(1 << 3); /* CCR1.3: 0 = Rx CAS */ xlb[0x12] |= (1 << 5); /* TCR1.5: 1 = ch 16 sig */ } if (sp->config.ifcoding != SDL_CODING_HDB3) { sp->config.ifcoding = SDL_CODING_HDB3; xlb[0x14] |= (1 << 6); /* CCR1.6: 1 = Tx HDB3 */ xlb[0x14] |= (1 << 2); /* CCR1.2: 1 = Rx HDB3 */ xlb[0x1a] |= (1 << 6); /* CCR2.6: 1 = count CVs */ } if (sp->config.ifgcrc != SDL_GCRC_CRC4) { sp->config.ifgcrc = SDL_GCRC_CRC4; xlb[0x14] |= (1 << 4); /* CCR1.4: 1 = Tx CRC4 */ xlb[0x14] |= (1 << 0); /* CCR1.0: 1 = Rx CRC4 */ } sp->status.config = 4; break; case 4: /* CAS, HDB3, CRC4 */ sp->config.ifgtype = SDL_GTYPE_E1; if (sp->config.ifframing != SDL_FRAMING_CAS) { sp->config.ifframing = SDL_FRAMING_CAS; xlb[0x14] &= ~(1 << 3); /* CCR1.3: 0 = Rx CAS */ xlb[0x12] |= (1 << 5); /* TCR1.5: 1 = ch 16 sig */ } if (sp->config.ifcoding != SDL_CODING_HDB3) { sp->config.ifcoding = SDL_CODING_HDB3; xlb[0x14] |= (1 << 6); /* CCR1.6: 1 = Tx HDB3 */ xlb[0x14] |= (1 << 2); /* CCR1.2: 1 = Rx HDB3 */ xlb[0x1a] |= (1 << 6); /* CCR2.6: 1 = count CVs */ } if (sp->config.ifgcrc != SDL_GCRC_CRC5) { sp->config.ifgcrc = SDL_GCRC_CRC5; xlb[0x14] |= (1 << 4); /* CCR1.4: 1 = Tx CRC4 */ xlb[0x14] &= ~(1 << 0); /* CCR1.0: 0 = Rx no CRC4 */ } sp->status.config = 5; break; case 5: /* CAS, HDB3, non-CRC4 */ sp->config.ifgtype = SDL_GTYPE_E1; if (sp->config.ifframing != SDL_FRAMING_CAS) { sp->config.ifframing = SDL_FRAMING_CAS; xlb[0x14] &= ~(1 << 3); /* CCR1.3: 0 = Rx CAS */ xlb[0x12] |= (1 << 5); /* TCR1.5: 1 = ch 16 sig */ } if (sp->config.ifcoding != SDL_CODING_AMI) { sp->config.ifcoding = SDL_CODING_AMI; xlb[0x14] &= ~(1 << 6); /* CCR1.6: 0 = Tx AMI */ xlb[0x14] &= ~(1 << 2); /* CCR1.2: 0 = Rx AMI */ xlb[0x1a] &= ~(1 << 6); /* CCR2.6: 0 = count BPVs */ } if (sp->config.ifgcrc != SDL_GCRC_CRC4) { sp->config.ifgcrc = SDL_GCRC_CRC4; xlb[0x14] |= (1 << 4); /* CCR1.4: 1 = Tx CRC4 */ xlb[0x14] |= (1 << 0); /* CCR1.0: 1 = Rx CRC4 */ } sp->status.config = 6; break; case 6: /* CAS, AMI, CRC4 */ sp->config.ifgtype = SDL_GTYPE_E1; if (sp->config.ifframing != SDL_FRAMING_CAS) { sp->config.ifframing = SDL_FRAMING_CAS; xlb[0x14] &= ~(1 << 3); /* CCR1.3: 0 = Rx CAS */ xlb[0x12] |= (1 << 5); /* TCR1.5: 1 = ch 16 sig */ } if (sp->config.ifcoding != SDL_CODING_AMI) { sp->config.ifcoding = SDL_CODING_AMI; xlb[0x14] &= ~(1 << 6); /* CCR1.6: 0 = Tx AMI */ xlb[0x14] &= ~(1 << 2); /* CCR1.2: 0 = Rx AMI */ xlb[0x1a] &= ~(1 << 6); /* CCR2.6: 0 = count BPVs */ } if (sp->config.ifgcrc != SDL_GCRC_CRC5) { sp->config.ifgcrc = SDL_GCRC_CRC5; xlb[0x14] |= (1 << 4); /* CCR1.4: 1 = Tx CRC4 */ xlb[0x14] &= ~(1 << 0); /* CCR1.0: 0 = Rx no CRC4 */ } sp->status.config = 7; break; case 7: /* CAS, AMI, non-CRC4 */ /* last configuration failed, go back to default */ sp->config.ifgtype = SDL_GTYPE_E1; if (sp->config.ifframing != SDL_FRAMING_CCS) { sp->config.ifframing = SDL_FRAMING_CCS; xlb[0x14] |= (1 << 3); /* CCR1.3: 1 = Rx CCS */ xlb[0x12] &= ~(1 << 5); /* TCR1.5: 0 = ch 16 data */ } if (sp->config.ifcoding != SDL_CODING_HDB3) { sp->config.ifcoding = SDL_CODING_HDB3; xlb[0x14] |= (1 << 6); /* CCR1.6: 1 = Tx HDB3 */ xlb[0x14] |= (1 << 2); /* CCR1.2: 1 = Rx HDB3 */ xlb[0x1a] |= (1 << 6); /* CCR2.6: 1 = count CVs */ } if (sp->config.ifgcrc != SDL_GCRC_CRC4) { sp->config.ifgcrc = SDL_GCRC_CRC4; xlb[0x14] |= (1 << 4); /* CCR1.4: 1 = Tx CRC4 */ xlb[0x14] |= (1 << 0); /* CCR1.0: 1 = Rx CRC4 */ } sp->status.config = 0; return (1); } return (0); } /** xp_e1_process_stats: - process statistics (performance measures) for the span * @sp: span structure pointer * @errors: error events accumulated so far. * * ERROR EVENTS: * Bipolar Violation BPV Error Event: A BPV error event for an AMI coded signal is the occurrence * of a pulse of the same polarity as the previous pulse. A BPV error event for a B8ZS or HDB3 * coded signal is the occurrence of a pulse of the same polarity as the previous pulse without * being part of the zero substitution code. * * Controlled Slip (CS) Error Event: A CS is the replication or deletion of the payload bits of a * DS1 frame. A CS may be performed when there is a difference between the timing of a * synchronous receiving terminal an the received signal. A CS does not acuase an Out of Frame * defect. * * Excessive Zeros (EXZ) Error Event: An EXZ error event for an AMI coded signal is the occurence * of more than fifteen contiguous zeros. For a B8ZS coded signal, the defect occurs when more * than seven contiguous zeros are detected. * * Line Coding Violation (LCV) Error Event: An LCV is the occurence of either a Bipolar Violation * or Excessive Zeros (EXZ) error event. * * Path Coding Violation (PCV) Error Event: A PCV error event is a frame synchronization bit error * in the D4 and E1-non-CRC-4 formats, or a CRC error in the ESF and E1-CRC-4 formats. * * PERFORMANCE PARAMETERS: * All performance parameters are accumulated in fifteen minute intervals and up to 96 intervals * (covering a 24-hour period) are kept by an agent. Fewer than 96 intervals of data will be * available if the agent has been restarted within the last 24 hours. In addition, there is a * rolling 24-hour total of each performance parameter. There is no requirement for an agent to * ensure a fixed relationship between the start of a fifteen minute interval and clock time; * however, some agents may align the fifteen minute intervals with quarter hours. * * Severely Errored Seconds (SES): An SES for ESF signals is a second with one of the following: * 320 or more PCV error events; one or more OOF defects; a detected AIS defect. For E1 CRC-4 * signals, an SES is a second with either 832 or more PCV error events or one or more OOF * defects. For E1 non-CRC-4 signals, an SES is a 2048 (LCV ????) PCV or more. For D4 signals, * an SES is a count of one-second intervals with Framing Error events, or an OOF defect, or * 1544 LCV or more. Controlled slips are not included in this parameter. This is not * incremented during an Unavailable Second. * * Severely Errored Framing Seconds (SEFS): An SEFS is a second with either one or more OOF * defects, or a detected AIS defect. * * Unavailable Seconds (UASs): A performance management event that is calculted by counting the * number of seconds for which the interface is unavailable. An interface is said to be * unavailable from the onset of 10 continugous Severely Errored Seconds (SESs), or on the * onset of a condition leading to a failutre. Once unavailable, and if no failure is present, * an interface becomes available at the onset of 10 contiguous seconds with no SESs. * * UAS are calculated by counting the number of seconds that the interface is unavailable. The * DS1 interface is said to be unavailable from the onset of ten contiguous SESs, or the onset * of the condition leadeing to a failure (see Failure States). If the condition leading to * the failure was immediately preceded by one or more continguous SES, then the DS1 interface * unavailability starts from the onset of these SES. Once unavailable, and if no failure is * present, the DS1 interfae becomes available at the onset of 10 contiguous seconds with no * SES. if the failure clearing time is less than or equat to ten seconds. If the failure * clearing time is more than ten seconds, the DS1 interface becoms available at the onset of * tem contiguous seconds with no SES, or the onset period leading to the successful clearing * condition, whichever occurs later. With respect to DS1 error counts, all coutners are * incremented while the DS1 interface is deemed available. While the interface is deemed * unavailable, the only count that is incremented is UAS. A special case exists when the ten * or more second period crosses the 900 second statistic window boundary, as the foregoing * description ipmlies that the SES and UAS counter must be adjusted when the UAS stats is * entered. Successive "gets" of the affectetd dsx1IntervalSESs and dsx1IntervalUASs objects * will return differing values if the first get occurs during the first few seconds of the * window. This is viewed as an unavoidable side-effect of selecting the presently-defined * objects. * * Bursty Errored Secods (BES): A BES (also known as an Errored Second Type B) is a second with * fewer than 320 and more than one PCV, no SEF defects, and no detected incoming AIS defects. * Controlled slips are not incldued in this parameter. * * Errored Seconds (ES): For ESF and E1-CRC links an Errored Second is a second with one of the * followng: one or more PCV; one or more OOF defects; one or more Controlled Slip events; a * detected AIS defect. * * Controlled Slip Seconds (CSS): A cCSS is a one-second interval containing one or more controlled * slips. * * Line Errored Seconds (LES): A LES, according to T1M1.3, is a second in which one or more LCV * error events were detected. While many implementations are currently unable to detect the * zero strings, it is expected that interface manufacturers will add this capability in * deference to ANSI; therefore, it will become available in time. In the T1M1.3 specification, * near end LCV and far end LES are counted. For consistency, we count LES at both ends. * * Degraded Minutes: A DM is one in which the estimated error rate exceeds 1E-06 but does not * exceed 1E-03. DM are determined by collecting all of the Available Seconds, removing any * Severely Errored Seconds grouping the result in 60-second long groups and counting a * 60-second long group (minute) as degraded if the cumulative errors during the seconds * present in the group exceed 1E-6. Available seconds are merely those seconds which are not * unavailable as described below. */ static noinline fastcall __hot void xp_e1_process_stats(struct sp *sp, register uint errors) { /* This is a one second timeout. */ /* This is a one second timeout */ /* Calculate severely errored seconds. */ switch (sp->config.ifgcrc) { case SDL_GCRC_CRC4: /* For E1 CRC4 signals, an SES is 832 or more PCV error events, or one or more Out of Frame defects. */ if (sp->stats[0].PCVs >= 832) errors |= XP_ERR_SES; break; case SDL_GCRC_CRC5: /* For E1 non-CRC4 signals, an SES is 2048 or more LCV. */ if (sp->stats[0].LCVs >= 2048) errors |= XP_ERR_SES; break; } /* The number of Unavailable Seconds (UASs) in the current interval. */ /* Track the number of consecutive severely errored seconds and the number of consecutive non-severely errored seconds */ if (errors & (XP_ERR_SES)) { sp->status.nses = 0; sp->status.sess++; if (sp->status.sess >= 10) { if (sp->status.sess == 10 && !(errors & XP_ERR_UAS)) { sp->stats[0].UASs += 9; errors |= XP_ERR_UAS; } errors |= XP_ERR_UAS; } } else { sp->status.sess = 0; sp->status.nses++; if (sp->status.nses >= 10) { if (sp->status.nses == 10 && (errors & XP_ERR_UAS)) { sp->stats[0].UASs -= 9; errors &= ~XP_ERR_UAS; } errors &= ~XP_ERR_UAS; } } if (errors & (XP_ERR_UAS)) sp->stats[0].UASs += 1; /* Calculate bursty errored seconds */ switch (sp->config.ifgcrc) { case SDL_GCRC_CRC4: if (1 < sp->stats[0].PCVs && sp->stats[0].PCVs < 832) if (!(errors & XP_ERR_SEFS)) if (!(errors & XP_FAIL_AIS)) errors |= XP_ERR_BES; break; case SDL_GCRC_CRC5: if (1 < sp->stats[0].LCVs && sp->stats[0].LCVs < 2048) if (!(errors & XP_ERR_SEFS)) if (!(errors & XP_FAIL_AIS)) errors |= XP_ERR_BES; break; } /* The number of Errored Seconds (ESs) in the current interval. */ if (sp->stats[0].PCVs > 0) errors |= XP_ERR_ES; if (errors & (XP_ERR_ES)) sp->stats[0].ESs = 1; /* The number of severely errored seconds (SESs) in the current interval. */ if (errors & (XP_ERR_SES)) sp->stats[0].SESs = 1; /* The number of Severely Errored Framing Seconds (SEFSs) in the current interval. */ if (errors & (XP_ERR_SEFS)) sp->stats[0].SEFSs = 1; /* The number of controlled slip seconds (CSSs) in the current interval. */ if (errors & (XP_ERR_CSS)) sp->stats[0].CSSs = 1; /* The number of Line Errored Seconds (LESs) in the current interval. */ if (errors & (XP_ERR_LES)) sp->stats[0].LESs = 1; /* The number of Bursty Errored Seconds (BESs) in the current interval. */ if (errors & (XP_ERR_BES)) sp->stats[0].BESs = 1; /* accumulate the one-second counts */ sp->stats[1].ESs += sp->stats[0].ESs; sp->stats[1].SESs += sp->stats[0].SESs; sp->stats[1].ESs += sp->stats[0].ESs; sp->stats[1].SESs += sp->stats[0].SESs; sp->stats[1].SEFSs += sp->stats[0].SEFSs; sp->stats[1].UASs += sp->stats[0].UASs; sp->stats[1].CSSs += sp->stats[0].CSSs; sp->stats[1].PCVs += sp->stats[0].PCVs; sp->stats[1].LESs += sp->stats[0].LESs; sp->stats[1].BESs += sp->stats[0].BESs; sp->stats[1].DMs += sp->stats[0].DMs; sp->stats[1].LCVs += sp->stats[0].LCVs; sp->stats[1].FASEs += sp->stats[0].FASEs; sp->stats[1].FABEs += sp->stats[0].FABEs; sp->stats[1].FEBEs += sp->stats[0].FEBEs; bzero(&sp->stats[0], sizeof(sp->stats[0])); if ((++sp->stats[1].SECs) == 60) { /* this is a minute timeout */ /* The number of degraded minutes (DMs) in the current interval. */ if (errors & (XP_ERR_DM)) sp->stats[1].DMs = 1; /* accumulate one-minute counts */ sp->stats[2].ESs += sp->stats[1].ESs; sp->stats[2].SESs += sp->stats[1].SESs; sp->stats[2].ESs += sp->stats[1].ESs; sp->stats[2].SESs += sp->stats[1].SESs; sp->stats[2].SEFSs += sp->stats[1].SEFSs; sp->stats[2].UASs += sp->stats[1].UASs; sp->stats[2].CSSs += sp->stats[1].CSSs; sp->stats[2].PCVs += sp->stats[1].PCVs; sp->stats[2].LESs += sp->stats[1].LESs; sp->stats[2].BESs += sp->stats[1].BESs; sp->stats[2].DMs += sp->stats[1].DMs; sp->stats[2].LCVs += sp->stats[1].LCVs; sp->stats[2].FASEs += sp->stats[1].FASEs; sp->stats[2].FABEs += sp->stats[1].FABEs; sp->stats[2].FEBEs += sp->stats[1].FEBEs; bzero(&sp->stats[1], sizeof(sp->stats[1])); if ((sp->stats[2].SECs += 60) == 900) { uint index = sp->curr; sp->hist[index] = sp->stats[2]; sp->hist[index].ValidData = 2; /* true(2) */ bzero(&sp->stats[2], sizeof(sp->stats[2])); if (++index == 96) index = 0; sp->curr = index; } } return; } static noinline fastcall __hot void xp_e1_process_alarms(struct cd *cd, struct sp *sp, register volatile uint8_t *xlb, register uint flags, uint timeout) { register uint alarms = sp->config.ifalarms; /* integrate alarms */ if ((flags & XP_STATE_RDMA) && (sp->config.ifframing == SDL_FRAMING_CAS)) alarms |= SDL_ALARM_DMF; else alarms &= ~SDL_ALARM_DMF; if (flags & (XP_STATE_RRA | XP_STATE_RYEL)) alarms |= SDL_ALARM_YEL; else alarms &= ~SDL_ALARM_YEL; if (flags & XP_STATE_RUA1) alarms |= SDL_ALARM_BLU; else alarms &= ~SDL_ALARM_BLU; if (flags & (XP_STATE_RLOS | XP_STATE_FRCL | XP_STATE_LRCL)) alarms |= SDL_ALARM_RED; else alarms &= ~SDL_ALARM_RED; if ((alarms & SDL_ALARM_REC) && (timeout)) { if (alarms & (SDL_ALARM_RED | SDL_ALARM_BLU)) alarms &= ~SDL_ALARM_REC; else { /* recovery time in terms of timeouts (5 seconds) */ if (sp->recovertime && !--sp->recovertime) { /* Note that this should not have to be performed because we have set Automatic RAI on, but it cannot hurt. */ xlb[0x21] &= ~(1 << 5); /* TNAF.5: A: 0 = no RAI */ alarms &= ~SDL_ALARM_REC; cd->eval_syncsrc = 1; } } } /* if any of the alarms (or recovery) changed we need to do this */ if ((alarms ^ sp->config.ifalarms) & (SDL_ALARM_RED | SDL_ALARM_BLU | SDL_ALARM_YEL | SDL_ALARM_REC)) { if ((alarms & (SDL_ALARM_RED | SDL_ALARM_BLU)) && !(sp->config.ifalarms & (SDL_ALARM_RED | SDL_ALARM_BLU))) { /* Local alarms have just begun. Signal a yellow (RAI) alarm to the other end. */ if (!(alarms & SDL_ALARM_REC)) { /* Note that this should not have to be performed because we have set Automatic RAI on, but it cannot hurt. */ xlb[0x21] |= (1 << 5); /* TNAF.5: A: 1 = RAI */ /* local alarms just begun and we were not in recovery */ if (alarms & SDL_ALARM_RED) cd->eval_syncsrc = 1; } else alarms &= ~SDL_ALARM_REC; } else if ((alarms & SDL_ALARM_RED) && !(sp->config.ifalarms & SDL_ALARM_RED)) { /* red alarm just got added to the set, reevaluate the sync source */ cd->eval_syncsrc = 1; } else if (!(alarms & (SDL_ALARM_RED | SDL_ALARM_BLU)) && (sp->config.ifalarms & (SDL_ALARM_RED | SDL_ALARM_BLU))) { /* Local alarms have just ended. */ alarms |= SDL_ALARM_REC; if (xlb[0x1a] & 0x80) /* CCR2.7: ECUS */ sp->recovertime = X400P_SDL_ALARM_SETTLE_E1; else sp->recovertime = X400P_SDL_ALARM_SETTLE_SECONDS; } sp->config.ifalarms &= ~(SDL_ALARM_RED | SDL_ALARM_BLU | SDL_ALARM_YEL | SDL_ALARM_REC); sp->config.ifalarms |= (alarms & (SDL_ALARM_RED | SDL_ALARM_BLU | SDL_ALARM_YEL | SDL_ALARM_REC)); { int leds = 0, all_leds; /* adjust leds */ if (alarms & SDL_ALARM_RED) leds |= LEDRED; else if (alarms & SDL_ALARM_YEL) leds |= LEDYEL; else leds |= LEDGRN; all_leds = cd->ledreg; all_leds &= ~(LEDYEL << (sp->span << 1)); all_leds |= (leds << (sp->span << 1)); if (cd->ledreg != all_leds) { cd->ledreg = all_leds; cd->xlb[LEDREG] = cd->ledreg; } } } } /** xp_e1_eval_syncsrc: - reevaluate synchronization source for card * @cd: card structure pointer * * There is really only one version of this function, it is just laid out in several places for * proper position with respect to the main interrupt service routine. */ static noinline fastcall __hot void xp_e1_eval_syncsrc(struct cd *cd) { /* for safety */ if (cd->config.ifsyncsrc[0] != 0) { int src, synreg = SYNCSELF, ctlreg, clkreg = cd->clkreg; for (src = 0; src < SDL_SYNCS; src++) { struct sp *sp; int span; if ((span = cd->config.ifsyncsrc[src]) == 0) break; if ((--span < cd->ports && span >= 0) && (sp = cd->spans[span]) && (sp->config.ifflags & SDL_IF_UP) && (sp->config.ifflags & SDL_IF_RX_UP) && (sp->config.ifflags & SDL_IF_RX_RUNNING) && (sp->config.ifclock != SDL_CLOCK_LOOP) && !(sp->config.ifalarms & (SDL_ALARM_BLU | SDL_ALARM_RED))) { synreg = cd->config.ifsyncsrc[src]; if (sp->config.ifgtype == SDL_GTYPE_E1) clkreg |= E1DIV; else clkreg &= ~E1DIV; break; } } if (cd->config.ifsync != synreg) { cd->config.ifsync = synreg; ctlreg = cd->ctlreg & ~E1DIV; ctlreg |= clkreg; /* use divider for span or clock */ cd->xlb[CTLREG] = cd->ctlreg = ctlreg; cd->xlb[SYNREG] = cd->synreg = synreg; } } } /* * DS21352/DS21552 Status Registers: * --------------------------------- * When a particular even has occurred (or is occuring), the appropriate bit in one of these * registers will be set to a one. All of the bits in SR1, SR2, RIR1, RIR2, and RIR3 registers * operate in a latched fashion. This means that if an event or an alarm occurs and a bit is set * to a one in any of the registers, it will remain set until the user reads that bit. The bill * will be cleared when it is read and it will not be set again until the event has occurred again * (or in the case of the RBL, RYES, LRCL, and RLOS alarms, the bit will rmain set if the alarm is * still present). * * The user will always proceed a read of any of the status registers with a write. The byte * written to the register will inform the DS21352/552 which bits the user wishes to read and have * cleared. The user will write a byte to one of these registers, with a one in the bit positions * she wishes to read and a zero in the bit positions she does not wish to obtain the latest * information on. When a one is written to a bit location, the read register will be updated with * the latest information. When a zero is written to a bit position, the read register will not be * updated and the previous value will be held. A write to the status and information registers * will be immediately followed by a read of the same register. The read result should be * logically AND'ed with the mask byte that was just written and this value should be written back * into the same register to ensure that the bit does indeed clear. This second write step is * necessary because the alarms and events in the status register occur asynchronously in respect * to their access via the parallel port. This write-read-write scheme allows an external * microcontroller or microprocessor to individually poll certain bits without disturbing the other * bits in the register. This operation is key in controlling the DS21352/552 with higher-order * software languages. * * The SR1 and SR2 registers have the unique ability to initiate a hardware interrupt via the INT * output pin. Each of the alarms and events in the SR1 and SR2 can be either masked or unmaksed * from the interrupt pin via the IMR1 and IMR2 register. * * The interrupts cause by alarms in SR1 (namely RYEL, LRCL, RBL and RLOS) act differently than the * interrupts caused by events in SR1 and SR2 (namely LUP, LDN, LOTC, RSLIP, RMF, TMF, SEC, RFDL, * TFDL, RMTCH, RAC and RSC). The alarm caused interrupts will force the INT pin low whenever the * alarm changes state (i.e., the alarm goes active or inactive according to the set/clear criteria * in Table 7-2). The INT pin will be allowed to return high (if no other interrrupts are present) * when the user reads the alarm bit that caused the interrupt to occur even if the alarm is still * present. The event caused interrupts will force the INT pin low when the event occurs. The INT * pin will be allowed to return high (if no other interrupts are present) when the user reads the * event bit that caused the interrupt to occur. * * RIR1 (0x22) * RIR1.7: COFA Change of Frame Alignment. Set when the last resync resulted in a change of frame * or multifram alignement. * RIR1.6: 8ZD Eight Zero Detect. Set when a string of at least eight consecutive zeros * (regardless of the length of the string) have been received at RPOS1 and RNEG1. * RIR1.5: 16ZD Sixteen Zero Detect. Set when a string of at least sixteen consecutive zeros * (regardless of the length of the string) have been received at RPOS1 and RNEG1. * RIR1.4: RESF Receive Elastic Store Full. Set when the receive elastic store buffer fills and * a frame is deleted. * RIR1.3: RESE Receive Elastic Store Empty. Set when the receive elastic store buffer empties * and a frame is repeated. * RIR1.2: SEFE Severetly Error Framing Event. Set when 2 our of 6 framing bits (Ft or FPS) are * received in error. * RIR1.1: B8ZS B8ZS Code Word Detect. Set when a B8ZS code word is detected at RPOS1 and RNEG1 * independent of whether the B8ZS mode is selected or not via CCR2.6. Useful for * automatically setting the line coding. * RIR1.0: FBE Frame Bit Error. Set when a Ft (D4) or FPS (ESF) framing bit is received in * error. * * RIR2 (0x31) * RIR2.7: RLOSC Receive Loss of Sync Clear. Set when the framer acheives syncrhonization; will * remain set until read. * RIR2.6: LRCLC Line Interface Receive Carrier Loss Clear. Set when the carrier signal is * restored; will remain set until read. See Table 7-2. * RIR2.5: TESF Transmit Elastic Store Full. Set when the transmit elastic store buffer fills * and a frame is deleted. * RIR2.4: TESE Transmit Elastic Store Empty. Set hwen the transmit elastic store buffer * empties and a frame is repeated. * RIR2.3: TSLIP Transmit Elastic Store Slip Occurence. Set when the transmit elastic store has * either repeated or deleted a frame. * RIR2.2: RBLC Receive Blue Alarm Clear. Set when the Blue Alarm (AIS) is no longer detected; * will remain set until read. See Table 7-2. * RIR2.1: RPDV Receive Pulse Density Violation. Set when the receive data stream does not meet * the ANSI T1.403 requirements for pulse density. * RIR2.0: TPDV Transmit Pulse Density Violation. Set when the transmit data stream does not * meet the ANSI T1.403 requirements for pulse density. * * RIR3 (0x10) * RIR3.7: RL1 Receive Level Bit 1. * RIR3.6: RL0 Receive Level Bit 0. * '00'B +2dB to -7.5dB * '01'B -7.4dB to -15dB * '10'B -15dB to -22.5dB * '11'B less than -22.5dB * RIR3.5: JALT Jitter Attenuation Trip Limit. Set when the jitter attenuator FIFO reachs to * within 4 bits of its limit; useful for debugging jitter attenuation operation. * RIR3.4: LORC Loss of Receive Clock. Set when the RCLKI pin has not transitioned for at least * 2 us (4 us max). * RIR3.3: FRCL Framer Receive Carrier Loss. Set when 192 consecutive zeros have been received * at the RPOSI and RNEGI pins; allowed to be cleared when 14 or more ones out of * 112 possible bit positions are received. * RIR3.2: N/A * RIR3.1: N/A * RIR3.0: N/A * * SR1 (0x20) * SR1.7: LUP Loop Up Code Detected. Set when the loop up code as defined in the RUPCD * register is being received. See section 16.5 for details. * SR1.6: LDN Loop Down Code Detected. Set when the loop down code as defined in the RDNCD * register is being received. See section 16.5 for details. * SR1.5: LOTC Loss of Transmit Clock. Set when the TCLK pin has not transitioned for one * channel time (or 5.2 us). Will force RLOS/LOTC pin high if enabled via CCR1.6. * Also will force transmit side formatter to switch to RCLK if so enabled with * TCR1.7. * SR1.4: RSLIP Receive Elastic Store Slip Occurrence. Set when the receive elastic store has * either repeated or deleted a frame. * SR1.3: RBL Receive Blue Alarm. Set when an unframed all one's code is received at RPOSI * and RNEGI. * SR1.2: RYEL Receive Yellow Alarm. Set when a yellow alarm is received at RPOSI and RNEGI. * SR1.1: LRCL Line Interface Receive Carrier Loss. Set when a red alarm is received at RTIP * and RRING. * SR1.0: RLOS Receive Loss of Sync. Set when the device is not synchronized to the receive T1 * stream. * * SR2 (0x21) * SR2.7: RMF Receive Multiframe. Set on receive multiframe boundaries. * SR2.6: TMF Transmit Multiframe. Set on transmit multiframe boundaries. * SR2.5: SEC One Second Timer. Set on increments of one second based on RCLK; will be set in * increments of 999ms, 999ms, and 1002ms every 3 seconds. * SR2.4: RFDL Receive FDL Buffer Full. Set when the receive FDL buffer (RFDL) fills to * capacity (8 bits). * SR2.3: TFDL Transmit FDL Buffer Empty. We then the transmit FDL buffer (TFDL) empties. * SR2.2: RMTCH Receive FDL Match Occurence. Set when the RFDL matches either RFDLM1 or RFDLM2. * SR2.1: RAF Receive FDL Abort. Set when eight conecutive one's are received in the FDL. * SR2.0: RSC Receive Signaling Change. Set when the DS21352/552 detects a change of stat in * any of the robbed-bit signalling bits. * * IMR1 (0x7f) * IMR1.7: LUP SR1.7 * IMR1.6: LDN SR1.6 * IMR1.5: LOTC SR1.5 * IMR1.4: RSLIP SR1.4 * IMR1.3: RBL SR1.3 * IMR1.2: RYEL SR1.2 * IMR1.1: LRCL SR1.1 * IMR1.0: RLOS SR1.0 * * IMR2 (0x6f) * IMR2.7: RMF SR2.7 * IMR2.6: TMF SR2.6 * IMR2.5: SEC SR2.5 * IMR2.4: RFDL SR2.4 * IMR2.3: TFDL SR2.3 * IMR2.2: RMTCH SR2.2 * IMR2.1: RAF SR2.1 * IMR2.0: RSC SR2.0 * */ static noinline fastcall __hot void xp_x1_txrx_burst(struct cd *cd); static noinline fastcall __hot void xp_x1_process_span(struct cd *cd, struct sp *sp, register volatile uint8_t *xlb, register uint ints); static noinline fastcall __hot void xp_x1_process_timeout(struct cd *cd, struct sp *sp, volatile uint8_t *xlb, register uint flags); static noinline fastcall __hot void xp_x1_process_state(struct cd *cd, struct sp *sp, volatile uint8_t *xlb, const register uint flags, const register uint errors); static noinline fastcall __hot void xp_x1_process_stats(struct sp *sp, register uint errors); static noinline fastcall __hot void xp_x1_process_alarms(struct cd *cd, struct sp *sp, register volatile uint8_t *xlb, register uint flags, uint timeout); static noinline fastcall __hot void xp_x1_eval_syncsrc(struct cd *cd); static noinline fastcall __unlikely void xp_x1_process_auto(struct cd *cd, struct sp *sp, register volatile uint8_t *xlb, register uint flags, const register uint errors, const uint timeout); noinline __unlikely int xp_x1_change_config(struct sp *sp, register volatile uint8_t *xlb); noinline __unlikely int xp_x1_change_gtype(struct sp *sp, register volatile uint8_t *xlb); /** xp_x1_interrupt: - process a TE400 interrupt * @irq: interrupt number * @dev_id: card structure pointer (opaque) * @regs: interrupted registers * * The user always precedes a read of any of the status registers with a write. The byte written * to the register informs the DS2155 which bits the user wishes to read and have cleared. The * user writes a byte to one of these registers, with a 1 in the bit potions the user wishes to * reate and a 0 in the bit positions the user does not wish to obtain the latest information on. * When a 1 is written to a bit location, the read register is updated with the latest information. * When a 0 is written to a bit position, the read register is not updated and the previous value * is held. A write to the status registers is immediately followed by a read of the same * register. This read-write scheme allows an external microcontroller or microprocessor to * individually poll certain bits without disturbing the other bits in the register. This * operation is key in controlling the DS2155 with higher order languages. * * Process an interrupt for a TE400 card (with a DS21Q55, DS21455 or DS21458 chip). The spans on * this card can be either E1 or T1/J1 spans. This is a departure from the previous driver which * counted frames to determine timeout events: here we utilize the Dallas interrupts available on * the card for non-frame events. This function should really be aligned on a page boundary and * the functions that it calls laid out immediately following the function, thus the forward * declarations above. */ STATIC __hot irqreturn_t #ifdef HAVE_KTYPE_IRQ_HANDLER_2ARGS xp_x1_interrupt(int irq, void *dev_id) #else xp_x1_interrupt(int irq, void *dev_id, struct pt_regs *regs) #endif { static unsigned long lasttime = 0; struct cd *cd = (struct cd *) dev_id; int safety; /* Keep another processor from entering the interrupt while another is already processing the interrupt. This means that the top half of the driver must disable interrupts when taking the card lock to avoid deadly embrace. */ spin_lock(&cd->lock); /* active interrupt (otherwise, supurios or shared) */ if (!(cd->xlb[STAREG] & (INTACTIVE | DINTACT))) { spin_unlock(&cd->lock); return (irqreturn_t) (IRQ_NONE); } if (likely(cd->xlb[STAREG] & INTACTIVE)) { cd->xlb[CTLREG] = cd->ctlreg | (INTENA | OUTBIT | DINTENA | INTACK); xp_x1_txrx_burst(cd); cd->xlb[CTLREG] = cd->ctlreg | (INTENA | DINTENA); } for (safety = 0; unlikely(cd->xlb[STAREG] & DINTACT); safety++) { uint span; struct sp *sp; /* Try to keep this burning a loop here when there is only one span that is responsible for the Dallas interrupt. */ for (span = 0; span < cd->ports; span++) if (likely((sp = cd->spans[span]) != NULL)) { register volatile uint8_t *xlb = (typeof(xlb)) sp->iobase; register uint ints; xlb[0x14] = 0x1f; /* SR1 thru SR5 */ if (likely((ints = xlb[0x14] & 0x1f) != 0)) xp_x1_process_span(cd, sp, xlb, ints); } if (unlikely(safety > 8)) { /* throttle software error message */ if (lasttime == 0 || (jiffies - lasttime) > HZ) { lasttime = jiffies; swerr(); } break; } } /* Reevaluate the sync source when necessary. Try to skip the call here whenever possible to keep the ISR tight. */ if (unlikely(xchg((int *) &cd->eval_syncsrc, 0) != 0)) { if (cd->config.ifsyncsrc[0] != 0) xp_x1_eval_syncsrc(cd); } spin_unlock(&cd->lock); return (irqreturn_t) (IRQ_HANDLED); } /** xp_x1_txrx_burst: - burst transfer TX and RX data * @cd: card structure pointer * * This function is responsible for transfering frame data to and from the card. This is being * done with host driven I/O because the PLX9030 is incapable of bus mastering DMA. When the * memory mapped I/O region is properly described, PCI burst transfers will occur. Transfers are * 1024 bytes written and 1024 bytes read. These are interleaved, but might better be performed as * 4 Lword interleaved transfers. * * This function is identical to xp_e1_txrx_burst(), but is laid out again here so that it is in * the correct location w.r.t. the main interrupt routine. */ static noinline fastcall __hot void xp_x1_txrx_burst(struct cd *cd) { int lebno; if ((lebno = (cd->lebno + 1) & (X400P_EBUFNO - 1)) != cd->uebno) { register int slot; register volatile uint32_t *xll; register const uint32_t *wbuf = cd->wbuf + (lebno << 8); register const uint32_t *const wend = wbuf + 256; register uint32_t *rbuf = cd->rbuf + (lebno << 8); cd->lebno = lebno; for (xll = cd->xll; wbuf < wend;) for (wbuf++, rbuf++, xll++, slot = 1; slot < 32; slot++, xll++, wbuf++, rbuf++) { prefetch(wbuf + 1); prefetchw(rbuf + 1); *xll = *wbuf; *rbuf = *xll; } tasklet_hi_schedule(&cd->tasklet); } else xp_overflow(cd); } /** xp_x1_process_span: - process Dallas interrupts for a single span * @cd: card structure pointer * @sp: span structure pointer * @xlb: Dallas chip address space * @ints: active interrupt status register mask * * PERFORMANCE DEFECTS: * * XP_DEF_AIS: Alarm Indication Signal (AIS) Defect: * For D4 and ESF links, the 'all ones' condition is detected at a DS1 line interface upon * observing an unframed signal with a one's density of at least 99.9 percent present for a * time equal to or greater than T, where 3ms is less than or equal to T, which is less than or * equal to 75ms. The AIS is terminated upon observing a signal not meeting the one's density * of the unframed signal criteria for a period equal to or greater than T. For E1 links, the * 'all-ones' condition is detected at the line interface as a string of 512 bits containing * fewer than three zero bits. * * XP_DEF_OOF: Out of Frame (OOF) Defect: * An OOF defect is the occurrence of a particular density of Framing Error events. For T1 * links, an OOF defect is declared when the receiver detects two or more framing errors within * a 3 ms period for ESF signals and 0.75 ms for D4 signals, or two or more errors out of five, * or fewer consecutive framing-bits. For E1 links, an OOF defect is declared when three * consecutive frame alignment signals have been received with an error. When an OOF defect is * declared, the frame starts searching for a correct pattern. The OOF defect ends when the * signal is in-frame. In-frame occurs when there are fewer than two frame bit errors within a * 3 ms period for ESF signals and 0.75 ms for D4 signals. For E1 links, in-frame occurs when * in frame N, the frame alignment signal is correct; and, in frame N+1, the frame alignment * signal is absent (that is, bit 2 in TS0 is set to one); and, in frame N+2, the frame * alignment signal is present and correct. * * FAILURE STATES: The following failure states are received or detected failures that are * reported. The conditions under which a DS1 interface would, if ever, produce the conditions * leading to the failure state are described in the appropriate specification. * * XP_FAIL_AIS: Alarm Indication Signal (AIS) Failure: * The AIS failure is declared when an AIS defect is detected at the input and the AIS defect * still exists after the LOF failure (which is caused by the unframed nature of the all-ones * signal) is detected. The AIS failure is cleared when the LOF failure is cleared. * * XP_FAIL_FEA: Far End Alarm Failure (Yellow Alarm): * The Far End Alarm failure is also known as Yellow Alarm in the T1 cases and Distant Alarm * (or RAI) in the E1 case. For D4 links, the FEA failure is declared when bit 6 of all * channels have been zero for at least 335 ms and is cleared when bit 6 of at least one * channel is non-zero for a period T, where T is usually less than one second and alway less * than five seconds. The FEA failure is not declared for D4 links when LOS is detected. For * ESF links, the FEA failure is declared if the Yellow Alarm signal pattern occurs in a least * seven out of ten contiguous 16-bit-pattern intervals and is cleared if the Yellow Alarm * signal pattern does not occur in ten contiguous 16-bit signal pattern intervals. For E1 * links, the FEA failure is declared when bit 3 of time-slot zero is set to one on two * consecutive occasions. The FEA failure is cleared when bit 3 of time-slot zero is received * set to zero. * * XP_FAIL_FELOM: Far End Loss of Multiframe Failure: * The FELOM failure is declared when bit 2 of TS16 of frame 0 is received set to one on two * consecutive occasions. The FELOM failure is cleared when bit 2 of TS16 of frame 0 is * received set to zero. The FELOM failure can only be declared for E1 links operating in CAS * mode. * * XP_FAIL_LPF: Loopback Pseudo-Failure: * The LPF is declared when the near end equipment has placed a loop-back (of any kind) on the * DS1. This allows a management entity to determine from one object whether the DS1 can be * considered to be in service or not (from the point of view of the near-end equipment). * * XP_FAIL_LOF: Loss of Frame (LOF) Failure: * For T1 links, the LOF failure is declared with an OOF or LOS defect has persisted for T * seconds, where T is greater than or equal to two, but less than or equal to ten. The LOF * failure is cleared when there have been no OOF or LOS defects during a period T is greater * than or equal to two, but less than or equal to twenty. Many systems will perform "hit * integration" with the period T before declaring or clearing the failure. * * XP_FAIL_LOM: Loss of Multiframe (LOM) Failure: * The LOM failure is declared when two consecutive multi-frame alignment signals (bit 4 * through 7 of TS16 of frame 0) have been received wtih an error. The LOM failure is cleared * when the first correct multi-frame alignment signal is received. The LOM failure can only * be declared for E1 links operating with framing (sometimes called CAS mode). * * XP_FAIL_LOS: Loss of Signal (LOS) Failure: * For T1, the Loss of Signal failure is declared upon observing 175 +/- 74 contiguous pulse * position with no pulses of either positive or negative polarity. The LOS failure is cleared * upon observing an average pulse density of at least 12.5 percent over a period of 175 +/- 74 * contiguous pulse positions starting with the receipt of a pulse. * * XP_FAIL_T16AIS: T16 Alarm Indication Signal Failure: * For E1 links, the Ts16 Alarm Indication Signal failure is declared when time-slot 16 is * received as all ones for all frames of two consecutive multi-frames. This condition is * never declared for T1. * */ static noinline fastcall __hot void xp_x1_process_span(struct cd *cd, struct sp *sp, register volatile uint8_t *xlb, register uint ints) { register uint8_t status, mask; register uint errors = sp->status.errors; register uint flags = sp->status.flags; uint timeout = 0; if (ints & (1 << 0)) { /* SR1 */ /* only examine bits set for interrupt */ if ((mask = xlb[0x17])) { /* IMR1 */ /* write-read cycle */ xlb[0x16] = mask; status = xlb[0x16] & mask; /* SR1.7: ILUT: Input Level Under Threshold. This bit is set whenever the input level at RTIP and RRING falls below the threshold set by the value in CCR4.4 thorugh CCR4.7. The level must remain below the programmed threshold for approximately 50ms for this bit to be set. This is a double interrupt bit. */ /* 0000 > -2.5dB, 00 = 0dB boost */ /* 0001 = -2.5dB */ /* 0010 = -5.0dB */ /* 0011 = -7.5dB */ /* 0100 = -10.0dB */ /* 0101 = -12.5dB */ /* 0110 = -15.0dB */ /* 0111 = -17.5dB */ /* 1000 = -20.0dB, 01 = 20dB boost */ /* 1001 = -22.5dB */ /* 1010 = -25.0dB */ /* 1011 = -27.5dB, 10 = 26dB boost */ /* 1100 = -30.0dB */ /* 1101 = -32.5dB, 11 = 32dB boost */ /* 1110 = -35.0dB */ /* 1111 < -37.5dB */ if (status & (1 << 7)) { flags |= XP_STATE_ILUT; } else if (mask & (1 << 7)) { flags &= ~XP_STATE_ILUT; } /* SR1.6: TIMER: Timer. Follows the error counter update interval as determined by the ECUS bit in the error counter configuration register (ERCNT). T1 mode: set on increments of one second or 42ms based on RCLK. E1 mode: set on increments of one second or 62.5ms based on RCLK. */ if (status & (1 << 6)) { timeout = 1; } /* SR1.5: RSCOS: Receive Sig. Change-of-State. Set when any channel selected by the receive signalling change of state interrupt-enable registers (RSCSE1 through RSCSE4) changes signalling state. */ if (status & (1 << 5)) { } /* SR1.4: JALT: Jitter Attenuator Limit Trip. Set when the jitter attenuator FIFO reaches to within 4 bits of its useful limit. Will be cleared when read. Useful for debugging jitter-attenuator operation. */ if (status & (1 << 4)) { /* The jitter attenuator trip limit can indicate a wrong E1/T1 setting. */ if (flags & SDL_IF_AUTOCONFIG) { switch (sp->config.ifgtype) { case SDL_GTYPE_E1: /* ETSI was not specified when the driver loaded, but that is the current setting, it should be T1. Reconfigure the span for T1 operation and do a LIRST. */ if (!etsi) { } break; case SDL_GTYPE_T1: /* ANSI was not specified when the driver loaded, but that is the current setting, it should be E1. Reconfigure the span for E1 operation and do a LIRST. */ if (!ansi) { } break; case SDL_GTYPE_J1: /* JAPAN was not specified when the driver loaded, but that is the current setting, it should be E1. Reconfigure the span for E1 operation and do a LIRST. */ if (!japan) { } break; } } } /* SR1.3: LRCL: Line Interface Receive Carrier-Loss. Set when the carrier signal is lost. */ if (status & (1 << 3)) { flags |= XP_STATE_LRCL; } else if (mask & (1 << 2)) { flags &= ~XP_STATE_LRCL; } /* SR1.2: TCLE: Transmit Current-Limit Exceeded. Set when the 50mA (RMS) current limiter is activate whether the current limiter is enabled or not. */ if (status & (1 << 2)) { flags |= XP_STATE_TSCD; } else if (mask & (1 << 2)) { flags &= ~XP_STATE_TSCD; } /* SR1.1: TOCD: Transmit Open-Circuit Detect. Set when the device detects that TTIP and TRING outputs are open-circuited. */ if (status & (1 << 1)) { flags |= XP_STATE_TOCD; } else if (mask & (1 << 1)) { flags &= ~XP_STATE_TOCD; } /* SR1.0: LOLITC: Loss of Line-Interface Transmit Clock. Set when TCLKI has not transitioned for one channel time. */ if (status & (1 << 0)) { flags |= XP_STATE_LOLITC; } else if (mask & (1 << 0)) { flags &= ~XP_STATE_LOLITC; } } } if (ints & (1 << 1)) { /* SR2 */ /* only examine bits set for interrupt */ if ((mask = xlb[0x19])) { /* IMR2 */ /* write-read cycle */ xlb[0x18] = mask; if ((status = xlb[0x18] & mask)) { /* SR2.7: RYELC: Receive Yellow Alarm Clear (T1) event. Set when the yellow alarm condition is no longer detected. */ if (status & (1 << 7)) { flags &= ~XP_STATE_RYEL; } /* SR2.6: RUA1C: Receive Unframed All-Ones Clear event. Set when the unframed all ones condition is no longer detected. */ if (status & (1 << 6)) { flags &= ~XP_STATE_RUA1; } /* SR2.5: FRCLC: Framer Receive Carrier-Loss Clear event. Set when carrier loss condition at RPOSI and RNEGI is no longer detected. */ if (status & (1 << 5)) { flags &= ~XP_STATE_FRCL; } /* SR2.4: RLOSC: Receive Loss-of-Sync Clear event. Set when the framer achieves synchronization; will remain set until read. */ if (status & (1 << 4)) { flags &= ~XP_STATE_RLOS; } /* SR2.3: RYEL: Receive Yellow Alarm (T1) condition. Set when a yellow alarm is received at RPOSI and RNEGI. */ if (status & (1 << 3)) { flags |= XP_STATE_RYEL; } /* SR2.2: RUA1: Receive Unframmed All-Ones condition. Set when an unframed all ones code is received at RPOSI and RNEGI. */ if (status & (1 << 2)) { flags |= XP_STATE_RUA1; } /* SR2.1: FRCL: Framer Receive Carrier-Loss condition. Set when 255 (or 2048 if E1RCR2.0=1) E1 mode or 192 T1 mode consecutive zeros have been detected at RPOSI and RNEGI. */ if (status & (1 << 1)) { flags |= XP_STATE_FRCL; } /* SR2.0: RLOS: Receive Loss-of-Sync condition. Set when the device is not synchronized to the received data stream. */ if (status & (1 << 0)) { flags |= XP_STATE_RLOS; } } } } if (ints & (1 << 2)) { /* SR3 */ /* only examine bits set for interrupt */ if ((mask = xlb[0x1b])) { /* IMR3 */ /* write-read cycle */ xlb[0x1a] = mask; status = xlb[0x1a] & mask; /* SR3.7: LSP: Spare Code Detected (T1). Set when the spare code defined in the RSCD1/2 registers is being received. */ if (status & (1 << 7)) { flags |= XP_STATE_SPARE; } else if (mask & (1 << 7)) { flags &= ~XP_STATE_SPARE; } /* SR3.6: LDN: Loop-Down Code Detected (T1). Set when the loop down code as defined in the RDNCD1/2 regsiter is being received. */ if (status & (1 << 6)) { flags |= XP_STATE_LDN; if (!(sp->config.ifgmode & SDL_GMODE_LOC_LB)) { if ((sp->config.ifmode & SDL_GMODE_REM_LB)) { if (sp->loopcnt > 80) { /* LCBR.2: RLB: 0 = no remote */ xlb[0x4a] &= ~0x04; sp->config.ifgmode &= ~SDL_GMODE_REM_LB; sp->loopcnt = 0; } else sp->loopcnt++; } } } else if (mask & (1 << 6)) { flags &= ~XP_STATE_LDN; } /* SR3.5: LUP: Loop-Up Code Detected (T1). Set when the loop up code as defined in the RUPCD1/2 register is being received. */ if (status & (1 << 5)) { flags |= XP_STATE_LUP; if (!(sp->config.ifgmode & SDL_GMODE_LOC_LB)) { if (!(sp->config.ifgmode & SDL_GMODE_REM_LB)) { if (sp->loopcnt > 80) { /* LCBR.2: RLB: 1 = remote */ xlb[0x4a] |= 0x04; sp->config.ifgmode |= SDL_GMODE_REM_LB; sp->loopcnt = 0; } else sp->loopcnt++; } } } else if (mask & (1 << 5)) { flags &= ~XP_STATE_LUP; } /* SR3.4: LOTC: Loss of Transmit Clock. Set when the TCLK pin has not transitioned for one channel time. WIll force the LOTC pin high if enabled via CCR1.0. */ if (status & (1 << 4)) { flags |= XP_STATE_LOTC; } else if (mask & (1 << 4)) { flags &= ~XP_STATE_LOTC; } /* SR3.3: LORC: Loss of Receive Clock. Set when the RCLKI pin has not transitioned for once channel time. */ if (status & (1 << 3)) { flags |= XP_STATE_LORC; } else if (mask & (1 << 3)) { flags &= ~XP_STATE_LORC; } /* SR3.2: V52: V5.2 Link Detect (E1). Set on detection of a V5.2 link identification signal. */ if (status & (1 << 2)) { } /* SR3.1: RDMA: Receive Distant MF Alarm (E1). Set when bit 6 of time slot 16 in frame 0 has been set for two consecutive multiframes. This alarm is not disabled in the CCS signaling mode. Note that we disable this interrupt when not E1-CAS. */ if (status & (1 << 1)) { flags |= XP_STATE_RDMA; /* Note that when we are in CCS signalling mode and we receive this alarm there is the possibility that we should have set CAS. */ } else if (mask & (1 << 1)) { flags &= ~XP_STATE_RDMA; } /* SR3.0: RRA: Receive Remote Alarm (E1). Set when a remote alarm is received at RPOSI and RNEGI. */ if (mask & (1 << 0)) { if (status & (1 << 0)) { flags |= XP_STATE_RRA; } else { flags &= ~XP_STATE_RRA; } } } } if (ints & (1 << 3)) { /* SR4 */ /* only examine bits set for interrupt */ /* Note: we are currently setting IMR4 to 10000000 for T1/J1 and 01100000 for E1 */ if ((mask = xlb[0x1d])) { /* IMR4 */ /* write-read cycle */ xlb[0x1c] = mask; status = xlb[0x1c] & mask; /* SR4.7: RAIS: Recevie AIS-CI (T1). Set when the receiver detects the AIS-CI pattern as deifned in ANSI T1.403. */ if (status & (1 << 7)) { flags |= XP_STATE_RAIS; } else if (mask & (1 << 7)) { flags &= ~XP_STATE_RAIS; } /* SR4.6: RSAO: Receive Sig. All-Ones (E1). Set when the contents of time slot 16 contains fewer than three zeroes over 16 consecutive frames. This alarm is not disabled in the CCS signalling mode. */ if (status & (1 << 6)) { flags |= XP_STATE_RSAO; /* Note that when we are in the CAS signalling mode and we receive this condition there is the possibilty that we should be in the CCS signalling mode because we appear to be receiving idle code in channel 16. */ if (sp->config.ifframing == SDL_FRAMING_CAS) { if (sp->config.ifflags & SDL_IF_AUTOCONFIG) { sp->config.ifframing = SDL_FRAMING_CCS; /* SIGCR.1: TCCS: 1 = signalling data in CCS format */ /* SIGCR.2: RCCS: 1 = signalling data in CCS format */ xlb[0x40] |= 0x06; xlb[0x33] |= 0x40; } } } else if (mask & (1 << 6)) { flags &= ~XP_STATE_RSAO; } /* SR4.5: RSAZ: Receive Sig. All-Zeros (E1). Set when over a full MF time slot 16 contains all zeros. */ /* Set when over a full MF time slot 16 contains all zeros. */ if (status & (1 << 5)) { flags |= XP_STATE_RSAZ; } else if (mask & (1 << 5)) { flags &= ~XP_STATE_RSAZ; } #if 0 /* SR4.4: TMF: Transmit Multiframe. E1 Mode: Set every 2ms (regardless if CRC-4 is enabled) on transmit multiframe boundaries. Use to alert the host that signaling data needs to be updated. T1 Mode: Set every 1.5ms on D4 MF boundaries or every 3ms on ESF MF boundaries. */ if (status & (1 << 4)) { } /* SR4.3: TAF: Transmit Align Frame (E1). Set every 250us at the beginning of align frames. Used to alert the host that the TAF and TNAF registers need to be updated. */ if (status & (1 << 3)) { } /* SR4.2: RMF: Receive Multiframce. E1 Mode: Set every 2ms (regardless if CAS signalling is enabled or not) on the receive multiframe boundaries. Use to alert the host that signaling data is available. T1 Mode: Set every 1.5ms on D4 MF boundaries or every 3ms on ESF MF boundaries. */ if (status & (1 << 2)) { } /* SR4.1: RCMF: Receive CRC4 Multiframe (E1). Set on CRC-4 multiframe boundaries; will continue to be set every 2ms on an arbitrary boundary if CRC-4 is disabled. */ if (status & (1 << 1)) { } /* SR4.0: RAF: Receive Align Frame (E1). Sett every 250us at the beginning of align frames. Used to alter the host that Si and Sa bits are available in the RAF and RNAF registers. */ if (status & (1 << 0)) { } #endif } } if (ints & (1 << 4)) { /* SR5 (Elastic Store) */ /* only examine bits set for interrupt */ if ((mask = xlb[0x1f])) { /* IMR5 */ /* write-read cycle */ xlb[0x1e] = mask; if ((status = xlb[0x1e] & mask)) { /* SR5.5: TESF: Transmit Elastic Store Full Event. Set when the transmit elastic store buffer fills and a frame is deleted. */ if (status & (1 << 5)) { errors |= XP_ERR_CSS; } /* SR5.4: TESEM: Transmit Elastic Store Empty Event. Set when the transmit elastic store buffer emtpies and a frame is repeated. */ if (status & (1 << 4)) { errors |= XP_ERR_CSS; } /* SR5.3: TSLIP: Transmit Elastic Store Slip-Occurrence Event. Set when the transmit elastic sotre has either repeated or deleted a frame. */ if (status & (1 << 3)) { errors |= XP_ERR_CSS; } /* SR5.2: RESF: Receive Elastic Store Full Event. Set when the receive elastic store buffer filles and a frame is deleted. */ if (status & (1 << 2)) { errors |= XP_ERR_CSS; } /* SR5.1: RESEM: Receive Elastic Store Empty Event. Set when the receive elastic store buffer empties and a frame is repeated. */ if (status & (1 << 1)) { errors |= XP_ERR_CSS; } /* SR5.0: RSLIP: Receive Elastic Store Slip-Occurrence Event. Set when the receive eleastic store has either repeated or deleted a frame. */ if (status & (1 << 0)) { errors |= XP_ERR_CSS; } } } } /* Note: at this point, any Dallas interrupt should have been cleared by reading the interrupt bits. Dallas interrupts generated by the IMR registers are acknowledged by reading the corresponding bit of the SR registers. */ if (timeout) xp_x1_process_timeout(cd, sp, xlb, flags); /* Note that alarms are processed asynchronously whereas interface state is only processed during timeouts. This keeps the interface state from thrashing around and detection mechanisms falsely triggering on transient conditions. */ if ((flags ^ sp->status.flags) != 0) xp_x1_process_alarms(cd, sp, xlb, flags, timeout); } /** xp_x1_process_timeout: - process timeout for a span * @cd: card structure (locked) * @sp: span structure * @xlb: span iobase pointer * @flags: span flags */ static noinline fastcall __hot void xp_x1_process_timeout(struct cd *cd, struct sp *sp, volatile uint8_t *xlb, register uint flags) { register uint mask, status; register uint errors = sp->status.errors; uint count; /* Read information registers and report. */ /* write-read cycle */ mask = 0x3f; xlb[0x11] = mask; status = xlb[0x11] & mask; sp->config.ifrxlevel = (status & 0x0f) / 3; if (status & 0x30) { /* INFO2.4: TOCD: Transmit Open-Circuit Detect. A real-time bit set when the device detects that the TTIP and TRING outputs are open-circuited. */ if (status & (1 << 4)) { flags |= XP_STATE_TOCD; } else if (mask & (1 << 4)) { flags &= ~XP_STATE_TOCD; } /* INFO2.5: TCLE: Transmit Current-Limit Exceeded. A real-time bit set when the 50mA (RMS) current limiter is activated, whether the current limiter is enabled or not. */ if (status & (1 << 5)) { flags |= XP_STATE_TSCD; } else if (mask & (1 << 5)) { flags &= ~XP_STATE_TSCD; } /* INFO2.6: BD: BOC Detected. A real-time bit that is set high when the BOC detector is presently seeing a valid sequence and set low when no BOC is currently being detected. */ if (status & (1 << 6)) { } /* INFO2.7: BSYNC: BERT Real-Time Synchronization Status. Real-time status of the synchronizer (this bit is not latched). Will be set when the incoming pattern matches for 32 consecutive bit positions. Will be cleared when six or more bits out of 64 are received in error. Refer to BSYNC in the BERT status register, SR9, for an interrupt-generating version of this signal. */ if (status & (1 << 7)) { } } switch (__builtin_expect(sp->config.ifgtype, SDL_GTYPE_E1)) { case SDL_GTYPE_T1: case SDL_GTYPE_J1: /* T1/J1-only register */ /* write-read cycle */ mask = 0xff; xlb[0x10] = mask; status = xlb[0x10] & mask; if (status) { /* INFO1.0: FBE: Frame Bit-Error Event. Set when a Ft(D4) or FPS(ESF) framing bit is received in error. Note that these can be counted by the MOSCR error counter. */ if (status & (1 << 0)) { errors |= XP_ERR_FASE; } /* INFO1.1: B8ZS: B8ZS Codeword Detect Event. Set when a B8SZ codeword is detected at RPOS and RNEG independent of whether the B8ZS mode is selected or not via T1TCR2.7. Useful for automatically setting the line coding. */ if (status & (1 << 1)) { /* A B8ZS codeword was detected. When we are set to T1 AMI and there are no bipolar violations, and a B8ZS codeword is detected, this certainly means that the line coding should be B8ZS instead of AMI. However, SS7 links are always B8ZS. */ if (sp->config.ifcoding != SDL_CODING_B8ZS) errors |= XP_ERR_B8ZS; } /* INFO1.2: SEFE: Severly Errored Framing Event. Set when two out of six framing bits (Ft or FPS) are received in error. This must trigger a Severely Errored Seconds Framing (SESF) count for the current second. */ if (status & (1 << 2)) { errors |= XP_ERR_SEFS; } /* INFO1.3: 16ZD: Sixteen Zero-Detect Event. Set when a string of at least 16 consecutive zeros (regardless of the length of the string) have been received at RPOSI and RNEGI. Note that these can be counted in the LCVCR error counter. */ if (status & (1 << 3)) { errors |= XP_ERR_LCV; } /* INFO1.4: 8ZD: Eight Zero-Detect Event. Set when a string of at least eight consecutive zeros (regardless of the length of the string) have been received at RPOSI and RNEGI. Note that these can be counted in the LCVCR error counter. */ if (status & (1 << 4)) { errors |= XP_ERR_LCV; } /* INFO1.5: COFA: Change of Frame Aligment Event. Set when the last resync resulted in a change of frame alignment or multiframe alignment. */ if (status & (1 << 5)) { errors |= XP_ERR_FASE; } /* INFO1.6: TPDV: Transmit Pulse Density Violation Event. Set when the transmit data stream does not meet ANSI T1.403 requirements for pulse density. */ if (status & (1 << 6)) { errors |= XP_ERR_PDV; } /* INFO1.7: RPDV: Receive Pulse Density Violation Event. Set when the receive data stream does not meet ANSI T1.403 requirements for pulse density. */ if (status & (1 << 7)) { errors |= XP_ERR_PDV; } } break; case SDL_GTYPE_E1: /* E1-only registers */ /* write-read cycle */ mask = 0x07; xlb[0x12] = mask; status = xlb[0x12] & mask; if (status) { /* INFO3.0: CASRC: CAS Resync Criteria Met. */ if (status & (1 << 0)) { } /* INFO3.1: FASRC: FAS Resync Criteria Met. */ if (status & (1 << 1)) { } /* INFO3.2: CRCRC: CRC Resync Criteria Met. */ if (status & (1 << 2)) { } } /* write-read cycle */ mask = 0xff; xlb[0x30] = mask; status = xlb[0x30] & mask; /* INFO7.0: CRC4SA: CRC4 MF Sync Active. */ /* G.706 specifies a method to allow automatic interworking between equipment with and without CRC-4 capability. When basic frame aligment is established the device begins searching for the CRC-4 capability. When basic frame alignment is established the device begins searching for the CRC-4 alignment pattern. If after 8ms the CRC-4 alignment is not found, it is assumed that frame frame alignment. After the new frame alignment is established the device starts a new 8ms search period for CRC-4 alignment. If CRC-4 alignment is not found, the device starts CRC-4 performance monitoring and setting of the transmitted E-bits according to G.706. If CRC-4 aligment is not achieved the device continues to return to the basic frame alignment procecedure followed by an 8ms search period for CRC-4. This process continues for 400ms. At the end of this 400ms period, it is assumed that the far end equipment is non-CRC-4, the search for CRC-4 alignment is terminated and the E-bits trasnmitter toward the far end equipment are set continuously = 0.l The DS21455/DS21458 provide a flexible method for implementing this procedure. Once the device is put into the receive CRC-4 mode, a counter begins to run. The user can access this counter via Information Register 7. */ /* When automatic E-bit generation is enabled (E1TCRC2.2 = 1), and the transmitter is in CRC-4 mode, the transmitter will automatically set the E-bit according to the following: receive CRC-4 disabled, e-bits = 0; receive CRC-4 enabled but not synchronized, e-bits = 0; receive CRC-4 enabled, synchronized, with CRC sub-multiframe codeword error, e-bits = 0; receiver syncrhonized in CRC-4 mode with no CRC sub-multiframe codeword errors, e-bits = 1. */ /* The count of the number of failed 8-ms CRC-4 alignment attempts that have occurred since the last sucessful CRC-4 alignment. This is for G.706 Annex B operation. When the CRC-4 alignment has failed for 400-ms (after achieving basic frame alignment), the CRC-4 capable equipment should assume that the other end is incapable of generating CRC-4 multiframes.A In this case, the transmitter continues transmitting CRC-4 multiframes; however, the E-bits should be set to zero (indicating distant MF alarm). The receiver; however, can be marked as non-CRC-4. */ if (status & 0x07) { if (status & (1 << 0)) if ((sp->config.ifflags & SDL_IF_AUTOCONFIG) && (sp->config.ifgcrc = SDL_GCRC_CRC4)) { count = ((status & 0xf0) >> 2) | ((status & 0x08) >> 3); if (count >= 49) { /* Basically we have 488 - 408 = 80 ms to determine that there has been a CRC-4 alignment failure for more than 392 milliseconds. When ECUS is set for 62.5 ms operation, we will detect within 31.25 ms of the event that the CRC-4 has failed for 392 milliseconds or more (i.e. before the CRC-4 counter rolls over). */ /* --1100-0 = 48 = 384 ms */ /* --1100-0 = 50 = 400 ms */ /* --1100-1 = 49 = 392 ms */ /* --1100-1 = 51 = 408 ms */ /* --1101-0 = 52 = 416 ms */ /* --1101-0 = 54 = 432 ms */ /* --1101-1 = 53 = 424 ms */ /* --1101-1 = 55 = 440 ms */ /* --1110-0 = 56 = 448 ms */ /* --1110-0 = 58 = 464 ms */ /* --1110-1 = 57 = 456 ms */ /* --1110-1 = 59 = 472 ms */ /* --1111-0 = 60 = 480 ms */ /* --1111-0 = 62 = 496 ms */ /* --1111-1 = 61 = 488 ms */ /* --1111-1 = 63 = 504 ms */ /* --0000-0 = 64 = 512 ms */ /* shut off CRC4 on rx */ /* E1RCR1.3: RCRC4: 0 = CRC-4 disabled */ xlb[0x33] &= ~(1 << 3); /* Note that this only affects Rx CRC-4. */ } } /* INFO7.1: CASSA: CAS MF Sync Active. */ if (status & (1 << 1)) { } /* INFO7.2: FASSA: FAS Sync Active. */ if (status & (1 << 2)) { } } break; } /* CRC-4 multiframe alignment algorithm: G.706/Annex B: The modified CRC-4 multiframe alignment algorithm is based on the following strategy: If a valid basic frame alignment signal is consistently present but CRC-4 multiframe alignment is not achieved by the end of the total CRC-4 multiframe alignment search period, it is assumed that the distant end is a Non-CRC-4 equipment. Under these circumstances, the following consquent actions apply at the equipment having the CRC-4 capability: a) provide an indication (not necessarily an alarm) that there is "no incoming CRC-4 multiframe alignment signal"; b) inhibit CRC-4 processing on the receive 2048 kbps signal; c) continue to transmit CRC-4 data to the distant end with both "E" bits (see Table 4b/G.704) set to zero. Note: This allows, as explained in G.706/B.2.5, the identification of failure of CRC-4 multiframe alignment generation/detection, but with correct basic framing, when interworking between equipment each having the modified CRC-4 multiframe alignment algorithm. The algorithm is robust against spurious basic frame alignment and there are no interworking problems with equipment having a manually selectable CRC-4 capability. */ /* A 400 ms CRC-4 multiframe alignment search period ensures that correct basic and CRC-4 multiframe alignment is possible for up to about 40 spurious simulations of the basic frame aligment sequence present between tow real basic frame alignment signal locations. The 400 ms timer is triggered on the initial (i.e, primary) recovery of basic frame alignment. Once the 400 ms timer is triggered, it is not reset unless the criteria for "loss of (primary) basic frame alignment" occurs (see G.706/4.1.1): The "loss of (primary) basic frame alignemnt" checkinig process runs continuously irrespective of the state of the CRC-4 multiframe aligment process below it. A research for basic frame alignment initiated if CRC-4 multiframe alignment cannot be acheived in 8 ms (as required in G.706/4.2) should not reset the 400 ms timer or invoke consequent actions associated with loss of primary basic frame alignment, that is, in this particular section of the alignment flow diagram, all searches for basic frame alignment are carried out in parallel with, and hence independent of, the primary basic frame loss checking process (see Figure B.1/G.706). All subsequent searches for CRC-4 multiframe alignment are associated with each basic framing sequence found during the parallel search. In order that the algorithm does not introduce a disturbance (of 400 ms maximum duration) to traffic during the search for CRC-4 multiframe alignment, traffic should be allowed through upon, and syncrhonized to, the intially determined primary basic frame alignment sequence. If a CRC-4 multiframe alignment signal is found before the 400 ms timer elapses, then the basic frame alignment sequence associated with the CRC-4 multiframe alignment signal should be the one chosen, i.e. if necessary, the primary basic frame alignment position should be amended saccordingly. CRC-4 processing would then determin if this was truly the valid alignment location (in accordance with 4.3.2/G.706). However, if a CRC-4 multiframe alignment sequence cannot be found before the 400 ms timer elapses, it should be concluded that a condition of interworking between equipment with and without a CRC-4 capability exists; in this case traffic should be maintained to the initially determined primary basic frame alignment signal location and the consequent actions given in B.2.2/G.706 invoked. If the 2048 kbps path is reconfigured at any time, then it is assumed that the (new) pair of path terminating equipments will need to re-establish the complete framing process, i.e., the algorithm is reset. */ /* Process Error Counters */ /* This is a one second timeout. For T1 this is no really 1 second when performing short timeout-outs, but is 999*8 frames or 0.999 seconds. But that is ok as we don't accumulate as a result of the interval. There are some conditions that we want to persist for a full second before we take any actions on them. One is the JALT. If the jitter attenuator limit threshold is being exceeded every short interval for a full second and we have nevery achieved syncrhonization since the last loss of sync or transmitter open circuit, we should think about switching from E1 to T1 or vise versa. */ /* This is a one second timeout. */ /* Line code violation count register (LCVCR). */ /* T1 Operation: T1 code violations are defined as bipolar violations (BPVs) or excessive zeros. If the B8ZS mode is set for the receive side, then B8ZS codewords are not counted. This counter is always enabled; it is not disbaled during receive loss of synchronization (RLOS=1) conditions. */ /* ERCNT.0=no exz, T1RCR2.5=AMI, BPVs */ /* ERCNT.0=exz, T1RCR2.5=AMI, BPVs + 16 consecutive zeros */ /* ERCNT.0=no exz, T1RCR2.5=B8ZS, BPVs (B8ZS Codewords Not Counted) */ /* ERCNT.0=exz, T1RCR2.5=B8ZS, BPVs + 8 consecutive zeros */ /* E1 Operation: Either bipolar violations or code violations can be counted. Bipolar violations are defined as consecutive marks of the same polarity. In this mode, if the HDB3 mode is set for the receive side, then HDB3 codewords are not counted as BPVs. If ERCNT.3 is set, then the LVC counts code violations as defined in IUT O.161. Code violations are defined as consecutive bipolar violations of the same polarity. In most applications, the frame should be programmed to count BPVs when receiving AMI code and to count CVs when receiving HDB3 code. This counter increments at all times and is not disabled by loss of sync conditions. The counter saturates at 65,535 and will not rollover. The bit error rate on an E1 line would have to be greater than 10E-02 before the VCR would saturate. */ /* ERCNT.3=0, count BPVs */ /* ERCNT.3=1, count CVs */ if ((count = ((uint) (xlb[0x42] & 0xff) << 8) | ((uint) (xlb[0x43] & 0xff) >> 0))) { sp->stats[0].LCVs += count; errors |= XP_ERR_LCV; } /* Path code violation count register (PCVCR) */ /* T1 Operation: The path code violation count register records either Ft, Fs, or CRC6 errors in T1 frames. When the receive side of a framer is set to operatin in the T1 ESF framing mode, PCVCR will record errors in the CRC6 codewords. When set to operate in the T1 D4 framing mode, PCVCR will count errors in the Ft framing bit position. Via the ERCNT.2 bit, a framer can be programmed to also report errors in the Fs framing bit position. The PCVCR will be disabled during receive loss of synchronization (RLOS=1) conditions. */ /* D4, No, Errors in Ft pattern */ /* D4, Yes, Errors in both Ft and Fs patterns. */ /* ESF, don't care, Errors in the CRC6 codewords. */ /* E1 Operation: The PCVCR records CRC-4 errors. Since the maximum CRC4 count in a one-second period is 1000, this counter cannot saturate. The counter is disabled during loss of sync at either the FAS or CRC-4 level; it will continue to count if loss of multiframe sync occurs at the CAS level. */ if ((count = ((uint) (xlb[0x44] & 0xff) << 8) | ((uint) (xlb[0x45] & 0xff) >> 0))) { sp->stats[0].PCVs += count; errors |= XP_ERR_PCV; } /* Frames out of sync count register (FOSCR) */ /* T1 Operation: The FOSCR is used to count the number of multiframes that the receive synchronizer is out of sync. This number is useful in ESF applications needing to measure the parameters loss of frame count (LOFC) and ESF error events as described in AT&T publication TR54016. When the FOSCR is operated in this mode, it is not disabled during receive loss of synchronization (RLOS=1) conditions. The FOSCR has alternate operating mode whereby it will count either errors in the Ft framing pattern (in the D4 mode) or errors in the FPS framing pattern (in the ESF mode). WHen the FOSCR is operated in this mode, it is disabled during receive loss of synchronization (RLOS=1) conditions. */ /* T1RCR1.3=D4, ERCNT.1=MOS, number of multiframes out of sync */ /* T1RCR1.3=D4, ERCNT.1=F-bit, errors in the Ft pattern */ /* T1RCR1.3=ESF, ERCNT.1=MOS, number of multiframes out of sync */ /* T1RCR1.3=ESF, ERCNT.1=F-bit, errors in the FPS pattern */ /* E1 Operation: The FOSCR counts word errors in the frame alignment signal in time slot 0. This counter is disabled when RLOS=1. FAS errors will not be counted when the framer is searching for FAS alignment and/or synchronization at either the CAS or CRC-4 multiframe level. Since the maximum FAS word error count in a one-second period is 4000, this counter cannot saturate. */ if ((count = ((uint) (xlb[0x46] & 0xff) << 8) | ((uint) (xlb[0x47] & 0xff) >> 0))) { sp->stats[0].FASEs += count; errors |= XP_ERR_FASE; } /* E-Bit Counter Register (EBCR) */ /* This counter is only available in E1 mode. The 16-bit counter records far end block errors (FEBE), as reported in the first bits of frame 13 and 15 on E1 lines running with CRC-4 multiframe. These count registers will increment once each time the received E-bit is set to zero. Since the maximum E-bit count in a one second period is 1000, this counter will not saturate. The counter is disabled during loss of sync at either the FAS or CRC-4 level; it will continue to count if loss of multiframe sync occurs at the CAS level. */ if (sp->config.ifgtype == SDL_GTYPE_E1) { if ((count = ((uint) (xlb[0x48] & 0xff) << 8) | ((uint) (xlb[0x49] & 0xff) >> 0))) { sp->stats[0].FEBEs += count; errors |= XP_ERR_FEBE; } } xp_x1_process_state(cd, sp, xlb, flags, errors); { int interval; /* interval in frames */ /* ERCNT.5: ECUS: 1 = 333/500 frames, 0 = 8000 frames */ if (xlb[0x41] & 0x20) { if (sp->config.ifgtype == SDL_GTYPE_E1) interval = 500; /* frames, 62.5ms */ else interval = 333; /* frames, 41.625ms */ } else interval = 8000; /* frames, 1.000 sec */ if ((sp->interval += interval) >= 8000) { sp->interval -= 8000; /* this is a 1 second timeout */ xp_x1_process_stats(sp, errors); sp->status.errors = 0; } else sp->status.errors = errors; } return; } /** xp_x1_process_state: - process state transitions for the device. * @cd: card structure pointer * @sp: span structure pointer * @xlb: span iobase * @flags: state flags (read only) * @errors: error flags (read only) * * Process state transitions once a timeout. This is to ensure that the interface state does not * change due to transient conditions of less than 40 ms. Also, any events or errors here have * accumulated for the entire timeout period (more than 40 ms). * * Processing DS2155/455/458 state transitions is eased by the wide range of receive level * determination as well as the ability to detect when the transmitters are open-circuit. This * makes it easier to determine whether the span is in a monitor configuration and whether linear * gain should be applied to the receievers. */ static noinline fastcall __hot void xp_x1_process_state(struct cd *cd, struct sp *sp, volatile uint8_t *xlb, const register uint flags, const register uint errors) { register uint ifflags = sp->config.ifflags; /* integrate receiver state */ if (flags & (XP_STATE_LRCL | XP_STATE_FRCL)) { ifflags &= ~SDL_IF_RX_UP; ifflags &= ~SDL_IF_RX_RUNNING; } else { ifflags |= SDL_IF_RX_UP; if (flags & (XP_STATE_ILUT | XP_STATE_RLOS | XP_STATE_RUA1 | XP_STATE_LORC)) { ifflags &= ~SDL_IF_RX_RUNNING; } else { ifflags |= SDL_IF_RX_RUNNING; } } /* integrate transmitter state */ if (flags & (XP_STATE_TOCD | XP_STATE_TSCD)) { ifflags &= ~SDL_IF_TX_UP; ifflags &= ~SDL_IF_TX_RUNNING; } else { ifflags |= SDL_IF_TX_UP; if (flags & (XP_STATE_LOLITC | XP_STATE_LOTC)) { ifflags &= ~SDL_IF_TX_RUNNING; } else { ifflags |= SDL_IF_TX_RUNNING; } } /* integrate interface state */ if (flags & (SDL_IF_RX_UP | SDL_IF_TX_UP)) { ifflags |= SDL_IF_UP; } else { ifflags &= ~SDL_IF_UP; } /* detect changes in transmitter state */ if ((ifflags ^ sp->config.ifflags) & (SDL_IF_TX_UP | SDL_IF_TX_RUNNING)) { } /* detect changes in receiver state */ if ((ifflags ^ sp->config.ifflags) & (SDL_IF_RX_UP | SDL_IF_RX_RUNNING)) { } /* detect changes in interface state */ if ((ifflags ^ sp->config. ifflags) & (SDL_IF_UP | SDL_IF_TX_UP | SDL_IF_RX_UP | SDL_IF_TX_RUNNING | SDL_IF_RX_RUNNING)) { } /* perform autoconfiguration when necessary */ if (ifflags & SDL_IF_AUTOCONFIG) { if (likely(sp->status.state == 40)) { if (unlikely((flags & (XP_STATE_LRCL)) != 0)) /* lost carrier, start full autoconfig */ sp->status.state = 0; else if (unlikely((flags & (XP_STATE_FRCL)) != 0)) /* lost signal, start partial autoconfig */ sp->status.state = 20; } if (unlikely(sp->status.state != 40)) /* lost configuration hold, process autoconfig */ xp_x1_process_auto(cd, sp, xlb, flags, errors, 1); } } /** xp_x1_process_auto: - process autoconfiguration state machine * @cd: card structure pointer * @sp: span structure pointer * @xlb: span iobase * @flags: state flags * @errors: error events * @timeout: true when timeout * * Note that we do not even execute this function unless SDL_IF_AUTOCONFIG is set in the interface * flags. The autoconfiguration states are a little different from the E1 and T1 chips because the * E1/T1 chip can do jitter attenuator trip limit detection (to detect the line rate) and * transmitter open- and short-circuit detection. Also the DS2155/455/458 chip can perform linear * gain for monitoring applications of 20dB, 26dB and 30dB. 20dB corresponds to a single 432-470 * Ohm isolation resistors on a single high-impedance monitoring tap. 26dB corresponds to double * 432-470 Ohm isolation resistors (tap of a tap). 30dB coresponds to triple 432-470 Ohm isolation * resistors (tap of a tap of a tap). The E1 and T1 only chips can only handle a single tap. */ static noinline fastcall __unlikely void xp_x1_process_auto(struct cd *cd, struct sp *sp, register volatile uint8_t *xlb, register uint flags, const register uint errors, const uint timeout) { register uint state = sp->status.state; const uint interval = timeout ? ((xlb[0x41] & 0x20) ? ((sp->config.ifgtype == SDL_GTYPE_E1) ? 500 : 333) : 8000) : 0; for (;;) { do { if (flags & XP_STATE_LIRST) { /* resetting line interface */ sp->status.count = 0; sp->status.config = 0; state = 0; break; } if ((flags & XP_STATE_LRCL) && (11 <= state)) { /* lost carrier */ sp->status.count = 0; state = 0; break; } if ((flags & XP_STATE_FRCL) && (12 <= state)) { /* lost signal */ sp->status.count = 0; state = 11; break; } if ((flags & XP_STATE_RUA1) && (13 <= state)) { /* lost service */ sp->status.count = 0; state = 12; break; } if ((flags & XP_STATE_RLOS) && (15 <= state && state < 18)) { /* lost sync */ sp->status.count = 0; state = 14; break; } } while (0); switch (state) { default: state = 0; /* fall through */ case 0: /* LIRST subsidance. Wait 125 ms or more when the LIRST condiiton remains, then clear the condition and move on to line detection. */ if (flags & (XP_STATE_LIRST)) { if ((sp->status.count += interval) < 1000) { /* wait for up to 125 ms */ break; } /* remove LIRST flag */ sp->status.flags &= ~(XP_STATE_LIRST); flags &= ~(XP_STATE_LIRST); /* reset elastic stores */ /* ESCR.6=0 TESR 0->1 reset. */ /* ESCR.2=0 RESR 0->1 reset. */ xlb[0x4f] &= ~((1 << 6) | (1 << 2)); xlb[0x4f] |= (1 << 6) | (1 << 2); xlb[0x4f] &= ~((1 << 6) | (1 << 2)); /* realign elastic stores */ /* ESCR.7=0 TESALIGN 0->1 align. */ /* ESCR.3=0 RESALGN 0->1 align. */ xlb[0x4f] &= ~((1 << 7) | (1 << 3)); xlb[0x4f] |= (1 << 7) | (1 << 3); xlb[0x4f] &= ~((1 << 7) | (1 << 3)); } /* remove linear gain */ /* LIC3.4-3: MM1-MM0: 00, no gain; 01, 20dB; 10, 26dB; 11, 32dB. */ xlb[0x7a] = (xlb[0x7a] & ~((1 << 4) | (1 << 3))) | (0x0 << 3); /* start transmitter */ /* LIC1.0=? TBD Transmit Power-Down (0, power-down; 1, normal) */ xlb[0x78] |= (1 << 0); /* send unframed all ones */ switch (sp->config.ifgtype) { case SDL_GTYPE_E1: /* E1TCR1.5: TUA1: Transmit Unframed All Ones. 0, normal; 1, tua1. */ xlb[0x35] |= (1 << 5); break; case SDL_GTYPE_T1: case SDL_GTYPE_J1: /* T1TCR1.1: TBL: Transmit blue alarm (0, data; 1, unframed all ones) */ xlb[0x05] |= (1 << 1); break; } sp->status.count = 0; sp->config.ifflags &= ~(SDL_IF_UP | SDL_IF_RX_UP | SDL_IF_TX_UP | SDL_IF_RX_MON); state = 1; /* fall through */ case 1: /* Line carrier detect, 0dB gain. */ if (flags & (XP_STATE_LRCL)) { if ((sp->status.count += interval) >= 1000) { /* try applying linear gain */ /* apply 20dB linear gain */ /* LIC3.4-3: MM1-MM0: 00, no gain; 01, 20dB; 10, 26dB; 11, 32dB. */ xlb[0x7a] = (xlb[0x7a] & ~((1 << 4) | (1 << 3))) | (0x1 << 3); sp->status.count = 0; state = 2; continue; } /* wait for 125 ms */ break; } /* turn on transmitter */ /* LIC1.0=? TBD Transmit Power-Down (0, power-down; 1, normal) */ xlb[0x78] |= (1 << 0); sp->config.ifflags &= ~SDL_IF_RX_MON; sp->status.count = 0; state = 11; continue; case 2: /* Line carrier detect, monitoring, 20dB gain. No line carrier was detected with 0dB linear gain, try applying 20dB gain. */ if (flags & (XP_STATE_LRCL)) { if ((sp->status.count += interval) >= 1000) { /* try applying more linear gain */ /* apply 26dB linear gain */ /* LIC3.4-3: MM1-MM0: 00, no gain; 01, 20dB; 10, 26dB; 11, 32dB. */ xlb[0x7a] = (xlb[0x7a] & ~((1 << 4) | (1 << 3))) | (0x2 << 3); sp->status.count = 0; state = 3; continue; } /* wait 125 ms */ break; } sp->status.count = 0; state = 7; continue; case 3: /* Line carrier detect, monitoring, 26dB gain. No line carrier was detected wtih 0dB and 20dB linea gain, try applying 26dB gain. */ if (flags & (XP_STATE_LRCL)) { if ((sp->status.count += interval) >= 1000) { /* try applying more linear gain */ /* apply 30dB linear gain */ /* LIC3.4-3: MM1-MM0: 00, no gain; 01, 20dB; 10, 26dB; 11, 32dB. */ xlb[0x7a] = (xlb[0x7a] & ~((1 << 4) | (1 << 3))) | (0x3 << 3); sp->status.count = 0; state = 4; continue; } /* wait 125 ms */ break; } /* apply 20dB linear gain */ sp->status.count = 0; state = 6; continue; case 4: /* Line carrier detect, monitoring, 30dB gain. No line carrier was detected with 0dB, 20dB and 26dB linear gain, try applying 30dB gain. */ if (flags & (XP_STATE_LRCL)) { if ((sp->status.count += interval) >= 1000) { /* try removing gain again */ /* apply 0dB linear gain */ /* LIC3.4-3: MM1-MM0: 00, no gain; 01, 20dB; 10, 26dB; 11, 32dB. */ xlb[0x7a] = (xlb[0x7a] & ~((1 << 4) | (1 << 3))) | (0x0 << 3); sp->status.count = 0; state = 1; continue; } /* wait 125 ms */ break; } /* apply 26dB linear gain */ sp->status.count = 0; state = 5; /* fall through */ case 5: /* Line carrier detect, monitoring, 26dB gain. 30dB gain was applied previously with success, drop back to 26dB gain to test that things were not just connected at a bad time. */ /* apply 20dB linear gain */ if (flags & (XP_STATE_LRCL)) { if ((sp->status.count += interval) >= 1000) { /* put back to 30dB gain */ /* apply 30dB linear gain */ /* LIC3.4-3: MM1-MM0: 00, no gain; 01, 20dB; 10, 26dB; 11, 32dB. */ xlb[0x7a] = (xlb[0x7a] & ~((1 << 4) | (1 << 3))) | (0x3 << 3); sp->status.count = 0; state = 8; continue; } /* wait 125 ms */ break; } /* apply 20dB linear gain */ sp->status.count = 0; state = 6; /* fall through */ case 6: /* Line carrier detect, monitoring, 20dB gain. 26dB gain was applied previously with success, drop back to 20dB gain to test that things were not just connected at a bad time. */ if (flags & (XP_STATE_LRCL)) { if ((sp->status.count += interval) >= 1000) { /* put back to 26dB gain */ /* apply 26dB linear gain */ /* LIC3.4-3: MM1-MM0: 00, no gain; 01, 20dB; 10, 26dB; 11, 32dB. */ xlb[0x7a] = (xlb[0x7a] & ~((1 << 4) | (1 << 3))) | (0x2 << 3); sp->status.count = 0; state = 9; continue; } /* wait 125 ms */ break; } /* apply 0dB linear gain */ sp->status.count = 0; state = 7; /* fall through */ case 7: /* Line carrier detect, monitoring, 0dB gain. 20dB gain was applied previously with success, drop back to 0dB gain to test that things were not just connected at a bad time. */ if (flags & (XP_STATE_LRCL)) { if ((sp->status.count += interval) >= 1000) { /* put back to 20dB gain */ /* apply 20dB linear gain */ /* LIC3.4-3: MM1-MM0: 00, no gain; 01, 20dB; 10, 26dB; 11, 32dB. */ xlb[0x7a] = (xlb[0x7a] & ~((1 << 4) | (1 << 3))) | (0x1 << 3); sp->status.count = 0; state = 10; continue; } /* wait 125 ms */ break; } /* turn on transmitter */ /* LIC1.0=? TBD Transmit Power-Down (0, power-down; 1, normal) */ xlb[0x78] |= (1 << 0); sp->config.ifflags &= ~SDL_IF_RX_MON; sp->status.count = 0; state = 11; break; case 8: /* Line carrier detected, monitoring, 30dB gain. 30dB worked, 26dB didn't, come back to 30 dB and lock in if successful. */ if (flags & (XP_STATE_LRCL)) { if ((sp->status.count += interval) >= 1000) { /* 30dB worked before but doesn't now, start again */ /* apply 0dB linear gain */ /* LIC3.4-3: MM1-MM0: 00, no gain; 01, 20dB; 10, 26dB; 11, 32dB. */ xlb[0x7a] = (xlb[0x7a] & ~((1 << 4) | (1 << 3))) | (0x0 << 3); sp->status.count = 0; state = 0; continue; } /* wait 125 ms */ break; } /* turn off transmitter */ /* LIC1.0=? TBD Transmit Power-Down (0, power-down; 1, normal) */ xlb[0x78] &= ~(1 << 0); sp->config.ifflags |= SDL_IF_RX_MON; sp->status.count = 0; state = 11; continue; case 9: /* Line carrier detected, monitoring, 26dB gain. 26dB worked, 20dB didn't, come back to 26dB and lock in if successful. */ if (flags & (XP_STATE_LRCL)) { if ((sp->status.count += interval) >= 1000) { /* 26dB worked before but doesn't now, start again */ /* apply 0dB linear gain */ /* LIC3.4-3: MM1-MM0: 00, no gain; 01, 20dB; 10, 26dB; 11, 32dB. */ xlb[0x7a] = (xlb[0x7a] & ~((1 << 4) | (1 << 3))) | (0x0 << 3); sp->status.count = 0; state = 0; continue; } /* wait 125 ms */ break; } /* turn off transmitter */ /* LIC1.0=? TBD Transmit Power-Down (0, power-down; 1, normal) */ xlb[0x78] &= ~(1 << 0); sp->config.ifflags |= SDL_IF_RX_MON; sp->status.count = 0; state = 11; continue; case 10: /* Line carrier detected, monitoring, 20dB gain. 20dB worked, 0dB didn't, come back to 20dB and lock in if successful. */ if (flags & (XP_STATE_LRCL)) { if ((sp->status.count += interval) >= 1000) { /* 20dB worked before but doesn't now, start again */ /* apply 0dB linear gain */ /* LIC3.4-3: MM1-MM0: 00, no gain; 01, 20dB; 10, 26dB; 11, 32dB. */ xlb[0x7a] = (xlb[0x7a] & ~((1 << 4) | (1 << 3))) | (0x0 << 3); sp->status.count = 0; state = 0; continue; } /* wait 125 ms */ break; } /* turn off transmitter */ /* LIC1.0=? TBD Transmit Power-Down (0, power-down; 1, normal) */ xlb[0x78] &= ~(1 << 0); sp->config.ifflags |= SDL_IF_RX_MON; sp->status.count = 0; state = 11; /* fall through */ case 11: /* Framer signal detect. Line carrier detected, 0dB, 20dB, 26dB or 30dB linear gain applied. When other than 0dB linear gain is applied, SDL_IF_RX_MON flag is set. */ if (flags & (XP_STATE_FRCL)) { if ((sp->status.count += interval) >= 1000) { /* no framer signal, start again */ sp->status.count = 0; state = 0; continue; } /* wait 125 ms */ break; } sp->status.count = 0; state = 12; /* fall through */ case 12: /* Framing detect, sending unframed all ones. If we are in a loop-around mode we will wait here for manual (specific) configuration because we will be both sending and receiving unframed all ones. However, only wait for 10 seconds and then restart in case there is an error in the state machine that locks us here. */ if (flags & (XP_STATE_RUA1)) { if ((sp->status.count += interval) >= 10 * 8000) { /* no service for 10 seconds, start again */ sp->status.count = 0; state = 0; continue; } /* wait for up to 10 seconds */ break; } sp->status.count = 0; state = 13; /* fall through */ case 13: /* Frequency detect. We have a carrer and a signal. We should be marshalling bits through the jitter attenuator so check whether the trip limit has been exceeded. This is because we might have the wrong E1/T1 setting and the attenuator will trip immediately in that case. It might trip anyway if we have the wrong synchronization. We really only need to check the jitter attenuator if we cannot acheive frame syncrhonization. Note that once the JALT has tripped we need to do a LIRST to reset the JA position. */ if (flags & (XP_STATE_JALT)) { if (xp_x1_change_gtype(sp, xlb)) { sp->status.flags |= XP_STATE_LIRST; sp->status.config = 0; sp->status.count = 0; state = 0; continue; } } sp->status.count = 0; state = 14; /* fall through */ case 14: /* Frame detect, not receiving unframed all ones. */ if (flags & (XP_STATE_RLOS)) { if ((sp->status.count += interval) >= 3200) { /* no sync after 400 ms */ /* reconfigure and try again */ if (xp_x1_change_config(sp, xlb)) { /* exhausted possibilities, start again */ sp->status.count = 0; state = 0; continue; } sp->status.count = 0; /* wait to test possibility */ break; } /* wait for up to 400 ms */ break; } sp->status.count = 0; state = 15; /* fall through */ case 15: /* Transmitter detection, transmitting unframed all ones. We are synchronized on the receiver. Check whether the transmitter is open or short circuited. When transmitters are not externall connected we are in monitoring mode only. */ /* Note that the transmitter might not be able to detect open- or short-circuit when the transmitter is tri-state. However, we only tri-state the transmitter when we already know that we are in monitoring mode (linear gain has been applied), so this should not be a problem. */ if (flags & (XP_STATE_TOCD | XP_STATE_TSCD)) { if ((sp->status.count += interval) >= 1000) { /* open or short circuit for 125 ms */ /* No transmitter connection after 125 milliseconds. When no linear gain is applied, this is a 0dB active monitoring tap. When linear gain is applied, this is a high-impeadance monitoring tap. */ /* turn off transmitter */ /* LIC1.0=? TBD Transmit Power-Down (0, power-down; 1, normal) */ xlb[0x78] &= ~(1 << 0); sp->config.ifflags |= SDL_IF_RX_MON; sp->config.ifflags &= ~(SDL_IF_TX_UP); sp->config.ifflags |= (SDL_IF_RX_UP | SDL_IF_UP); sp->status.count = 0; state = 18; continue; } /* wait up to 125 ms */ break; } sp->status.count = 0; state = 16; /* fall through */ case 16: /* Transmitter detection, externally connected, transmitting unframed all ones. The transmitters are not open- or short-circuited, but they might still be disconnected from the interface (e.g. terminated by an active monitoring tap). We are transmitting unframed all ones, so when there is no remote alarm after 125 ms the transmitters must be disconnected. */ if (!(flags & (XP_STATE_RYEL | XP_STATE_RRA))) { if ((sp->status.count += interval) >= 1000) { /* No alarm after 125 milliseconds, transmitters must be disconnected. When no linear gain is applied, but transmitters are disconnected: this is a 0dB active monitoring tap. When linear gain applied, already monitoring so this is an expected result. */ /* turn off transmitter */ /* LIC1.0=? TBD Transmit Power-Down (0, power-down; 1, normal) */ xlb[0x78] &= ~(1 << 0); sp->config.ifflags |= SDL_IF_RX_MON; sp->config.ifflags &= ~(SDL_IF_TX_UP); sp->config.ifflags |= (SDL_IF_RX_UP | SDL_IF_UP); sp->status.count = 0; state = 18; continue; } /* wait up to 125 ms */ break; } /* transmit normal frames */ switch (sp->config.ifgtype) { case SDL_GTYPE_E1: /* E1TCR1.5: TUA1: Transmit Unframed All Ones. 0, normal; 1, tua1. */ xlb[0x35] &= ~(1 << 5); break; case SDL_GTYPE_T1: case SDL_GTYPE_J1: /* T1TCR1.1: TBL: Transmit blue alarm (0, data; 1, unframed all ones) */ xlb[0x05] &= ~(1 << 1); break; } sp->status.count = 0; state = 17; /* fall through */ case 17: /* Transmitter detection, sending normal frames. We previously had a remote alarm condition when sending unframed all ones. We start sending normal frames and check that the alarm clears within 10 seconds. */ if (flags & (XP_STATE_RYEL | XP_STATE_RRA)) { if ((sp->status.count += interval) < 10 * 8000) { /* wait up to 10 seconds */ break; } /* Alarms did not clear after 10 seconds, but this might just be a sync problem. */ } /* turn on transmitter */ /* LIC1.0=? TBD Transmit Power-Down (0, power-down; 1, normal) */ xlb[0x78] |= (1 << 0); sp->config.ifflags &= ~SDL_IF_RX_MON; sp->config.ifflags |= (SDL_IF_TX_UP); sp->config.ifflags |= (SDL_IF_RX_UP | SDL_IF_UP); sp->status.count = 0; state = 18; /* fall through */ case 18: /* Stable state, normal mode, transmitters externally connected, sending normal frames. This is an active connection, not a monitoring tap. Flags have been set accordingly. Stay in this state unless we lose carrier, signal, start receiving unframed all ones, or lose sync for more than 400 ms. */ /* Stable state, monitoring mode, transmitters externally disconnected, sending unframed all ones. This is a monitoring tap (active or passive). Flags have been set accordingly. Stay in this state unless we lose carrier, signal, start receiving unframed all ones, or lose sync for more than 400 ms. */ if (flags & (XP_STATE_RLOS)) { /* lost sync */ if ((sp->status.count += interval) >= 3200) { /* send unframed all ones */ switch (sp->config.ifgtype) { case SDL_GTYPE_E1: /* E1TCR1.5: TUA1: Transmit Unframed All Ones. 0, normal; 1, tua1. */ xlb[0x35] |= (1 << 5); break; case SDL_GTYPE_T1: case SDL_GTYPE_J1: /* T1TCR1.1: TBL: Transmit blue alarm (0, data; 1, unframed all ones) */ xlb[0x05] |= (1 << 1); break; } sp->status.count = 0; state = 14; continue; } /* wait for up to 400 ms */ break; } sp->status.count = 0; /* stay in this state */ break; } break; } /* set the new state variable */ sp->status.state = state; } /** xp_x1_change_config: - try changing span configuration for sync * @sp: span structure pointer * @xlb: span iobase * * Diagnose the problem and attempt to change the configuration accordingly. This is a T1/J1/E1 * line so likely difficulties are ESF instead of D4 or CCS instead of CAS; CRC6 instead of CRC6J * or CRC4 instead of non-CRC4; B8ZS instead of AMI or HDB3 instead of AMI. We should simply walk * through the possible configurations until one that works is found or all are exhausted. */ noinline __unlikely int xp_x1_change_config(struct sp *sp, register volatile uint8_t *xlb) { switch (sp->config.ifgtype) { case SDL_GTYPE_E1: switch (sp->status.config) { case 0: /* E1, CCS, HDB3, CRC4 */ sp->config.ifgtype = SDL_GTYPE_E1; if (sp->config.ifframing != SDL_FRAMING_CCS) { sp->config.ifframing = SDL_FRAMING_CCS; xlb[0x40] |= (1 << 1); /* SIGCR.1: TCCS: 1 = Tx CCS. */ xlb[0x40] |= (1 << 2); /* SIGCR.2: RCCS: 1 = Rx CCS. */ xlb[0x33] |= (1 << 6); /* E1RCR1.6: RSIGM: 1 = Rx CCS */ } if (sp->config.ifcoding != SDL_CODING_HDB3) { sp->config.ifcoding = SDL_CODING_HDB3; xlb[0x33] |= (1 << 5); /* E1RCR1.5: RHDB3: 1 = Rx HDB3. */ xlb[0x35] |= (1 << 2); /* E1TCR1.2: THDB3: 1 = Tx HDB3. */ } if (sp->config.ifgcrc != SDL_GCRC_CRC5) { sp->config.ifgcrc = SDL_GCRC_CRC5; xlb[0x33] &= ~(1 << 3); /* E1RCR1.3: RCRC4: 0, Rx non-CRC-4. */ xlb[0x35] &= ~(1 << 0); /* E1TCR1.0: TCRC4: 0, Tx non-CRC-4. */ } sp->status.config = 1; break; case 1: /* E1, CCS, HDB3, non-CRC4 */ sp->config.ifgtype = SDL_GTYPE_E1; if (sp->config.ifframing != SDL_FRAMING_CCS) { sp->config.ifframing = SDL_FRAMING_CCS; xlb[0x40] |= (1 << 1); /* SIGCR.1: TCCS: 1 = Tx CCS. */ xlb[0x40] |= (1 << 2); /* SIGCR.2: RCCS: 1 = Rx CCS. */ xlb[0x33] |= (1 << 6); /* E1RCR1.6: RSIGM: 1 = Rx CCS */ } if (sp->config.ifcoding != SDL_CODING_AMI) { sp->config.ifcoding = SDL_CODING_AMI; xlb[0x33] &= ~(1 << 5); /* E1RCR1.5: RHDB3: 0 = Rx AMI. */ xlb[0x35] &= ~(1 << 2); /* E1TCR1.2: THDB3: 0 = Tx AMI. */ } if (sp->config.ifgcrc != SDL_GCRC_CRC4) { sp->config.ifgcrc = SDL_GCRC_CRC4; xlb[0x33] |= (1 << 3); /* E1RCR1.3: RCRC4: 1, Rx CRC-4. */ xlb[0x35] |= (1 << 0); /* E1TCR1.0: TCRC4: 1, Tx CRC-4. */ } sp->status.config = 2; break; case 2: /* E1, CCS, AMI, CRC4 */ sp->config.ifgtype = SDL_GTYPE_E1; if (sp->config.ifframing != SDL_FRAMING_CCS) { sp->config.ifframing = SDL_FRAMING_CCS; xlb[0x40] |= (1 << 1); /* SIGCR.1: TCCS: 1 = Tx CCS. */ xlb[0x40] |= (1 << 2); /* SIGCR.2: RCCS: 1 = Rx CCS. */ xlb[0x33] |= (1 << 6); /* E1RCR1.6: RSIGM: 1 = Rx CCS */ } if (sp->config.ifcoding != SDL_CODING_AMI) { sp->config.ifcoding = SDL_CODING_AMI; xlb[0x33] &= ~(1 << 5); /* E1RCR1.5: RHDB3: 0 = Rx AMI. */ xlb[0x35] &= ~(1 << 2); /* E1TCR1.2: THDB3: 0 = Tx AMI. */ } if (sp->config.ifgcrc != SDL_GCRC_CRC5) { sp->config.ifgcrc = SDL_GCRC_CRC5; xlb[0x33] &= ~(1 << 3); /* E1RCR1.3: RCRC4: 0, Rx non-CRC-4. */ xlb[0x35] &= ~(1 << 0); /* E1TCR1.0: TCRC4: 0, Tx non-CRC-4. */ } sp->status.config = 3; break; case 3: /* E1, CCS, AMI, non-CRC4 */ sp->config.ifgtype = SDL_GTYPE_E1; if (sp->config.ifframing != SDL_FRAMING_CAS) { sp->config.ifframing = SDL_FRAMING_CAS; xlb[0x40] &= ~(1 << 1); /* SIGCR.1: TCCS: 0 = Tx CAS. */ xlb[0x40] &= ~(1 << 2); /* SIGCR.2: RCCS: 0 = Rx CAS. */ xlb[0x33] &= ~(1 << 6); /* E1RCR1.6: RSIGM: 0 = Rx CAS. */ } if (sp->config.ifcoding != SDL_CODING_HDB3) { sp->config.ifcoding = SDL_CODING_HDB3; xlb[0x33] |= (1 << 5); /* E1RCR1.5: RHDB3: 1 = Rx HDB3. */ xlb[0x35] |= (1 << 2); /* E1TCR1.2: THDB3: 1 = Tx HDB3. */ } if (sp->config.ifgcrc != SDL_GCRC_CRC4) { sp->config.ifgcrc = SDL_GCRC_CRC4; xlb[0x33] |= (1 << 3); /* E1RCR1.3: RCRC4: 1, Rx CRC-4. */ xlb[0x35] |= (1 << 0); /* E1TCR1.0: TCRC4: 1, Tx CRC-4. */ } sp->status.config = 4; break; case 4: /* E1, CAS, HDB3, CRC4 */ sp->config.ifgtype = SDL_GTYPE_E1; if (sp->config.ifframing != SDL_FRAMING_CAS) { sp->config.ifframing = SDL_FRAMING_CAS; xlb[0x40] &= ~(1 << 1); /* SIGCR.1: TCCS: 0 = Tx CAS. */ xlb[0x40] &= ~(1 << 2); /* SIGCR.2: RCCS: 0 = Rx CAS. */ xlb[0x33] &= ~(1 << 6); /* E1RCR1.6: RSIGM: 0 = Rx CAS. */ } if (sp->config.ifcoding != SDL_CODING_HDB3) { sp->config.ifcoding = SDL_CODING_HDB3; xlb[0x33] |= (1 << 5); /* E1RCR1.5: RHDB3: 1 = Rx HDB3. */ xlb[0x35] |= (1 << 2); /* E1TCR1.2: THDB3: 1 = Tx HDB3. */ } if (sp->config.ifgcrc != SDL_GCRC_CRC5) { sp->config.ifgcrc = SDL_GCRC_CRC5; xlb[0x33] &= ~(1 << 3); /* E1RCR1.3: RCRC4: 0, Rx non-CRC-4. */ xlb[0x35] &= ~(1 << 0); /* E1TCR1.0: TCRC4: 0, Tx non-CRC-4. */ } sp->status.config = 5; break; case 5: /* E1, CAS, HDB3, non-CRC4 */ sp->config.ifgtype = SDL_GTYPE_E1; if (sp->config.ifframing != SDL_FRAMING_CAS) { sp->config.ifframing = SDL_FRAMING_CAS; xlb[0x40] &= ~(1 << 1); /* SIGCR.1: TCCS: 0 = Tx CAS. */ xlb[0x40] &= ~(1 << 2); /* SIGCR.2: RCCS: 0 = Rx CAS. */ xlb[0x33] &= ~(1 << 6); /* E1RCR1.6: RSIGM: 0 = Rx CAS. */ } if (sp->config.ifcoding != SDL_CODING_AMI) { sp->config.ifcoding = SDL_CODING_AMI; xlb[0x33] &= ~(1 << 5); /* E1RCR1.5: RHDB3: 0 = Rx AMI. */ xlb[0x35] &= ~(1 << 2); /* E1TCR1.2: THDB3: 0 = Tx AMI. */ } if (sp->config.ifgcrc != SDL_GCRC_CRC4) { sp->config.ifgcrc = SDL_GCRC_CRC4; xlb[0x33] |= (1 << 3); /* E1RCR1.3: RCRC4: 1, Rx CRC-4. */ xlb[0x35] |= (1 << 0); /* E1TCR1.0: TCRC4: 1, Tx CRC-4. */ } sp->status.config = 6; break; case 6: /* E1, CAS, AMI, CRC4 */ sp->config.ifgtype = SDL_GTYPE_E1; if (sp->config.ifframing != SDL_FRAMING_CAS) { sp->config.ifframing = SDL_FRAMING_CAS; xlb[0x40] &= ~(1 << 1); /* SIGCR.1: TCCS: 0 = Tx CAS. */ xlb[0x40] &= ~(1 << 2); /* SIGCR.2: RCCS: 0 = Rx CAS. */ xlb[0x33] &= ~(1 << 6); /* E1RCR1.6: RSIGM: 0 = Rx CAS. */ } if (sp->config.ifcoding != SDL_CODING_AMI) { sp->config.ifcoding = SDL_CODING_AMI; xlb[0x33] &= ~(1 << 5); /* E1RCR1.5: RHDB3: 0 = Rx AMI. */ xlb[0x35] &= ~(1 << 2); /* E1TCR1.2: THDB3: 0 = Tx AMI. */ } if (sp->config.ifgcrc != SDL_GCRC_CRC5) { sp->config.ifgcrc = SDL_GCRC_CRC5; xlb[0x33] &= ~(1 << 3); /* E1RCR1.3: RCRC4: 0, Rx non-CRC-4. */ xlb[0x35] &= ~(1 << 0); /* E1TCR1.0: TCRC4: 0, Tx non-CRC-4. */ } sp->status.config = 7; break; case 7: /* E1, CAS, AMI, non-CRC4 */ sp->config.ifgtype = SDL_GTYPE_E1; if (sp->config.ifframing != SDL_FRAMING_CCS) { sp->config.ifframing = SDL_FRAMING_CCS; xlb[0x40] |= (1 << 1); /* SIGCR.1: TCCS: 1 = Tx CCS. */ xlb[0x40] |= (1 << 2); /* SIGCR.2: RCCS: 1 = Rx CCS. */ xlb[0x33] |= (1 << 6); /* E1RCR1.6: RSIGM: 1 = Rx CAS. */ } if (sp->config.ifcoding != SDL_CODING_HDB3) { sp->config.ifcoding = SDL_CODING_HDB3; xlb[0x33] |= (1 << 5); /* E1RCR1.5: RHDB3: 1 = Rx HDB3. */ xlb[0x35] |= (1 << 2); /* E1TCR1.2: THDB3: 1 = Tx HDB3. */ } if (sp->config.ifgcrc != SDL_GCRC_CRC4) { sp->config.ifgcrc = SDL_GCRC_CRC4; xlb[0x33] |= (1 << 3); /* E1RCR1.3: RCRC4: 1, Rx CRC-4. */ xlb[0x35] |= (1 << 0); /* E1TCR1.0: TCRC4: 1, Tx CRC-4. */ } sp->status.config = 0; return (1); } break; case SDL_GTYPE_T1: case SDL_GTYPE_J1: switch (sp->status.config) { case 0: /* T1, ESF, B8ZS, CRC6 */ if (!ansi || japan) { sp->config.ifgtype = SDL_GTYPE_J1; if (sp->config.ifframing != SDL_FRAMING_ESF) { sp->config.ifframing = SDL_FRAMING_ESF; xlb[0x04] |= (1 << 6); /* T1RCR2.6: RFM: 1 = Rx ESF. */ xlb[0x07] |= (1 << 2); /* T1CCR1.2: TFM: 1 = Tx ESF. */ } if (sp->config.ifcoding != SDL_CODING_B8ZS) { sp->config.ifcoding = SDL_CODING_B8ZS; xlb[0x04] |= (1 << 5); /* T1RCR2.5: RB8ZS: 1 = Rx B8ZS. */ xlb[0x06] |= (1 << 7); /* T1TCR2.7: TB8ZS: 1 = Tx B8ZS. */ xlb[0x41] |= (1 << 3); /* ERCNT.3: VCRFS: 1 = count CVs. */ } if (sp->config.ifgcrc != SDL_GCRC_CRC6J) { sp->config.ifgcrc = SDL_GCRC_CRC6J; xlb[0x04] |= (1 << 1); /* T1RCR2.1: RJC: 1 = Rx JT-G704. */ xlb[0x05] |= (1 << 7); /* T1TCR1.7: TJC: 1 = Tx JT-G704. */ xlb[0x04] &= ~(1 << 0); /* T1RCR2.0: RD4YM: 0 = bit 2. */ xlb[0x06] &= ~(1 << 2); /* T1TCR2.2: TD4YM: 0 = bit 2. */ } sp->status.config = 1; break; } /* fall through */ case 1: /* J1, ESF, B8ZS, CRC6J */ if (ansi || !japan) { sp->config.ifgtype = SDL_GTYPE_T1; if (sp->config.ifframing != SDL_FRAMING_ESF) { sp->config.ifframing = SDL_FRAMING_ESF; xlb[0x04] |= (1 << 6); /* T1RCR2.6: RFM: 1 = Rx ESF. */ xlb[0x07] |= (1 << 2); /* T1CCR1.2: TFM: 1 = Tx ESF. */ } if (sp->config.ifcoding != SDL_CODING_AMI) { sp->config.ifcoding = SDL_CODING_AMI; xlb[0x04] &= ~(1 << 5); /* T1RCR2.5: RB8ZS: 0 = Rx AMI. */ xlb[0x06] &= ~(1 << 7); /* T1TCR2.7: TB8ZS: 0 = Tx AMI. */ xlb[0x41] &= ~(1 << 3); /* ERCNT.3: VCRFS: 0 = count BPVs. */ } if (sp->config.ifgcrc != SDL_GCRC_CRC6) { sp->config.ifgcrc = SDL_GCRC_CRC6; xlb[0x04] &= ~(1 << 1); /* T1RCR2.1: RJC: 0 = Rx ANSI CRC6. */ xlb[0x05] &= ~(1 << 7); /* T1TCR1.7: TJC: 0 = Tx ANSI CRC6. */ xlb[0x04] &= ~(1 << 0); /* T1RCR2.0: RD4YM: 0 = Rx ANSI. */ xlb[0x06] &= ~(1 << 2); /* T1TCR2.2: TD4YM: 0 = Tx ANSI. */ } sp->status.config = 2; break; } /* fall through */ case 2: /* T1, ESF, AMI, CRC6 */ if (!ansi || japan) { sp->config.ifgtype = SDL_GTYPE_J1; if (sp->config.ifframing != SDL_FRAMING_ESF) { sp->config.ifframing = SDL_FRAMING_ESF; xlb[0x04] |= (1 << 6); /* T1RCR2.6: RFM: 1 = Rx ESF. */ xlb[0x07] |= (1 << 2); /* T1CCR1.2: TFM: 1 = Tx ESF. */ } if (sp->config.ifcoding != SDL_CODING_AMI) { sp->config.ifcoding = SDL_CODING_AMI; xlb[0x04] &= ~(1 << 5); /* T1RCR2.5: RB8ZS: 0 = Rx AMI. */ xlb[0x06] &= ~(1 << 7); /* T1TCR2.7: TB8ZS: 0 = Tx AMI. */ xlb[0x41] &= ~(1 << 3); /* ERCNT.3: VCRFS: 0 = count BPVs. */ } if (sp->config.ifgcrc != SDL_GCRC_CRC6J) { sp->config.ifgcrc = SDL_GCRC_CRC6J; xlb[0x04] |= (1 << 1); /* T1RCR2.1: RJC: 1 = Rx JT-G704. */ xlb[0x05] |= (1 << 7); /* T1TCR1.7: TJC: 1 = Tx JT-G704. */ xlb[0x04] &= ~(1 << 0); /* T1RCR2.0: RD4YM: 0 = bit 2. */ xlb[0x06] &= ~(1 << 2); /* T1TCR2.2: TD4YM: 0 = bit 2. */ } sp->status.config = 3; break; } /* fall through */ case 3: /* J1, ESF, AMI, CRC6J */ if (ansi || !japan) { sp->config.ifgtype = SDL_GTYPE_T1; if (sp->config.ifframing != SDL_FRAMING_D4) { sp->config.ifframing = SDL_FRAMING_D4; xlb[0x04] &= ~(1 << 6); /* T1RCR2.6: RFM: 0 = Rx D4. */ xlb[0x07] &= ~(1 << 2); /* T1CCR1.2: TFM: 0 = Tx D4. */ } if (sp->config.ifcoding != SDL_CODING_B8ZS) { sp->config.ifcoding = SDL_CODING_B8ZS; xlb[0x04] |= (1 << 5); /* T1RCR2.5: RB8ZS: 1 = Rx B8ZS. */ xlb[0x06] |= (1 << 7); /* T1TCR2.7: TB8ZS: 1 = Tx B8ZS. */ xlb[0x41] |= (1 << 3); /* ERCNT.3: VCRFS: 1 = count CVs. */ } if (sp->config.ifgcrc != SDL_GCRC_CRC6) { sp->config.ifgcrc = SDL_GCRC_CRC6; xlb[0x04] &= ~(1 << 1); /* T1RCR2.1: RJC: 0 = Rx ANSI CRC6. */ xlb[0x05] &= ~(1 << 7); /* T1TCR1.7: TJC: 0 = Tx ANSI CRC6. */ xlb[0x04] &= ~(1 << 0); /* T1RCR2.0: RD4YM: 0 = Rx ANSI. */ xlb[0x06] &= ~(1 << 2); /* T1TCR2.2: TD4YM: 0 = Tx ANSI. */ } sp->status.config = 4; break; } /* fall through */ case 4: /* T1, D4, B8ZS, CRC6 */ if (!ansi || japan) { sp->config.ifgtype = SDL_GTYPE_J1; if (sp->config.ifframing != SDL_FRAMING_D4) { sp->config.ifframing = SDL_FRAMING_D4; xlb[0x04] &= ~(1 << 6); /* T1RCR2.6: RFM: 0 = Rx D4. */ xlb[0x07] &= ~(1 << 2); /* T1CCR1.2: TFM: 0 = Tx D4. */ } if (sp->config.ifcoding != SDL_CODING_B8ZS) { sp->config.ifcoding = SDL_CODING_B8ZS; xlb[0x04] |= (1 << 5); /* T1RCR2.5: RB8ZS: 1 = Rx B8ZS. */ xlb[0x06] |= (1 << 7); /* T1TCR2.7: TB8ZS: 1 = Tx B8ZS. */ xlb[0x41] |= (1 << 3); /* ERCNT.3: VCRFS: 1 = count CVs. */ } if (sp->config.ifgcrc != SDL_GCRC_CRC6J) { sp->config.ifgcrc = SDL_GCRC_CRC6J; xlb[0x04] |= (1 << 1); /* T1RCR2.1: RJC: 1 = Rx JT-G704. */ xlb[0x05] |= (1 << 7); /* T1TCR1.7: TJC: 1 = Tx JT-G704. */ xlb[0x04] |= (1 << 0); /* T1RCR2.0: RD4YM: 1 = fm 12. */ xlb[0x06] |= (1 << 2); /* T1TCR2.2: TD4YM: 1 = fm 12. */ } sp->status.config = 5; break; } /* fall through */ case 5: /* J1, D4, B8ZS, CRC6J */ if (ansi || !japan) { sp->config.ifgtype = SDL_GTYPE_T1; if (sp->config.ifframing != SDL_FRAMING_D4) { sp->config.ifframing = SDL_FRAMING_D4; xlb[0x04] &= ~(1 << 6); /* T1RCR2.6: RFM: 0 = Rx D4. */ xlb[0x07] &= ~(1 << 2); /* T1CCR1.2: TFM: 0 = Tx D4. */ } if (sp->config.ifcoding != SDL_CODING_AMI) { sp->config.ifcoding = SDL_CODING_AMI; xlb[0x04] &= ~(1 << 5); /* T1RCR2.5: RB8ZS: 0 = Rx AMI. */ xlb[0x06] &= ~(1 << 7); /* T1TCR2.7: TB8ZS: 0 = Tx AMI. */ xlb[0x41] &= ~(1 << 3); /* ERCNT.3: VCRFS: 0 = count BPVs. */ } if (sp->config.ifgcrc != SDL_GCRC_CRC6) { sp->config.ifgcrc = SDL_GCRC_CRC6; xlb[0x04] &= ~(1 << 1); /* T1RCR2.1: RJC: 0 = Rx ANSI CRC6. */ xlb[0x05] &= ~(1 << 7); /* T1TCR1.7: TJC: 0 = Tx ANSI CRC6. */ xlb[0x04] &= ~(1 << 0); /* T1RCR2.0: RD4YM: 0 = Rx ANSI. */ xlb[0x06] &= ~(1 << 2); /* T1TCR2.2: TD4YM: 0 = Tx ANSI. */ } sp->status.config = 6; break; } /* fall through */ case 6: /* T1, D4, AMI, CRC6 */ if (!ansi || japan) { sp->config.ifgtype = SDL_GTYPE_J1; if (sp->config.ifframing != SDL_FRAMING_D4) { sp->config.ifframing = SDL_FRAMING_D4; xlb[0x04] &= ~(1 << 6); /* T1RCR2.6: RFM: 0 = Rx D4. */ xlb[0x07] &= ~(1 << 2); /* T1CCR1.2: TFM: 0 = Tx D4. */ } if (sp->config.ifcoding != SDL_CODING_AMI) { sp->config.ifcoding = SDL_CODING_AMI; xlb[0x04] &= ~(1 << 5); /* T1RCR2.5: RB8ZS: 0 = Rx AMI. */ xlb[0x06] &= ~(1 << 7); /* T1TCR2.7: TB8ZS: 0 = Tx AMI. */ xlb[0x41] &= ~(1 << 3); /* ERCNT.3: VCRFS: 0 = count BPVs. */ } if (sp->config.ifgcrc != SDL_GCRC_CRC6J) { sp->config.ifgcrc = SDL_GCRC_CRC6J; xlb[0x04] |= (1 << 1); /* T1RCR2.1: RJC: 1 = Rx JT-G704. */ xlb[0x05] |= (1 << 7); /* T1TCR1.7: TJC: 1 = Tx JT-G704. */ xlb[0x04] |= (1 << 0); /* T1RCR2.0: RD4YM: 1 = fm 12. */ xlb[0x06] |= (1 << 2); /* T1TCR2.2: TD4YM: 1 = fm 12. */ } sp->status.config = 7; break; } /* fall through */ case 7: /* J1, D4, AMI, CRC6J */ if (ansi || !japan) { sp->config.ifgtype = SDL_GTYPE_T1; if (sp->config.ifframing != SDL_FRAMING_ESF) { sp->config.ifframing = SDL_FRAMING_ESF; xlb[0x04] |= (1 << 6); /* T1RCR2.6: RFM: 1 = Rx ESF. */ xlb[0x07] |= (1 << 2); /* T1CCR1.2: TFM: 1 = Tx ESF. */ } if (sp->config.ifcoding != SDL_CODING_B8ZS) { sp->config.ifcoding = SDL_CODING_B8ZS; xlb[0x04] |= (1 << 5); /* T1RCR2.5: RB8ZS: 1 = Rx B8ZS. */ xlb[0x06] |= (1 << 7); /* T1TCR2.7: TB8ZS: 1 = Tx B8ZS. */ xlb[0x41] |= (1 << 3); /* ERCNT.3: VCRFS: 1 = count CVs. */ } if (sp->config.ifgcrc != SDL_GCRC_CRC6) { sp->config.ifgcrc = SDL_GCRC_CRC6; xlb[0x04] &= ~(1 << 1); /* T1RCR2.1: RJC: 0 = Rx ANSI CRC6. */ xlb[0x05] &= ~(1 << 7); /* T1TCR1.7: TJC: 0 = Tx ANSI CRC6. */ xlb[0x04] &= ~(1 << 0); /* T1RCR2.0: RD4YM: 0 = Rx ANSI. */ xlb[0x06] &= ~(1 << 2); /* T1TCR2.2: TD4YM: 0 = Tx ANSI. */ } sp->status.config = 0; } else { sp->config.ifgtype = SDL_GTYPE_J1; if (sp->config.ifframing != SDL_FRAMING_ESF) { sp->config.ifframing = SDL_FRAMING_ESF; xlb[0x04] |= (1 << 6); /* T1RCR2.6: RFM: 1 = Rx ESF. */ xlb[0x07] |= (1 << 2); /* T1CCR1.2: TFM: 1 = Tx ESF. */ } if (sp->config.ifcoding != SDL_CODING_B8ZS) { sp->config.ifcoding = SDL_CODING_B8ZS; xlb[0x04] |= (1 << 5); /* T1RCR2.5: RB8ZS: 1 = Rx B8ZS. */ xlb[0x06] |= (1 << 7); /* T1TCR2.7: TB8ZS: 1 = Tx B8ZS. */ xlb[0x41] |= (1 << 3); /* ERCNT.3: VCRFS: 1 = count CVs. */ } if (sp->config.ifgcrc != SDL_GCRC_CRC6J) { sp->config.ifgcrc = SDL_GCRC_CRC6J; xlb[0x04] |= (1 << 1); /* T1RCR2.1: RJC: 1 = Rx JT-G704. */ xlb[0x05] |= (1 << 7); /* T1TCR1.7: TJC: 1 = Tx JT-G704. */ xlb[0x04] &= ~(1 << 0); /* T1RCR2.0: RD4YM: 0 = bit 2. */ xlb[0x06] &= ~(1 << 2); /* T1TCR2.2: TD4YM: 0 = bit 2. */ } sp->status.config = 1; } return (1); } break; } return (0); } /** xp_x1_change_gtype: - change span type to or from E1 from or to T1/J1 or vise versa * @sp: span structure pointer * @xlb: span iobase * * Returns true (1) when a reconfiguration has been performed, and false (0), otherwise. */ noinline __unlikely int xp_x1_change_gtype(struct sp *sp, register volatile uint8_t *xlb) { struct ch *ch; int chan, offset; switch (sp->config.ifgtype) { case SDL_GTYPE_E1: if (!etsi) { /* We are not directed in the E1 configuration by driver parameters, sot the setting should likely be T1 or J1. Reconfigure T1 or J1, do a LIRST and go back to the start. */ /* remove interrupt mask for E1 mode */ xlb[0x19] &= ~((1 << 7) | (1 << 3)); xlb[0x1b] &= ~((1 << 2) | (1 << 1) | (1 << 0)); xlb[0x1d] &= ~((1 << 6) | (1 << 5)); /* first set up all T1/J1 registers */ /* need to change from E1 to T1 */ sp->config = sdl_default_t1_span; for (chan = 1; chan < 24; chan++) { if ((ch = sp->chans[chan]) != NULL) { ch->option = lmi_default_t1_chan; ch->sdl.config = sdl_default_t1_chan; ch->sdt.config = sdt_default_t1_chan; ch->sl.config = sl_default_t1_chan; xp_x1_chan_config(sp, ch, xlb); continue; } swerr(); } /* set up line interface */ xlb[0x78] = (xlb[0x78] & ~((0x7 << 5) | (1 << 4))) | (0x00 << 5) | (0 << 4); /* LIC1 */ xlb[0x79] |= (1 << 3); /* LIC2.3: 1 = JAMUX: 1 = PLL 2.048 at MCLK. */ // xlb[0x7a] = xlb[0x7a]; /* LIC3 */ /* leave linear gain alone */ xlb[0x7c] = 0x00; /* Unused */ xlb[0x7d] = 0x00; /* TLBC: Automatic gain control. */ xlb[0x7e] = (1 << 7) | (1 << 6); /* IAAR.7(GTIC), IAAR.6(GRIC) */ xlb[0x7f] = 0x7f; /* PCICR set idle code 0xff */ /* next switch to T1 mode */ xlb[0x00] &= ~(1 << 1); /* MSTRREG.1=0: T1/J1 mode. */ xlb[0x79] &= ~(1 << 7); /* LIC2.7: 0 = T1 */ xlb[0x7b] = (0x00 << 4) | (0x02 << 2) | (0x02 << 0); /* 100 Ohm term, MCLK 2.048 MHz */ /* last zero all E1 registers */ /* 0x33 to 0x36 are E1 Tx and Rx control registers */ for (offset = 0; offset < 4; offset++) xlb[0x33 + offset] = 0x00; /* except maybe these two */ xlb[0xd0] = 0x1b; /* TAF.0-7='00011011'B (default) */ xlb[0xd1] = 0x40; /* TNAF.0-7='01000000'B (default) */ /* apply interrupt mask for T1/J1 mode */ xlb[0x1b] |= (1 << 7) | (1 << 6) | (1 << 5); xlb[0x1d] |= (1 << 7); /* FIXME: do a LIRST to reset the JALT */ return (1); } break; case SDL_GTYPE_T1: case SDL_GTYPE_J1: if ((sp->config.ifgtype == SDL_GTYPE_T1 && !ansi) || (sp->config.ifgtype == SDL_GTYPE_J1 && !japan)) { /* We are not directed in the T1 or J1 configuration by driver parameters, so the setting should likely be E1. Reconfigure E1, do a LIRST and go back to the start. */ /* remove interrupt mask for T1/J1 mode */ xlb[0x1b] &= ~((1 << 7) | (1 << 6) | (1 << 5)); xlb[0x1d] &= ~((1 << 7)); /* first set up all E1 registers */ xlb[0xd0] = 0x1b; /* TAF.0-7='00011011'B (default) */ xlb[0xd1] = 0x40; /* TNAF.0-7='01000000'B (default) */ xlb[0x50] = (1 << 3) | (1 << 1) | (1 << 0); /* TS1: X=1, Y=0, CAS align word */ /* need to change from T1/J1 to E1 */ sp->config = sdl_default_e1_span; for (chan = 1; chan < 32; chan++) { if ((ch = sp->chans[chan]) != NULL) { ch->option = lmi_default_e1_chan; ch->sdl.config = sdl_default_e1_chan; ch->sdt.config = sdt_default_e1_chan; ch->sl.config = sl_default_e1_chan; xp_x1_chan_config(sp, ch, xlb); continue; } swerr(); } /* set up line interface */ xlb[0x78] = (xlb[0x78] & ~((0x7 << 5) | (1 << 4))) | (0x01 << 5) | (1 << 4); /* LIC1 */ xlb[0x79] |= (1 << 3); /* LIC2.3: 1 = JAMUX: 1 = PLL 2.048 at MCLK. */ // xlb[0x7a] = xlb[0x7a]; /* LIC3 */ /* leave linear gain alone */ xlb[0x7c] = 0x00; /* Unused */ xlb[0x7d] = 0x00; /* TLBC: Automatic gain control. */ xlb[0x7e] = (1 << 7) | (1 << 6); /* IAAR.7(GTIC), IAAR.6(GRIC) */ xlb[0x7f] = 0xff; /* PCICR set idle code 0xff */ /* next switch to E1 mode */ xlb[0x00] |= (1 << 1); /* MSTRREG.1=1: E1 mode. */ xlb[0x79] |= (1 << 7); /* LIC2.7: 1 = E1. */ xlb[0x7b] = (0x00 << 4) | (0x03 << 2) | (0x03 << 0); /* 120 Ohm term, MCLK 2.048 MHz */ /* last zero all T1/J1 registers */ /* 0x03 to 0x07 are T1 Tx and Rx control registers */ for (offset = 0; offset < 5; offset++) xlb[0x03 + offset] = 0x00; /* 0xb6 to 0xbf are programmable in-band loop code generatiion and detection that are only applicable to T1. */ for (offset = 0; offset < 10; offset++) xlb[0xb6 + offset] = 0x00; /* apply interrupt mask for E1 mode */ xlb[0x19] |= (1 << 7) | (1 << 3); xlb[0x1b] |= (1 << 2) | (1 << 1) | (1 << 0); xlb[0x1d] |= (1 << 6) | (1 << 5); /* FIXME: do a LIRST to reset the JALT */ return (1); } break; } return (0); } /** xp_x1_process_stats: - process statistics (performance measures) for the span * @sp: span structure pointer * @errors: error events accumulated so far. * * ERROR EVENTS: * Bipolar Violation BPV Error Event: A BPV error event for an AMI coded signal is the occurrence * of a pulse of the same polarity as the previous pulse. A BPV error event for a B8ZS or HDB3 * coded signal is the occurrence of a pulse of the same polarity as the previous pulse without * being part of the zero substitution code. * * Controlled Slip (CS) Error Event: A CS is the replication or deletion of the payload bits of a * DS1 frame. A CS may be performed when there is a difference between the timing of a * synchronous receiving terminal an the received signal. A CS does not acuase an Out of Frame * defect. * * Excessive Zeros (EXZ) Error Event: An EXZ error event for an AMI coded signal is the occurence * of more than fifteen contiguous zeros. For a B8ZS coded signal, the defect occurs when more * than seven contiguous zeros are detected. * * Line Coding Violation (LCV) Error Event: An LCV is the occurence of either a Bipolar Violation * or Excessive Zeros (EXZ) error event. * * Path Coding Violation (PCV) Error Event: A PCV error event is a frame synchronization bit error * in the D4 and E1-non-CRC-4 formats, or a CRC error in the ESF and E1-CRC-4 formats. * * PERFORMANCE PARAMETERS: * All performance parameters are accumulated in fifteen minute intervals and up to 96 intervals * (covering a 24-hour period) are kept by an agent. Fewer than 96 intervals of data will be * available if the agent has been restarted within the last 24 hours. In addition, there is a * rolling 24-hour total of each performance parameter. There is no requirement for an agent to * ensure a fixed relationship between the start of a fifteen minute interval and clock time; * however, some agents may align the fifteen minute intervals with quarter hours. * * Severely Errored Seconds (SES): An SES for ESF signals is a second with one of the following: * 320 or more PCV error events; one or more OOF defects; a detected AIS defect. For E1 CRC-4 * signals, an SES is a second with either 832 or more PCV error events or one or more OOF * defects. For E1 non-CRC-4 signals, an SES is a 2048 (LCV ????) PCV or more. For D4 signals, * an SES is a count of one-second intervals with Framing Error events, or an OOF defect, or * 1544 LCV or more. Controlled slips are not included in this parameter. This is not * incremented during an Unavailable Second. * * Severely Errored Framing Seconds (SEFS): An SEFS is a second with either one or more OOF * defects, or a detected AIS defect. * * Unavailable Seconds (UASs): A performance management event that is calculted by counting the * number of seconds for which the interface is unavailable. An interface is said to be * unavailable from the onset of 10 continugous Severely Errored Seconds (SESs), or on the * onset of a condition leading to a failutre. Once unavailable, and if no failure is present, * an interface becomes available at the onset of 10 contiguous seconds with no SESs. * * UAS are calculated by counting the number of seconds that the interface is unavailable. The * DS1 interface is said to be unavailable from the onset of ten contiguous SESs, or the onset * of the condition leadeing to a failure (see Failure States). If the condition leading to * the failure was immediately preceded by one or more continguous SES, then the DS1 interface * unavailability starts from the onset of these SES. Once unavailable, and if no failure is * present, the DS1 interfae becomes available at the onset of 10 contiguous seconds with no * SES. if the failure clearing time is less than or equat to ten seconds. If the failure * clearing time is more than ten seconds, the DS1 interface becoms available at the onset of * tem contiguous seconds with no SES, or the onset period leading to the successful clearing * condition, whichever occurs later. With respect to DS1 error counts, all coutners are * incremented while the DS1 interface is deemed available. While the interface is deemed * unavailable, the only count that is incremented is UAS. A special case exists when the ten * or more second period crosses the 900 second statistic window boundary, as the foregoing * description ipmlies that the SES and UAS counter must be adjusted when the UAS stats is * entered. Successive "gets" of the affectetd dsx1IntervalSESs and dsx1IntervalUASs objects * will return differing values if the first get occurs during the first few seconds of the * window. This is viewed as an unavoidable side-effect of selecting the presently-defined * objects. * * Bursty Errored Secods (BES): A BES (also known as an Errored Second Type B) is a second with * fewer than 320 and more than one PCV, no SEF defects, and no detected incoming AIS defects. * Controlled slips are not incldued in this parameter. * * Errored Seconds (ES): For ESF and E1-CRC links an Errored Second is a second with one of the * followng: one or more PCV; one or more OOF defects; one or more Controlled Slip events; a * detected AIS defect. * * Controlled Slip Seconds (CSS): A cCSS is a one-second interval containing one or more controlled * slips. * * Line Errored Seconds (LES): A LES, according to T1M1.3, is a second in which one or more LCV * error events were detected. While many implementations are currently unable to detect the * zero strings, it is expected that interface manufacturers will add this capability in * deference to ANSI; therefore, it will become available in time. In the T1M1.3 specification, * near end LCV and far end LES are counted. For consistency, we count LES at both ends. * * Degraded Minutes: A DM is one in which the estimated error rate exceeds 1E-06 but does not * exceed 1E-03. DM are determined by collecting all of the Available Seconds, removing any * Severely Errored Seconds grouping the result in 60-second long groups and counting a * 60-second long group (minute) as degraded if the cumulative errors during the seconds * present in the group exceed 1E-6. Available seconds are merely those seconds which are not * unavailable as described below. */ static noinline fastcall __hot void xp_x1_process_stats(struct sp *sp, register uint errors) { /* This is a one second timeout */ /* Calculate severely errored seconds. */ switch (sp->config.ifgtype) { case SDL_GTYPE_E1: switch (sp->config.ifgcrc) { case SDL_GCRC_CRC4: /* For E1 CRC4 signals, an SES is 832 or more PCV error events, or one or more Out of Frame defects. */ if (sp->stats[0].PCVs >= 832) errors |= XP_ERR_SES; break; case SDL_GCRC_CRC5: /* For E1 non-CRC4 signals, an SES is 2048 or more LCV. */ if (sp->stats[0].LCVs >= 2048) errors |= XP_ERR_SES; break; } break; case SDL_GTYPE_T1: case SDL_GTYPE_J1: /* Note: when there are a lot of PCV and the span is T1, there is possibility that it should be set to J1 instead. When there are a lot of PCV and the span is J1, there is a possibility that it should be set to T1 instead. */ switch (sp->config.ifframing) { case SDL_FRAMING_ESF: /* A Severely Errored Second for ESF signals is a second with one of the following: 320 or more PCV error events; one or more OOF defects; or a detected AIS defect. */ if (sp->stats[0].PCVs >= 320) errors |= XP_ERR_SES; break; case SDL_FRAMING_D4: /* For D4 signals, an SES is a count of one-second intervals with Framing Error events, or an Out of Frame defect; or 1544 or more LCVs. */ if (sp->stats[0].LCVs >= 1544) errors |= XP_ERR_SES; break; } break; } /* The number of Unavailable Seconds (UASs) in the current interval. */ /* Track the number of consecutive severely errored seconds and the number of consecutive non-severely errored seconds */ if (errors & (XP_ERR_SES)) { sp->status.nses = 0; sp->status.sess++; if (sp->status.sess >= 10) { if (sp->status.sess == 10 && !(errors & XP_ERR_UAS)) { sp->stats[0].UASs += 9; errors |= XP_ERR_UAS; } errors |= XP_ERR_UAS; } } else { sp->status.sess = 0; sp->status.nses++; if (sp->status.nses >= 10) { if (sp->status.nses == 10 && (errors & XP_ERR_UAS)) { sp->stats[0].UASs -= 9; errors &= ~XP_ERR_UAS; } errors &= ~XP_ERR_UAS; } } if (errors & (XP_ERR_UAS)) sp->stats[0].UASs = 1; /* Calculate bursty errored seconds */ switch (sp->config.ifgtype) { case SDL_GTYPE_E1: switch (sp->config.ifgcrc) { case SDL_GCRC_CRC4: if (1 < sp->stats[0].PCVs && sp->stats[0].PCVs < 832) if (!(errors & XP_ERR_SEFS)) if (!(errors & XP_FAIL_AIS)) errors |= XP_ERR_BES; break; case SDL_GCRC_CRC5: if (1 < sp->stats[0].LCVs && sp->stats[0].LCVs < 2048) if (!(errors & XP_ERR_SEFS)) if (!(errors & XP_FAIL_AIS)) errors |= XP_ERR_BES; break; } break; case SDL_GTYPE_T1: case SDL_GTYPE_J1: switch (sp->config.ifframing) { case SDL_FRAMING_ESF: if (1 < sp->stats[0].PCVs && sp->stats[0].PCVs < 320) if (!(errors & XP_ERR_SEFS)) if (!(errors & XP_FAIL_AIS)) errors |= XP_ERR_BES; break; case SDL_FRAMING_D4: if (1 < sp->stats[0].LCVs && sp->stats[0].LCVs < 1544) if (!(errors & XP_ERR_SEFS)) if (!(errors & XP_FAIL_AIS)) errors |= XP_ERR_BES; break; } break; } /* The number of Errored Seconds (ESs) in the current interval. */ if (sp->stats[0].PCVs > 0) errors |= XP_ERR_ES; if (errors & (XP_ERR_ES)) sp->stats[0].ESs = 1; /* The number of severely errored seconds (SESs) in the current interval. */ if (errors & (XP_ERR_SES)) sp->stats[0].SESs = 1; /* The number of Severely Errored Framing Seconds (SEFSs) in the current interval. */ if (errors & (XP_ERR_SEFS)) sp->stats[0].SEFSs = 1; /* The number of controlled slip seconds (CSSs) in the current interval. */ if (errors & (XP_ERR_CSS)) sp->stats[0].CSSs = 1; /* The number of Line Errored Seconds (LESs) in the current interval. */ if (errors & (XP_ERR_LES)) sp->stats[0].LESs = 1; /* The number of Bursty Errored Seconds (BESs) in the current interval. */ if (errors & (XP_ERR_BES)) sp->stats[0].BESs = 1; /* accumulate the one-second counts */ sp->stats[1].ESs += sp->stats[0].ESs; sp->stats[1].SESs += sp->stats[0].SESs; sp->stats[1].ESs += sp->stats[0].ESs; sp->stats[1].SESs += sp->stats[0].SESs; sp->stats[1].SEFSs += sp->stats[0].SEFSs; sp->stats[1].UASs += sp->stats[0].UASs; sp->stats[1].CSSs += sp->stats[0].CSSs; sp->stats[1].PCVs += sp->stats[0].PCVs; sp->stats[1].LESs += sp->stats[0].LESs; sp->stats[1].BESs += sp->stats[0].BESs; sp->stats[1].DMs += sp->stats[0].DMs; sp->stats[1].LCVs += sp->stats[0].LCVs; sp->stats[1].FASEs += sp->stats[0].FASEs; sp->stats[1].FABEs += sp->stats[0].FABEs; sp->stats[1].FEBEs += sp->stats[0].FEBEs; bzero(&sp->stats[0], sizeof(sp->stats[0])); if ((++sp->stats[1].SECs) == 60) { /* The number of degraded minutes (DMs) in the current interval. */ if (errors & (XP_ERR_DM)) sp->stats[1].DMs = 1; /* accumulate one-minute counts */ sp->stats[2].ESs += sp->stats[1].ESs; sp->stats[2].SESs += sp->stats[1].SESs; sp->stats[2].ESs += sp->stats[1].ESs; sp->stats[2].SESs += sp->stats[1].SESs; sp->stats[2].SEFSs += sp->stats[1].SEFSs; sp->stats[2].UASs += sp->stats[1].UASs; sp->stats[2].CSSs += sp->stats[1].CSSs; sp->stats[2].PCVs += sp->stats[1].PCVs; sp->stats[2].LESs += sp->stats[1].LESs; sp->stats[2].BESs += sp->stats[1].BESs; sp->stats[2].DMs += sp->stats[1].DMs; sp->stats[2].LCVs += sp->stats[1].LCVs; sp->stats[2].FASEs += sp->stats[1].FASEs; sp->stats[2].FABEs += sp->stats[1].FABEs; sp->stats[2].FEBEs += sp->stats[1].FEBEs; bzero(&sp->stats[1], sizeof(sp->stats[1])); if ((sp->stats[2].SECs += 60) == 900) { uint index = sp->curr; sp->hist[index] = sp->stats[2]; sp->hist[index].ValidData = 2; /* true(2) */ bzero(&sp->stats[2], sizeof(sp->stats[2])); if (++index == 96) index = 0; sp->curr = index; } } return; } static noinline fastcall __hot void xp_x1_process_alarms(struct cd *cd, struct sp *sp, register volatile uint8_t *xlb, register uint flags, uint timeout) { register uint alarms = sp->config.ifalarms; /* integrate alarms */ if ((flags & SDL_IF_RX_RDMA) && (sp->config.ifframing == SDL_FRAMING_CAS)) alarms |= SDL_ALARM_DMF; else alarms &= ~SDL_ALARM_DMF; if (flags & (SDL_IF_RX_RRA | SDL_IF_RX_RYEL)) alarms |= SDL_ALARM_YEL; else alarms &= ~SDL_ALARM_YEL; if (flags & SDL_IF_RX_RUA1) alarms |= SDL_ALARM_BLU; else alarms &= ~SDL_ALARM_BLU; if (flags & (SDL_IF_RX_RLOS | SDL_IF_RX_FRCL | SDL_IF_RX_LRCL)) alarms |= SDL_ALARM_RED; else alarms &= ~SDL_ALARM_RED; if ((alarms & SDL_ALARM_REC) && (timeout)) { if (alarms & (SDL_ALARM_RED | SDL_ALARM_BLU)) /* can't recover, alarms started again */ alarms &= ~SDL_ALARM_REC; else { /* recovery time is in terms of timeouts (5 seconds) */ if (sp->recovertime && !--sp->recovertime) { if (sp->config.ifgtype == SDL_GTYPE_E1) { /* Not required as we are setting automatic RAI generation, but it cannot hurt. */ xlb[0xd1] &= ~(1 << 5); /* TNAF.5: A: 0 = no RAI */ } else { xlb[0x05] &= ~(1 << 0); /* T1RCR1.0: TYEL: 0 = no YEL */ } alarms &= ~SDL_ALARM_REC; cd->eval_syncsrc = 1; } } } /* if any of the alarms (or recovery) changed we need to do this */ if ((alarms ^ sp->config.ifalarms) & (SDL_ALARM_RED | SDL_ALARM_BLU | SDL_ALARM_YEL | SDL_ALARM_REC)) { if ((alarms & (SDL_ALARM_RED | SDL_ALARM_BLU)) && !(sp->config.ifalarms & (SDL_ALARM_RED | SDL_ALARM_BLU))) { /* Local alarms have just begun. Signal a yellow (RAI) alarm to the other end. */ if (!(alarms & SDL_ALARM_REC)) { /* local alarms just begun and we were not in recovery */ if (sp->config.ifgtype == SDL_GTYPE_E1) { /* Not required as we are setting automatic RAI generation, but it cannot hurt. */ xlb[0xd1] |= (1 << 5); /* TNAF.5: A: 1 = RAI */ } else { xlb[0x05] |= (1 << 0); /* T1TCR1.0: TYEL: 1 = transmit yellow alarm */ } if (alarms & SDL_ALARM_RED) cd->eval_syncsrc = 1; } else alarms &= ~SDL_ALARM_REC; } else if ((alarms & SDL_ALARM_RED) && !(sp->config.ifalarms & SDL_ALARM_RED)) { /* red alarm just got added to the set, reevaluate the sync source */ cd->eval_syncsrc = 1; } else if (!(alarms & (SDL_ALARM_RED | SDL_ALARM_BLU)) && (sp->config.ifalarms & (SDL_ALARM_RED | SDL_ALARM_BLU))) { /* Local alarms have just ended. */ alarms |= SDL_ALARM_REC; if (xlb[0x41] & 0x20) { if (sp->config.ifgtype == SDL_GTYPE_E1) sp->recovertime = X400P_SDL_ALARM_SETTLE_E1; else sp->recovertime = X400P_SDL_ALARM_SETTLE_T1; } else sp->recovertime = X400P_SDL_ALARM_SETTLE_SECONDS; } sp->config.ifalarms &= ~(SDL_ALARM_RED | SDL_ALARM_BLU | SDL_ALARM_YEL | SDL_ALARM_REC); sp->config.ifalarms |= (alarms & (SDL_ALARM_RED | SDL_ALARM_BLU | SDL_ALARM_YEL | SDL_ALARM_REC)); { int leds = 0, all_leds; /* adjust leds */ if (alarms & SDL_ALARM_RED) leds |= LEDRED; else if (alarms & SDL_ALARM_YEL) leds |= LEDYEL; else leds |= LEDGRN; all_leds = cd->ledreg; all_leds &= ~(LEDYEL << (sp->span << 1)); all_leds |= (leds << (sp->span << 1)); if (cd->ledreg != all_leds) { cd->ledreg = all_leds; cd->xlb[LEDREG] = cd->ledreg; } } } } /** xp_x1_eval_syncsrc: - reevalute the synchronization source * @cd: card structur pointer * * There is really only one version of this function, it is just laid out in several places for * proper position with respect to the main interrupt service routine. */ static noinline fastcall __hot void xp_x1_eval_syncsrc(struct cd *cd) { /* for safety */ if (cd->config.ifsyncsrc[0] != 0) { int src, synreg = SYNCSELF, ctlreg, clkreg = cd->clkreg; for (src = 0; src < SDL_SYNCS; src++) { struct sp *sp; int span; if ((span = cd->config.ifsyncsrc[src]) == 0) break; if ((--span < cd->ports && span >= 0) && (sp = cd->spans[span]) && (sp->config.ifflags & SDL_IF_UP) && (sp->config.ifflags & SDL_IF_RX_UP) && (sp->config.ifflags & SDL_IF_RX_RUNNING) && (sp->config.ifclock != SDL_CLOCK_LOOP) && !(sp->config.ifalarms & (SDL_ALARM_BLU | SDL_ALARM_RED))) { synreg = cd->config.ifsyncsrc[src]; if (sp->config.ifgtype == SDL_GTYPE_E1) clkreg |= E1DIV; else clkreg &= ~E1DIV; break; } } if (cd->config.ifsync != synreg) { cd->config.ifsync = synreg; ctlreg = cd->ctlreg & ~E1DIV; ctlreg |= clkreg; /* use divider for span or clock */ cd->xlb[CTLREG] = cd->ctlreg = ctlreg; cd->xlb[SYNREG] = cd->synreg = synreg; } } } /* * ========================================================================= * * STREAMS Message Handling * * ========================================================================= * * M_IOCTL Handling * ------------------------------------------------------------------------- */ noinline fastcall __unlikely int dsx_copyin2(queue_t *q, mblk_t *mp, struct xp *xp, struct copyresp *cp, mblk_t *dp) { int err; switch (_IOC_NR(cp->cp_cmd)) { case _IOC_NR(DSX_IOCGINFO): /* dsx_info_t */ case _IOC_NR(DSX_IOCGOPTION): /* dsx_option_t */ goto eproto; case _IOC_NR(DSX_IOCSOPTION): /* dsx_option_t */ err = dsx_iocsoption(q, mp, dp); break; case _IOC_NR(DSX_IOCLCONFIG): /* dsx_config_t */ case _IOC_NR(DSX_IOCGCONFIG): /* dsx_config_t */ goto eproto; case _IOC_NR(DSX_IOCSCONFIG): /* dsx_config_t */ err = dsx_iocsconfig(q, mp, dp); break; case _IOC_NR(DSX_IOCTCONFIG): /* dsx_config_t */ err = dsx_ioctconfig(q, mp, dp); break; case _IOC_NR(DSX_IOCCCONFIG): /* dsx_config_t */ err = dsx_ioccconfig(q, mp, dp); break; case _IOC_NR(DSX_IOCGSTATEM): /* dsx_statem_t */ goto eproto; case _IOC_NR(DSX_IOCCMRESET): /* dsx_statem_t */ err = dsx_ioccmreset(q, mp, dp); break; case _IOC_NR(DSX_IOCGSTATUS): /* dsx_status_t */ goto eproto; case _IOC_NR(DSX_IOCSSTATUS): /* dsx_status_t */ err = dsx_iocsstatus(q, mp, dp); break; case _IOC_NR(DSX_IOCCSTATUS): /* dsx_status_t */ err = dsx_ioccstatus(q, mp, dp); break; case _IOC_NR(DSX_IOCGSTATSP): /* dsx_stats_t */ case _IOC_NR(DSX_IOCGSTATS): /* dsx_stats_t */ goto eproto; case _IOC_NR(DSX_IOCSSTATSP): /* dsx_stats_t */ err = dsx_iocsstatsp(q, mp, dp); break; case _IOC_NR(DSX_IOCCSTATS): /* dsx_stats_t */ err = dsx_ioccstats(q, mp, dp); break; case _IOC_NR(DSX_IOCGNOTIFY): /* dsx_notify_t */ goto eproto; case _IOC_NR(DSX_IOCSNOTIFY): /* dsx_notify_t */ err = dsx_iocsnotify(q, mp, dp); break; case _IOC_NR(DSX_IOCCNOTIFY): /* dsx_notify_t */ err = dsx_ioccnotify(q, mp, dp); break; case _IOC_NR(DSX_IOCGATTR): /* dsx_attr_t */ goto eproto; case _IOC_NR(DSX_IOCCMGMT): /* dsx_mgmt_t */ err = dsx_ioccmgmt(q, mp, dp); break; case _IOC_NR(DSX_IOCCPASS): /* dsx_pass_t */ err = dsx_ioccpass(q, mp, dp); break; default: goto einval; break; } return (err); eproto: __swerr(); return (-EPROTO); einval: return (-EINVAL); } /** dsx_copyin: - first copyin stage for DSX_IOC * * This function must return <0, error; 0, copyout or copydone performed, >0, additional copyin * required. */ noinline fastcall __unlikely int dsx_copyin(queue_t *q, mblk_t *mp, struct xp *xp, struct copyresp *cp, mblk_t *dp) { int err; switch (_IOC_NR(cp->cp_cmd)) { case _IOC_NR(DSX_IOCGINFO): /* dsx_info_t */ err = dsx_iocginfo(q, mp, dp); break; case _IOC_NR(DSX_IOCGOPTION): /* dsx_option_t */ err = dsx_iocgoption(q, mp, dp); break; case _IOC_NR(DSX_IOCSOPTION): /* dsx_option_t */ err = dsx_option_size((dsx_option_t *) dp->b_rptr); break; case _IOC_NR(DSX_IOCLCONFIG): /* dsx_config_t */ err = dsx_ioclconfig(q, mp, dp); break; case _IOC_NR(DSX_IOCGCONFIG): /* dsx_config_t */ err = dsx_iocgconfig(q, mp, dp); break; case _IOC_NR(DSX_IOCSCONFIG): /* dsx_config_t */ case _IOC_NR(DSX_IOCTCONFIG): /* dsx_config_t */ case _IOC_NR(DSX_IOCCCONFIG): /* dsx_config_t */ err = dsx_config_size((dsx_config_t *) dp->b_rptr); break; case _IOC_NR(DSX_IOCGSTATEM): /* dsx_statem_t */ err = dsx_iocgstatem(q, mp, dp); break; case _IOC_NR(DSX_IOCCMRESET): /* dsx_statem_t */ err = dsx_statem_size((dsx_statem_t *) dp->b_rptr); break; case _IOC_NR(DSX_IOCGSTATUS): /* dsx_status_t */ err = dsx_iocgstatus(q, mp, dp); case _IOC_NR(DSX_IOCSSTATUS): /* dsx_status_t */ case _IOC_NR(DSX_IOCCSTATUS): /* dsx_status_t */ err = dsx_status_size((dsx_status_t *) dp->b_rptr); break; case _IOC_NR(DSX_IOCGSTATSP): /* dsx_stats_t */ err = dsx_iocgstatsp(q, mp, dp); break; case _IOC_NR(DSX_IOCGSTATS): /* dsx_stats_t */ err = dsx_iocgstats(q, mp, dp); break; case _IOC_NR(DSX_IOCSSTATSP): /* dsx_stats_t */ case _IOC_NR(DSX_IOCCSTATS): /* dsx_stats_t */ err = dsx_stats_size((dsx_stats_t *) dp->b_rptr); break; case _IOC_NR(DSX_IOCGNOTIFY): /* dsx_notify_t */ err = dsx_iocgnotify(q, mp, dp); break; case _IOC_NR(DSX_IOCSNOTIFY): /* dsx_notify_t */ case _IOC_NR(DSX_IOCCNOTIFY): /* dsx_notify_t */ err = dsx_notify_size((dsx_notify_t *) dp->b_rptr); break; case _IOC_NR(DSX_IOCGATTR): /* dsx_attr_t */ err = dsx_iocgattr(q, mp, dp); break; case _IOC_NR(DSX_IOCCMGMT): /* dsx_mgmt_t */ err = dsx_mgmt_size((dsx_mgmt_t *) dp->b_rptr); break; case _IOC_NR(DSX_IOCCPASS): /* dsx_pass_t */ err = dsx_pass_size((dsx_pass_t *) dp->b_rptr); break; default: err = -EINVAL; } return (err); } noinline fastcall __unlikely int dsx_ioctl(queue_t *q, mblk_t *mp, struct xp *xp, struct iocblk *ioc) { int err; switch (_IOC_NR(ioc->ioc_cmd)) { case _IOC_NR(DSX_IOCGINFO): /* dsx_info_t */ err = sizeof(dsx_info_t); break; case _IOC_NR(DSX_IOCGOPTION): /* dsx_option_t */ case _IOC_NR(DSX_IOCSOPTION): /* dsx_option_t */ err = sizeof(dsx_option_t); break; case _IOC_NR(DSX_IOCLCONFIG): /* dsx_config_t */ case _IOC_NR(DSX_IOCGCONFIG): /* dsx_config_t */ case _IOC_NR(DSX_IOCSCONFIG): /* dsx_config_t */ case _IOC_NR(DSX_IOCTCONFIG): /* dsx_config_t */ case _IOC_NR(DSX_IOCCCONFIG): /* dsx_config_t */ err = sizeof(dsx_config_t); break; case _IOC_NR(DSX_IOCGSTATEM): /* dsx_statem_t */ case _IOC_NR(DSX_IOCCMRESET): /* dsx_statem_t */ err = sizeof(dsx_statem_t); break; case _IOC_NR(DSX_IOCGSTATUS): /* dsx_status_t */ case _IOC_NR(DSX_IOCSSTATUS): /* dsx_status_t */ case _IOC_NR(DSX_IOCCSTATUS): /* dsx_status_t */ err = sizeof(dsx_status_t); break; case _IOC_NR(DSX_IOCGSTATSP): /* dsx_stats_t */ case _IOC_NR(DSX_IOCSSTATSP): /* dsx_stats_t */ case _IOC_NR(DSX_IOCGSTATS): /* dsx_stats_t */ case _IOC_NR(DSX_IOCCSTATS): /* dsx_stats_t */ err = sizeof(dsx_stats_t); break; case _IOC_NR(DSX_IOCGNOTIFY): /* dsx_notify_t */ case _IOC_NR(DSX_IOCSNOTIFY): /* dsx_notify_t */ case _IOC_NR(DSX_IOCCNOTIFY): /* dsx_notify_t */ err = sizeof(dsx_notify_t); break; case _IOC_NR(DSX_IOCGATTR): /* dsx_attr_t */ err = sizeof(dsx_attr_t); break; case _IOC_NR(DSX_IOCCMGMT): /* dsx_mgmt_t */ err = sizeof(dsx_mgmt_t); break; case _IOC_NR(DSX_IOCCPASS): /* dsx_pass_t */ err = sizeof(dsx_pass_t); break; default: err = -EINVAL; break; } return (err); } noinline fastcall __unlikely int mx_copyin2(queue_t *q, mblk_t *mp, struct xp *xp, struct copyresp *cp, mblk_t *dp) { int err; switch (_IOC_NR(cp->cp_cmd)) { case _IOC_NR(MX_IOCGINFO): /* mx_info_t */ case _IOC_NR(MX_IOCGOPTION): /* mx_option_t */ goto eproto; case _IOC_NR(MX_IOCSOPTION): /* mx_option_t */ err = mx_iocsoption(q, mp, dp); break; case _IOC_NR(MX_IOCLCONFIG): /* mx_config_t */ case _IOC_NR(MX_IOCGCONFIG): /* mx_config_t */ goto eproto; case _IOC_NR(MX_IOCSCONFIG): /* mx_config_t */ err = mx_iocsconfig(q, mp, dp); break; case _IOC_NR(MX_IOCTCONFIG): /* mx_config_t */ err = mx_ioctconfig(q, mp, dp); break; case _IOC_NR(MX_IOCCCONFIG): /* mx_config_t */ err = mx_ioccconfig(q, mp, dp); break; case _IOC_NR(MX_IOCGSTATEM): /* mx_statem_t */ goto eproto; case _IOC_NR(MX_IOCCMRESET): /* mx_statem_t */ err = mx_ioccmreset(q, mp, dp); break; case _IOC_NR(MX_IOCGSTATUS): /* mx_status_t */ goto eproto; case _IOC_NR(MX_IOCSSTATUS): /* mx_status_t */ err = mx_iocsstatus(q, mp, dp); break; case _IOC_NR(MX_IOCCSTATUS): /* mx_status_t */ err = mx_ioccstatus(q, mp, dp); break; case _IOC_NR(MX_IOCGSTATSP): /* mx_stats_t */ goto eproto; case _IOC_NR(MX_IOCGSTATS): /* mx_stats_t */ goto eproto; case _IOC_NR(MX_IOCSSTATSP): /* mx_stats_t */ err = mx_iocsstatsp(q, mp, dp); break; case _IOC_NR(MX_IOCCSTATS): /* mx_stats_t */ err = mx_ioccstats(q, mp, dp); break; case _IOC_NR(MX_IOCGNOTIFY): /* mx_notify_t */ goto eproto; case _IOC_NR(MX_IOCSNOTIFY): /* mx_notify_t */ err = mx_iocsnotify(q, mp, dp); break; case _IOC_NR(MX_IOCCNOTIFY): /* mx_notify_t */ err = mx_ioccnotify(q, mp, dp); break; case _IOC_NR(MX_IOCGATTR): /* mx_attr_t */ goto eproto; case _IOC_NR(MX_IOCCMGMT): /* mx_mgmt_t */ err = mx_ioccmgmt(q, mp, dp); break; case _IOC_NR(MX_IOCCPASS): /* mx_pass_t */ err = mx_ioccpass(q, mp, dp); break; default: goto einval; } return (err); eproto: __swerr(); return (-EPROTO); einval: return (-EINVAL); } noinline fastcall __unlikely int mx_copyin(queue_t *q, mblk_t *mp, struct xp *xp, struct copyresp *cp, mblk_t *dp) { int err; switch (_IOC_NR(cp->cp_cmd)) { case _IOC_NR(MX_IOCGINFO): /* mx_info_t */ err = mx_iocginfo(q, mp, dp); break; case _IOC_NR(MX_IOCGOPTION): /* mx_option_t */ err = mx_iocgoption(q, mp, dp); break; case _IOC_NR(MX_IOCSOPTION): /* mx_option_t */ err = mx_option_size((mx_option_t *) dp->b_rptr); break; case _IOC_NR(MX_IOCLCONFIG): /* mx_config_t */ err = mx_ioclconfig(q, mp, dp); break; case _IOC_NR(MX_IOCGCONFIG): /* mx_config_t */ err = mx_iocgconfig(q, mp, dp); break; case _IOC_NR(MX_IOCSCONFIG): /* mx_config_t */ case _IOC_NR(MX_IOCTCONFIG): /* mx_config_t */ case _IOC_NR(MX_IOCCCONFIG): /* mx_config_t */ err = mx_config_size((mx_config_t *) dp->b_rptr); break; case _IOC_NR(MX_IOCGSTATEM): /* mx_statem_t */ err = mx_iocgstatem(q, mp, dp); break; case _IOC_NR(MX_IOCCMRESET): /* mx_statem_t */ err = mx_statem_size((mx_statem_t *) dp->b_rptr); break; case _IOC_NR(MX_IOCGSTATUS): /* mx_status_t */ err = mx_iocgstatus(q, mp, dp); break; case _IOC_NR(MX_IOCSSTATUS): /* mx_status_t */ case _IOC_NR(MX_IOCCSTATUS): /* mx_status_t */ err = mx_status_size((mx_status_t *) dp->b_rptr); break; case _IOC_NR(MX_IOCGSTATSP): /* mx_stats_t */ err = mx_iocgstatsp(q, mp, dp); break; case _IOC_NR(MX_IOCGSTATS): /* mx_stats_t */ err = mx_iocgstats(q, mp, dp); break; case _IOC_NR(MX_IOCSSTATSP): /* mx_stats_t */ case _IOC_NR(MX_IOCCSTATS): /* mx_stats_t */ err = mx_stats_size((mx_stats_t *) dp->b_rptr); break; case _IOC_NR(MX_IOCGNOTIFY): /* mx_notify_t */ err = mx_iocgnotify(q, mp, dp); break; case _IOC_NR(MX_IOCSNOTIFY): /* mx_notify_t */ case _IOC_NR(MX_IOCCNOTIFY): /* mx_notify_t */ err = mx_notify_size((mx_notify_t *) dp->b_rptr); break; case _IOC_NR(MX_IOCGATTR): /* mx_attr_t */ err = mx_iocgattr(q, mp, dp); break; case _IOC_NR(MX_IOCCMGMT): /* mx_mgmt_t */ err = mx_mgmt_size((mx_mgmt_t *) dp->b_rptr); break; case _IOC_NR(MX_IOCCPASS): /* mx_pass_t */ err = mx_pass_size((mx_pass_t *) dp->b_rptr); break; default: err = -EINVAL; } return (err); } noinline fastcall __unlikely int mx_ioctl(queue_t *q, mblk_t *mp, struct xp *xp, struct iocblk *ioc) { int err; switch (_IOC_NR(ioc->ioc_cmd)) { case _IOC_NR(MX_IOCGINFO): /* mx_info_t */ err = sizeof(mx_info_t); break; case _IOC_NR(MX_IOCGOPTION): /* mx_option_t */ case _IOC_NR(MX_IOCSOPTION): /* mx_option_t */ err = sizeof(mx_option_t); break; case _IOC_NR(MX_IOCLCONFIG): /* mx_config_t */ case _IOC_NR(MX_IOCGCONFIG): /* mx_config_t */ case _IOC_NR(MX_IOCSCONFIG): /* mx_config_t */ case _IOC_NR(MX_IOCTCONFIG): /* mx_config_t */ case _IOC_NR(MX_IOCCCONFIG): /* mx_config_t */ err = sizeof(mx_config_t); break; case _IOC_NR(MX_IOCGSTATEM): /* mx_statem_t */ case _IOC_NR(MX_IOCCMRESET): /* mx_statem_t */ err = sizeof(mx_statem_t); break; case _IOC_NR(MX_IOCGSTATUS): /* mx_status_t */ case _IOC_NR(MX_IOCSSTATUS): /* mx_status_t */ case _IOC_NR(MX_IOCCSTATUS): /* mx_status_t */ err = sizeof(mx_status_t); break; case _IOC_NR(MX_IOCGSTATSP): /* mx_stats_t */ case _IOC_NR(MX_IOCSSTATSP): /* mx_stats_t */ case _IOC_NR(MX_IOCGSTATS): /* mx_stats_t */ case _IOC_NR(MX_IOCCSTATS): /* mx_stats_t */ err = sizeof(mx_stats_t); break; case _IOC_NR(MX_IOCGNOTIFY): /* mx_notify_t */ case _IOC_NR(MX_IOCSNOTIFY): /* mx_notify_t */ case _IOC_NR(MX_IOCCNOTIFY): /* mx_notify_t */ err = sizeof(mx_notify_t); break; case _IOC_NR(MX_IOCGATTR): /* mx_attr_t */ err = sizeof(mx_attr_t); break; case _IOC_NR(MX_IOCCMGMT): /* mx_mgmt_t */ err = sizeof(mx_mgmt_t); break; case _IOC_NR(MX_IOCCPASS): /* mx_pass_t */ err = sizeof(mx_pass_t); break; default: err = -EINVAL; } return (err); } noinline fastcall __unlikely int sl_copyin2(queue_t *q, mblk_t *mp, struct xp *xp, struct copyresp *cp, mblk_t *dp) { /* SL has no copyin2 stage. */ __swerr(); return (-EPROTO); } noinline fastcall __unlikely int sl_copyin(queue_t *q, mblk_t *mp, struct xp *xp, struct copyresp *cp, mblk_t *dp) { struct ch *ch; int err; if ((ch = xp->ch) == NULL) return (-ENXIO); spin_lock_bh(&ch->lock); { switch (_IOC_NR(cp->cp_cmd)) { case _IOC_NR(SL_IOCSOPTIONS): /* lmi_option_t */ err = sl_iocsoptions(ch, dp); break; case _IOC_NR(SL_IOCSCONFIG): /* sl_config_t */ err = sl_iocsconfig(ch, dp); break; case _IOC_NR(SL_IOCTCONFIG): /* sl_config_t */ err = sl_ioctconfig(ch, dp); break; case _IOC_NR(SL_IOCCCONFIG): /* sl_config_t */ err = sl_ioccconfig(ch, dp); break; case _IOC_NR(SL_IOCCMRESET): /* sl_statem_t */ err = sl_ioccmreset(ch, dp); break; case _IOC_NR(SL_IOCSSTATSP): /* lmi_sta_t */ err = sl_iocsstatsp(ch, dp); break; case _IOC_NR(SL_IOCCSTATS): /* sl_stats_t */ err = sl_ioccstats(ch, dp); break; case _IOC_NR(SL_IOCSNOTIFY): /* sl_notify_t */ err = sl_iocsnotify(ch, dp); break; case _IOC_NR(SL_IOCCNOTIFY): /* sl_notify_t */ err = sl_ioccnotify(ch, dp); break; default: __swerr(); err = -EPROTO; break; } } spin_unlock_bh(&ch->lock); return (err); } noinline fastcall __unlikely int sl_ioctl(queue_t *q, mblk_t *mp, struct xp *xp, struct iocblk *ioc) { int err; switch (_IOC_NR(ioc->ioc_cmd)) { case _IOC_NR(SL_IOCGOPTIONS): /* lmi_option_t */ err = (int)-sizeof(lmi_option_t); break; case _IOC_NR(SL_IOCSOPTIONS): /* lmi_option_t */ err = (int)sizeof(lmi_option_t); break; case _IOC_NR(SL_IOCGCONFIG): /* sl_config_t */ err = (int)-sizeof(sl_config_t); break; case _IOC_NR(SL_IOCSCONFIG): /* sl_config_t */ case _IOC_NR(SL_IOCTCONFIG): /* sl_config_t */ case _IOC_NR(SL_IOCCCONFIG): /* sl_config_t */ err = (int)sizeof(sl_config_t); break; case _IOC_NR(SL_IOCGSTATEM): /* sl_statem_t */ err = (int)-sizeof(sl_statem_t); break; case _IOC_NR(SL_IOCCMRESET): /* sl_statem_t */ err = (int)sizeof(sl_statem_t); break; case _IOC_NR(SL_IOCGSTATSP): /* sl_stats_t */ case _IOC_NR(SL_IOCGSTATS): /* sl_stats_t */ err = (int)-sizeof(sl_stats_t); break; case _IOC_NR(SL_IOCSSTATSP): /* sl_stats_t */ case _IOC_NR(SL_IOCCSTATS): /* sl_stats_t */ err = (int)sizeof(sl_stats_t); break; case _IOC_NR(SL_IOCGNOTIFY): /* sl_notify_t */ err = (int)-sizeof(sl_notify_t); break; case _IOC_NR(SL_IOCSNOTIFY): /* sl_notify_t */ case _IOC_NR(SL_IOCCNOTIFY): /* sl_notify_t */ err = (int)sizeof(sl_notify_t); break; default: goto einval; } if (err <= 0) { mblk_t *db; struct ch *ch; if ((ch = xp->ch) == NULL) goto enxio; if (-err > 0 && !(db = mi_copyout_alloc(q, mp, 0, -err, 0))) goto enosr; err = 0; spin_lock_bh(&ch->lock); { switch (_IOC_NR(ioc->ioc_cmd)) { case _IOC_NR(SL_IOCGOPTIONS): /* lmi_option_t */ sl_iocgoptions(ch, db); break; case _IOC_NR(SL_IOCGCONFIG): /* sl_config_t */ sl_iocgconfig(ch, db); break; case _IOC_NR(SL_IOCGSTATEM): /* sl_statem_t */ sl_iocgstatem(ch, db); break; case _IOC_NR(SL_IOCGSTATSP): /* sl_stats_t */ sl_iocgstatsp(ch, db); break; case _IOC_NR(SL_IOCGSTATS): /* sl_stats_t */ sl_iocgstats(ch, db); break; case _IOC_NR(SL_IOCGNOTIFY): /* sl_notify_t */ sl_iocgnotify(ch, db); break; default: err = -EFAULT; break; } } spin_unlock_bh(&ch->lock); } return (err); enxio: return (-ENXIO); einval: return (-EINVAL); enosr: return (-ENOSR); } noinline fastcall __unlikely int sdt_copyin2(queue_t *q, mblk_t *mp, struct xp *xp, struct copyresp *cp, mblk_t *dp) { /* SDT has no copyin2 stage. */ __swerr(); return (-EPROTO); } noinline fastcall __unlikely int sdt_copyin(queue_t *q, mblk_t *mp, struct xp *xp, struct copyresp *cp, mblk_t *dp) { struct ch *ch; int err; if ((ch = xp->ch) == NULL) return (-ENXIO); spin_lock_bh(&ch->lock); { switch (_IOC_NR(cp->cp_cmd)) { case _IOC_NR(SDT_IOCSOPTIONS): /* lmi_option_t */ err = sdt_iocsoptions(ch, dp); break; case _IOC_NR(SDT_IOCSCONFIG): /* sdt_config_t */ err = sdt_iocsconfig(ch, dp); break; case _IOC_NR(SDT_IOCTCONFIG): /* sdt_config_t */ err = sdt_ioctconfig(ch, dp); break; case _IOC_NR(SDT_IOCCCONFIG): /* sdt_config_t */ err = sdt_ioccconfig(ch, dp); break; case _IOC_NR(SDT_IOCCMRESET): /* sdt_statem_t */ err = sdt_ioccmreset(ch, dp); break; case _IOC_NR(SDT_IOCSSTATSP): /* lmi_sta_t */ err = sdt_iocsstatsp(ch, dp); break; case _IOC_NR(SDT_IOCCSTATS): /* sdt_stats_t */ err = sdt_ioccstats(ch, dp); break; case _IOC_NR(SDT_IOCSNOTIFY): /* sdt_notify_t */ err = sdt_iocsnotify(ch, dp); break; case _IOC_NR(SDT_IOCCNOTIFY): /* sdt_notify_t */ err = sdt_ioccnotify(ch, dp); break; default: __swerr(); err = -EPROTO; break; } } spin_unlock_bh(&ch->lock); return (err); } noinline fastcall __unlikely int sdt_ioctl(queue_t *q, mblk_t *mp, struct xp *xp, struct iocblk *ioc) { int err; switch (_IOC_NR(ioc->ioc_cmd)) { case _IOC_NR(SDT_IOCGOPTIONS): /* lmi_option_t */ err = (int)-sizeof(lmi_option_t); break; case _IOC_NR(SDT_IOCSOPTIONS): /* lmi_option_t */ err = (int)sizeof(lmi_option_t); break; case _IOC_NR(SDT_IOCGCONFIG): /* sdt_config_t */ err = (int)-sizeof(sdt_config_t); break; case _IOC_NR(SDT_IOCSCONFIG): /* sdt_config_t */ case _IOC_NR(SDT_IOCTCONFIG): /* sdt_config_t */ case _IOC_NR(SDT_IOCCCONFIG): /* sdt_config_t */ err = (int)sizeof(sdt_config_t); break; case _IOC_NR(SDT_IOCGSTATEM): /* sdt_statem_t */ err = (int)-sizeof(sdt_statem_t); break; case _IOC_NR(SDT_IOCCMRESET): /* sdt_statem_t */ err = (int)sizeof(sdt_statem_t); break; case _IOC_NR(SDT_IOCGSTATSP): /* lmi_sta_t */ err = (int)-sizeof(sdt_stats_t); break; case _IOC_NR(SDT_IOCSSTATSP): /* lmi_sta_t */ err = (int)sizeof(lmi_sta_t); break; case _IOC_NR(SDT_IOCGSTATS): /* sdt_stats_t */ err = (int)-sizeof(sdt_stats_t); break; case _IOC_NR(SDT_IOCCSTATS): /* sdt_stats_t */ err = (int)sizeof(sdt_stats_t); break; case _IOC_NR(SDT_IOCGNOTIFY): /* sdt_notify_t */ err = (int)-sizeof(sdt_notify_t); break; case _IOC_NR(SDT_IOCSNOTIFY): /* sdt_notify_t */ case _IOC_NR(SDT_IOCCNOTIFY): /* sdt_notify_t */ err = (int)sizeof(sdt_notify_t); break; case _IOC_NR(SDT_IOCCABORT): /* */ err = 0; break; default: goto einval; } if (err <= 0) { mblk_t *db; struct ch *ch; if ((ch = xp->ch) == NULL) goto enxio; if (err == 0) db = NULL; else if (!(db = mi_copyout_alloc(q, mp, 0, -err, 0))) goto enosr; err = 0; spin_lock_bh(&ch->lock); { switch (_IOC_NR(ioc->ioc_cmd)) { case _IOC_NR(SDT_IOCGOPTIONS): /* lmi_option_t */ sdt_iocgoptions(ch, db); break; case _IOC_NR(SDT_IOCGCONFIG): /* sdt_config_t */ sdt_iocgconfig(ch, db); break; case _IOC_NR(SDT_IOCGSTATEM): /* sdt_statem_t */ sdt_iocgstatem(ch, db); break; case _IOC_NR(SDT_IOCGSTATSP): /* lmi_sta_t */ sdt_iocgstatsp(ch, db); break; case _IOC_NR(SDT_IOCGSTATS): /* sdt_stats_t */ sdt_iocgstats(ch, db); break; case _IOC_NR(SDT_IOCGNOTIFY): /* sdt_notify_t */ sdt_iocgnotify(ch, db); break; case _IOC_NR(SDT_IOCCABORT): /* */ sdt_ioccabort(ch); break; default: __swerr(); err = -EFAULT; break; } } spin_unlock_bh(&ch->lock); } return (err); enxio: return (-ENXIO); einval: return (-EINVAL); enosr: return (-ENOSR); } noinline fastcall __unlikely int sdl_copyin2(queue_t *q, mblk_t *mp, struct xp *xp, struct copyresp *cp, mblk_t *dp) { /* SDL has no copyin2 stage. */ __swerr(); return (-EPROTO); } noinline fastcall __unlikely int sdl_copyin(queue_t *q, mblk_t *mp, struct xp *xp, struct copyresp *cp, mblk_t *dp) { struct ch *ch; int err; if ((ch = xp->ch) == NULL) return (-ENXIO); spin_lock_bh(&ch->lock); { switch (_IOC_NR(cp->cp_cmd)) { case _IOC_NR(SDL_IOCSOPTIONS): /* lmi_option_t */ err = sdl_iocsoptions(ch, dp); break; case _IOC_NR(SDL_IOCSCONFIG): /* sdl_config_t */ err = sdl_iocsconfig(ch, dp); break; case _IOC_NR(SDL_IOCTCONFIG): /* sdl_config_t */ err = sdl_ioctconfig(ch, dp); break; case _IOC_NR(SDL_IOCCCONFIG): /* sdl_config_t */ err = sdl_ioccconfig(ch, dp); break; case _IOC_NR(SDL_IOCCMRESET): /* sdl_statem_t */ err = sdl_ioccmreset(ch, dp); break; case _IOC_NR(SDL_IOCSSTATSP): /* sdl_stats_t */ err = sdl_iocsstatsp(ch, dp); break; case _IOC_NR(SDL_IOCCSTATS): /* sdl_stats_t */ err = sdl_ioccstats(ch, dp); break; case _IOC_NR(SDL_IOCSNOTIFY): /* sdl_notify_t */ err = sdl_iocsnotify(ch, dp); break; case _IOC_NR(SDL_IOCCNOTIFY): /* sdl_notify_t */ err = sdl_ioccnotify(ch, dp); break; default: __swerr(); err = -EPROTO; break; } } spin_unlock_bh(&ch->lock); return (err); } noinline fastcall __unlikely int sdl_ioctl(queue_t *q, mblk_t *mp, struct xp *xp, struct iocblk *ioc) { int err; switch (_IOC_NR(ioc->ioc_cmd)) { case _IOC_NR(SDL_IOCGOPTIONS): /* lmi_option_t */ err = (int)-sizeof(lmi_option_t); break; case _IOC_NR(SDL_IOCSOPTIONS): /* lmi_option_t */ err = (int)sizeof(lmi_option_t); break; case _IOC_NR(SDL_IOCGCONFIG): /* sdl_config_t */ err = (int)-sizeof(sdl_config_t); break; case _IOC_NR(SDL_IOCSCONFIG): /* sdl_config_t */ case _IOC_NR(SDL_IOCTCONFIG): /* sdl_config_t */ case _IOC_NR(SDL_IOCCCONFIG): /* sdl_config_t */ err = (int)sizeof(sdl_config_t); break; case _IOC_NR(SDL_IOCGSTATEM): /* sdl_statem_t */ err = (int)-sizeof(sdl_statem_t); break; case _IOC_NR(SDL_IOCCMRESET): /* sdl_statem_t */ err = (int)sizeof(sdl_statem_t); break; case _IOC_NR(SDL_IOCGSTATSP): /* sdl_stats_t */ err = (int)-sizeof(sdl_stats_t); break; case _IOC_NR(SDL_IOCGSTATS): /* sdl_stats_t */ err = (int)-sizeof(sdl_stats_t); break; case _IOC_NR(SDL_IOCSSTATSP): /* sdl_stats_t */ case _IOC_NR(SDL_IOCCSTATS): /* sdl_stats_t */ err = (int)sizeof(sdl_stats_t); break; case _IOC_NR(SDL_IOCGNOTIFY): /* sdl_notify_t */ err = (int)-sizeof(sdl_notify_t); break; case _IOC_NR(SDL_IOCSNOTIFY): /* sdl_notify_t */ case _IOC_NR(SDL_IOCCNOTIFY): /* sdl_notify_t */ err = (int)sizeof(sdl_notify_t); break; case _IOC_NR(SDL_IOCCDISCTX): /* */ err = 0; break; case _IOC_NR(SDL_IOCCCONNTX): /* */ err = 0; break; default: goto einval; } if (err <= 0) { mblk_t *db; struct ch *ch; if ((ch = xp->ch) == NULL) goto enxio; if (err == 0) db = NULL; else if (!(db = mi_copyout_alloc(q, mp, 0, -err, 0))) goto enosr; err = 0; spin_lock_bh(&ch->lock); { switch (_IOC_NR(ioc->ioc_cmd)) { case _IOC_NR(SDL_IOCGOPTIONS): /* lmi_option_t */ sdl_iocgoptions(ch, db); break; case _IOC_NR(SDL_IOCGCONFIG): /* sdl_config_t */ sdl_iocgconfig(ch, db); break; case _IOC_NR(SDL_IOCGSTATEM): /* sdl_statem_t */ sdl_iocgstatem(ch, db); break; case _IOC_NR(SDL_IOCGSTATSP): /* sdl_stats_t */ sdl_iocgstatsp(ch, db); break; case _IOC_NR(SDL_IOCGSTATS): /* sdl_stats_t */ sdl_iocgstats(ch, db); break; case _IOC_NR(SDL_IOCGNOTIFY): /* sdl_notify_t */ sdl_iocgnotify(ch, db); break; case _IOC_NR(SDL_IOCCDISCTX): /* */ sdl_ioccdisctx(ch); break; case _IOC_NR(SDL_IOCCCONNTX): /* */ sdl_ioccconntx(ch); break; default: __swerr(); err = -EFAULT; break; } } spin_unlock_bh(&ch->lock); } return (err); enxio: return (-ENXIO); einval: return (-EINVAL); enosr: return (-ENOSR); } noinline fastcall __unlikely int nit_copyin(queue_t *q, mblk_t *mp, struct xp *xp, struct copyresp *cp, mblk_t *dp) { int err; switch (_IOC_NR(cp->cp_cmd)) { case _IOC_NR(NIOCBIND): err = nit_niocbind(xp, dp); break; case _IOC_NR(NIOCSSNAP): #ifdef __LP64__ if (cp->cp_flag == IOC_ILP32) err = nit_niocssnap32(xp, dp); else #endif /* __LP64__ */ err = nit_niocssnap(xp, dp); break; case _IOC_NR(NIOCGSNAP): __swerr(); err = -EPROTO; break; case _IOC_NR(NIOCSFLAGS): #ifdef __LP64__ if (cp->cp_flag == IOC_ILP32) err = nit_niocsflags32(xp, dp); else #endif /* __LP64__ */ err = nit_niocsflags(xp, dp); break; case _IOC_NR(NIOCGFLAGS): __swerr(); err = -EPROTO; break; default: __swerr(); err = -EPROTO; break; } return (err); } noinline fastcall __unlikely int nit_ioctl(queue_t *q, mblk_t *mp, struct xp *xp, struct iocblk *ioc) { int err; switch (_IOC_NR(ioc->ioc_cmd)) { case _IOC_NR(NIOCBIND): err = sizeof(struct ifreq); break; case _IOC_NR(NIOCSSNAP): /* ulong */ #ifdef __LP64__ if (ioc->ioc_flag == IOC_ILP32) err = sizeof(uint32_t); else #endif /* __LP64__ */ err = sizeof(ulong); break; case _IOC_NR(NIOCGSNAP): /* ulong */ #ifdef __LP64__ if (ioc->ioc_flag == IOC_ILP32) err = nit_niocgsnap32(q, mp, xp); else #endif /* __LP64__ */ err = nit_niocgsnap(q, mp, xp); break; case _IOC_NR(NIOCSFLAGS): /* ulong */ #ifdef __LP64__ if (ioc->ioc_flag == IOC_ILP32) err = sizeof(uint32_t); else #endif /* __LP64__ */ err = sizeof(ulong); break; case _IOC_NR(NIOCGFLAGS): /* ulong */ #ifdef __LP64__ if (ioc->ioc_flag == IOC_ILP32) err = nit_niocgflags32(q, mp, xp); else #endif /* __LP64__ */ err = nit_niocgflags(q, mp, xp); break; default: err = -EINVAL; break; } return (err); } noinline fastcall __unlikely int bpf_copyin(queue_t *q, mblk_t *mp, struct xp *xp, struct copyresp *cp, mblk_t *dp) { int err; switch (_IOC_NR(cp->cp_cmd)) { case _IOC_NR(BIOCGDLT): /* uint */ goto eproto; case _IOC_NR(BIOCSDLT): /* uint */ err = bpf_biocsdlt(q, mp, xp, dp); break; case _IOC_NR(BIOCGDLTLIST): /* bpf_dltlist */ err = bpf_biocgdltlist(q, mp, xp, cp, dp); break; case _IOC_NR(BIOCPROMISC): /* (none) */ goto eproto; case _IOC_NR(BIOCFLUSH): /* (none) */ goto eproto; case _IOC_NR(BIOCGETIF): /* ifreq */ // se _IOC_NR(BIOCGETLIF): /* lifreq */ switch (cp->cp_cmd) { case BIOCGETIF: goto eproto; case BIOCGETLIF: goto eproto; } goto eopnotsupp; case _IOC_NR(BIOCSETIF): /* ifreq */ // se _IOC_NR(BIOCSETLIF): /* lifreq */ switch (cp->cp_cmd) { case BIOCSETIF: err = bpf_biocsetif(q, xp, dp); break; case BIOCSETLIF: err = bpf_biocsetlif(q, xp, dp); break; } goto eproto; case _IOC_NR(BIOCGSTATS): /* bpf_stat or bpf_stat_old */ switch (cp->cp_cmd) { case BIOCGSTATS: goto eproto; case BIOCGSTATSOLD: goto eproto; } goto eopnotsupp; case _IOC_NR(BIOCGHDRCMPLT): /* uint */ goto eproto; case _IOC_NR(BIOCSHDRCMPLT): /* uint */ err = bpf_biocshdrcmplt(xp, dp); break; case _IOC_NR(BIOCGSEESENT): /* uint */ goto eproto; case _IOC_NR(BIOCSSEESENT): /* uint */ err = bpf_biocsseesent(xp, dp); break; #ifdef BIOCGDIRECTION case _IOC_NR(BIOCGDIRECTION): /* uint */ goto eproto; #endif #ifdef BIOCSDIRECTION case _IOC_NR(BIOCSDIRECTION): /* uint */ err = bpf_biocsdirection(xp, dp); break; #endif #ifdef BIOCGDIRFILT case _IOC_NR(BIOCGDIRFILT): /* uint */ goto eproto; #endif /* BIOCGDIRFILT */ #ifdef BIOCSDIRFILT case _IOC_NR(BIOCSDIRFILT): /* uint */ err = bpf_biocsdirfilt(xp, dp); break; #endif /* BIOCSDIRFILT */ #ifdef BIOCFEEDBACK case _IOC_NR(BIOCFEEDBACK): /* uint */ #endif case _IOC_NR(BIOCSFEEDBACK): /* uint */ err = bpf_biocsfeedback(xp, dp); break; case _IOC_NR(BIOCGFEEDBACK): /* uint */ goto eproto; /* -------------------------------------------------------------------------- */ /* Remaining input-output controls must be processed by the module bpfmod(4). */ /* -------------------------------------------------------------------------- */ case _IOC_NR(BIOCGBLEN): // or _IOC_NR(BIOCSBLEN): switch (cp->cp_cmd) { case BIOCSBLEN: goto eio; case BIOCGBLEN: goto eio; } goto eopnotsupp; case _IOC_NR(BIOCGRTIMEOUT): goto eio; case _IOC_NR(BIOCSRTIMEOUT): // or _IOC_NR(BIOCLOCK): switch (cp->cp_cmd) { case BIOCSRTIMEOUT: goto eio; case BIOCLOCK: goto eio; } goto eopnotsupp; #ifdef BIOCGFILDROP case _IOC_NR(BIOCGFILDROP): goto eio; #endif /* BIOCGFILDROP */ #ifdef BIOCSFILDROP case _IOC_NR(BIOCSFILDROP): goto eio; #endif /* BIOCSFILDROP */ case _IOC_NR(BIOCIMMEDIATE): goto eio; case _IOC_NR(BIOCSETF): goto eio; case _IOC_NR(BIOCSETFNR): goto eio; #ifdef BIOCSETWF case _IOC_NR(BIOCSETWF): goto eio; #endif /* BIOCSETWF */ case _IOC_NR(BIOCVERSION): goto eio; case _IOC_NR(BIOCSTCPF): // or _IOC_NR(BIOCGRSIG): switch (cp->cp_cmd) { case BIOCSTCPF: goto eio; case BIOCGRSIG: goto eio; } goto eopnotsupp; case _IOC_NR(BIOCSUDPF): // se _IOC_NR(BIOCSRSIG): switch (cp->cp_cmd) { case BIOCSUDPF: goto eio; case BIOCSRSIG: goto eio; } goto eopnotsupp; case _IOC_NR(BIOCSTSTAMP): goto eio; case _IOC_NR(BIOCGTSTAMP): // or _IOC_NR(BIOCGETBUFMODE): switch (cp->cp_cmd) { case BIOCGTSTAMP: goto eio; case BIOCGETBUFMODE: goto eio; } goto eopnotsupp; case _IOC_NR(BIOCSETBUFMODE): goto eio; case _IOC_NR(BIOCSETZBUF): goto eio; case _IOC_NR(BIOCGETZMAX): goto eio; case _IOC_NR(BIOCROTZBUF): goto eio; default: goto eopnotsupp; } return (err); eopnotsupp: /* This would be simple, but because this is M_IOCDATA that we should have rejected at the M_IOCTL stage, it means that some upper module is leaking M_IOCDATA down to us. The problem is likely with that module and not in this driver. Return EPROTO to distinguish. */ __swerr(); return (-EPROTO); eproto: /* Should have completed before this stage. This is a pretty significant error and indicates that we are not processing phases for the input-output control correctly. */ __swerr(); return (-EPROTO); eio: /* Should have been processed by module bpfmod(4). This is a pretty significant error because we should have rejected the input-output control in bpf_ioctl(). So, this probably represents a leakage from and bug in bpfmod(4) rather than here. */ __swerr(); return (-EIO); } noinline fastcall __unlikely int bpf_ioctl(queue_t *q, mblk_t *mp, struct xp *xp, struct iocblk *ioc) { int err; switch (_IOC_NR(ioc->ioc_cmd)) { case _IOC_NR(BIOCGDLT): /* uint */ err = bpf_biocgdlt(q, mp, xp); break; case _IOC_NR(BIOCSDLT): /* uint */ err = sizeof(uint); break; case _IOC_NR(BIOCGDLTLIST): /* bpf_dltlist */ #ifdef __LP64__ if (ioc->ioc_flag == IOC_ILP32) err = sizeof(struct bpf_dltlist32); else #endif /* __LP64__ */ err = sizeof(struct bpf_dltlist); break; case _IOC_NR(BIOCPROMISC): /* (none) */ err = bpf_biocpromisc(xp); break; case _IOC_NR(BIOCFLUSH): /* (none) */ err = bpf_biocflush(q, xp); break; case _IOC_NR(BIOCGETIF): /* ifreq */ switch (ioc->ioc_cmd) { case BIOCGETIF: err = bpf_biocgetif(q, mp, xp); break; case BIOCGETLIF: err = bpf_biocgetlif(q, mp, xp); break; default: goto eopnotsupp; } break; case _IOC_NR(BIOCSETIF): /* ifreq */ // se _IOC_NR(BIOCSETLIF): /* lifreq */ switch (ioc->ioc_cmd) { case BIOCGETIF: err = sizeof(struct ifreq); break; case BIOCGETLIF: err = sizeof(struct lifreq); break; default: goto eopnotsupp; } case _IOC_NR(BIOCGSTATS): /* bpf_stat or bpf_stat_old */ switch (ioc->ioc_cmd) { case BIOCGSTATS: err = bpf_biocgstats(q, mp, xp); break; case BIOCGSTATSOLD: err = bpf_biocgstatsold(q, mp, xp); break; default: goto eopnotsupp; } break; case _IOC_NR(BIOCGHDRCMPLT): /* uint */ err = bpf_biocghdrcmplt(q, mp, xp); break; case _IOC_NR(BIOCSHDRCMPLT): /* uint */ err = sizeof(uint); break; case _IOC_NR(BIOCGSEESENT): /* uint */ err = bpf_biocgseesent(q, mp, xp); break; case _IOC_NR(BIOCSSEESENT): /* uint */ err = sizeof(uint); break; #ifdef BIOCGDIRECTION case _IOC_NR(BIOCGDIRECTION): /* uint */ err = bpf_biocgdirection(q, mp, xp); break; #endif /* BIOCGDIRECTION */ #ifdef BIOCSDIRECTION case _IOC_NR(BIOCSDIRECTION): /* uint */ err = sizeof(uint); break; #endif /* BIOCSDIRECTION */ #ifdef BIOCGDIRFILT case _IOC_NR(BIOCGDIRFILT): /* uint */ err = bpf_biocgdirfilt(q, mp, xp); break; #endif /* BIOCGDIRFILT */ #ifdef BIOCSDIRFILT case _IOC_NR(BIOCSDIRFILT): /* uint */ err = sizeof(uint); break; #endif /* BIOCSDIRFILT */ #ifdef BIOCFEEDBACK case _IOC_NR(BIOCFEEDBACK): /* uint */ err = sizeof(uint); break; #endif /* BIOCFEEDBACK */ case _IOC_NR(BIOCGFEEDBACK): /* uint */ err = bpf_biocgfeedback(q, mp, xp); break; case _IOC_NR(BIOCSFEEDBACK): /* uint */ err = sizeof(uint); break; /* -------------------------------------------------------------------------- */ /* Remaining input-output controls must be processed by the module bpfmod(4). */ /* -------------------------------------------------------------------------- */ case _IOC_NR(BIOCGBLEN): // or _IOC_NR(BIOCSBLEN): switch (ioc->ioc_cmd) { case BIOCSBLEN: goto eio; case BIOCGBLEN: goto eio; } goto eopnotsupp; case _IOC_NR(BIOCGRTIMEOUT): goto eio; case _IOC_NR(BIOCSRTIMEOUT): // or _IOC_NR(BIOCLOCK): switch (ioc->ioc_cmd) { case BIOCSRTIMEOUT: goto eio; case BIOCLOCK: goto eio; } goto eopnotsupp; #ifdef BIOCGFILDROP case _IOC_NR(BIOCGFILDROP): goto eio; #endif /* BIOCGFILDROP */ #ifdef BIOCSFILDROP case _IOC_NR(BIOCSFILDROP): goto eio; #endif /* BIOCSFILDROP */ case _IOC_NR(BIOCIMMEDIATE): goto eio; case _IOC_NR(BIOCSETF): goto eio; case _IOC_NR(BIOCSETFNR): goto eio; #ifdef BIOCSETWF case _IOC_NR(BIOCSETWF): goto eio; #endif /* BIOCSETWF */ case _IOC_NR(BIOCVERSION): goto eio; case _IOC_NR(BIOCSTCPF): // or _IOC_NR(BIOCGRSIG): switch (ioc->ioc_cmd) { case BIOCSTCPF: goto eio; case BIOCGRSIG: goto eio; } goto eopnotsupp; case _IOC_NR(BIOCSUDPF): // se _IOC_NR(BIOCSRSIG): switch (ioc->ioc_cmd) { case BIOCSUDPF: goto eio; case BIOCSRSIG: goto eio; } goto eopnotsupp; case _IOC_NR(BIOCSTSTAMP): goto eio; case _IOC_NR(BIOCGTSTAMP): // or _IOC_NR(BIOCGETBUFMODE): switch (ioc->ioc_cmd) { case BIOCGTSTAMP: goto eio; case BIOCGETBUFMODE: goto eio; } goto eopnotsupp; case _IOC_NR(BIOCSETBUFMODE): goto eio; case _IOC_NR(BIOCSETZBUF): goto eio; case _IOC_NR(BIOCGETZMAX): goto eio; case _IOC_NR(BIOCROTZBUF): goto eio; default: goto eopnotsupp; } return (err); eopnotsupp: /* This is pretty simple: we were passed an input-output control that we do not recognize. Because BPF is a BSD'ish thing, we return EOPNOTSUPP as BSD does instead of EINVAL as SVR4 does. */ return (-EOPNOTSUPP); eio: /* Should have been processed by module bpfmod(4). This is a pretty significant error because we autopush bpfmod(4) so this probably represents a leakage from and bug in bpfmod(4) rather than here. */ __swerr(); return (-EINVAL); } noinline fastcall __unlikely int sio_copyin(queue_t *q, mblk_t *mp, struct xp *xp, struct copyresp *cp, mblk_t *dp) { int err; switch (_IOC_NR(cp->cp_cmd)) { #ifdef SIOCGIFNUM case _IOC_NR(SIOCGIFNUM): goto eproto; #endif case _IOC_NR(SIOCGIFCONF): #ifdef __LP64__ if (cp->cp_flag == IOC_ILP32) err = sio_siocgifconf32(q, mp, xp, dp); else #endif /* __LP64__ */ err = sio_siocgifconf(q, mp, xp, dp); break; case _IOC_NR(SIOCGIFFLAGS): err = sio_siocgifflags(q, mp, xp, dp); break; case _IOC_NR(SIOCSIFFLAGS): err = sio_siocsifflags(q, mp, xp, dp); break; case _IOC_NR(SIOCGIFINDEX): err = sio_siocgifindex(q, mp, xp, dp); break; #ifdef SIOCSIFINDEX case _IOC_NR(SIOCSIFINDEX): err = sio_siocsifindex(q, mp, xp, dp); break; #endif case _IOC_NR(SIOCGIFHWADDR): err = sio_siocgifhwaddr(q, mp, xp, dp); break; case _IOC_NR(SIOCSIFHWADDR): err = sio_siocsifhwaddr(q, mp, xp, dp); break; #ifdef SIOCGLIFNUM case _IOC_NR(SIOCGLIFNUM): err = sio_siocglifnum(q, mp, xp, dp); break; #endif #ifdef SIOCGLIFCONF case _IOC_NR(SIOCGLIFCONF): #ifdef __LP64__ if (cp->cp_flag == IOC_ILP32) err = sio_siocglifconf32(q, mp, xp, dp); else #endif /* __LP64__ */ err = sio_siocglifconf(q, mp, xp, dp); break; #endif #ifdef SIOCSLIFNAME case _IOC_NR(SIOCSLIFNAME): err = sio_siocslifname(q, mp, xp, dp); break; #endif #ifdef SIOCGLIFFLAGS case _IOC_NR(SIOCGLIFFLAGS): err = sio_siocglifflags(q, mp, xp, dp); break; #endif #ifdef SIOCSLIFFLAGS case _IOC_NR(SIOCSLIFFLAGS): err = sio_siocslifflags(q, mp, xp, dp); break; #endif #ifdef SIOCGLIFINDEX case _IOC_NR(SIOCGLIFINDEX): err = sio_siocglifindex(q, mp, xp, dp); break; #endif #ifdef SIOCSLIFINDEX case _IOC_NR(SIOCSLIFINDEX): err = sio_siocslifindex(q, mp, xp, dp); break; #endif #ifdef SIOCGLIFHWADDR case _IOC_NR(SIOCGLIFHWADDR): err = sio_siocglifhwaddr(q, mp, xp, dp); break; #endif #ifdef SIOCSLIFHWADDR case _IOC_NR(SIOCSLIFHWADDR): err = sio_siocslifhwaddr(q, mp, xp, dp); break; #endif /* ---------------------------------------------------------- */ /* All of the remaining use addresses that are not supported. */ /* ---------------------------------------------------------- */ case _IOC_NR(SIOCGIFADDR): case _IOC_NR(SIOCSIFADDR): case _IOC_NR(SIOCGIFNETMASK): case _IOC_NR(SIOCSIFNETMASK): case _IOC_NR(SIOCGIFBRDADDR): case _IOC_NR(SIOCSIFBRDADDR): case _IOC_NR(SIOCGIFDSTADDR): case _IOC_NR(SIOCSIFDSTADDR): #ifdef SIOCGLIFADDR case _IOC_NR(SIOCGLIFADDR): #endif #ifdef SIOCSLIFADDR case _IOC_NR(SIOCSLIFADDR): #endif #ifdef SIOCGLIFNETMASK case _IOC_NR(SIOCGLIFNETMASK): #endif #ifdef SIOCSLIFNETMASK case _IOC_NR(SIOCSLIFNETMASK): #endif #ifdef SIOCGLIFBRDADDR case _IOC_NR(SIOCGLIFBRDADDR): #endif #ifdef SIOCSLIFBRDADDR case _IOC_NR(SIOCSLIFBRDADDR): #endif #ifdef SIOCGLIFDSTADDR case _IOC_NR(SIOCGLIFDSTADDR): #endif #ifdef SIOCSLIFDSTADDR case _IOC_NR(SIOCSLIFDSTADDR): #endif goto eproto; default: goto eopnotsupp; } return (err); eproto: __swerr(); return (-EPROTO); eopnotsupp: __swerr(); return (-EPROTO); } noinline fastcall __unlikely int sio_ioctl(queue_t *q, mblk_t *mp, struct xp *xp, struct iocblk *ioc) { int err; switch (_IOC_NR(ioc->ioc_cmd)) { #ifdef SIOCGIFNUM case _IOC_NR(SIOCGIFNUM): err = sio_siocgifnum(q, mp, xp); break; #endif case _IOC_NR(SIOCGIFCONF): #ifdef __LP64__ if (ioc->ioc_flag == IOC_ILP32) err = sizeof(struct ifconf32); else #endif /* __LP64__ */ err = sizeof(struct ifconf); break; case _IOC_NR(SIOCGIFFLAGS): err = sizeof(struct ifreq); break; case _IOC_NR(SIOCSIFFLAGS): /* Note that SIOCSIFFLAGS also sets the PPA. */ err = sizeof(struct ifreq); break; #ifdef SIOCGLIFNUM case _IOC_NR(SIOCGLIFNUM): err = sizeof(struct lifnum); break; #endif #ifdef SIOCGLIFCONF case _IOC_NR(SIOCGLIFCONF): #ifdef __LP64__ if (ioc->ioc_flag == IOC_ILP32) err = sizeof(struct lifconf32); else #endif /* __LP64__ */ err = sizeof(struct lifconf); break; #endif #ifdef SIOCSLIFNAME case _IOC_NR(SIOCSLIFNAME): /* Note that SIOCSLIFNAME also sets the PPA */ err = sizeof(struct lifreq); break; #endif #ifdef SIOCGLIFFLAGS case _IOC_NR(SIOCGLIFFLAGS): err = sizeof(struct lifreq); break; #endif #ifdef SIOCSLIFFLAGS case _IOC_NR(SIOCSLIFFLAGS): /* Note that SIOCSLIFFLAGS could also be used to set PPA. */ err = sizeof(struct lifreq); break; #endif #ifdef SIOCGLIFINDEX case _IOC_NR(SIOCGLIFINDEX): err = sizeof(struct lifreq); break; #endif #ifdef SIOCSLIFINDEX case _IOC_NR(SIOCSLIFINDEX): err = sizeof(struct lifreq); break; #endif #ifdef SIOCGLIFHWADDR case _IOC_NR(SIOCGLIFHWADDR): err = sizeof(struct lifreq); break; #endif #ifdef SIOCSLIFHWADDR case _IOC_NR(SIOCSLIFHWADDR): err = sizeof(struct lifreq); break; #endif /* ---------------------------------------------------------- */ /* All of the remaining use addresses that are not supported. */ /* ---------------------------------------------------------- */ case _IOC_NR(SIOCGIFADDR): case _IOC_NR(SIOCSIFADDR): case _IOC_NR(SIOCGIFNETMASK): case _IOC_NR(SIOCSIFNETMASK): case _IOC_NR(SIOCGIFBRDADDR): case _IOC_NR(SIOCSIFBRDADDR): case _IOC_NR(SIOCGIFDSTADDR): case _IOC_NR(SIOCSIFDSTADDR): #ifdef SIOCGLIFADDR case _IOC_NR(SIOCGLIFADDR): #endif #ifdef SIOCSLIFADDR case _IOC_NR(SIOCSLIFADDR): #endif #ifdef SIOCGLIFNETMASK case _IOC_NR(SIOCGLIFNETMASK): #endif #ifdef SIOCSLIFNETMASK case _IOC_NR(SIOCSLIFNETMASK): #endif #ifdef SIOCGLIFBRDADDR case _IOC_NR(SIOCGLIFBRDADDR): #endif #ifdef SIOCSLIFBRDADDR case _IOC_NR(SIOCSLIFBRDADDR): #endif #ifdef SIOCGLIFDSTADDR case _IOC_NR(SIOCGLIFDSTADDR): #endif #ifdef SIOCSLIFDSTADDR case _IOC_NR(SIOCSLIFDSTADDR): #endif err = -EADDRNOTAVAIL; break; default: err = -EINVAL; break; } return (err); } noinline fastcall __unlikely int dl_copyin(queue_t *q, mblk_t *mp, struct xp *xp, struct copyresp *cp, mblk_t *dp) { int err; switch (_IOC_NR(cp->cp_cmd)) { #ifdef DLIOCRAW case _IOC_NR(DLIOCRAW): /* */ goto eproto; #endif /* DLIOCRAW */ #ifdef DLIOCNATIVE case _IOC_NR(DLIOCNATIVE): /* *//* new dl_mac_type in return value */ goto eproto; #endif /* DLIOCNATIVE */ #ifdef DLIOCMARGININFO case _IOC_NR(DLIOCMARGININFO): /* int */ goto eproto; #endif /* DLIOCMARGININFO */ #ifdef DLIOCHDRINFO case _IOC_NR(DLIOCHDRINFO): if (cp->cp_flag != IOC_NONE) goto eacces; err = dl_dliochdrinfo(xp, dp); break; #endif /* DLIOCHDRINFO */ #ifdef DL_IOC_DRIVER_OPTIONS case _IOC_NR(DL_IOC_DRIVER_OPTIONS): /* driver_ops_t */ if (cp->cp_flag != IOC_NONE) goto eacces; err = dl_ioc_driver_options(xp, dp); break; #endif /* DL_IOC_DRIVER_OPTIONS */ #ifndef DLIOCHDRINFO #ifdef DL_IOC_HDR_INFO case _IOC_NR(DL_IOC_HDR_INFO): if (cp->cp_flag != IOC_NONE) goto eacces; err = dl_ioc_hdr_info(xp, dp); break; #endif /* DL_IOC_HDR_INFO */ #endif /* DLIOCHDRINFO */ #ifdef DL_HP_SET_DRV_PARAM_IOCTL case _IOC_NR(DL_HP_SET_DRV_PARAM_IOCTL): /* dl_hp_set_drv_param_ioctl_t */ err = dl_hp_set_drv_param_ioctl(xp, dp); break; #endif /* DL_HP_SET_DRV_PARAM_IOCTL */ #ifdef DL_HP_GET_DRV_PARAM_IOCTL case _IOC_NR(DL_HP_GET_DRV_PARAM_IOCTL): /* dl_hp_set_drv_param_ioctl_t */ goto eproto; #endif /* DL_HP_GET_DRV_PARAM_IOCTL */ #ifdef DLPI_SET_NO_LOOPBACK case _IOC_NR(DLPI_SET_NO_LOOPBACK): /* uint32_t */ err = dl_set_no_loopback(xp, dp); break; #endif /* DLPI_SET_NO_LOOPBACK */ default: goto eproto; } return (err); eproto: __swerr(); return (-EPROTO); eacces: return (-EACCES); } noinline fastcall __unlikely int dl_ioctl(queue_t *q, mblk_t *mp, struct xp *xp, struct iocblk *ioc) { int err; switch (_IOC_NR(ioc->ioc_cmd)) { #ifdef DLIOCRAW case _IOC_NR(DLIOCRAW): /* */ err = dl_dliocraw(q, mp, xp); break; #endif /* DLIOCRAW */ #ifdef DLIOCNATIVE case _IOC_NR(DLIOCNATIVE): /* *//* new dl_mac_type in return value */ err = dl_dliocnative(q, mp, xp); break; #endif /* DLIOCNATIVE */ #ifdef DLIOCMARGININFO case _IOC_NR(DLIOCMARGININFO): /* int */ err = dl_dliocmargininfo(q, mp, xp); break; #endif /* DLIOCMARGININFO */ #ifdef DLIOCHDRINFO case _IOC_NR(DLIOCHDRINFO): /* dl_unitdata_req_t */ /* Solaris doesn't let user space programs issue this. */ if (ioc->ioc_flag != IOC_NONE) goto eacces; err = sizeof(dl_unitdata_req_t); break; #endif /* DLIOCHDRINFO */ #ifdef DL_IOC_DRIVER_OPTIONS case _IOC_NR(DL_IOC_DRIVER_OPTIONS): /* driver_ops_t */ /* HP doesn't let user space programs issue this. */ if (ioc->ioc_flag != IOC_NONE) goto eacces; err = sizeof(driver_ops_t); break; #endif /* DL_IOC_DRIVER_OPTIONS */ #ifndef DLIOCHDRINFO #ifdef DL_IOC_HDR_INFO case _IOC_NR(DL_IOC_HDR_INFO): /* dl_unitdata_req_t */ /* HP doesn't let user space programs issue this. */ if (ioc->ioc_flag != IOC_NONE) goto eacces; err = sizeof(dl_unitdata_req_t); break; #endif /* DL_IOC_HDR_INFO */ #endif /* DLIOCHDRINFO */ #ifdef DL_HP_SET_DRV_PARAM_IOCTL case _IOC_NR(DL_HP_SET_DRV_PARAM_IOCTL): /* dl_hp_set_drv_param_ioctl_t */ err = sizeof(dl_hp_set_drv_param_ioctl_t); break; #endif /* DL_HP_SET_DRV_PARAM_IOCTL */ #ifdef DL_HP_GET_DRV_PARAM_IOCTL case _IOC_NR(DL_HP_GET_DRV_PARAM_IOCTL): err = dl_hp_get_drv_param_ioctl(q, mp, xp); #endif /* DL_HP_GET_DRV_PARAM_IOCTL */ #ifdef DLPI_SET_NO_LOOPBACK case _IOC_NR(DLPI_SET_NO_LOOPBACK): /* uint32_t */ err = sizeof(uint32_t); break; #endif /* DLPI_SET_NO_LOOPBACK */ default: goto einval; } return (err); einval: return (-EINVAL); eacces: return (-EACCES); } /** xp_w_copyin2: - second copyin stage * @q: the write queue * @mp: the M_COPYIN message * @xp: private structure pointer * @cp: the copyresp structure pointer * @dp: the M_COPYIN data block * * This is the second stage copyin. The first stage copyin is used to copy in the header of the * structure used for set commands and other commands that require an object-specific structure * following the header. The second stage is used to copy in the object-specific structure. */ noinline fastcall __unlikely int xp_w_copyin2(queue_t *q, mblk_t *mp, struct xp *xp, struct copyresp *cp, mblk_t *dp) { int err; switch (_IOC_TYPE(cp->cp_cmd)) { case DSX_IOC_MAGIC: err = dsx_copyin2(q, mp, xp, cp, dp); break; case MX_IOC_MAGIC: err = mx_copyin2(q, mp, xp, cp, dp); break; case SL_IOC_MAGIC: err = sl_copyin2(q, mp, xp, cp, dp); break; case SDT_IOC_MAGIC: err = sdt_copyin2(q, mp, xp, cp, dp); break; case SDL_IOC_MAGIC: err = sdl_copyin2(q, mp, xp, cp, dp); break; default: __swerr(); err = -EPROTO; break; } return (err); } /** xp_w_copyin: - first copyin stage * @q: write queue * @mp: M_COPYIN message * @xp: private structure pointer * @cp: copyresp structure pointer * @dp: M_COPYIN data block * * This is the first copyin stage. Many of the input-output controls require that a structure with * the object type and identifier first be copied in, even on get operations. Usually get * operations return their result at this first stage; set operations perform an additional copyin * stage and return their result from the second copyin stage. */ noinline fastcall __unlikely int xp_w_copyin(queue_t *q, mblk_t *mp, struct xp *xp, struct copyresp *cp, mblk_t *dp) { int err; switch (_IOC_TYPE(cp->cp_cmd)) { case DSX_IOC_MAGIC: err = dsx_copyin(q, mp, xp, cp, dp); break; case MX_IOC_MAGIC: err = mx_copyin(q, mp, xp, cp, dp); break; case SL_IOC_MAGIC: err = sl_copyin(q, mp, xp, cp, dp); break; case SDT_IOC_MAGIC: err = sdt_copyin(q, mp, xp, cp, dp); break; case SDL_IOC_MAGIC: err = sdl_copyin(q, mp, xp, cp, dp); break; default: __swerr(); err = -EPROTO; break; } return (err); } noinline fastcall __unlikely int xp_w_iocdata(queue_t *q, mblk_t *mp) { struct xp *xp = XP_PRIV(q); struct copyresp *cp = (typeof(cp)) mp->b_rptr; mblk_t *dp; int err = 0; switch (mi_copy_state(q, mp, &dp)) { case MI_COPY_CASE(MI_COPY_IN, 1): err = xp_w_copyin(q, mp, xp, cp, dp); break; case MI_COPY_CASE(MI_COPY_IN, 2): err = xp_w_copyin2(q, mp, xp, cp, dp); break; case MI_COPY_CASE(MI_COPY_OUT, 1): __trace(); break; case -1: __trace(); goto efault; default: __swerr(); err = -EPROTO; break; } if (err > 0) mi_copyin(q, mp, NULL, err); else if (err < 0) mi_copy_done(q, mp, -err); else mi_copyout(q, mp); efault: return (0); } noinline fastcall __unlikely int xp_w_ioctl(queue_t *q, mblk_t *mp) { struct xp *xp = XP_PRIV(q); struct iocblk *ioc = (typeof(ioc)) mp->b_rptr; int err = 0; switch (_IOC_TYPE(ioc->ioc_cmd)) { case DSX_IOC_MAGIC: err = dsx_ioctl(q, mp, xp, ioc); break; case MX_IOC_MAGIC: err = mx_ioctl(q, mp, xp, ioc); break; case SL_IOC_MAGIC: err = sl_ioctl(q, mp, xp, ioc); break; case SDT_IOC_MAGIC: err = sdt_ioctl(q, mp, xp, ioc); break; case SDL_IOC_MAGIC: err = sdl_ioctl(q, mp, xp, ioc); break; default: err = -EINVAL; break; } if (err > 0) mi_copyin(q, mp, NULL, err); else if (err < 0) mi_copy_done(q, mp, -err); else mi_copyout(q, mp); return (0); } noinline fastcall __unlikely int nit_w_copyin(queue_t *q, mblk_t *mp, struct xp *xp, struct copyresp *cp, mblk_t *dp) { int err; switch (_IOC_TYPE(cp->cp_cmd)) { case _IOC_TYPE(NIOC): err = nit_copyin(q, mp, xp, cp, dp); break; case _IOC_TYPE(SIOCGIFCONF): err = sio_copyin(q, mp, xp, cp, dp); break; default: err = -EINVAL; break; } return (err); } noinline fastcall __unlikely int nit_w_iocdata(queue_t *q, mblk_t *mp) { struct xp *xp = XP_PRIV(q); struct copyresp *cp = (typeof(cp)) mp->b_rptr; mblk_t *dp; int err = 0; switch (mi_copy_state(q, mp, &dp)) { case MI_COPY_CASE(MI_COPY_IN, 1): err = nit_w_copyin(q, mp, xp, cp, dp); break; case MI_COPY_CASE(MI_COPY_OUT, 1): break; case -1: goto efault; default: __swerr(); err = -EPROTO; break; } if (err > 0) mi_copyin(q, mp, NULL, err); else if (err < 0) mi_copy_done(q, mp, -err); else mi_copyout(q, mp); efault: return (0); } noinline fastcall __unlikely int nit_w_ioctl(queue_t *q, mblk_t *mp) { struct xp *xp = XP_PRIV(q); struct iocblk *ioc = (typeof(ioc)) mp->b_rptr; int err = 0; switch (_IOC_TYPE(ioc->ioc_cmd)) { case _IOC_TYPE(NIOC): err = nit_ioctl(q, mp, xp, ioc); break; case _IOC_TYPE(SIOCGIFCONF): err = sio_ioctl(q, mp, xp, ioc); break; default: err = -EINVAL; break; } if (err > 0) mi_copyin(q, mp, NULL, err); else if (err < 0) mi_copy_done(q, mp, -err); else mi_copyout(q, mp); return (0); } #if 0 int bind_it(struct xp *xp) { struct cd *cd; struct sp *sp; struct ch *ch; psw_t flags = 0; int card, span, chan; switch (xp->monitor) { case XP_MONITOR_NONE: return (ENXIO); case XP_MONITOR_GLOB: read_lock_irqsave(&x400p_lock, flags); if ((xp->xray.next = x400p_xrays)) xp->xray.next->xray.prev = &xp->xray.next; xp->xray.prev = &x400p_xrays; x400p_xrays = xp; read_unlock_irqrestore(&x400p_lock, flags); for (card = 0; card < X400_CARDS; card++) { if (!(cd = x400p_cards[card])) continue; for (span = 0; span < cd->ports; span++) { if (!(sp = cd->spans[span])) continue; if (xp->level == XP_LEVEL_MON_SDT && sp->config.iftxlevel > 7) startup_span(sp); for (chan = 0; chan < 32; chan++) { if (!(ch = sp->chans[chan])) continue; spin_lock(&ch->lock); ch->xray.flags |= xp->xray.flags; if (xp->level == XP_LEVEL_MON_SDT && sp->config.iftxlevel > 7) { sl_daedt_start(ch); sl_daedr_start(ch); } spin_unlock(&ch->lock); } } } break; case XP_MONITOR_CARD: spin_lock_irqsave(&cd->lock, flags); if ((xp->xray.next = cd->xray)) xp->xray.next->xray.prev = &xp->xray.next; xp->xray.prev = &cd->xray; cd->xray = xp; spin_unlock_irqrestore(&cd->lock, flags); for (span = 0; span < cd->ports; span++) { if ((sp = cd->spans[span])) { for (chan = 0; chan < 32; chan++) { if ((ch = sp->chans[chan])) { spin_lock_irqsave(&ch->lock, flags); ch->xray.flags |= xp->xray.flags; if (xp->level == XP_LEVEL_MON_SDT && sp->config.iftxlevel > 7) { sl_daedt_start(ch); sl_daedr_start(ch); } spin_unlock_irqrestore(&ch->lock, flags); } } if (xp->level == XP_LEVEL_MON_SDT && sp->config.iftxlevel > 7) startup_span(sp); } } break; case XP_MONITOR_SPAN: xp->xray.flags = XP_XRAY_SDT_CHAN; spin_lock_irqsave(&sp->lock, flags); if ((xp->xray.next = sp->xray)) xp->xray.next->xray.prev = &xp->xray.next; xp->xray.prev = &sp->xray; sp->xray = xp; spin_unlock_irqrestore(&sp->lock, flags); for (chan = 0; chan < 32; chan++) { if ((ch = sp->chans[chan])) { spin_lock_irqsave(&ch->lock, flags); ch->xray.flags |= xp->xray.flags; if (xp->level == XP_LEVEL_MON_SDT && sp->config.iftxlevel > 7) { sl_daedt_start(ch); sl_daedr_start(ch); } spin_unlock_irqrestore(&ch->lock, flags); } } if (xp->level == XP_LEVEL_MON_SDT && sp->config.iftxlevel > 7) startup_span(sp); break; case XP_MONITOR_CHAN: spin_lock_irqsave(&ch->lock, flags); if ((xp->xray.next = ch->xray.list)) xp->xray.next->xray.prev = &xp->xray.next; xp->xray.prev = &ch->xray.list; ch->xray.list = xp; ch->xray.flags |= xp->xray.flags; if (xp->level == XP_LEVEL_MON_SDT && sp->config.iftxlevel > 7) { sl_daedt_start(ch); sl_daedr_start(ch); } spin_unlock_irqrestore(&ch->lock, flags); if (xp->level == XP_LEVEL_MON_SDT && sp->config.iftxlevel > 7) startup_span(sp); break; } return (0); } #endif noinline fastcall __unlikely int bpf_w_copyin(queue_t *q, mblk_t *mp, struct xp *xp, struct copyresp *cp, mblk_t *dp) { int err; switch (_IOC_TYPE(cp->cp_cmd)) { case _IOC_TYPE(BIOCSBLEN): err = bpf_copyin(q, mp, xp, cp, dp); break; case _IOC_TYPE(SIOCGIFCONF): err = sio_copyin(q, mp, xp, cp, dp); break; default: err = -EOPNOTSUPP; break; } return (err); } noinline fastcall __unlikely int bpf_w_iocdata(queue_t *q, mblk_t *mp) { struct xp *xp = XP_PRIV(q); struct copyresp *cp = (typeof(cp)) mp->b_rptr; mblk_t *dp; int err = 0; switch (mi_copy_state(q, mp, &dp)) { case MI_COPY_CASE(MI_COPY_IN, 1): err = bpf_w_copyin(q, mp, xp, cp, dp); break; case MI_COPY_CASE(MI_COPY_OUT, 1): break; case MI_COPY_CASE(MI_COPY_OUT, 2): break; case -1: goto efault; default: __swerr(); err = -EPROTO; break; } if (err > 0) mi_copyin(q, mp, NULL, err); else if (err < 0) mi_copy_done(q, mp, -err); else mi_copyout(q, mp); efault: return (0); } noinline fastcall __unlikely int bpf_w_ioctl(queue_t *q, mblk_t *mp) { struct xp *xp = XP_PRIV(q); struct iocblk *ioc = (typeof(ioc)) mp->b_rptr; int err = 0; switch (_IOC_TYPE(ioc->ioc_cmd)) { case _IOC_TYPE(BIOCSBLEN): err = bpf_ioctl(q, mp, xp, ioc); break; case _IOC_TYPE(SIOCGIFCONF): err = sio_ioctl(q, mp, xp, ioc); break; default: err = -EINVAL; break; } if (err > 0) mi_copyin(q, mp, NULL, err); else if (err < 0) mi_copy_done(q, mp, -err); else mi_copyout(q, mp); return (0); } noinline fastcall __unlikely int dl_w_copyin(queue_t *q, mblk_t *mp, struct xp *xp, struct copyresp *cp, mblk_t *dp) { int err; switch (_IOC_TYPE(cp->cp_cmd)) { case _IOC_TYPE(DLIOC): err = dl_copyin(q, mp, xp, cp, dp); break; case _IOC_TYPE(NIOC): err = nit_copyin(q, mp, xp, cp, dp); break; default: err = -EINVAL; break; } return (err); } noinline fastcall __unlikely int dl_w_iocdata(queue_t *q, mblk_t *mp) { struct xp *xp = XP_PRIV(q); struct copyresp *cp = (typeof(cp)) mp->b_rptr; mblk_t *dp; int err = 0; switch (mi_copy_state(q, mp, &dp)) { case MI_COPY_CASE(MI_COPY_IN, 1): err = dl_w_copyin(q, mp, xp, cp, dp); break; case MI_COPY_CASE(MI_COPY_OUT, 1): break; case -1: goto efault; default: __swerr(); err = -EPROTO; break; } if (err > 0) mi_copyin(q, mp, NULL, err); else if (err < 0) mi_copy_done(q, mp, -err); else mi_copyout(q, mp); efault: return (0); } noinline fastcall __unlikely int dl_w_ioctl(queue_t *q, mblk_t *mp) { struct xp *xp = XP_PRIV(q); struct iocblk *ioc = (typeof(ioc)) mp->b_rptr; int err; switch (_IOC_TYPE(ioc->ioc_cmd)) { case _IOC_TYPE(DLIOC): err = dl_ioctl(q, mp, xp, ioc); break; case _IOC_TYPE(NIOC): err = nit_ioctl(q, mp, xp, ioc); break; default: err = -EINVAL; break; } if (err > 0) mi_copyin(q, mp, NULL, err); else if (err < 0) mi_copy_done(q, mp, -err); else mi_copyout(q, mp); return (0); } /* * M_PROTO, M_PCPROTO Handling * ------------------------------------------------------------------------- */ noinline fastcall __unlikely int xp_w_proto_return(mblk_t *mp, int rtn) { switch (-rtn) { case EBUSY: case EAGAIN: case ENOMEM: case ENOBUFS: case EDEADLK: return (rtn); default: freemsg(mp); case 0: return (0); } } noinline fastcall int sl_w_proto_return(struct xp *xp, queue_t *q, mblk_t *mp, int rtn) { int err = 0; switch (rtn) { case -EBUSY: case -EAGAIN: case -ENOMEM: case -ENOBUFS: case -EDEADLK: return (rtn); case -EFAULT: case -EPROTO: case -EMSGSIZE: err = -rtn; break; case 0: return (0); } if (err) { m_error(xp, q, mp, err); rtn = 0; } return (rtn); } noinline fastcall __unlikely int lmi_w_proto_return(struct xp *xp, queue_t *q, mblk_t *mp, lmi_ulong prim, int rtn) { if (unlikely(rtn < 0)) { lmi_ulong reason = 0; switch (rtn) { case -EINVAL: reason = LMI_BADPRIM; break; case -EOPNOTSUPP: reason = LMI_NOTSUPP; break; case -EMSGSIZE: reason = LMI_PROTOSHORT; break; case -EFAULT: reason = LMI_SYSERR; break; case -EPROTO: reason = LMI_OUTSTATE; break; case -EADDRNOTAVAIL: reason = LMI_BADPPA; break; } if (reason) { lmi_error_ack(xp, q, mp, xp_get_state(xp), prim, -rtn, reason); rtn = 0; } } return (rtn); } /** __sl_w_proto_slow: - process SLI primitive * @xp: private structure (locked) * @q: active queue (write queue) * @mp: the SLI primitive * @prim: the SLI primitive type */ noinline fastcall int __sl_w_proto_slow(struct xp *xp, queue_t *q, mblk_t *mp, sl_long prim) { int rtn; if (likely(prim != SL_PDU_REQ)) { struct ch *ch; LOGRX(xp2sid(xp), "-> %s", sl_primname(prim)); if (unlikely(xp_get_state(xp) != LMI_ENABLED)) rtn = -EPROTO; else if (unlikely((ch = xp->ch) == NULL)) rtn = -EFAULT; else { spin_lock_bh(&ch->lock); { switch (prim - SL_PROTO_BASE) { case (SL_EMERGENCY_REQ - SL_PROTO_BASE): rtn = sl_emergency_req(ch, q, mp); break; case (SL_EMERGENCY_CEASES_REQ - SL_PROTO_BASE): rtn = sl_emergency_ceases_req(ch, q, mp); break; case (SL_START_REQ - SL_PROTO_BASE): rtn = sl_start_req(ch, q, mp); break; case (SL_STOP_REQ - SL_PROTO_BASE): rtn = sl_stop_req(ch, q, mp); break; case (SL_RETRIEVE_BSNT_REQ - SL_PROTO_BASE): rtn = sl_retrieve_bsnt_req(ch, q, mp); break; case (SL_RETRIEVAL_REQUEST_AND_FSNC_REQ - SL_PROTO_BASE): rtn = sl_retrieval_request_and_fsnc_req(ch, q, mp); break; case (SL_CLEAR_BUFFERS_REQ - SL_PROTO_BASE): rtn = sl_clear_buffers_req(ch, q, mp); break; case (SL_CLEAR_RTB_REQ - SL_PROTO_BASE): rtn = sl_clear_rtb_req(ch, q, mp); break; case (SL_LOCAL_PROCESSOR_OUTAGE_REQ - SL_PROTO_BASE): rtn = sl_local_processor_outage_req(ch, q, mp); break; case (SL_CONTINUE_REQ - SL_PROTO_BASE): rtn = sl_continue_req(ch, q, mp); break; case (SL_RESUME_REQ - SL_PROTO_BASE): rtn = sl_resume_req(ch, q, mp); break; case (SL_CONGESTION_DISCARD_REQ - SL_PROTO_BASE): rtn = sl_congestion_discard_req(ch, q, mp); break; case (SL_CONGESTION_ACCEPT_REQ - SL_PROTO_BASE): rtn = sl_congestion_accept_req(ch, q, mp); break; case (SL_NO_CONGESTION_REQ - SL_PROTO_BASE): rtn = sl_no_congestion_req(ch, q, mp); break; case (SL_POWER_ON_REQ - SL_PROTO_BASE): rtn = sl_power_on_req(ch, q, mp); break; default: rtn = -EFAULT; break; } } spin_unlock_bh(&ch->lock); } rtn = sl_w_proto_return(xp, q, mp, rtn); } else { /* should have been processed in the fast path */ LOGDA(xp2sid(xp), "-> SL_PDU_REQ"); rtn = sl_pdu_req(xp, q, mp); } return (rtn); } /** __sdt_w_proto_slow: - process SDTI primitive * @xp: private structure (locked) * @q: active queue (write queue) * @mp: the SDTI primitive * @prim: the SDTI primitive type */ noinline fastcall int __sdt_w_proto_slow(struct xp *xp, queue_t *q, mblk_t *mp, sdt_long prim) { int rtn; if (likely(prim != SDT_DAEDT_TRANSMISSION_REQ)) { struct ch *ch; LOGRX(xp2sid(xp), "-> %s", sdt_primname(prim)); if (unlikely(xp_get_state(xp) != LMI_ENABLED)) rtn = -EPROTO; else if (unlikely((ch = xp->ch) == NULL)) rtn = -EFAULT; else { spin_lock_bh(&ch->lock); { switch (prim - SDT_PROTO_BASE) { case (SDT_DAEDT_START_REQ - SDT_PROTO_BASE): rtn = sdt_daedt_start_req(ch, q, mp); break; case (SDT_DAEDR_START_REQ - SDT_PROTO_BASE): rtn = sdt_daedr_start_req(ch, q, mp); break; case (SDT_AERM_START_REQ - SDT_PROTO_BASE): rtn = sdt_aerm_start_req(ch, q, mp); break; case (SDT_AERM_STOP_REQ - SDT_PROTO_BASE): rtn = sdt_aerm_stop_req(ch, q, mp); break; case (SDT_AERM_SET_TI_TO_TIN_REQ - SDT_PROTO_BASE): rtn = sdt_aerm_set_ti_to_tin_req(ch, q, mp); break; case (SDT_AERM_SET_TI_TO_TIE_REQ - SDT_PROTO_BASE): rtn = sdt_aerm_set_ti_to_tie_req(ch, q, mp); break; case (SDT_SUERM_START_REQ - SDT_PROTO_BASE): rtn = sdt_suerm_start_req(ch, q, mp); break; case (SDT_SUERM_STOP_REQ - SDT_PROTO_BASE): rtn = sdt_suerm_stop_req(ch, q, mp); break; default: rtn = -EFAULT; break; } } spin_unlock_bh(&ch->lock); } rtn = sl_w_proto_return(xp, q, mp, rtn); } else { /* should have been processed in the fast path */ LOGDA(xp2sid(xp), "-> SDT_DAEDT_TRANSMISSION_REQ"); rtn = sdt_daedt_transmission_req(xp, q, mp); } return (rtn); } /** __sdl_w_proto_slow: - process SDLI primitive * @xp: private structure (locked) * @q: active queue (write queue) * @mp: the SDLI primitive * @prim: the SDLI primitive type */ noinline fastcall int __sdl_w_proto_slow(struct xp *xp, queue_t *q, mblk_t *mp, sdl_long prim) { int rtn; if (likely(prim != SDL_BITS_FOR_TRANSMISSION_REQ)) { struct ch *ch; LOGRX(xp2sid(xp), "-> %s", sdl_primname(prim)); if (unlikely(xp_get_state(xp) != LMI_ENABLED)) rtn = -EPROTO; else if (unlikely((ch = xp->ch) == NULL)) rtn = -EFAULT; else { spin_lock_bh(&ch->lock); { switch (prim - SDL_PROTO_BASE) { case (SDL_CONNECT_REQ - SDL_PROTO_BASE): rtn = sdl_connect_req(ch, q, mp); break; case (SDL_DISCONNECT_REQ - SDL_PROTO_BASE): rtn = sdl_disconnect_req(ch, q, mp); break; default: rtn = -EFAULT; break; } } spin_unlock_bh(&ch->lock); } rtn = sl_w_proto_return(xp, q, mp, rtn); } else { /* should have been processed in the fast path */ LOGDA(xp2sid(xp), "-> SDL_BITS_FOR_TRANSMISION_REQ"); rtn = sdl_bits_for_transmission_req(xp, q, mp); } return (rtn); } /** __lmi_w_proto_slow: - process LMI primitive * @xp: private structure (locked) * @q: active queue (write queue) * @mp: the LMI primitive * @prim: the LMI primitive type */ noinline fastcall int __lmi_w_proto_slow(struct xp *xp, queue_t *q, mblk_t *mp, lmi_long prim) { int rtn; xp_save_state(xp); LOGRX(xp2sid(xp), "-> %s", lmi_primname(prim)); switch (prim - LMI_PROTO_BASE) { case (LMI_INFO_REQ - LMI_PROTO_BASE): rtn = lmi_info_req(xp, q, mp); break; case (LMI_ATTACH_REQ - LMI_PROTO_BASE): rtn = lmi_attach_req(xp, q, mp); break; case (LMI_DETACH_REQ - LMI_PROTO_BASE): rtn = lmi_detach_req(xp, q, mp); break; case (LMI_ENABLE_REQ - LMI_PROTO_BASE): rtn = lmi_enable_req(xp, q, mp); break; case (LMI_DISABLE_REQ - LMI_PROTO_BASE): rtn = lmi_disable_req(xp, q, mp); break; case (LMI_OPTMGMT_REQ - LMI_PROTO_BASE): rtn = lmi_optmgmt_req(xp, q, mp); break; default: rtn = -EINVAL; break; } if (rtn < 0) { xp_restore_state(xp); /* The put and srv procedures do not recognize all errors. Sometimes we return an error here just to restore the previous state. */ return lmi_w_proto_return(xp, q, mp, prim, rtn); } return (rtn); } /** __xp_w_proto_slow: - process M_PROTO/M_PCPROTO message on write queue * @xp: private structure (locked) * @q: active queue (write queue) * @mp: the M_(PC)PROTO message * @prim: the primitive type of the message */ noinline fastcall int __xp_w_proto_slow(struct xp *xp, queue_t *q, mblk_t *mp, lmi_long prim) { int rtn; if (SDL_DSTR_FIRST <= prim && prim <= SDL_DSTR_LAST) { rtn = __sdl_w_proto_slow(xp, q, mp, prim); } else if (SDT_DSTR_FIRST <= prim && prim <= SDT_DSTR_LAST) { rtn = __sdt_w_proto_slow(xp, q, mp, prim); } else if (SL_DSTR_FIRST <= prim && prim <= SL_DSTR_LAST) { rtn = __sl_w_proto_slow(xp, q, mp, prim); } else { rtn = __lmi_w_proto_slow(xp, q, mp, prim); } if (rtn < 0) return xp_w_proto_return(mp, rtn); return (rtn); } noinline fastcall int xp_w_proto_slow(queue_t *q, mblk_t *mp, lmi_long prim) { struct xp *xp = XP_PRIV(q); int err; if (likely((xp = (struct xp *) mi_acquire((caddr_t) xp, q)) != NULL)) { err = __xp_w_proto_slow(xp, q, mp, prim); mi_release((caddr_t) xp); } else err = -EDEADLK; return (err); } /** __xp_w_proto: - process M_PROTO or M_PCPROTO message locked * @xp: private structure (locked) * @q: active queue (write queue) * @mp: the M_PROTO or M_PCPROTO message * * This locked version is for use by the service procedure that takes private structure locks once * for the entire service procedure run. The fastpath for data should probably be ordered in the * reverse order (SDL priority before SDT or SL, because SDL has tighter latency constraints), but * it likely doesn't matter that much on a relatively fast machine. The driver is more intended * for use as signalling links instead of as a raw channel driver. */ static inline fastcall __hot_write int __xp_w_proto(struct xp *xp, queue_t *q, mblk_t *mp) { if (likely(MBLKIN(mp, 0, sizeof(lmi_ulong)) != 0)) { lmi_long prim = *(lmi_long *) mp->b_rptr; int rtn; if (likely(prim == SL_PDU_REQ)) { if (likely((rtn = sl_pdu_req(xp, q, mp)) == 0)) return (0); } else if (likely(prim == SDT_DAEDT_TRANSMISSION_REQ)) { if (likely((rtn = sdt_daedt_transmission_req(xp, q, mp)) == 0)) return (0); } else if (likely(prim == SDL_BITS_FOR_TRANSMISSION_REQ)) { if (likely((rtn = sdl_bits_for_transmission_req(xp, q, mp)) == 0)) return (0); } else return __xp_w_proto_slow(xp, q, mp, prim); return xp_w_proto_return(mp, rtn); } LOGRX(xp2sid(xp), "%s() replying with error %d", __FUNCTION__, -EPROTO); return m_error(xp, q, mp, -EPROTO); } /** xp_w_proto: - process M_PROTO or M_PCPROTO message * @q: active queue * @mp: the M_PROTO or M_PCPROTO message * * This lock version is for use by the put procedure which does not take locks. For data messages * we simply return (-EAGAIN) for performance. */ static inline fastcall __hot_write int xp_w_proto(queue_t *q, mblk_t *mp) { if (likely(MBLKIN(mp, 0, sizeof(lmi_ulong)) != 0)) { lmi_long prim = *(lmi_long *) mp->b_rptr; if (likely(prim == SL_PDU_REQ)) { } else if (likely(prim == SDT_DAEDT_TRANSMISSION_REQ)) { } else if (likely(prim == SDL_BITS_FOR_TRANSMISSION_REQ)) { } else return xp_w_proto_slow(q, mp, prim); } return (-EAGAIN); } /** __nit_w_proto: - process M_PROTO message * @xp: private structure (locked) * @q: active queue (write queue) * @mp: the M_PROTO message * * See nit_if(4). nit accepts packets form the module above it in the stream and relays them to * the associated network interface for transmission. Packets must be formatted with the * destination address in a leading M_PROTO(9) message block, followed by the packet itself, * complete with link-level header, in a sequence of M_DATA(9) message blocks. The destination * address must be expressed as a struct sockaddr whose sa_family field is AF_UNSPEC and whose * sa_data field is a copy of the link-level header. (See <sys/socket.h> for the definition of * this structure.) If the packet does not conform to this format, an M_ERROR(9) message with * [EINVAL] will be sent upstream. */ static inline fastcall __hot_write int __nit_w_proto(struct xp *xp, queue_t *q, mblk_t *mp) { LOGRX(xp2sid(xp), "%s() M_PROTO/M_PCPROTO on write queue", __FUNCTION__); freemsg(mp); return (0); } static inline fastcall __hot_write int nit_w_proto(queue_t *q, mblk_t *mp) { struct xp *xp = XP_PRIV(q); return __nit_w_proto(xp, q, mp); } static inline fastcall __hot_write int __bpf_w_proto(struct xp *xp, queue_t *q, mblk_t *mp) { LOGRX(xp2sid(xp), "%s() M_PROTO/M_PCPROTO on write queue", __FUNCTION__); freemsg(mp); return (0); } static inline fastcall __hot_write int bpf_w_proto(queue_t *q, mblk_t *mp) { struct xp *xp = XP_PRIV(q); return __bpf_w_proto(xp, q, mp); } noinline fastcall int __dl_w_proto_slow(struct xp *xp, queue_t *q, mblk_t *mp, dl_ulong prim) { int rtn; xp_save_state(xp); switch (prim) { case DL_UNITDATA_REQ: LOGDA(xp2sid(xp), "-> %s", dlpi_primname(prim)); break; default: LOGRX(xp2sid(xp), "-> %s", dlpi_primname(prim)); break; } switch (prim) { case DL_INFO_REQ: rtn = dl_info_req(xp, q, mp); break; case DL_ATTACH_REQ: rtn = dl_attach_req(xp, q, mp); break; case DL_DETACH_REQ: rtn = dl_detach_req(xp, q, mp); break; case DL_BIND_REQ: rtn = dl_bind_req(xp, q, mp); break; case DL_UNBIND_REQ: rtn = dl_unbind_req(xp, q, mp); break; case DL_SUBS_BIND_REQ: rtn = dl_subs_bind_req(xp, q, mp); break; case DL_SUBS_UNBIND_REQ: rtn = dl_subs_unbind_req(xp, q, mp); break; case DL_UNITDATA_REQ: rtn = dl_unitdata_req(xp, q, mp); break; case DL_UDQOS_REQ: rtn = dl_udqos_req(xp, q, mp); break; case DL_CONNECT_REQ: rtn = dl_connect_req(xp, q, mp); break; case DL_CONNECT_RES: rtn = dl_connect_res(xp, q, mp); break; case DL_TOKEN_REQ: rtn = dl_token_req(xp, q, mp); break; case DL_DISCONNECT_REQ: rtn = dl_disconnect_req(xp, q, mp); break; case DL_RESET_REQ: rtn = dl_reset_req(xp, q, mp); break; case DL_RESET_RES: rtn = dl_reset_res(xp, q, mp); break; case DL_ENABMULTI_REQ: rtn = dl_enabmulti_req(xp, q, mp); break; case DL_DISABMULTI_REQ: rtn = dl_disabmulti_req(xp, q, mp); break; case DL_PROMISCON_REQ: rtn = dl_promiscon_req(xp, q, mp); break; case DL_PROMISCOFF_REQ: rtn = dl_promiscoff_req(xp, q, mp); break; case DL_XID_REQ: rtn = dl_xid_req(xp, q, mp); break; case DL_XID_RES: rtn = dl_xid_res(xp, q, mp); break; case DL_TEST_REQ: rtn = dl_test_req(xp, q, mp); break; case DL_TEST_RES: rtn = dl_test_res(xp, q, mp); break; case DL_PHYS_ADDR_REQ: rtn = dl_phys_addr_req(xp, q, mp); break; case DL_SET_PHYS_ADDR_REQ: rtn = dl_set_phys_addr_req(xp, q, mp); break; case DL_GET_STATISTICS_REQ: rtn = dl_get_statistics_req(xp, q, mp); break; case DL_MONITOR_LINK_LAYER: rtn = dl_monitor_link_layer(xp, q, mp); break; #ifdef _SUN_SOURCE #ifdef DL_NOTIFY_REQ case DL_NOTIFY_REQ: rtn = dl_notify_req(xp, q, mp); break; #endif /* DL_NOTIFY_REQ */ #ifdef DL_AGGR_REQ case DL_AGGR_REQ: rtn = dl_aggr_req(xp, q, mp); break; #endif /* DL_AGGR_REQ */ #ifdef DL_UNAGGR_REQ case DL_UNAGGR_REQ: rtn = dl_unaggr_req(xp, q, mp); break; #endif /* DL_UNAGGR_REQ */ #ifdef DL_CAPABILITY_REQ case DL_CAPABILITY_REQ: rtn = dl_capability_req(xp, q, mp); break; #endif /* DL_CAPABILITY_REQ */ #ifdef DL_CONTROL_REQ case DL_CONTROL_REQ: rtn = dl_control_req(xp, q, mp); break; #endif /* DL_CONTROL_REQ */ #ifdef DL_PASSIVE_REQ case DL_PASSIVE_REQ: rtn = dl_passive_req(xp, q, mp); break; #endif /* DL_PASSIVE_REQ */ #ifdef DL_INTR_MODE_REQ case DL_INTR_MODE_REQ: rtn = dl_intr_mode_req(xp, q, mp); break; #endif /* DL_INTR_MODE_REQ */ #endif /* SUN_SOURCE */ #ifdef _HPUX_SOURCE #ifdef DL_HP_PPA_REQ case DL_HP_PPA_REQ: rtn = dl_hp_ppa_req(xp, q, mp); break; #endif /* DL_HP_PPA_REQ */ #ifdef DL_HP_MULTICAST_LIST_REQ case DL_HP_MULTICAST_LIST_REQ: rtn = dl_hp_multicast_list_req(xp, q, mp); break; #endif /* DL_HP_MULTICAST_LIST_REQ */ #ifdef DL_HP_RAWDATA_REQ case DL_HP_RAWDATA_REQ: rtn = dl_hp_rawdata_req(xp, q, mp); break; #endif /* DL_HP_RAWDATA_REQ */ #ifdef DL_HP_HW_RESET_REQ case DL_HP_HW_RESET_REQ: rtn = dl_hp_hw_reset_req(xp, q, mp); break; #endif /* DL_HP_HW_RESET_REQ */ #endif /* _HPUX_SOURCE */ default: rtn = -EBADMSG; break; } if (rtn < 0) { ulong reason = 0; xp_restore_state(xp); switch (rtn) { case -EAFNOSUPPORT: reason = DL_BADSAP; break; case -EPROTONOSUPPORT: reason = DL_UNSUPPORTED; break; case -EOPNOTSUPP: reason = DL_NOTSUPPORTED; break; case -EBADMSG: case -EMSGSIZE: reason = DL_BADPRIM; break; case -EFAULT: reason = DL_SYSERR; break; case -EPROTO: reason = DL_OUTSTATE; break; case -EADDRNOTAVAIL: reason = DL_BADPPA; break; case -ENOENT: reason = DL_NOTENAB; break; case -EPERM: reason = DL_ACCESS; break; } if (reason) { dl_error_ack(xp, q, mp, prim, -rtn, reason); rtn = 0; } } /* The put and srv procedures do not recognize all errors. Sometimes we return an error here just to restore the previous state. */ return xp_w_proto_return(mp, rtn); } noinline fastcall int dl_w_proto_slow(queue_t *q, mblk_t *mp, dl_ulong prim) { struct xp *xp = XP_PRIV(q); int err; if (likely((xp = (struct xp *) mi_acquire((caddr_t) xp, q)) != NULL)) { err = __dl_w_proto_slow(xp, q, mp, prim); mi_release((caddr_t) xp); } else err = -EDEADLK; return (err); } /** __dl_w_proto: - process M_PROTO or M_PCPROTO message locked * @xp: private structure (locked) * @q: active queue (write queue) * @mp: the M_PROTO or M_PCPROTO message * * This locked version is for use by the service procedure that takes private structure locks once * for the entire service procedure run. Keep this out of the fast path because DLPI uses M_DATA * for DL_CODLS data transfer. */ noinline fastcall int __dl_w_proto(struct xp *xp, queue_t *q, mblk_t *mp) { if (likely(mp->b_wptr >= mp->b_rptr + sizeof(dl_ulong))) { dl_ulong prim = *(dl_ulong *) mp->b_rptr; return __dl_w_proto_slow(xp, q, mp, prim); } LOGRX(xp2sid(xp), "%s() replying with error %d", __FUNCTION__, -EPROTO); return m_error(xp, q, mp, -EPROTO); } /** dl_w_proto: - process M_PROTO or M_PCPROTO message * @q: active queue (write queue) * @mp: the M_PROTO or M_PCPROTO message * * This lock version is for use by the put procedure which does not take locks. For data messages * we simply return (-EAGAIN) for performance. Keep this out of the fast path because DLPI uses * M_DATA for DL_CODLS data transfer. */ noinline fastcall int dl_w_proto(queue_t *q, mblk_t *mp) { if (likely(mp->b_wptr >= mp->b_rptr + sizeof(dl_ulong))) { dl_ulong prim = *(dl_ulong *) mp->b_rptr; return dl_w_proto_slow(q, mp, prim); } return (-EAGAIN); } #if 0 /* * M_SIG/M_PCSIG Handling * ------------------------------------------------------------------------- */ /** __xp_r_sig: - process M_(PC)SIG message * @xp: private structure (locked) * @q: active queue (read queue) * @mp: the M_(PC)SIG message * * This really needs to be worked back to the point where the timeout invocations of the state * machine are independent of any Streams queue being present. This is because we would like the * signalling link state machine to be able to run without an attached Stream. This would permit * placing a signalling link into a local processor outage state when a Stream closes unexpectedly. */ static noinline fastcall __unlikely int __xp_r_sig(struct xp *xp, queue_t *q, mblk_t *mp) { struct ch *ch; if (likely(mi_timer_valid(mp))) { if (likely((ch = xp->ch) != NULL)) { const int timer = *(int *) mp->b_rptr; spin_lock_bh(&ch->lock); { switch (timer) { case t1: LOGTO(ch2sid(ch), "-> T1 TIMEOUT <-"); xp_t1_timeout(ch); break; case t2: LOGTO(ch2sid(ch), "-> T2 TIMEOUT <-"); xp_t2_timeout(ch); break; case t3: LOGTO(ch2sid(ch), "-> T3 TIMEOUT <-"); xp_t3_timeout(ch); break; case t4: LOGTO(ch2sid(ch), "-> T4 TIMEOUT <-"); xp_t4_timeout(ch); break; case t5: LOGTO(ch2sid(ch), "-> T5 TIMEOUT <-"); xp_t5_timeout(ch); break; case t6: LOGTO(ch2sid(ch), "-> T6 TIMEOUT <-"); xp_t6_timeout(ch); break; case t7: LOGTO(ch2sid(ch), "-> T7 TIMEOUT <-"); xp_t7_timeout(ch); break; case t8: LOGTO(ch2sid(ch), "-> T8 TIMEOUT <-"); xp_t8_timeout(ch); break; #if 0 case t9: LOGTO(ch2sid(ch), "-> T9 TIMEOUT <-"); xp_t9_timeout(xp); break; #endif default: LOGERR(xp2sid(xp), "SWERR: invalid M_SIG/M_PCSIG on read queue"); break; } } spin_unlock_bh(&ch->lock); } else LOGERR(xp2sid(xp), "SWERR: timeout with not attached channel"); } return (0); } #endif /* * M_DATA Handling * ------------------------------------------------------------------------- */ /** __xp_w_data: - process M_DATA message * @xp: private structure (locked) * @q: active queue (write queue) * @mp: the M_DATA message * * This function either returns zero (0) when the message is consumed, or a negative error number * when the message is to be (re)queued. This non-locking version is used by the service * procedure. */ static inline fastcall __hot_write int __xp_w_data(struct xp *xp, queue_t *q, mblk_t *mp) { return xp_send_data(xp, q, mp); } /** xp_w_data: - process M_DATA message (put procedure) * @q: active queue (write queue) * @mp: the M_DATA message * * This function always returns -%EAGAIN for performance. This version is used by the put * procedure. Note that we do not actually call this function: we use a fastpath check for M_DATA * message types. See xp_wput(). */ static inline fastcall __hot_write int xp_w_data(queue_t *q, mblk_t *mp) { /* Always queue from put procedure for performance. */ return (-EAGAIN); } /** __xp_r_data: - process M_DATA message (service procedure) * @xp: private structure (locked) * @q: active queue (read queue) * @mp: the M_DATA message * * Note that SL-level packets are always sent upstream as M_DATA messages. SDT-level packets are * always sent as M_DATA when they do not have a repetition number, M_PROTO otherwise. SDL-level * packets are always sent as M_DATA. */ noinline fastcall __hot_read int __xp_r_data(struct xp *xp, queue_t *q, mblk_t *mp) { struct ch *ch; if (likely((ch = xp->ch) != NULL)) { if (likely(canputnext(q))) { if (likely(xp->monitor == 0)) { /* we should likely make this an atomic integer */ spin_lock_bh(&ch->lock); ch->sl.statem.Cr--; spin_unlock_bh(&ch->lock); } putnext(q, mp); return (0); } return (-EBUSY); } /* discard extra message */ freemsg(mp); return (0); } /* * M_FLUSH Handling * ------------------------------------------------------------------------- */ /** xp_w_flush: - process M_FLUSH * @q: active queue (write queue) * @mp: the M_FLUSH message * * This canonical driver write flush procedure flushes the write side queue if requested and * cancels write flush. If read side flush is also requeested, the read side is flushed and the * message is passed upward. If read side flush is not requested, the message is freeed. There is * the added wrinkle that FISU/LSSU compression buffers are cleared on the transmit and the receive * when the corresponding queue is flushed. * * There is a little bit of a problem here: the dereference to acquire the xp pointer is ok because * the private structure cannot disappear while the flush is being processed, however, the xp->ch * dereference is problematic: the pointer might exist at one point and not at another because the * xp structure is not locked (has not been acquired). If we are going to support ch structures * going away while streams are open, this could cause crashes. */ noinline fastcall __unlikely int xp_w_flush(queue_t *q, mblk_t *mp) { struct xp *xp = XP_PRIV(q); if (mp->b_rptr[0] & FLUSHW) { struct ch *ch; if ((ch = xp->ch)) { spin_lock_bh(&ch->lock); if (ch->tx.cmp) { ch->tx.cmp = NULL; ch->tx.repeat = 0; } spin_unlock_bh(&ch->lock); } if (mp->b_rptr[0] & FLUSHBAND) flushband(q, mp->b_rptr[1], FLUSHDATA); else flushq(q, FLUSHDATA); mp->b_rptr[0] &= ~FLUSHW; } if (mp->b_rptr[0] & FLUSHR) { struct ch *ch; if ((ch = xp->ch)) { spin_lock_bh(&ch->lock); if (ch->rx.cmp) { freeb(ch->rx.cmp); ch->rx.cmp = NULL; ch->rx.repeat = 0; } spin_unlock_bh(&ch->lock); } if (mp->b_rptr[0] & FLUSHBAND) flushband(OTHERQ(q), mp->b_rptr[1], FLUSHDATA); else flushq(OTHERQ(q), FLUSHDATA); qreply(q, mp); return (0); } freemsg(mp); return (0); } /* * ========================================================================= * * WAKEUPS * * ========================================================================= */ noinline fastcall void __xp_r_wakeup(struct xp *xp, queue_t *q) { if (unlikely(xp->i_flags == 0)) return; /* FIXME: when a flag is set, attempt to perform the action */ } /* * ========================================================================= * * PUT and SRV * * ========================================================================= */ STATIC streamscall __hot_in int xp_r_prim_srv(struct xp *xp, queue_t *q, mblk_t *mp) { switch (__builtin_expect(DB_TYPE(mp), M_DATA)) { case M_DATA: return __xp_r_data(xp, q, mp); #if 0 case M_SIG: case M_PCSIG: return __xp_r_sig(xp, q, mp); #endif default: if (DB_TYPE(mp) >= QPCTL || bcanputnext(q, mp->b_band)) { putnext(q, mp); return (0); } return (-EBUSY); } } #ifndef DL_NODE #define DL_NODE 5 #endif /** xp_w_other: - put or service a primitive * @q: active queue (write queue) * @mp: the primitive * * This is the slow path for the write put procedure. These should happen rarely. We keep this * out of line and in the unlikely text block. */ noinline fastcall __unlikely int xp_w_other(queue_t *q, mblk_t *mp) { switch (__builtin_expect(DB_TYPE(mp), M_FLUSH)) { case M_FLUSH: return xp_w_flush(q, mp); case M_IOCTL: switch (XP_PRIV(q)->bminor) { case 0: default: return xp_w_ioctl(q, mp); case DL_NODE: return dl_w_ioctl(q, mp); case BPF_NODE: return bpf_w_ioctl(q, mp); case NIT_NODE: return nit_w_ioctl(q, mp); } case M_IOCDATA: switch (XP_PRIV(q)->bminor) { case 0: default: return xp_w_iocdata(q, mp); case DL_NODE: return dl_w_iocdata(q, mp); case BPF_NODE: return bpf_w_iocdata(q, mp); case NIT_NODE: return nit_w_iocdata(q, mp); } } LOGERR(XP_PRIV(q)->cminor, "SWERR: %s %s:%d", __FUNCTION__, __FILE__, __LINE__); freemsg(mp); return (0); } /** xp_w_prim_put: - put a primitive * @q: active queue (write queue) * @mp: the primitive * * This is the fast path for the write put procedure. Data is simply queue by returning -%EAGAIN. * This provides better flow control and scheduling for maximum throughput. */ static inline streamscall __hot_put int xp_w_prim_put(queue_t *q, mblk_t *mp) { if (likely(DB_TYPE(mp) == M_DATA)) return xp_w_data(q, mp); switch (__builtin_expect(DB_TYPE(mp), M_PROTO)) { case M_PROTO: case M_PCPROTO: switch (__builtin_expect(XP_PRIV(q)->bminor, 0)) { case 0: default: return xp_w_proto(q, mp); case DL_NODE: return dl_w_proto(q, mp); case BPF_NODE: return bpf_w_proto(q, mp); case NIT_NODE: return nit_w_proto(q, mp); } default: return xp_w_other(q, mp); } } /** xp_w_prim_srv: - service a primitive * @xp: private structure (locked) * @q: active queue (write queue) * @mp: the primitive * * This is the fast path for the write service procedure. Data is processed. Processing data form * the write service procedure provides better flow control and scheduling for maximum throughput * and minimum latency. */ static inline streamscall __hot_put int xp_w_prim_srv(struct xp *xp, queue_t *q, mblk_t *mp) { if (likely(DB_TYPE(mp) == M_DATA)) return __xp_w_data(xp, q, mp); switch (__builtin_expect(DB_TYPE(mp), M_PROTO)) { case M_PROTO: case M_PCPROTO: switch (__builtin_expect(xp->bminor, 0)) { case 0: default: return __xp_w_proto(xp, q, mp); case DL_NODE: return __dl_w_proto(xp, q, mp); case BPF_NODE: return __bpf_w_proto(xp, q, mp); case NIT_NODE: return __nit_w_proto(xp, q, mp); } default: return xp_w_other(q, mp); } } /* * ========================================================================= * * QUEUE PUT and SERVICE routines * * ========================================================================= */ /** xp_rput: - read put procedure * @q: active queue (read queue) * @mp: message to put * * There are several reasons for using a read put and service procedure in the driver. One is that * we want to monitor upstream flow control by the depth of the queue instead of just with * canputnext. However, we do not do any checking but merely put the message on the queue. Note * that timers messages are inserted into the queue instead of calling put(9) so we won't see them * here. */ STATIC streamscall __hot_out int xp_rput(queue_t *q, mblk_t *mp) { xp_rstat.ms_acnt++; if (unlikely(!putq(q, mp))) { mp->b_band = 0; putq(q, mp); /* must succeed */ } return (0); } /** xp_rsrv: - read service procedure * @q: active queue (read queue) * * This is a canonical service procedure for read. Locking is performed outside the loop so that * locks do not need to be released and acquired with each loop. Note that the wakeup function * must also be exectued with the private structure locked. * * There are several reasons for using a read service procedure in the driver. One is that we want * timer messages to be placed on the queue and the service procedure is the only way of processing * them. */ STATIC streamscall __hot_in int xp_rsrv(queue_t *q) { struct xp *xp = XP_PRIV(q); if (likely((xp = (struct xp *) mi_acquire((caddr_t) xp, q)) != NULL)) { mblk_t *mp; while (likely((mp = getq(q)) != NULL)) { if (unlikely(xp_r_prim_srv(xp, q, mp))) { putbq(q, mp); break; } } if (unlikely(xp->i_flags != 0)) __xp_r_wakeup(xp, q); mi_release((caddr_t) xp); } return (0); } /** xp_wput: - write put procedure * @q: active queue (write queue) * @mp: message to put * * This is a canonical put procedure for write. Locking is performed by the individual message * handling procedures. Note that M_DATA messages are always queued for performance. Therefore, * everywhere we call put(9) to place an M_DATA message on the queue, this function queues the * M_DATA and does not process it immediately. */ STATIC streamscall __hot_in int xp_wput(queue_t *q, mblk_t *mp) { if (likely(DB_TYPE(mp) == M_DATA) || unlikely(DB_TYPE(mp) < QPCTL && (q->q_first || (q->q_flag & QSVCBUSY))) || unlikely(xp_w_prim_put(q, mp))) { xp_wstat.ms_acnt++; if (unlikely(!putq(q, mp))) { mp->b_band = 0; putq(q, mp); /* must succeed */ } } return (0); } /** xp_wsrv: - write service procedure * @q: active queue (write queue) * * This is a canonical service procedure for write. Locking is performed outside the loop so that * locks do not need to be released and reacquired with each loop. Note that the wakeup function * must also be executed with the private structure locked. */ STATIC streamscall __hot_in int xp_wsrv(queue_t *q) { struct xp *xp = XP_PRIV(q); if (likely((xp = (struct xp *) mi_acquire((caddr_t) xp, q)) != NULL)) { mblk_t *mp; while (likely((mp = getq(q)) != NULL)) { if (unlikely(xp_w_prim_srv(xp, q, mp))) { putbq(q, mp); break; } } mi_release((caddr_t) xp); } return (0); } /* * ========================================================================= * * OPEN and CLOSE * * ========================================================================= * Open is called on the first open of a character special device stream * head; close is called on the last close of the same device. */ #define FIRST_CMINOR 0 #define LAST_CMINOR 10 #define FREE_CMINOR 11 STATIC kmem_cachep_t xp_priv_cachep; static caddr_t xp_opens = NULL; STATIC major_t xp_majors[CMAJORS] = { CMAJOR_0, }; /** xp_qopen: - each open of a stream * @q: queue pair * @devp: device pointer * @flag: open flags * @sflag: STREAMS flag * @crp: credentials pointer */ STATIC streamscall int xp_qopen(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *crp) { minor_t bminor = getminor(*devp); psw_t flags; int err; if (q->q_ptr) return (0); /* already open */ if (sflag != CLONEOPEN) return (ENXIO); if (bminor < FIRST_CMINOR || bminor > LAST_CMINOR) return (ENXIO); *devp = makedevice(getmajor(*devp), FREE_CMINOR); if (!mi_set_sth_lowat(q, 0)) return (ENOBUFS); if (!mi_set_sth_hiwat(q, SHEADHIWAT >> 1)) return (ENOBUFS); write_lock_irqsave(&xp_list_lock, flags); err = mi_open_comm_cache(&xp_opens, xp_priv_cachep, q, devp, flag, sflag, crp); write_unlock_irqrestore(&xp_list_lock, flags); if (err) return (err); { struct xp *xp = XP_PRIV(q); /* fill out xp structure and perform other allocations */ bzero(xp, sizeof(*xp)); xp->rq = RD(q); xp->wq = WR(q); xp->cmajor = getmajor(*devp); xp->cminor = getminor(*devp); xp->bminor = bminor; switch (bminor) { default: case 0: xp->i_version = 1; xp->i_style = LMI_STYLE2; xp->i_state = LMI_UNATTACHED; break; case BPF_NODE: xp->i_version = 1; xp->i_style = LMI_STYLE2; xp->i_state = 0; break; case NIT_NODE: xp->i_version = 1; xp->i_style = LMI_STYLE2; xp->i_state = 0; break; case DL_NODE: xp->i_version = DL_CURRENT_VERSION; xp->i_style = DL_STYLE2; xp->i_state = DL_UNATTACHED; break; } } qprocson(q); return (0); } /** xp_qclose: - last close of a stream * @q: queue pair * @flag: open flags * @crp: credentials */ STATIC streamscall __unlikely int xp_qclose(queue_t *q, int flag, cred_t *crp) { struct xp *xp = XP_PRIV(q); caddr_t ptr = (caddr_t) xp; struct ch *ch; psw_t flags; int err; qprocsoff(q); write_lock_irqsave(&xp_list_lock, flags); mi_acquire_sleep_nosignal(ptr, &ptr, &xp_list_lock, &flags); if ((ch = xp->ch)) { xp->ch = NULL; spin_lock(&ch->lock); { if (ch->xp == xp) { ch->xp = NULL; ch->sdl.config.ifflags &= ~SDL_IF_UP; /* FIXME FIXME FIXME: more to do here: worry about the state of the state machine, perform local processor outage if necessary, etc. */ } ch_put(ch); } spin_unlock(&ch->lock); } mi_release(ptr); err = mi_close_comm_cache(&xp_opens, xp_priv_cachep, q); write_unlock_irqrestore(&xp_list_lock, flags); return (err); } /* * ========================================================================== * * Private and Card structure allocation and deallocation * * ========================================================================== */ STATIC kmem_cachep_t xp_priv_cachep = NULL; STATIC kmem_cachep_t xp_sync_cachep = NULL; STATIC kmem_cachep_t xp_chan_cachep = NULL; STATIC kmem_cachep_t xp_span_cachep = NULL; STATIC kmem_cachep_t xp_card_cachep = NULL; STATIC kmem_cachep_t xp_xbuf_cachep = NULL; /* * Cache allocation * ------------------------------------------------------------------------- */ noinline int xp_term_caches(void) { int err = 0; if (xp_xbuf_cachep) { #ifdef HAVE_KTYPE_KMEM_CACHE_T_P if (kmem_cache_destroy(xp_xbuf_cachep)) { cmn_err(CE_WARN, "%s: did not destroy xp_xbuf_cachep", __FUNCTION__); err = -EBUSY; } else printd(("%s: shrunk xp_xbuf_cache to zero\n", DRV_NAME)); #else kmem_cache_destroy(xp_xbuf_cachep); #endif } if (xp_sync_cachep) { #ifdef HAVE_KTYPE_KMEM_CACHE_T_P if (kmem_cache_destroy(xp_sync_cachep)) { cmn_err(CE_WARN, "%s: did not destroy xp_sync_cachep", __FUNCTION__); err = -EBUSY; } else printd(("%s: shrunk xp_sync_cache to zero\n", DRV_NAME)); #else kmem_cache_destroy(xp_sync_cachep); #endif } if (xp_card_cachep) { #ifdef HAVE_KTYPE_KMEM_CACHE_T_P if (kmem_cache_destroy(xp_card_cachep)) { cmn_err(CE_WARN, "%s: did not destroy xp_card_cachep", __FUNCTION__); err = -EBUSY; } else printd(("%s: shrunk xp_card_cache to zero\n", DRV_NAME)); #else kmem_cache_destroy(xp_card_cachep); #endif } if (xp_span_cachep) { #ifdef HAVE_KTYPE_KMEM_CACHE_T_P if (kmem_cache_destroy(xp_span_cachep)) { cmn_err(CE_WARN, "%s: did not destroy xp_span_cachep", __FUNCTION__); err = -EBUSY; } else printd(("%s: shrunk xp_span_cache to zero\n", DRV_NAME)); #else kmem_cache_destroy(xp_span_cachep); #endif } if (xp_chan_cachep) { #ifdef HAVE_KTYPE_KMEM_CACHE_T_P if (kmem_cache_destroy(xp_chan_cachep)) { cmn_err(CE_WARN, "%s: did not destroy xp_chan_cachep", __FUNCTION__); err = -EBUSY; } else printd(("%s: shrunk xp_slot_cache to zero\n", DRV_NAME)); #else kmem_cache_destroy(xp_chan_cachep); #endif } if (xp_priv_cachep) { #ifdef HAVE_KTYPE_KMEM_CACHE_T_P if (kmem_cache_destroy(xp_priv_cachep)) { cmn_err(CE_WARN, "%s: did not destroy xp_priv_cachep", __FUNCTION__); err = -EBUSY; } else printd(("%s: shrunk xp_priv_cache to zero\n", DRV_NAME)); #else kmem_cache_destroy(xp_priv_cachep); #endif } return (err); } noinline __devinit int xp_init_caches(void) { if (!xp_priv_cachep && !(xp_priv_cachep = kmem_create_cache("xp_priv_cachep", mi_open_size(sizeof(struct xp)), 0, SLAB_HWCACHE_ALIGN, NULL, NULL))) { cmn_err(CE_PANIC, "%s: Cannot allocate xp_priv_cachep", __FUNCTION__); goto error; } else printd(("%s: initialized device private structure cache\n", DRV_NAME)); if (!xp_chan_cachep && !(xp_chan_cachep = kmem_create_cache("xp_chan_cachep", sizeof(struct ch), 0, SLAB_HWCACHE_ALIGN, NULL, NULL))) { cmn_err(CE_PANIC, "%s: Cannot allocate xp_chan_cachep", __FUNCTION__); goto error; } else printd(("%s: initialized chan private structure cache\n", DRV_NAME)); if (!xp_span_cachep && !(xp_span_cachep = kmem_create_cache("xp_span_cachep", sizeof(struct sp), 0, SLAB_HWCACHE_ALIGN, NULL, NULL))) { cmn_err(CE_PANIC, "%s: Cannot allocate xp_span_cachep", __FUNCTION__); goto error; } else printd(("%s: initialized span private structure cache\n", DRV_NAME)); if (!xp_card_cachep && !(xp_card_cachep = kmem_create_cache("xp_card_cachep", sizeof(struct cd), 0, SLAB_HWCACHE_ALIGN, NULL, NULL))) { cmn_err(CE_PANIC, "%s: Cannot allocate xp_card_cachep", __FUNCTION__); goto error; } else printd(("%s: initialized card private structure cache\n", DRV_NAME)); if (!xp_sync_cachep && !(xp_sync_cachep = kmem_create_cache("xp_sync_cachep", sizeof(struct sg), 0, SLAB_HWCACHE_ALIGN, NULL, NULL))) { cmn_err(CE_PANIC, "%s: Cannot allocate xp_sync_cachep", __FUNCTION__); goto error; } else printd(("%s: initialized sync private structure cache\n", DRV_NAME)); if (!xp_xbuf_cachep && !(xp_xbuf_cachep = kmem_create_cache("xp_xbuf_cachep", X400P_EBUFNO * 1024, 0, SLAB_HWCACHE_ALIGN, NULL, NULL))) { cmn_err(CE_PANIC, "%s: Cannot allocate xp_xbuf_cachep", __FUNCTION__); goto error; } else printd(("%s: initialized card read/write buffer cache\n", DRV_NAME)); return (0); error: return (-EFAULT); } /* * Channel allocation and deallocation * ------------------------------------------------------------------------- */ noinline __unlikely void xp_init_ch(struct sp *sp, struct ch *ch, uint8_t chan) { ch->ppa = ((chan & 0xff) << 0) | ((sp->span & 0x0f) << 8) | ((sp->cd->card & 0x0f) << 12); ch->chan = chan; /* fill out channel structure */ printd(("%s: linked channel private structure\n", DRV_NAME)); switch (sp->config.ifgtype) { case SDL_GTYPE_E1: if (chan != 0) { ch->option = lmi_default_e1_chan; ch->sdl.config = sdl_default_e1_chan; ch->sdt.config = sdt_default_e1_chan; ch->sl.config = sl_default_e1_chan; } else { ch->option = lmi_default_e1_span; ch->sdl.config = sdl_default_e1_span; ch->sdt.config = sdt_default_e1_span; ch->sl.config = sl_default_e1_span; } break; case SDL_GTYPE_T1: if (chan != 0) { ch->option = lmi_default_t1_chan; ch->sdl.config = sdl_default_t1_chan; ch->sdt.config = sdt_default_t1_chan; ch->sl.config = sl_default_t1_chan; } else { ch->option = lmi_default_t1_span; ch->sdl.config = sdl_default_t1_span; ch->sdt.config = sdt_default_t1_span; ch->sl.config = sl_default_t1_span; } break; case SDL_GTYPE_J1: if (chan != 0) { ch->option = lmi_default_j1_chan; ch->sdl.config = sdl_default_j1_chan; ch->sdt.config = sdt_default_j1_chan; ch->sl.config = sl_default_j1_chan; } else { ch->option = lmi_default_j1_span; ch->sdl.config = sdl_default_j1_span; ch->sdt.config = sdt_default_j1_span; ch->sl.config = sl_default_j1_span; } break; } /* initialize buffer queues */ bufq_init(&ch->sdl.tb); bufq_init(&ch->sdt.tb); bufq_init(&ch->sl.rb); bufq_init(&ch->sl.tb); bufq_init(&ch->sl.rtb); } noinline __unlikely struct ch * xp_alloc_ch(struct sp *sp, uint8_t chan) { struct ch *ch; if ((ch = kmem_cache_alloc(xp_chan_cachep, GFP_ATOMIC))) { printd(("%s: allocated channel private structure\n", DRV_NAME)); bzero(ch, sizeof(*ch)); ch_get(ch); /* first get */ spin_lock_init(&ch->lock); /* "ch-priv-lock" */ /* create linkage */ sp->chans[chan] = ch_get(ch); ch->sp = sp_get(sp); ss7_bufpool_reserve(&xp_bufpool, 2); printd(("%s: setting channel private structure defaults\n", DRV_NAME)); xp_init_ch(sp, ch, chan); } else ptrace(("%s: ERROR: Could not allocate channel private structure\n", DRV_NAME)); return (ch); } noinline __unlikely void xp_free_ch(struct ch *ch) { struct sp *sp; ensure(ch, return); spin_lock_bh(&ch->lock); { #if 1 xp_timer_stop(ch, tall); #endif if ((sp = ch->sp)) { struct cd *cd; /* remove span linkage */ if ((cd = sp->cd)) { spin_lock(&cd->lock); { int chan; uchar idle = (cd->config.ifgtype == SDL_GTYPE_T1) ? 0x7f : 0xff; uchar *base = (uchar *) cd->wbuf + span_to_byte(sp->span); for (chan = 0; chan < 32; chan++) { if (sp->chans[chan] == ch) { int boff, slot; ch_put(xchg(&sp->chans[chan], NULL)); slot = (sp->config.ifgtype == SDL_GTYPE_E1) ? xp_e1_chan_map[chan] : xp_t1_chan_map[chan]; for (boff = 0; boff < X400P_EBUFNO; boff++) *(base + (boff << 10) + (slot << 2)) = idle; } } } spin_unlock(&cd->lock); } else { int chan; for (chan = 0; chan < 32; chan++) if (sp->chans[chan] == ch) ch_put(xchg(&sp->chans[chan], NULL)); } sp_put(xchg(&ch->sp, NULL)); printd(("%s: unliked chan private structure from span\n", DRV_NAME)); } else ptrace(("%s: ERROR: chans cannot exist without spans\n", DRV_NAME)); #if 0 xp_free_timers(ch); #endif if (ch->tx.msg && ch->tx.msg != ch->tx.cmp) freemsg(xchg(&ch->tx.msg, NULL)); if (ch->tx.cmp) freemsg(xchg(&ch->tx.cmp, NULL)); if (ch->rx.msg) freemsg(xchg(&ch->rx.msg, NULL)); if (ch->rx.nxt) freemsg(xchg(&ch->rx.nxt, NULL)); if (ch->rx.cmp) freemsg(xchg(&ch->rx.cmp, NULL)); bufq_purge(&ch->sdl.tb); bufq_purge(&ch->sdt.tb); ss7_bufpool_release(&xp_bufpool, 2); bufq_purge(&ch->sl.rb); bufq_purge(&ch->sl.tb); bufq_purge(&ch->sl.rtb); } spin_unlock_bh(&ch->lock); assure(atomic_read(&ch->refcnt) == 1); ch_put(ch); /* final put */ } STATIC struct ch * ch_get(struct ch *ch) { if (ch) atomic_inc(&ch->refcnt); return (ch); } STATIC void ch_put(struct ch *ch) { if (atomic_dec_and_test(&ch->refcnt)) { printd(("%s: freed slot private structure\n", DRV_NAME)); kmem_cache_free(xp_chan_cachep, ch); } } STATIC struct ch * ch_find(uint ppa) { struct sp *sp; uint chan; if ((sp = sp_find(ppa)) == NULL) return ERR_PTR(-ESRCH); chan = (ppa >> 0) & 0xff; switch (sp->config.ifgtype) { case SDL_GTYPE_E1: if (chan > 31) return ERR_PTR(-ESRCH); break; case SDL_GTYPE_T1: case SDL_GTYPE_J1: if (chan > 24) return ERR_PTR(-ESRCH); break; default: return ERR_PTR(-ESRCH); } return (sp->chans[chan]); } /* * Span allocation and deallocation * ------------------------------------------------------------------------- */ noinline __unlikely void xp_init_sp(struct cd *cd, struct sp *sp, uint8_t span) { sp->iobase = cd->iobase + (span << 8); sp->span = span; sp->config = cd->config; sp->config.ifflags = 0; sp->config.ifalarms = 0; sp->config.ifrxlevel = 0; } noinline __unlikely struct sp * xp_alloc_sp(struct cd *cd, uint8_t span) { struct sp *sp; if ((sp = kmem_cache_alloc(xp_span_cachep, GFP_ATOMIC))) { printd(("%s: allocated span private structure\n", DRV_NAME)); bzero(sp, sizeof(*sp)); sp_get(sp); /* first get */ spin_lock_init(&sp->lock); /* "sp-priv-lock" */ /* create linkage */ cd->spans[span] = sp_get(sp); sp->cd = cd_get(cd); /* fill out span structure */ printd(("%s: linked span private structure\n", DRV_NAME)); xp_init_sp(cd, sp, span); printd(("%s: set span private structure defaults\n", DRV_NAME)); } else ptrace(("%s: ERROR: Could not allocate span private structure\n", DRV_NAME)); return (sp); } /* Note: called with card interrupts disabled */ noinline __unlikely void xp_free_sp(struct sp *sp) { struct cd *cd; ensure(sp, return); if ((cd = sp->cd)) { int chan; /* remove card linkage */ sp_put(xchg(&cd->spans[sp->span], NULL)); cd_put(xchg(&sp->cd, NULL)); sp->span = 0; printd(("%s: unlinked span private structure from card\n", DRV_NAME)); /* remove any remaining chans */ for (chan = 0; chan < 32; chan++) { struct ch *ch; if ((ch = sp->chans[chan])) xp_free_ch(ch); } printd(("%s: unlinked span private structure from slots\n", DRV_NAME)); } else ptrace(("%s: ERROR: spans cannot exist without cards\n", DRV_NAME)); assure(atomic_read(&sp->refcnt) == 1); sp_put(sp); /* final put */ } STATIC struct sp * sp_get(struct sp *sp) { if (sp) atomic_inc(&sp->refcnt); return (sp); } STATIC void sp_put(struct sp *sp) { if (atomic_dec_and_test(&sp->refcnt)) { printd(("%s: freed span private structure\n", DRV_NAME)); kmem_cache_free(xp_span_cachep, sp); } } STATIC struct sp * sp_find(uint ppa) { struct cd *cd; struct sp *sp = NULL; uint span = (ppa >> 8) & 0x0f; if (span < X400_SPANS && (cd = cd_find(ppa)) != NULL) sp = cd->spans[span]; return (sp); } /* * Synchronization Group allocation and deallocation. * ------------------------------------------------------------------------- */ noinline __unlikely struct sg * xp_alloc_sg(void) { struct sg *sg; if ((sg = kmem_cache_alloc(xp_sync_cachep, GFP_ATOMIC))) { psw_t flags; bzero(sg, sizeof(*sg)); sg_get(sg); /* first get */ spin_lock_init(&sg->lock); write_lock_irqsave(&x400p_lock, flags); if (x400p_groups >= X400_SYNCS) { kmem_cache_free(xp_sync_cachep, sg); write_unlock_irqrestore(&x400p_lock, flags); return (NULL); } sg->group = x400p_groups++; x400p_syncs[sg->group] = sg_get(sg); write_unlock_irqrestore(&x400p_lock, flags); printd(("%s: linked sync private structure\n", DRV_NAME)); } else ptrace(("%s: ERROR: Could not allocate sync private structure\n", DRV_NAME)); return (sg); } noinline __unlikely void xp_free_sg(struct sg *sg) { psw_t flags; ensure(sg, return); write_lock_irqsave(&x400p_lock, flags); x400p_syncs[sg->group] = NULL; write_unlock_irqrestore(&x400p_lock, flags); sg_put(sg); printd(("%s: unlinked sync private structure\n", DRV_NAME)); assure(atomic_read(&sg->refcnt) == 1); sg_put(sg); /* final put */ } STATIC struct sg * sg_get(struct sg *sg) { if (sg) atomic_inc(&sg->refcnt); return (sg); } STATIC void sg_put(struct sg *sg) { if (atomic_dec_and_test(&sg->refcnt)) { kmem_cache_free(xp_sync_cachep, sg); printd(("%s: freed sync private structure\n", DRV_NAME)); } } STATIC struct sg * sg_find(uint group) { struct sg *sg = NULL; if (group < X400_SYNCS) sg = x400p_syncs[group]; return (sg); } /* * Card allocation and deallocation * ------------------------------------------------------------------------- */ noinline __unlikely struct cd * xp_alloc_cd(void) { struct cd *cd; if ((cd = kmem_cache_alloc(xp_card_cachep, GFP_ATOMIC))) { uint32_t *wbuf; uint32_t *rbuf; psw_t flags; printd(("%s: allocated card private structure\n", DRV_NAME)); if (!(wbuf = kmem_cache_alloc(xp_xbuf_cachep, GFP_ATOMIC))) { ptrace(("%s: could not allocate write buffer\n", DRV_NAME)); kmem_cache_free(xp_card_cachep, cd); return (NULL); } if (!(rbuf = kmem_cache_alloc(xp_xbuf_cachep, GFP_ATOMIC))) { ptrace(("%s: could not allocate read buffer\n", DRV_NAME)); kmem_cache_free(xp_xbuf_cachep, wbuf); kmem_cache_free(xp_card_cachep, cd); return (NULL); } bzero(cd, sizeof(*cd)); cd_get(cd); /* first get */ spin_lock_init(&cd->lock); /* "cd-priv-lock" */ write_lock_irqsave(&x400p_lock, flags); if (x400p_boards >= X400_CARDS) { kmem_cache_free(xp_xbuf_cachep, rbuf); kmem_cache_free(xp_xbuf_cachep, wbuf); kmem_cache_free(xp_card_cachep, cd); write_unlock_irqrestore(&x400p_lock, flags); return (NULL); } cd->card = x400p_boards++; x400p_cards[cd->card] = cd_get(cd); write_unlock_irqrestore(&x400p_lock, flags); bzero(wbuf, X400P_EBUFNO * 1024); bzero(rbuf, X400P_EBUFNO * 1024); cd->wbuf = wbuf; cd->rbuf = rbuf; tasklet_init(&cd->tasklet, &xp_card_tasklet, (unsigned long) cd); printd(("%s: linked card private structure\n", DRV_NAME)); } else ptrace(("%s: ERROR: Could not allocate card private structure\n", DRV_NAME)); return (cd); } /* Note: called with card interrupts disabled and pci resources deallocated */ noinline __unlikely void xp_free_cd(struct cd *cd) { psw_t flags; ensure(cd, return); spin_lock_irqsave(&cd->lock, flags); { int span; struct sg *sg; if (cd->tasklet.func) tasklet_kill(&cd->tasklet); if (cd->rbuf) kmem_cache_free(xp_xbuf_cachep, (uint32_t *) xchg(&cd->rbuf, NULL)); if (cd->wbuf) kmem_cache_free(xp_xbuf_cachep, (uint32_t *) xchg(&cd->wbuf, NULL)); /* remove any remaining spans */ for (span = 0; span < X400_SPANS; span++) { struct sp *sp; if ((sp = cd->spans[span])) xp_free_sp(sp); } /* unlink from sync list */ if ((sg = cd->sg.sg) != NULL) { spin_lock(&sg->lock); if ((*(cd->sg.prev) = cd->sg.next)) cd->sg.next->sg.prev = cd->sg.prev; cd->sg.next = NULL; cd->sg.prev = &cd->sg.next; sg->members--; cd->sg.sg = NULL; spin_unlock(&sg->lock); sg_put(sg); } /* unlink from board array */ x400p_cards[cd->card] = NULL; cd_put(cd); printd(("%s: unlinked card private structure\n", DRV_NAME)); } spin_unlock_irqrestore(&cd->lock, flags); assure(atomic_read(&cd->refcnt) == 1); cd_put(cd); /* final put */ } STATIC struct cd * cd_get(struct cd *cd) { if (cd) atomic_inc(&cd->refcnt); return (cd); } STATIC void cd_put(struct cd *cd) { if (atomic_dec_and_test(&cd->refcnt)) { kmem_cache_free(xp_card_cachep, cd); printd(("%s: freed card private structure\n", DRV_NAME)); } } STATIC struct cd * cd_find(uint ppa) { struct cd *cd = NULL; uint card = (ppa >> 12) & 0x0f; if (card < X400_CARDS) cd = x400p_cards[card]; return (cd); } /* * ========================================================================= * * PCI Initialization * * ========================================================================= */ /** xp_remove: - X400P-SS7 Remove * * These cards do not support hotplug, so removes only occur after all the channels have been * closed, so we only have to stop interrupts and deallocate board-level resources. Nevertheless, * if we get a hot removal of a card, we must be prepared to deallocate the span structures. */ STATIC void xp_remove(struct pci_dev *dev) { struct cd *cd; if (!(cd = pci_get_drvdata(dev))) goto disable; if (cd->plx) { cd->plx[INTCSR] = 0; /* disable interrupts */ } if (cd->xlb) { cd->xlb[SYNREG] = cd->synreg = SYNCSELF; cd->xlb[CTLREG] = cd->ctlreg = 0; cd->xlb[LEDREG] = cd->ledreg = 0; cd->xlb[TSTREG] = cd->tstreg = 0; cd->xlb[CTLREG1] = 0; } if (cd->irq) { free_irq(cd->irq, cd); printd(("%s: freed irq\n", DRV_NAME)); } if (cd->xlb_region) { release_mem_region(cd->xlb_region, cd->xlb_length); printd(("%s: released xlb region %lx length %ld\n", DRV_NAME, cd->xlb_region, cd->xlb_length)); } if (cd->xll_region) { release_mem_region(cd->xll_region, cd->xll_length); printd(("%s: released xll region %lx length %ld\n", DRV_NAME, cd->xll_region, cd->xll_length)); } if (cd->plx_region) { release_mem_region(cd->plx_region, cd->plx_length); printd(("%s: released plx region %lx length %ld\n", DRV_NAME, cd->plx_region, cd->plx_length)); } if (cd->xlb) { iounmap((void *) cd->xlb); printd(("%s: unmapped xlb memory at %p\n", DRV_NAME, cd->xlb)); } if (cd->xll) { iounmap((void *) cd->xll); printd(("%s: unmapped xll memory at %p\n", DRV_NAME, cd->xll)); } if (cd->plx) { iounmap((void *) cd->plx); printd(("%s: unmapped plx memory at %p\n", DRV_NAME, cd->plx)); } xp_free_cd(cd); disable: pci_disable_device(dev); } #ifdef X400P_DOWNLOAD_FIRMWARE /** xp_download_fw: - download Xilinx firmware to card. * @cd: card structure * @board: board number (not used) * * This procedure downloads firmware to the card. It is usually not necessary to download firmware * to the card. Only a very ancient and experimental Tormenta card would not already have the * proper firmware loaded. */ STATIC int __devinit xp_download_fw(struct cd *cd, enum xp_board board) { unsigned int byte; unsigned char *f; size_t flen; volatile unsigned long *data; unsigned long timeout; #if 0 /* prints out PLX registers for debugging */ { char buf[64] = { 0, }; volatile unsigned char *c; int i, offs = 0; for (c = (volatile unsigned char *) cd->plx, i = 0; i < cd->plx_length; i++, c++) { if (i && !(i & 0x0f)) { __printd(("%s\n", buf)); buf[0] = '\0'; offs = 0; } offs += snprintf(buf + offs, sizeof(buf) - offs, "%02x ", *c); } if (offs) { __printd(("%s\n", buf)); } } #endif f = (unsigned char *) v401pfw; flen = sizeof(v401pfw); data = (volatile unsigned long *) &cd->plx[GPIOC]; *data |= GPIO_WRITE; *data &= ~GPIO_PROGRAM; while (*data & (GPIO_INIT | GPIO_DONE)) ; printd(("%s: Xilinx Firmware Load: Init and done are low\n", DRV_NAME)); *data |= GPIO_PROGRAM; while (!(*data & GPIO_INIT)) ; printd(("%s: Xilinx Firmware Load: Init is high\n", DRV_NAME)); *data &= ~GPIO_WRITE; printd(("%s: Xilinx Firmware Load: Loading\n", DRV_NAME)); for (byte = 0; byte < flen; byte++) { *cd->xlb = *f++; if (*data & GPIO_DONE) break; if (!(*data & GPIO_INIT)) break; } if (!(*data & GPIO_INIT)) { printd(("%s: ERROR: Xilinx Firmware Load: Failed\n", DRV_NAME)); return (-EIO); } printd(("%s: Xilinx Firmware Load: Loaded %d bytes\n", DRV_NAME, byte)); timeout = (volatile unsigned long) jiffies + 20 * HZ / 1000; while ((volatile unsigned long) jiffies < timeout) ; *data |= GPIO_WRITE; printd(("%s: Xilinx Firmware Load: Done\n", DRV_NAME)); timeout = (volatile unsigned long) jiffies + 20 * HZ / 1000; while ((volatile unsigned long) jiffies < timeout) ; if (!(*data & GPIO_INIT)) { cmn_err(CE_WARN, "%s: ERROR: Xilinx Firmware Load: Failed", DRV_NAME); return (-EIO); } if (!(*data & GPIO_DONE)) { cmn_err(CE_WARN, "%s: ERROR: Xilinx Firmware Load: Failed", DRV_NAME); return (-EIO); } cmn_err(CE_NOTE, "%s: Xilinx Firmware Load: Successful", DRV_NAME); return (0); } #endif #ifdef IRQF_DISABLED #undef SA_INTERRUPT #define SA_INTERRUPT IRQF_DISABLED #endif #ifdef IRQF_SHARED #undef SA_SHIRQ #define SA_SHIRQ IRQF_SHARED #endif #ifndef HAVE_KFUNC_PCI_IS_PCIE #define pci_is_pcie(dev) (dev->is_pcie) #endif /** xp_probe: - X400P-SS7 Probe * @dev: PCI device * @id: PCI device id * * Probes will be called for all PCI devices which match our criteria at pci init time (module * load). Successful return from the probe function will have the device configured for operation. */ STATIC int __devinit xp_probe(struct pci_dev *dev, const struct pci_device_id *id) { int board; struct cd *cd; const char *name; if (!dev || !id) { cmn_err(CE_WARN, "%s: ERROR: Device or id is null!", DRV_NAME); return (-ENXIO); } board = id->driver_data; name = xp_board_info[board].name; if (!(xp_board_info[board].hw_flags & XPF_SUPPORTED)) { cmn_err(CE_WARN, "%s: ERROR: Driver does not support %s card.", DRV_NAME, name); return (-ENXIO); } if (pci_enable_device(dev)) { cmn_err(CE_WARN, "%s: ERROR: Could not enable %s pci card", DRV_NAME, name); return (-ENODEV); } printd(("%s: enabled %s pci card type %ld\n", DRV_NAME, name, id->driver_data)); if (dev->irq < 1) { cmn_err(CE_WARN, "%s: ERROR: No IRQ allocated for %s card.", DRV_NAME, name); pci_disable_device(dev); return (-ENXIO); } printd(("%s: card %s allocated IRQ %d\n", DRV_NAME, name, dev->irq)); if (!(cd = xp_alloc_cd())) { pci_disable_device(dev); return (-ENOMEM); } pci_set_drvdata(dev, cd); if ((pci_resource_flags(dev, 0) & IORESOURCE_IO) || !(cd->plx_region = pci_resource_start(dev, 0)) || !(cd->plx_length = pci_resource_len(dev, 0)) || !(cd->plx = ioremap(cd->plx_region, cd->plx_length))) { cmn_err(CE_WARN, "%s: ERROR: Invalid PLX 9030 base resource", DRV_NAME); goto error_remove; } printd(("%s: plx region %ld bytes at %lx, remapped %p\n", DRV_NAME, cd->plx_length, cd->plx_region, cd->plx)); if ((pci_resource_flags(dev, 2) & IORESOURCE_IO) || !(cd->xll_region = pci_resource_start(dev, 2)) || !(cd->xll_length = pci_resource_len(dev, 2)) || !(cd->xll = ioremap(cd->xll_region, cd->xll_length))) { cmn_err(CE_WARN, "%s: ERROR: Invalid Xilinx 32-bit base resource", DRV_NAME); goto error_remove; } printd(("%s: xll region %ld bytes at %lx, remapped %p\n", DRV_NAME, cd->xll_length, cd->xll_region, cd->xll)); if ((pci_resource_flags(dev, 3) & IORESOURCE_IO) || !(cd->xlb_region = pci_resource_start(dev, 3)) || !(cd->xlb_length = pci_resource_len(dev, 3)) || !(cd->xlb = ioremap(cd->xlb_region, cd->xlb_length))) { cmn_err(CE_WARN, "%s: ERROR: Invalid Xilinx 8-bit base resource", DRV_NAME); goto error_remove; } printd(("%s: xlb region %ld bytes at %lx, remapped %p\n", DRV_NAME, cd->xlb_length, cd->xlb_region, cd->xlb)); cd->iobase = (ulong) cd->xlb; cd->config.ifname = xp_board_info[id->driver_data].name; if (!request_mem_region(cd->plx_region, cd->plx_length, cd->config.ifname)) { cmn_err(CE_WARN, "%s: ERROR: Unable to reserve PLX memory", DRV_NAME); goto error_remove; } printd(("%s: plx region %lx reserved %ld bytes\n", DRV_NAME, cd->plx_region, cd->plx_length)); if (!request_mem_region(cd->xll_region, cd->xll_length, cd->config.ifname)) { cmn_err(CE_WARN, "%s: ERROR: Unable to reserve Xilinx 32-bit memory", DRV_NAME); goto error_remove; } printd(("%s: xll region %lx reserved %ld bytes\n", DRV_NAME, cd->xll_region, cd->xll_length)); if (!request_mem_region(cd->xlb_region, cd->xlb_length, cd->config.ifname)) { cmn_err(CE_WARN, "%s: ERROR: Unable to reserve Xilinx 8-bit memory", DRV_NAME); goto error_remove; } printd(("%s: xlb region %lx reserved %ld bytes\n", DRV_NAME, cd->xlb_region, cd->xlb_length)); cmn_err(CE_NOTE, "%s: card detected %s at 0x%lx/0x%lx irq %d", DRV_NAME, cd->config.ifname, cd->xll_region, cd->xlb_region, dev->irq); #ifdef X400P_DOWNLOAD_FIRMWARE if (xp_download_fw(cd, board) != 0) goto error_remove; #endif cd->plx[INTCSR] = 0; /* disable interrupts */ /* all boards have these registers regardless of framer */ cd->xlb[SYNREG] = cd->synreg = SYNCSELF; /* default autosync */ cd->xlb[CTLREG] = cd->ctlreg = 0; /* interrupts disabled */ cd->xlb[LEDREG] = cd->ledreg = 0; /* turn off leds */ cd->xlb[TSTREG] = cd->tstreg = 0; /* do not drive TEST2 pin */ cd->xlb[CTLREG1] = 0; /* Rev. A mode */ /* Note: only check the device id of the first framer of 4. */ cd->devrev = cd->xlb[0x0f]; /* Device id - same place for all Dallas chips */ cd->device = (cd->devrev & XP_DEV_IDMASK) >> XP_DEV_SHIFT; cd->devrev &= XP_DEV_REVMASK; if (!(xp_device_info[cd->device].hw_flags & XPF_SUPPORTED)) { cmn_err(CE_WARN, "%s: Usupported framer device %s", DRV_NAME, xp_device_info[cd->device].name); goto error_remove; } switch (cd->device) { case XP_DEV_DS2154: case XP_DEV_DS21354: case XP_DEV_DS21554: /* ISR depends only on device type. */ cd->isr = &xp_e1_interrupt; /* The only way to tell whether E1 from T1 boards; i.e., by chipset. */ switch (board) { case V400P: /* This will also handle any older ATCOM cards that also used the '4000'H PCI id yet had these chipsets. */ cd->board = V400PE; break; case X400P: cd->board = E400P; break; case X400PSS7: cd->board = E400PSS7; break; default: cd->board = -1; break; } break; case XP_DEV_DS2152: case XP_DEV_DS21352: case XP_DEV_DS21552: /* ISR depends only on device type. */ cd->isr = &xp_t1_interrupt; /* The only way to tell whether E1 from T1 boards; i.e., by chipset. */ switch (board) { case V400P: /* This will also handle any older ATCOM cards that also used the '4000'H PCI id yet had these chipsets. */ cd->board = V400PT; break; case X400P: cd->board = T400P; break; case X400PSS7: cd->board = T400PSS7; break; default: cd->board = -1; break; } break; case XP_DEV_DS2155: case XP_DEV_DS21455: case XP_DEV_DS21458: case XP_DEV_DS2156: /* ISR depends only on device type. */ cd->isr = &xp_x1_interrupt; switch (board) { case V400P: /* This is the only way to distinguish a ATCOM TE400P card from an old tor3 Varion card: i.e., by chipset. */ cd->board = A400P; break; case V401PE: cd->board = V401PE; break; case A400PE: cd->board = A400PE; break; case V401PT: cd->board = V401PT; break; case A400PT: cd->board = A400PT; break; case CP100: cd->board = pci_is_pcie(dev) ? CP100E : CP100P; break; case CP200: cd->board = pci_is_pcie(dev) ? CP200E : CP200P; break; case CP400: cd->board = pci_is_pcie(dev) ? CP400E : CP400P; break; default: cd->board = -1; break; } break; } if (cd->board == -1) { cmn_err(CE_WARN, "%s: Device %s not supported for card %s", DRV_NAME, xp_device_info[cd->device].name, xp_board_info[board].name); goto error_remove; } cd->ports = xp_board_info[cd->board].ports; cd->hw_flags = xp_board_info[cd->board].hw_flags; cd->hw_flags |= xp_device_info[cd->device].hw_flags; cmn_err(CE_NOTE, "%s: %s (%s Rev. %c)", DRV_NAME, xp_board_info[cd->board].name, xp_device_info[cd->device].name, (char) (cd->devrev + 65)); if (request_irq(dev->irq, cd->isr, SA_INTERRUPT | SA_SHIRQ, DRV_NAME, cd)) { cmn_err(CE_WARN, "%s: ERROR: Unable to request IRQ %d", DRV_NAME, dev->irq); goto error_remove; } cd->irq = dev->irq; cd->bus = dev->bus->number; cd->slot = PCI_SLOT(dev->devfn); printd(("%s: acquired IRQ %ld for %s card\n", DRV_NAME, cd->irq, xp_board_info[cd->board].name)); if (xp_card_config(cd) != 0) goto error_remove; cd->plx[INTCSR] = PLX_INTENA; /* enable interrupts */ return (0); error_remove: xp_remove(dev); return (-ENODEV); } #if 0 #ifdef CONFIG_PM #ifndef HAVE_KTYPE_PM_MESSAGE_T typedef u32 pm_message_t; #endif /** xp_suspend: - X400P-SS7 Suspend * @pdev: PCI device * @state: suspend state */ STATIC int xp_suspend(struct pci_dev *pdev, pm_message_t state) { fixme(("Write a suspend routine.\n")); return 0; } /** xp_resume: - X400P-SS7 Resume * @pdev: PCI device */ STATIC int xp_resume(struct pci_dev *pdev) { fixme(("Write a resume routine.\n")); return 0; } #endif /* CONFIG_PM */ #endif STATIC struct pci_driver xp_driver = { .name = DRV_NAME, .probe = xp_probe, .remove = __devexit_p(xp_remove), .id_table = xp_pci_tbl, #if 0 #ifdef CONFIG_PM .suspend = xp_suspend, .resume = xp_resume, #endif /* CONFIG_PM */ #endif }; /** xp_pci_init: - X400P-SS7 PCI Init * * Here we need to scan for all available boards, configure the board-level structures, and then * release all system resources. The purpose of this is to identify the boards in the system at * module startup or Linux Fast-STREAMS initialization. * * Later, when a stream is opened for any span, the span is configured, the drivers will be enabled * and all channels in the span will have their power-on sequence completed and each channel will * idle SIOS. Closing channels will result in the transmitters resuming idle SIOS operation. */ noinline __devinit int xp_pci_init(void) { #ifdef HAVE_KFUNC_PCI_MODULE_INIT return pci_module_init(&xp_driver); #else /* HAVE_KFUNC_PCI_MODULE_INIT */ return pci_register_driver(&xp_driver); #endif /* HAVE_KFUNC_PCI_MODULE_INIT */ } /** xp_pci_cleanup: - X400P-SS7 PCI Cleanup * * Because this is a style 2 driver, if there are any boards that are atill configured, we need to * stop the boards and deallocate the board-level resources and structures. */ noinline int xp_pci_cleanup(void) { pci_unregister_driver(&xp_driver); return (0); } /* * ========================================================================= * * Registration and initialization * * ========================================================================= */ #ifdef LINUX /* * Linux Registration * ------------------------------------------------------------------------- */ unsigned short modid = DRV_ID; #ifndef module_param MODULE_PARM(modid, "h"); #else module_param(modid, ushort, 0444); #endif MODULE_PARM_DESC(modid, "Module ID for the SL-X400P driver. (0 for allocation.)"); major_t major = CMAJOR_0; #ifndef module_param MODULE_PARM(major, "h"); #else module_param(major, uint, 0444); #endif MODULE_PARM_DESC(major, "Device number for the SL-X400P driver. (0 for allocation.)"); /* * Linux Fast-STREAMS Registration * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ STATIC struct cdevsw xp_cdev = { .d_name = DRV_NAME, .d_str = &sl_x400pinfo, .d_flag = D_MP, .d_fop = NULL, .d_mode = S_IFCHR, .d_kmod = THIS_MODULE, }; noinline __devinit int xp_register_strdev(major_t major) { int err; if ((err = register_strdev(&xp_cdev, major)) < 0) return (err); return (0); } noinline int xp_unregister_strdev(major_t major) { int err; if ((err = unregister_strdev(&xp_cdev, major)) < 0) return (err); return (0); } MODULE_STATIC void sl_x400pterminate(void) { int err, mindex; if (xp_majors[0]) { unregister_bpf(&xp_cdev); unregister_nit(&xp_cdev); } for (mindex = CMAJORS - 1; mindex >= 0; mindex--) { if (xp_majors[mindex]) { if ((err = xp_unregister_strdev(xp_majors[mindex]))) cmn_err(CE_PANIC, "%s: cannot unregister major %d", DRV_NAME, xp_majors[mindex]); if (mindex) xp_majors[mindex] = 0; } } ss7_bufpool_term(&xp_bufpool); if ((err = xp_free_tables())) cmn_err(CE_WARN, "%s: could not free tables", DRV_NAME); if ((err = xp_pci_cleanup())) cmn_err(CE_WARN, "%s: could not cleanup pci device", DRV_NAME); if ((err = xp_term_caches())) cmn_err(CE_WARN, "%s: could not terminate caches", DRV_NAME); return; } MODULE_STATIC int __init sl_x400pinit(void) { int err, mindex = 0; (void) &xp_free_ch; (void) &xp_alloc_sg; (void) &xp_free_sg; (void) &sg_find; (void) &xp_span_config; cmn_err(CE_NOTE, DRV_BANNER); /* console splash */ if ((err = xp_init_caches())) { cmn_err(CE_WARN, "%s: could not init caches, err = %d", DRV_NAME, err); sl_x400pterminate(); return (err); } if ((err = xp_pci_init())) { cmn_err(CE_WARN, "%s: no PCI devices found, err = %d", DRV_NAME, err); sl_x400pterminate(); return (err); } if ((err = xp_init_tables())) { cmn_err(CE_WARN, "%s: could not allocate tables, err = %d", DRV_NAME, err); sl_x400pterminate(); return (err); } ss7_bufpool_init(&xp_bufpool); for (mindex = 0; mindex < CMAJORS; mindex++) { if ((err = xp_register_strdev(xp_majors[mindex])) < 0) { if (mindex) { cmn_err(CE_WARN, "%s: could not register major %d", DRV_NAME, xp_majors[mindex]); continue; } else { cmn_err(CE_WARN, "%s: could not register driver, err = %d", DRV_NAME, err); sl_x400pterminate(); return (err); } } if (xp_majors[mindex] == 0) xp_majors[mindex] = err; #if 0 LIS_DEVFLAGS(xp_majors[mindex]) |= LIS_MODFLG_CLONE; #endif if (major == 0) major = xp_majors[0]; } if ((err = register_nit(&xp_cdev)) < 0) { cmn_err(CE_WARN, "%s: Could not register with nit driver, err = %d", DRV_NAME, err); sl_x400pterminate(); return (err); } if ((err = register_bpf(&xp_cdev)) < 0) { cmn_err(CE_WARN, "%s: Could not register with bpf driver, err = %d", DRV_NAME, err); sl_x400pterminate(); return (err); } return (0); } /* * Linux Kernel Module Initialization * ------------------------------------------------------------------------- */ module_init(sl_x400pinit); module_exit(sl_x400pterminate); #endif /* LINUX */
kerr-huang/openss7
src/drivers/sl_x400p.c
C
agpl-3.0
1,008,459
/* * Generated by asn1c-0.9.29 (http://lionet.info/asn1c) * From ASN.1 module "NGAP-IEs" * found in "../support/ngap-r16.4.0/38413-g40.asn" * `asn1c -pdu=all -fcompound-names -findirect-choice -fno-include-deps -no-gen-BER -no-gen-XER -no-gen-OER -no-gen-UPER` */ #ifndef _NGAP_RATRestrictions_H_ #define _NGAP_RATRestrictions_H_ #include <asn_application.h> /* Including external dependencies */ #include <asn_SEQUENCE_OF.h> #include <constr_SEQUENCE_OF.h> #ifdef __cplusplus extern "C" { #endif /* Forward declarations */ struct NGAP_RATRestrictions_Item; /* NGAP_RATRestrictions */ typedef struct NGAP_RATRestrictions { A_SEQUENCE_OF(struct NGAP_RATRestrictions_Item) list; /* Context for parsing across buffer boundaries */ asn_struct_ctx_t _asn_ctx; } NGAP_RATRestrictions_t; /* Implementation */ extern asn_TYPE_descriptor_t asn_DEF_NGAP_RATRestrictions; extern asn_SET_OF_specifics_t asn_SPC_NGAP_RATRestrictions_specs_1; extern asn_TYPE_member_t asn_MBR_NGAP_RATRestrictions_1[1]; extern asn_per_constraints_t asn_PER_type_NGAP_RATRestrictions_constr_1; #ifdef __cplusplus } #endif #endif /* _NGAP_RATRestrictions_H_ */ #include <asn_internal.h>
acetcom/nextepc
lib/asn1c/ngap/NGAP_RATRestrictions.h
C
agpl-3.0
1,176
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2017.11.06 at 05:19:55 PM ICT // package org.opencps.api.dossierlog.model; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="total" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/> * &lt;element name="data" type="{}DossierLogModel" maxOccurs="unbounded" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "total", "data" }) @XmlRootElement(name = "DossierLogResultsModel") public class DossierLogResultsModel { protected Integer total; protected List<DossierLogModel> data; /** * Gets the value of the total property. * * @return * possible object is * {@link Integer } * */ public Integer getTotal() { return total; } /** * Sets the value of the total property. * * @param value * allowed object is * {@link Integer } * */ public void setTotal(Integer value) { this.total = value; } /** * Gets the value of the data property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the data property. * * <p> * For example, to add a new item, do as follows: * <pre> * getData().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link DossierLogModel } * * */ public List<DossierLogModel> getData() { if (data == null) { data = new ArrayList<DossierLogModel>(); } return this.data; } }
VietOpenCPS/opencps-v2
modules/backend-api-rest/src/main/java/org/opencps/api/dossierlog/model/DossierLogResultsModel.java
Java
agpl-3.0
2,858
<?php namespace App\AdminBundle\Entity; use Symfony\Component\Validator\Constraints as Assert; use Doctrine\ORM\Mapping as ORM; /** * @ORM\Entity * @ORM\Table(name="User") * @ORM\Entity(repositoryClass="App\AdminBundle\Entity\UserRepository") */ class User { /** * @ORM\Id * @ORM\Column(type="integer") * @ORM\GeneratedValue(strategy="AUTO") */ private $id; /** * @ORM\Column(type="string") * @Assert\NotBlank() */ private $nombre; /** * @ORM\Column(type="string") * @Assert\NotBlank() */ private $apellido; /** * @ORM\Column(type="string") */ private $sexo; /** * @ORM\Column(type="integer") * @Assert\Max(limit = 99, message = "No puedes tener más de 99 años.") * @Assert\Min(limit = 14, message = "No puedes tener menos de 14 años.") */ private $edad; /** * @ORM\Column(type="string",name="fecha_nacimiento") */ private $fechaNacimiento; /** * @ORM\Column(type="string",name="lugar_nacimiento") */ private $lugarNacimiento; /** * @ORM\Column(type="string",name="documento_id") */ private $documentoId; /** * @ORM\Column(type="string") */ private $departamento; /** * @ORM\Column(type="string") */ private $ciudad; /** * @ORM\Column(type="string") */ private $direccion; /** * @ORM\Column(type="integer") * @Assert\NotNull() * @Assert\Max(limit = 3, message = "Lo sentimos, está beca solo aplica para estratos de 1 a 3.") * @Assert\Min(limit = 1, message = "Lo sentimos, está beca solo aplica para estratos de 1 a 3.") */ private $estrato; /** * @ORM\Column(type="string") */ private $telefono; /** * @ORM\Column(type="string") */ private $correo; /** * @ORM\Column(type="string") */ private $acudiente; /** * @ORM\Column(type="string") */ private $parentesco; /** * @ORM\Column(type="string",name="estado_civil") */ private $estadoCivil; /** * @ORM\Column(type="integer",name="numeros_hermanos") */ private $numerosHermanos; /** * @ORM\Column(type="string",name="carrera_del_aspirante") */ private $carreraDelAspirante; /** * @ORM\Column(type="string",name="nombre_colegio") */ private $nombreColegio; /** * @ORM\Column(type="string",name="municipio_colegio") */ private $municipioColegio; /** * @ORM\Column(type="string",name="telefono_colegio") */ private $telefonoColegio; /** * @ORM\Column(type="string",name="nombre_rector_colegio") */ private $nombreRectorColegio; /** * @ORM\Column(type="string",name="fecha_graduacion") */ private $fechaGraduacion; /** * @ORM\Column(type="string",name="tipo_documento_icfes") */ private $tipoDocumentoIcfes; /** * @ORM\Column(type="string",name="documento_id_icfes") */ private $documentoIdIcfes; /** * @ORM\Column(type="decimal",name="promedio_icfes") */ private $promedioIcfes; /** * @ORM\Column(type="decimal",name="punt_matem_icfes") */ private $puntMatemIcfes; /** * @ORM\Column(type="decimal",name="punt_lengu_icfes") */ private $puntLenguIcfes; /** * @ORM\Column(type="decimal",name="punt_fisica_icfes") */ private $puntFisicaIcfes; /** * @ORM\Column(type="decimal",name="punt_filos_icfes") */ private $puntFilosIcfes; /** * @ORM\Column(type="decimal",name="punt_min_nucleo") */ private $puntMinNucleo; /** * @ORM\Column(type="string",name="nombre_padre") */ private $nombrePadre; /** * @ORM\Column(type="string",name="estado_trabajo_padre") */ private $estadoTrabajoPadre; /** * @ORM\Column(type="string",name="trabajo_padre") */ private $trabajoPadre; /** * @ORM\Column(type="string",name="ocupacion_padre") */ private $ocupacionPadre; /** * @ORM\Column(type="string",name="telefono_padre") */ private $telefonoPadre; /** * @ORM\Column(type="string",name="nombre_madre") */ private $nombreMadre; /** * @ORM\Column(type="string",name="estado_trabajo_madre") */ private $estadoTrabajoMadre; /** * @ORM\Column(type="string",name="trabajo_madre") */ private $trabajoMadre; /** * @ORM\Column(type="string",name="ocupacion_madre") */ private $ocupacionMadre; /** * @ORM\Column(type="string",name="telefono_madre") */ private $telefonoMadre; /** * @ORM\Column(type="string",name="estado_civil_padres") */ private $estadoCivilPadres; /** * @ORM\Column(type="string",name="responsable_del_sostenimiento_del_hogar") */ private $responsableDelSostenimientoDelHogar; /** * @ORM\Column(type="string",name="dirrecion_familiar") */ private $dirrecionFamiliar; /** * @ORM\Column(type="string",name="tipo_de_vivienda") */ private $tipoDeVivienda; /** * @ORM\Column(type="integer",name="numero_de_habitantes_en_vivienda") */ private $numeroDeHabitantesEnVivienda; /** * @ORM\Column(type="string",name="creado") */ private $creado; /** * Get id * * @return integer */ public function getId() { return $this->id; } /** * Set nombre * * @param string $nombre */ public function setNombre($nombre) { $this->nombre = $nombre; } /** * Get nombre * * @return string */ public function getNombre() { return $this->nombre; } /** * Set apellido * * @param string $apellido */ public function setApellido($apellido) { $this->apellido = $apellido; } /** * Get apellidoe * * @return string */ public function getApellido() { return $this->apellido; } /** * Set sexo * * @param string $sexo */ public function setSexo($sexo) { $this->sexo = $sexo; } /** * Get sexo * * @return string */ public function getSexo() { return $this->sexo; } /** * Set edad * * @param integer $edad */ public function setEdad($edad) { $this->edad = $edad; } /** * Get edad * * @return integer */ public function getEdad() { return $this->edad; } /** * Set fechaNacimiento * * @param string $fechaNacimiento */ public function setFechaNacimiento($fn) { $this->fechaNacimiento = $fn ; } /** * Get fechaNacimiento * * @return string */ public function getFechaNacimiento() { return $this->fechaNacimiento; } /** * Set lugarNacimiento * * @param string $lugarNacimiento */ public function setLugarNacimiento($lugarNacimiento) { $this->lugarNacimiento = $lugarNacimiento; } /** * Get lugarNacimiento * * @return string */ public function getLugarNacimiento() { return $this->lugarNacimiento; } /** * Set documentoId * * @param string $documentoId */ public function setDocumentoId($documentoId) { $this->creado = \time(); $this->documentoId = $documentoId; } /** * Get documentoId * * @return string */ public function getDocumentoId() { return $this->documentoId; } /** * Set departamento * * @param string $departamento */ public function setDepartamento($departamento) { $this->departamento = $departamento; } /** * Get departamento * * @return string */ public function getDepartamento() { return $this->departamento; } /** * Set ciudad * * @param string $ciudad */ public function setCiudad($ciudad) { $this->ciudad = $ciudad; } /** * Get ciudad * * @return string */ public function getCiudad() { return $this->ciudad; } /** * Set direccion * * @param string $direccion */ public function setDireccion($direccion) { $this->direccion = $direccion; } /** * Get direccion * * @return string */ public function getDireccion() { return $this->direccion; } /** * Set estrato * * @param string $estrato */ public function setEstrato($estrato) { $this->estrato = $estrato; } /** * Get estrato * * @return string */ public function getEstrato() { return $this->estrato; } /** * Set telefono * * @param string $telefono */ public function setTelefono($telefono) { $this->telefono = $telefono; } /** * Get telefono * * @return string */ public function getTelefono() { return $this->telefono; } /** * Set correo * * @param string $correo */ public function setCorreo($correo) { $this->correo = $correo; } /** * Get correo * * @return string */ public function getCorreo() { return $this->correo; } /** * Set acudiente * * @param string $acudiente */ public function setAcudiente($acudiente) { $this->acudiente = $acudiente; } /** * Get acudiente * * @return string */ public function getAcudiente() { return $this->acudiente; } /** * Set parentesco * * @param string $parentesco */ public function setParentesco($parentesco) { $this->parentesco = $parentesco; } /** * Get parentesco * * @return string */ public function getParentesco() { return $this->parentesco; } /** * Set estadoCivil * * @param string $estadoCivil */ public function setEstadoCivil($estadoCivil) { $this->estadoCivil = $estadoCivil; } /** * Get estadoCivil * * @return string */ public function getEstadoCivil() { return $this->estadoCivil; } /** * Set numerosHermanos * * @param integer $numerosHermanos */ public function setNumerosHermanos($numerosHermanos) { $this->numerosHermanos = $numerosHermanos; } /** * Get numerosHermanos * * @return integer */ public function getNumerosHermanos() { return $this->numerosHermanos; } /** * Set carreraDelAspirante * * @param integer $carreraDelAspirante */ public function setCarreraDelAspirante($carreraDelAspirante) { $this->carreraDelAspirante = $carreraDelAspirante; } /** * Get carreraDelAspirante * * @return integer */ public function getCarreraDelAspirante() { return $this->carreraDelAspirante; } /** * Set nombreColegio * * @param string $nombreColegio */ public function setNombreColegio($nombreColegio) { $this->nombreColegio = $nombreColegio; } /** * Get nombreColegio * * @return string */ public function getNombreColegio() { return $this->nombreColegio; } /** * Set municipioColegio * * @param string $municipioColegio */ public function setMunicipioColegio($municipioColegio) { $this->municipioColegio = $municipioColegio; } /** * Get municipioColegio * * @return string */ public function getMunicipioColegio() { return $this->municipioColegio; } /** * Set telefonoColegio * * @param string $telefonoColegio */ public function setTelefonoColegio($telefonoColegio) { $this->telefonoColegio = $telefonoColegio; } /** * Get telefonoColegio * * @return string */ public function getTelefonoColegio() { return $this->telefonoColegio; } /** * Set nombreRectorColegio * * @param string $nombreRectorColegio */ public function setNombreRectorColegio($nombreRectorColegio) { $this->nombreRectorColegio = $nombreRectorColegio; } /** * Get nombreRectorColegio * * @return string */ public function getNombreRectorColegio() { return $this->nombreRectorColegio; } /** * Set fechaGraduacion * * @param string $fechaGraduacion */ public function setFechaGraduacion($fechaGraduacion) { $this->fechaGraduacion = $fechaGraduacion; } /** * Get fechaGraduacion * * @return string */ public function getFechaGraduacion() { return $this->fechaGraduacion; } /** * Set tipoDocumentoIcfes * * @param string $tipoDocumentoIcfes */ public function setTipoDocumentoIcfes($tipoDocumentoIcfes) { $this->tipoDocumentoIcfes = $tipoDocumentoIcfes; } /** * Get tipoDocumentoIcfes * * @return string */ public function getTipoDocumentoIcfes() { return $this->tipoDocumentoIcfes; } /** * Set documentoIdIcfes * * @param string $documentoIdIcfes */ public function setDocumentoIdIcfes($documentoIdIcfes) { $this->documentoIdIcfes = $documentoIdIcfes; } /** * Get documentoIdIcfess * * @return string */ public function getDocumentoIdIcfes() { return $this->documentoIdIcfes; } /** * Set promedioIcfes * * @param decimal $promedioIcfes */ public function setPromedioIcfes($promedioIcfes) { $this->promedioIcfes = $promedioIcfes; } /** * Get promedioIcfes * * @return decimal */ public function getPromedioIcfes() { return $this->promedioIcfes; } /** * Set puntMatemIcfes * * @param decimal $puntMatemIcfes */ public function setPuntMatemIcfes($puntMatemIcfes) { $this->puntMatemIcfes = $puntMatemIcfes; } /** * Get puntMatemIcfes * * @return decimal */ public function getPuntMatemIcfes() { return $this->puntMatemIcfes; } /** * Set puntLenguIcfes * * @param decimal $puntLenguIcfes */ public function setPuntLenguIcfes($puntLenguIcfes) { $this->puntLenguIcfes = $puntLenguIcfes; } /** * Get puntLenguIcfes * * @return decimal */ public function getPuntLenguIcfes() { return $this->puntLenguIcfes; } /** * Set puntFisicaIcfes * * @param decimal $puntFisicaIcfes */ public function setPuntFisicaIcfes($puntFisicaIcfes) { $this->puntFisicaIcfes = $puntFisicaIcfes; } /** * Get puntFisicaIcfes * * @return decimal */ public function getPuntFisicaIcfes() { return $this->puntFisicaIcfes; } /** * Set puntFilosIcfes * * @param decimal $puntFilosIcfes */ public function setPuntFilosIcfes($puntFilosIcfes) { $this->puntFilosIcfes = $puntFilosIcfes; } /** * Get puntFilosIcfes * * @return decimal */ public function getPuntFilosIcfes() { return $this->puntFilosIcfes; } /** * Set puntMinNucleo * * @param decimal $puntMinNucleo */ public function setPuntMinNucleo($puntMinNucleo) { $this->puntMinNucleo = $puntMinNucleo; } /** * Get puntMinNucleo * * @return decimal */ public function getPuntMinNucleo() { return $this->puntMinNucleo; } /** * Set nombrePadre * * @param string $nombrePadre */ public function setNombrePadre($nombrePadre) { $this->nombrePadre = $nombrePadre; } /** * Get nombrePadre * * @return string */ public function getNombrePadre() { return $this->nombrePadre; } /** * Set estadoTrabajoPadre * * @param string $estadoTrabajoPadre */ public function setEstadoTrabajoPadre($estadoTrabajoPadre) { $this->estadoTrabajoPadre = $estadoTrabajoPadre; } /** * Get estadoTrabajoPadre * * @return string */ public function getEstadoTrabajoPadre() { return $this->estadoTrabajoPadre; } /** * Set trabajoPadre * * @param string $trabajoPadre */ public function setTrabajoPadre($trabajoPadre) { $this->trabajoPadre = $trabajoPadre; } /** * Get trabajoPadre * * @return string */ public function getTrabajoPadre() { return $this->trabajoPadre; } /** * Set ocupacionPadre * * @param string $ocupacionPadre */ public function setOcupacionPadre($ocupacionPadre) { $this->ocupacionPadre = $ocupacionPadre; } /** * Get ocupacionPadre * * @return string */ public function getOcupacionPadre() { return $this->ocupacionPadre; } /** * Set telefonoPadre * * @param string $telefonoPadre */ public function setTelefonoPadre($telefonoPadre) { $this->telefonoPadre = $telefonoPadre; } /** * Get telefonoPadre * * @return string */ public function getTelefonoPadre() { return $this->telefonoPadre; } /** * Set nombreMadre * * @param string $nombreMadre */ public function setNombreMadre($nombreMadre) { $this->nombreMadre = $nombreMadre; } /** * Get nombreMadre * * @return string */ public function getNombreMadre() { return $this->nombreMadre; } /** * Set estadoTrabajoMadre * * @param string $estadoTrabajoMadre */ public function setEstadoTrabajoMadre($estadoTrabajoMadre) { $this->estadoTrabajoMadre = $estadoTrabajoMadre; } /** * Get estadoTrabajoMadre * * @return string */ public function getEstadoTrabajoMadre() { return $this->estadoTrabajoMadre; } /** * Set trabajoMadre * * @param string $trabajoMadre */ public function setTrabajoMadre($trabajoMadre) { $this->trabajoMadre = $trabajoMadre; } /** * Get trabajoMadre * * @return string */ public function getTrabajoMadre() { return $this->trabajoMadre; } /** * Set ocupacionMadre * * @param string $ocupacionMadre */ public function setOcupacionMadre($ocupacionMadre) { $this->ocupacionMadre = $ocupacionMadre; } /** * Get ocupacionMadre * * @return string */ public function getOcupacionMadre() { return $this->ocupacionMadre; } /** * Set telefonoMadre * * @param integer $telefonoMadre */ public function setTelefonoMadre($telefonoMadre) { $this->telefonoMadre = $telefonoMadre; } /** * Get telefonoMadre * * @return integer */ public function getTelefonoMadre() { return $this->telefonoMadre; } /** * Set estadoCivilPadres * * @param string $estadoCivilPadres */ public function setEstadoCivilPadres($estadoCivilPadres) { $this->estadoCivilPadres = $estadoCivilPadres; } /** * Get estadoCivilPadres * * @return string */ public function getEstadoCivilPadres() { return $this->estadoCivilPadres; } /** * Set responsableDelSostenimientoDelHogar * * @param string $responsableDelSostenimientoDelHogar */ public function setResponsableDelSostenimientoDelHogar($responsableDelSostenimientoDelHogar) { $this->responsableDelSostenimientoDelHogar = $responsableDelSostenimientoDelHogar; } /** * Get responsableDelSostenimientoDelHogar * * @return string */ public function getResponsableDelSostenimientoDelHogar() { return $this->responsableDelSostenimientoDelHogar; } /** * Set dirrecionFamiliar * * @param string $dirrecionFamiliar */ public function setDirrecionFamiliar($dirrecionFamiliar) { $this->dirrecionFamiliar = $dirrecionFamiliar; } /** * Get dirrecionFamiliar * * @return string */ public function getDirrecionFamiliar() { return $this->dirrecionFamiliar; } /** * Set tipoDeVivienda * * @param string $tipoDeVivienda */ public function setTipoDeVivienda($tipoDeVivienda) { $this->tipoDeVivienda = $tipoDeVivienda; } /** * Get tipoDeVivienda * * @return string */ public function getTipoDeVivienda() { return $this->tipoDeVivienda; } /** * Set numeroDeHabitantesEnVivienda * * @param integer $numeroDeHabitantesEnVivienda */ public function setNumeroDeHabitantesEnVivienda($numeroDeHabitantesEnVivienda) { $this->numeroDeHabitantesEnVivienda = $numeroDeHabitantesEnVivienda; } /** * Get numeroDeHabitantesEnVivienda * * @return integer */ public function getNumeroDeHabitantesEnVivienda() { return $this->numeroDeHabitantesEnVivienda; } }
jairoserrano/becasUTB
src/App/AdminBundle/Entity/User.php
PHP
agpl-3.0
22,224
import factory from .models import User USER_PASSWORD = "2fast2furious" class UserFactory(factory.DjangoModelFactory): name = "John Doe" email = factory.Sequence(lambda n: "john{}@example.com".format(n)) password = factory.PostGenerationMethodCall('set_password', USER_PASSWORD) gender = "male" class Meta: model = User
ballotify/django-backend
ballotify/apps/accounts/factories.py
Python
agpl-3.0
353
// ----------> GENERATED FILE - DON'T TOUCH! <---------- // generator: ilarkesto.mda.legacy.generator.DaoGenerator package scrum.server.admin; import java.util.*; import ilarkesto.persistence.*; import ilarkesto.core.logging.Log; import ilarkesto.base.*; import ilarkesto.base.time.*; import ilarkesto.auth.*; import ilarkesto.fp.*; public abstract class GUserDao extends ilarkesto.auth.AUserDao<User> { public final String getEntityName() { return User.TYPE; } public final Class getEntityClass() { return User.class; } public Set<User> getEntitiesVisibleForUser(final scrum.server.admin.User user) { return getEntities(new Predicate<User>() { public boolean test(User e) { return Auth.isVisible(e, user); } }); } // --- clear caches --- public void clearCaches() { namesCache = null; usersByAdminCache.clear(); usersByEmailVerifiedCache.clear(); emailsCache = null; usersByCurrentProjectCache.clear(); currentProjectsCache = null; usersByColorCache.clear(); colorsCache = null; usersByLastLoginDateAndTimeCache.clear(); lastLoginDateAndTimesCache = null; usersByRegistrationDateAndTimeCache.clear(); registrationDateAndTimesCache = null; usersByDisabledCache.clear(); usersByHideUserGuideBlogCache.clear(); usersByHideUserGuideCalendarCache.clear(); usersByHideUserGuideFilesCache.clear(); usersByHideUserGuideForumCache.clear(); usersByHideUserGuideImpedimentsCache.clear(); usersByHideUserGuideIssuesCache.clear(); usersByHideUserGuideJournalCache.clear(); usersByHideUserGuideNextSprintCache.clear(); usersByHideUserGuideProductBacklogCache.clear(); usersByHideUserGuideCourtroomCache.clear(); usersByHideUserGuideQualityBacklogCache.clear(); usersByHideUserGuideReleasesCache.clear(); usersByHideUserGuideRisksCache.clear(); usersByHideUserGuideSprintBacklogCache.clear(); usersByHideUserGuideWhiteboardCache.clear(); loginTokensCache = null; openIdsCache = null; } @Override public void entityDeleted(EntityEvent event) { super.entityDeleted(event); if (event.getEntity() instanceof User) { clearCaches(); } } @Override public void entitySaved(EntityEvent event) { super.entitySaved(event); if (event.getEntity() instanceof User) { clearCaches(); } } // ----------------------------------------------------------- // - name // ----------------------------------------------------------- public final User getUserByName(java.lang.String name) { return getEntity(new IsName(name)); } private Set<java.lang.String> namesCache; public final Set<java.lang.String> getNames() { if (namesCache == null) { namesCache = new HashSet<java.lang.String>(); for (User e : getEntities()) { if (e.isNameSet()) namesCache.add(e.getName()); } } return namesCache; } private static class IsName implements Predicate<User> { private java.lang.String value; public IsName(java.lang.String value) { this.value = value; } public boolean test(User e) { return e.isName(value); } } // ----------------------------------------------------------- // - admin // ----------------------------------------------------------- private final Cache<Boolean,Set<User>> usersByAdminCache = new Cache<Boolean,Set<User>>( new Cache.Factory<Boolean,Set<User>>() { public Set<User> create(Boolean admin) { return getEntities(new IsAdmin(admin)); } }); public final Set<User> getUsersByAdmin(boolean admin) { return usersByAdminCache.get(admin); } private static class IsAdmin implements Predicate<User> { private boolean value; public IsAdmin(boolean value) { this.value = value; } public boolean test(User e) { return value == e.isAdmin(); } } // ----------------------------------------------------------- // - emailVerified // ----------------------------------------------------------- private final Cache<Boolean,Set<User>> usersByEmailVerifiedCache = new Cache<Boolean,Set<User>>( new Cache.Factory<Boolean,Set<User>>() { public Set<User> create(Boolean emailVerified) { return getEntities(new IsEmailVerified(emailVerified)); } }); public final Set<User> getUsersByEmailVerified(boolean emailVerified) { return usersByEmailVerifiedCache.get(emailVerified); } private static class IsEmailVerified implements Predicate<User> { private boolean value; public IsEmailVerified(boolean value) { this.value = value; } public boolean test(User e) { return value == e.isEmailVerified(); } } // ----------------------------------------------------------- // - email // ----------------------------------------------------------- public final User getUserByEmail(java.lang.String email) { return getEntity(new IsEmail(email)); } private Set<java.lang.String> emailsCache; public final Set<java.lang.String> getEmails() { if (emailsCache == null) { emailsCache = new HashSet<java.lang.String>(); for (User e : getEntities()) { if (e.isEmailSet()) emailsCache.add(e.getEmail()); } } return emailsCache; } private static class IsEmail implements Predicate<User> { private java.lang.String value; public IsEmail(java.lang.String value) { this.value = value; } public boolean test(User e) { return e.isEmail(value); } } // ----------------------------------------------------------- // - currentProject // ----------------------------------------------------------- private final Cache<scrum.server.project.Project,Set<User>> usersByCurrentProjectCache = new Cache<scrum.server.project.Project,Set<User>>( new Cache.Factory<scrum.server.project.Project,Set<User>>() { public Set<User> create(scrum.server.project.Project currentProject) { return getEntities(new IsCurrentProject(currentProject)); } }); public final Set<User> getUsersByCurrentProject(scrum.server.project.Project currentProject) { return usersByCurrentProjectCache.get(currentProject); } private Set<scrum.server.project.Project> currentProjectsCache; public final Set<scrum.server.project.Project> getCurrentProjects() { if (currentProjectsCache == null) { currentProjectsCache = new HashSet<scrum.server.project.Project>(); for (User e : getEntities()) { if (e.isCurrentProjectSet()) currentProjectsCache.add(e.getCurrentProject()); } } return currentProjectsCache; } private static class IsCurrentProject implements Predicate<User> { private scrum.server.project.Project value; public IsCurrentProject(scrum.server.project.Project value) { this.value = value; } public boolean test(User e) { return e.isCurrentProject(value); } } // ----------------------------------------------------------- // - color // ----------------------------------------------------------- private final Cache<java.lang.String,Set<User>> usersByColorCache = new Cache<java.lang.String,Set<User>>( new Cache.Factory<java.lang.String,Set<User>>() { public Set<User> create(java.lang.String color) { return getEntities(new IsColor(color)); } }); public final Set<User> getUsersByColor(java.lang.String color) { return usersByColorCache.get(color); } private Set<java.lang.String> colorsCache; public final Set<java.lang.String> getColors() { if (colorsCache == null) { colorsCache = new HashSet<java.lang.String>(); for (User e : getEntities()) { if (e.isColorSet()) colorsCache.add(e.getColor()); } } return colorsCache; } private static class IsColor implements Predicate<User> { private java.lang.String value; public IsColor(java.lang.String value) { this.value = value; } public boolean test(User e) { return e.isColor(value); } } // ----------------------------------------------------------- // - lastLoginDateAndTime // ----------------------------------------------------------- private final Cache<ilarkesto.base.time.DateAndTime,Set<User>> usersByLastLoginDateAndTimeCache = new Cache<ilarkesto.base.time.DateAndTime,Set<User>>( new Cache.Factory<ilarkesto.base.time.DateAndTime,Set<User>>() { public Set<User> create(ilarkesto.base.time.DateAndTime lastLoginDateAndTime) { return getEntities(new IsLastLoginDateAndTime(lastLoginDateAndTime)); } }); public final Set<User> getUsersByLastLoginDateAndTime(ilarkesto.base.time.DateAndTime lastLoginDateAndTime) { return usersByLastLoginDateAndTimeCache.get(lastLoginDateAndTime); } private Set<ilarkesto.base.time.DateAndTime> lastLoginDateAndTimesCache; public final Set<ilarkesto.base.time.DateAndTime> getLastLoginDateAndTimes() { if (lastLoginDateAndTimesCache == null) { lastLoginDateAndTimesCache = new HashSet<ilarkesto.base.time.DateAndTime>(); for (User e : getEntities()) { if (e.isLastLoginDateAndTimeSet()) lastLoginDateAndTimesCache.add(e.getLastLoginDateAndTime()); } } return lastLoginDateAndTimesCache; } private static class IsLastLoginDateAndTime implements Predicate<User> { private ilarkesto.base.time.DateAndTime value; public IsLastLoginDateAndTime(ilarkesto.base.time.DateAndTime value) { this.value = value; } public boolean test(User e) { return e.isLastLoginDateAndTime(value); } } // ----------------------------------------------------------- // - registrationDateAndTime // ----------------------------------------------------------- private final Cache<ilarkesto.base.time.DateAndTime,Set<User>> usersByRegistrationDateAndTimeCache = new Cache<ilarkesto.base.time.DateAndTime,Set<User>>( new Cache.Factory<ilarkesto.base.time.DateAndTime,Set<User>>() { public Set<User> create(ilarkesto.base.time.DateAndTime registrationDateAndTime) { return getEntities(new IsRegistrationDateAndTime(registrationDateAndTime)); } }); public final Set<User> getUsersByRegistrationDateAndTime(ilarkesto.base.time.DateAndTime registrationDateAndTime) { return usersByRegistrationDateAndTimeCache.get(registrationDateAndTime); } private Set<ilarkesto.base.time.DateAndTime> registrationDateAndTimesCache; public final Set<ilarkesto.base.time.DateAndTime> getRegistrationDateAndTimes() { if (registrationDateAndTimesCache == null) { registrationDateAndTimesCache = new HashSet<ilarkesto.base.time.DateAndTime>(); for (User e : getEntities()) { if (e.isRegistrationDateAndTimeSet()) registrationDateAndTimesCache.add(e.getRegistrationDateAndTime()); } } return registrationDateAndTimesCache; } private static class IsRegistrationDateAndTime implements Predicate<User> { private ilarkesto.base.time.DateAndTime value; public IsRegistrationDateAndTime(ilarkesto.base.time.DateAndTime value) { this.value = value; } public boolean test(User e) { return e.isRegistrationDateAndTime(value); } } // ----------------------------------------------------------- // - disabled // ----------------------------------------------------------- private final Cache<Boolean,Set<User>> usersByDisabledCache = new Cache<Boolean,Set<User>>( new Cache.Factory<Boolean,Set<User>>() { public Set<User> create(Boolean disabled) { return getEntities(new IsDisabled(disabled)); } }); public final Set<User> getUsersByDisabled(boolean disabled) { return usersByDisabledCache.get(disabled); } private static class IsDisabled implements Predicate<User> { private boolean value; public IsDisabled(boolean value) { this.value = value; } public boolean test(User e) { return value == e.isDisabled(); } } // ----------------------------------------------------------- // - hideUserGuideBlog // ----------------------------------------------------------- private final Cache<Boolean,Set<User>> usersByHideUserGuideBlogCache = new Cache<Boolean,Set<User>>( new Cache.Factory<Boolean,Set<User>>() { public Set<User> create(Boolean hideUserGuideBlog) { return getEntities(new IsHideUserGuideBlog(hideUserGuideBlog)); } }); public final Set<User> getUsersByHideUserGuideBlog(boolean hideUserGuideBlog) { return usersByHideUserGuideBlogCache.get(hideUserGuideBlog); } private static class IsHideUserGuideBlog implements Predicate<User> { private boolean value; public IsHideUserGuideBlog(boolean value) { this.value = value; } public boolean test(User e) { return value == e.isHideUserGuideBlog(); } } // ----------------------------------------------------------- // - hideUserGuideCalendar // ----------------------------------------------------------- private final Cache<Boolean,Set<User>> usersByHideUserGuideCalendarCache = new Cache<Boolean,Set<User>>( new Cache.Factory<Boolean,Set<User>>() { public Set<User> create(Boolean hideUserGuideCalendar) { return getEntities(new IsHideUserGuideCalendar(hideUserGuideCalendar)); } }); public final Set<User> getUsersByHideUserGuideCalendar(boolean hideUserGuideCalendar) { return usersByHideUserGuideCalendarCache.get(hideUserGuideCalendar); } private static class IsHideUserGuideCalendar implements Predicate<User> { private boolean value; public IsHideUserGuideCalendar(boolean value) { this.value = value; } public boolean test(User e) { return value == e.isHideUserGuideCalendar(); } } // ----------------------------------------------------------- // - hideUserGuideFiles // ----------------------------------------------------------- private final Cache<Boolean,Set<User>> usersByHideUserGuideFilesCache = new Cache<Boolean,Set<User>>( new Cache.Factory<Boolean,Set<User>>() { public Set<User> create(Boolean hideUserGuideFiles) { return getEntities(new IsHideUserGuideFiles(hideUserGuideFiles)); } }); public final Set<User> getUsersByHideUserGuideFiles(boolean hideUserGuideFiles) { return usersByHideUserGuideFilesCache.get(hideUserGuideFiles); } private static class IsHideUserGuideFiles implements Predicate<User> { private boolean value; public IsHideUserGuideFiles(boolean value) { this.value = value; } public boolean test(User e) { return value == e.isHideUserGuideFiles(); } } // ----------------------------------------------------------- // - hideUserGuideForum // ----------------------------------------------------------- private final Cache<Boolean,Set<User>> usersByHideUserGuideForumCache = new Cache<Boolean,Set<User>>( new Cache.Factory<Boolean,Set<User>>() { public Set<User> create(Boolean hideUserGuideForum) { return getEntities(new IsHideUserGuideForum(hideUserGuideForum)); } }); public final Set<User> getUsersByHideUserGuideForum(boolean hideUserGuideForum) { return usersByHideUserGuideForumCache.get(hideUserGuideForum); } private static class IsHideUserGuideForum implements Predicate<User> { private boolean value; public IsHideUserGuideForum(boolean value) { this.value = value; } public boolean test(User e) { return value == e.isHideUserGuideForum(); } } // ----------------------------------------------------------- // - hideUserGuideImpediments // ----------------------------------------------------------- private final Cache<Boolean,Set<User>> usersByHideUserGuideImpedimentsCache = new Cache<Boolean,Set<User>>( new Cache.Factory<Boolean,Set<User>>() { public Set<User> create(Boolean hideUserGuideImpediments) { return getEntities(new IsHideUserGuideImpediments(hideUserGuideImpediments)); } }); public final Set<User> getUsersByHideUserGuideImpediments(boolean hideUserGuideImpediments) { return usersByHideUserGuideImpedimentsCache.get(hideUserGuideImpediments); } private static class IsHideUserGuideImpediments implements Predicate<User> { private boolean value; public IsHideUserGuideImpediments(boolean value) { this.value = value; } public boolean test(User e) { return value == e.isHideUserGuideImpediments(); } } // ----------------------------------------------------------- // - hideUserGuideIssues // ----------------------------------------------------------- private final Cache<Boolean,Set<User>> usersByHideUserGuideIssuesCache = new Cache<Boolean,Set<User>>( new Cache.Factory<Boolean,Set<User>>() { public Set<User> create(Boolean hideUserGuideIssues) { return getEntities(new IsHideUserGuideIssues(hideUserGuideIssues)); } }); public final Set<User> getUsersByHideUserGuideIssues(boolean hideUserGuideIssues) { return usersByHideUserGuideIssuesCache.get(hideUserGuideIssues); } private static class IsHideUserGuideIssues implements Predicate<User> { private boolean value; public IsHideUserGuideIssues(boolean value) { this.value = value; } public boolean test(User e) { return value == e.isHideUserGuideIssues(); } } // ----------------------------------------------------------- // - hideUserGuideJournal // ----------------------------------------------------------- private final Cache<Boolean,Set<User>> usersByHideUserGuideJournalCache = new Cache<Boolean,Set<User>>( new Cache.Factory<Boolean,Set<User>>() { public Set<User> create(Boolean hideUserGuideJournal) { return getEntities(new IsHideUserGuideJournal(hideUserGuideJournal)); } }); public final Set<User> getUsersByHideUserGuideJournal(boolean hideUserGuideJournal) { return usersByHideUserGuideJournalCache.get(hideUserGuideJournal); } private static class IsHideUserGuideJournal implements Predicate<User> { private boolean value; public IsHideUserGuideJournal(boolean value) { this.value = value; } public boolean test(User e) { return value == e.isHideUserGuideJournal(); } } // ----------------------------------------------------------- // - hideUserGuideNextSprint // ----------------------------------------------------------- private final Cache<Boolean,Set<User>> usersByHideUserGuideNextSprintCache = new Cache<Boolean,Set<User>>( new Cache.Factory<Boolean,Set<User>>() { public Set<User> create(Boolean hideUserGuideNextSprint) { return getEntities(new IsHideUserGuideNextSprint(hideUserGuideNextSprint)); } }); public final Set<User> getUsersByHideUserGuideNextSprint(boolean hideUserGuideNextSprint) { return usersByHideUserGuideNextSprintCache.get(hideUserGuideNextSprint); } private static class IsHideUserGuideNextSprint implements Predicate<User> { private boolean value; public IsHideUserGuideNextSprint(boolean value) { this.value = value; } public boolean test(User e) { return value == e.isHideUserGuideNextSprint(); } } // ----------------------------------------------------------- // - hideUserGuideProductBacklog // ----------------------------------------------------------- private final Cache<Boolean,Set<User>> usersByHideUserGuideProductBacklogCache = new Cache<Boolean,Set<User>>( new Cache.Factory<Boolean,Set<User>>() { public Set<User> create(Boolean hideUserGuideProductBacklog) { return getEntities(new IsHideUserGuideProductBacklog(hideUserGuideProductBacklog)); } }); public final Set<User> getUsersByHideUserGuideProductBacklog(boolean hideUserGuideProductBacklog) { return usersByHideUserGuideProductBacklogCache.get(hideUserGuideProductBacklog); } private static class IsHideUserGuideProductBacklog implements Predicate<User> { private boolean value; public IsHideUserGuideProductBacklog(boolean value) { this.value = value; } public boolean test(User e) { return value == e.isHideUserGuideProductBacklog(); } } // ----------------------------------------------------------- // - hideUserGuideCourtroom // ----------------------------------------------------------- private final Cache<Boolean,Set<User>> usersByHideUserGuideCourtroomCache = new Cache<Boolean,Set<User>>( new Cache.Factory<Boolean,Set<User>>() { public Set<User> create(Boolean hideUserGuideCourtroom) { return getEntities(new IsHideUserGuideCourtroom(hideUserGuideCourtroom)); } }); public final Set<User> getUsersByHideUserGuideCourtroom(boolean hideUserGuideCourtroom) { return usersByHideUserGuideCourtroomCache.get(hideUserGuideCourtroom); } private static class IsHideUserGuideCourtroom implements Predicate<User> { private boolean value; public IsHideUserGuideCourtroom(boolean value) { this.value = value; } public boolean test(User e) { return value == e.isHideUserGuideCourtroom(); } } // ----------------------------------------------------------- // - hideUserGuideQualityBacklog // ----------------------------------------------------------- private final Cache<Boolean,Set<User>> usersByHideUserGuideQualityBacklogCache = new Cache<Boolean,Set<User>>( new Cache.Factory<Boolean,Set<User>>() { public Set<User> create(Boolean hideUserGuideQualityBacklog) { return getEntities(new IsHideUserGuideQualityBacklog(hideUserGuideQualityBacklog)); } }); public final Set<User> getUsersByHideUserGuideQualityBacklog(boolean hideUserGuideQualityBacklog) { return usersByHideUserGuideQualityBacklogCache.get(hideUserGuideQualityBacklog); } private static class IsHideUserGuideQualityBacklog implements Predicate<User> { private boolean value; public IsHideUserGuideQualityBacklog(boolean value) { this.value = value; } public boolean test(User e) { return value == e.isHideUserGuideQualityBacklog(); } } // ----------------------------------------------------------- // - hideUserGuideReleases // ----------------------------------------------------------- private final Cache<Boolean,Set<User>> usersByHideUserGuideReleasesCache = new Cache<Boolean,Set<User>>( new Cache.Factory<Boolean,Set<User>>() { public Set<User> create(Boolean hideUserGuideReleases) { return getEntities(new IsHideUserGuideReleases(hideUserGuideReleases)); } }); public final Set<User> getUsersByHideUserGuideReleases(boolean hideUserGuideReleases) { return usersByHideUserGuideReleasesCache.get(hideUserGuideReleases); } private static class IsHideUserGuideReleases implements Predicate<User> { private boolean value; public IsHideUserGuideReleases(boolean value) { this.value = value; } public boolean test(User e) { return value == e.isHideUserGuideReleases(); } } // ----------------------------------------------------------- // - hideUserGuideRisks // ----------------------------------------------------------- private final Cache<Boolean,Set<User>> usersByHideUserGuideRisksCache = new Cache<Boolean,Set<User>>( new Cache.Factory<Boolean,Set<User>>() { public Set<User> create(Boolean hideUserGuideRisks) { return getEntities(new IsHideUserGuideRisks(hideUserGuideRisks)); } }); public final Set<User> getUsersByHideUserGuideRisks(boolean hideUserGuideRisks) { return usersByHideUserGuideRisksCache.get(hideUserGuideRisks); } private static class IsHideUserGuideRisks implements Predicate<User> { private boolean value; public IsHideUserGuideRisks(boolean value) { this.value = value; } public boolean test(User e) { return value == e.isHideUserGuideRisks(); } } // ----------------------------------------------------------- // - hideUserGuideSprintBacklog // ----------------------------------------------------------- private final Cache<Boolean,Set<User>> usersByHideUserGuideSprintBacklogCache = new Cache<Boolean,Set<User>>( new Cache.Factory<Boolean,Set<User>>() { public Set<User> create(Boolean hideUserGuideSprintBacklog) { return getEntities(new IsHideUserGuideSprintBacklog(hideUserGuideSprintBacklog)); } }); public final Set<User> getUsersByHideUserGuideSprintBacklog(boolean hideUserGuideSprintBacklog) { return usersByHideUserGuideSprintBacklogCache.get(hideUserGuideSprintBacklog); } private static class IsHideUserGuideSprintBacklog implements Predicate<User> { private boolean value; public IsHideUserGuideSprintBacklog(boolean value) { this.value = value; } public boolean test(User e) { return value == e.isHideUserGuideSprintBacklog(); } } // ----------------------------------------------------------- // - hideUserGuideWhiteboard // ----------------------------------------------------------- private final Cache<Boolean,Set<User>> usersByHideUserGuideWhiteboardCache = new Cache<Boolean,Set<User>>( new Cache.Factory<Boolean,Set<User>>() { public Set<User> create(Boolean hideUserGuideWhiteboard) { return getEntities(new IsHideUserGuideWhiteboard(hideUserGuideWhiteboard)); } }); public final Set<User> getUsersByHideUserGuideWhiteboard(boolean hideUserGuideWhiteboard) { return usersByHideUserGuideWhiteboardCache.get(hideUserGuideWhiteboard); } private static class IsHideUserGuideWhiteboard implements Predicate<User> { private boolean value; public IsHideUserGuideWhiteboard(boolean value) { this.value = value; } public boolean test(User e) { return value == e.isHideUserGuideWhiteboard(); } } // ----------------------------------------------------------- // - loginToken // ----------------------------------------------------------- public final User getUserByLoginToken(java.lang.String loginToken) { return getEntity(new IsLoginToken(loginToken)); } private Set<java.lang.String> loginTokensCache; public final Set<java.lang.String> getLoginTokens() { if (loginTokensCache == null) { loginTokensCache = new HashSet<java.lang.String>(); for (User e : getEntities()) { if (e.isLoginTokenSet()) loginTokensCache.add(e.getLoginToken()); } } return loginTokensCache; } private static class IsLoginToken implements Predicate<User> { private java.lang.String value; public IsLoginToken(java.lang.String value) { this.value = value; } public boolean test(User e) { return e.isLoginToken(value); } } // ----------------------------------------------------------- // - openId // ----------------------------------------------------------- public final User getUserByOpenId(java.lang.String openId) { return getEntity(new IsOpenId(openId)); } private Set<java.lang.String> openIdsCache; public final Set<java.lang.String> getOpenIds() { if (openIdsCache == null) { openIdsCache = new HashSet<java.lang.String>(); for (User e : getEntities()) { if (e.isOpenIdSet()) openIdsCache.add(e.getOpenId()); } } return openIdsCache; } private static class IsOpenId implements Predicate<User> { private java.lang.String value; public IsOpenId(java.lang.String value) { this.value = value; } public boolean test(User e) { return e.isOpenId(value); } } // --- valueObject classes --- @Override protected Set<Class> getValueObjectClasses() { Set<Class> ret = new HashSet<Class>(super.getValueObjectClasses()); return ret; } @Override public Map<String, Class> getAliases() { Map<String, Class> aliases = new HashMap<String, Class>(super.getAliases()); return aliases; } // --- dependencies --- scrum.server.project.ProjectDao projectDao; public void setProjectDao(scrum.server.project.ProjectDao projectDao) { this.projectDao = projectDao; } }
hogi/kunagi
src/generated/java/scrum/server/admin/GUserDao.java
Java
agpl-3.0
31,402
<ol class="breadcrumb"> <li>Outil de publication</li> <li><a ui-sref="root.account.organizations">Sélection de l'organisation</a></li> <li><a ui-sref="root.account.organization.index({ organizationId: currentOrganization._id })">{{ currentOrganization.name }}</a></li> <li class="active">Sélection du catalogue source</li> </ol> <div ng-if="currentOrganization.sourceCatalog.length" class="alert alert-info"> Actuellement votre organisation est configurée avec le catalogue <strong>{{ selectedCatalog().name }}</strong>. </div> <!-- Catalog --> <div class="panel panel-primary"> <div class="panel-heading"> <h2 class="panel-title"><i class="fa fa-book"></i> Catalogue source</h2> </div> <div class="panel-body"> Choisissez le catalogue à partir duquel vous souhaitez importer les jeux de données : </div> <div class="list-group"> <a href class="list-group-item" ng-click="selectCatalog(catalog)" ng-repeat="catalog in catalogs | orderBy:'name'">{{ catalog.name }}</a> </div> </div>
jdesboeufs/geogw-datagouvfr
app/partials/account/organization/catalog.html
HTML
agpl-3.0
1,049
/* * RapidMiner * * Copyright (C) 2001-2011 by Rapid-I and the contributors * * Complete list of developers available at our web site: * * http://rapid-i.com * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see http://www.gnu.org/licenses/. */ package com.rapidminer.operator; /** * These listeners will be notified after a new operator was added to a chain. * * @author Ingo Mierswa */ public interface AddListener { public void operatorAdded(Operator newChild); }
aborg0/rapidminer-vega
src/com/rapidminer/operator/AddListener.java
Java
agpl-3.0
1,124
package info.nightscout.androidaps.plugins.SmsCommunicator; import android.app.Activity; import android.os.Bundle; import android.support.v4.app.Fragment; import android.text.Html; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.squareup.otto.Subscribe; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Collections; import java.util.Comparator; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.plugins.Common.SubscriberFragment; import info.nightscout.androidaps.plugins.SmsCommunicator.events.EventSmsCommunicatorUpdateGui; import info.nightscout.utils.DateUtil; /** * A simple {@link Fragment} subclass. */ public class SmsCommunicatorFragment extends SubscriberFragment { private static Logger log = LoggerFactory.getLogger(SmsCommunicatorFragment.class); private static SmsCommunicatorPlugin smsCommunicatorPlugin; public static SmsCommunicatorPlugin getPlugin() { if(smsCommunicatorPlugin==null){ smsCommunicatorPlugin = new SmsCommunicatorPlugin(); } return smsCommunicatorPlugin; } TextView logView; public SmsCommunicatorFragment() { super(); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.smscommunicator_fragment, container, false); logView = (TextView) view.findViewById(R.id.smscommunicator_log); updateGUI(); return view; } @Subscribe public void onStatusEvent(final EventSmsCommunicatorUpdateGui ev) { updateGUI(); } @Override protected void updateGUI() { Activity activity = getActivity(); if (activity != null) activity.runOnUiThread(new Runnable() { @Override public void run() { class CustomComparator implements Comparator<SmsCommunicatorPlugin.Sms> { public int compare(SmsCommunicatorPlugin.Sms object1, SmsCommunicatorPlugin.Sms object2) { return (int) (object1.date.getTime() - object2.date.getTime()); } } Collections.sort(getPlugin().messages, new CustomComparator()); int messagesToShow = 40; int start = Math.max(0, getPlugin().messages.size() - messagesToShow); String logText = ""; for (int x = start; x < getPlugin().messages.size(); x++) { SmsCommunicatorPlugin.Sms sms = getPlugin().messages.get(x); if (sms.received) { logText += DateUtil.timeString(sms.date) + " &lt;&lt;&lt; " + (sms.processed ? "● " : "○ ") + sms.phoneNumber + " <b>" + sms.text + "</b><br>"; } else if (sms.sent) { logText += DateUtil.timeString(sms.date) + " &gt;&gt;&gt; " + (sms.processed ? "● " : "○ ") + sms.phoneNumber + " <b>" + sms.text + "</b><br>"; } } logView.setText(Html.fromHtml(logText)); } }); } }
RoumenGeorgiev/AndroidAPS
app/src/main/java/info/nightscout/androidaps/plugins/SmsCommunicator/SmsCommunicatorFragment.java
Java
agpl-3.0
3,402
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <meta name="description" content="" /> <meta name="keywords" content="" /> <meta name="author" content="" /> <link rel="stylesheet" type="text/css" href="style.css" media="screen" /> <title>ByteJudge</title> </head> <body> <div id="wrapper"> <?php require('./scripts/determineidentityfunc.php'); if(!(isloggedin("admin")==true)) { header('Location: ./home.php'); } else { include("./includes/header.php"); include("includes/nav.php"); echo ' <div id="content"> '; include("./includes/view_facultygroups_form.php"); echo ' </div> <!-- end #content --> '; include("./includes/sidebar.php"); include("./includes/footer.php"); } ?> </div> <!-- End #wrapper --> </body> </html>
jdramani/Judge
ByteJudge/view_facultygroups.php
PHP
agpl-3.0
954
--- _id: 81739fa0-1995-11e8-a313-257d004a4890 date_posted: '2018-02-24' layout: post full_name: John poster_email: [email protected] business_name: Bakery business_url: '' location: North Lamar title: Comment category: management description: >- We are looking for an experienced pastry manager with a background in high volume baking and management experience. qualifications: >- Extensive knowledge of baking and pastries is a must. Experience managing 10+ employees. Knowledge of P&L's, inventory , gross profit reports, etc. and a serious passion for food. job_type: full_time hours: 5am to 3pm start: ASAP compensation: Salary how_to_apply: >- Please contact my personal email ([email protected]) to discuss application process. date: '2018-02-24T19:04:15.083Z' approved: false ---
intheweedsjobs/intheweeds
jobs/2018-02-24-pastry-manager-1519499055084.md
Markdown
agpl-3.0
811
/* * ADL2-core * Copyright (c) 2013-2014 Marand d.o.o. (www.marand.com) * * This file is part of ADL2-core. * * ADL2-core is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.openehr.adl.am.mixin; import com.google.common.collect.ImmutableMap; import org.openehr.jaxb.am.CAttribute; import org.openehr.jaxb.am.Cardinality; import org.openehr.jaxb.rm.*; import java.lang.reflect.Constructor; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * @author markopi */ class AmMixinsInternal { private static final Map<Class<?>, Class<? extends AmMixin>> configuration; private static final Map<Class<?>, Constructor<? extends AmMixin>> constructors; static { Map<Class<?>, Class<? extends AmMixin>> conf = ImmutableMap.<Class<?>, Class<? extends AmMixin>>builder() .put(IntervalOfDate.class, IntervalOfDateMixin.class) .put(IntervalOfTime.class, IntervalOfTimeMixin.class) .put(IntervalOfDateTime.class, IntervalOfDateTimeMixin.class) .put(IntervalOfInteger.class, IntervalOfIntegerMixin.class) .put(IntervalOfReal.class, IntervalOfRealMixin.class) .put(MultiplicityInterval.class, MultiplicityIntervalMixin.class) .put(CAttribute.class, CAttributeMixin.class) .put(IntervalOfDuration.class, IntervalOfDurationMixin.class) .put(Cardinality.class, CardinalityMixin.class) .build(); configuration = ImmutableMap.copyOf(conf); constructors = new ConcurrentHashMap<>(); } static <T, M extends AmMixin<?>> M create(T from) { Constructor<? extends AmMixin> mixinConstructor = getMixinClass(from.getClass()); try { return (M) mixinConstructor.newInstance(from); } catch (ReflectiveOperationException e) { throw new IllegalArgumentException( "Error constructing mixin class " + mixinConstructor.getDeclaringClass() + " for class " + from.getClass()); } } private static Constructor<? extends AmMixin> getMixinClass(Class<?> fromClass) { Constructor<? extends AmMixin> result = constructors.get(fromClass); if (result == null) { Class<?> cls = fromClass; while (cls != null) { Class<? extends AmMixin> mixinClass = configuration.get(cls); if (mixinClass != null) { try { result = mixinClass.getConstructor(fromClass); } catch (NoSuchMethodException e) { throw new IllegalStateException( "Missing mixin " + mixinClass.getName() + " constructor for " + fromClass.getName()); } constructors.put(fromClass, result); return result; } cls = cls.getSuperclass(); } throw new IllegalArgumentException("No mixin defined for class " + fromClass); } return result; } }
lonangel/adl2-core
adl-parser/src/main/java/org/openehr/adl/am/mixin/AmMixinsInternal.java
Java
agpl-3.0
3,715
/* Copyright (c) 2009, Yahoo! Inc. All rights reserved. Code licensed under the BSD License: http://developer.yahoo.net/yui/license.txt version: 2.8.0r4 */ /* Copyright (c) 2008, Yahoo! Inc. All rights reserved. Code licensed under the BSD License: http://developer.yahoo.net/yui/license.txt version: 2.5.2 */ /* the style of the div around each node */ .ygtvitem { } table.ygtvtable { margin-bottom: 0; border: none; border-collapse: collapse; } /*.ygtvitem td {*/ td.ygtvcell { border: none; padding: 0; } a.ygtvspacer { text-decoration: none; outline-style: none; display: block; } /* first or middle sibling, no children */ .ygtvtn { width: 18px; height: 22px; background: url(treeview-sprite.gif) 0 -5600px no-repeat; cursor: pointer; } /* first or middle sibling, collapsable */ .ygtvtm { width: 18px; height: 22px; cursor: pointer; background: url(treeview-sprite.gif) 0 -4000px no-repeat; } /* first or middle sibling, collapsable, hover */ .ygtvtmh, .ygtvtmhh { width: 18px; height: 22px; cursor: pointer; background: url(treeview-sprite.gif) 0 -4800px no-repeat; } /* first or middle sibling, expandable */ .ygtvtp { width: 18px; height: 22px; cursor: pointer; background: url(treeview-sprite.gif) 0 -6400px no-repeat; } /* first or middle sibling, expandable, hover */ .ygtvtph, .ygtvtphh { width: 18px; height: 22px; cursor: pointer; background: url(treeview-sprite.gif) 0 -7200px no-repeat; } /* last sibling, no children */ .ygtvln { width: 18px; height: 22px; background: url(treeview-sprite.gif) 0 -1600px no-repeat; cursor: pointer; } /* Last sibling, collapsable */ .ygtvlm { width: 18px; height: 22px; cursor: pointer; background: url(treeview-sprite.gif) 0 0px no-repeat; } /* Last sibling, collapsable, hover */ .ygtvlmh, .ygtvlmhh { width: 18px; height: 22px; cursor: pointer; background: url(treeview-sprite.gif) 0 -800px no-repeat; } /* Last sibling, expandable */ .ygtvlp { width: 18px; height: 22px; cursor: pointer; background: url(treeview-sprite.gif) 0 -2400px no-repeat; } /* Last sibling, expandable, hover */ .ygtvlph, .ygtvlphh { width: 18px; height: 22px; cursor: pointer; background: url(treeview-sprite.gif) 0 -3200px no-repeat; cursor: pointer; } /* Loading icon */ .ygtvloading { width: 18px; height: 22px; background: url(treeview-loading.gif) 0 0 no-repeat; } /* the style for the empty cells that are used for rendering the depth * of the node */ .ygtvdepthcell { width: 18px; height: 22px; background: url(treeview-sprite.gif) 0 -8000px no-repeat; } .ygtvblankdepthcell { width: 18px; height: 22px; } /* the style of the div around each node's collection of children */ .ygtvchildren { } * html .ygtvchildren { height: 2%; } /* the style of the text label in ygTextNode */ .ygtvlabel, .ygtvlabel:link, .ygtvlabel:visited, .ygtvlabel:hover { margin-left: 2px; text-decoration: none; background-color: white; /* workaround for IE font smoothing bug */ cursor: pointer; } .ygtvcontent { cursor: default; } .ygtvspacer { height: 22px; width: 18px; } .ygtvfocus { background-color: #c0e0e0; border: none; } .ygtvfocus .ygtvlabel, .ygtvfocus .ygtvlabel:link, .ygtvfocus .ygtvlabel:visited, .ygtvfocus .ygtvlabel:hover { background-color: #c0e0e0; } .ygtvfocus a { outline-style: none; } .ygtvok { width: 18px; height: 22px; background: url(treeview-sprite.gif) 0 -8800px no-repeat; } .ygtvok:hover { background: url(treeview-sprite.gif) 0 -8844px no-repeat; } .ygtvcancel { width: 18px; height: 22px; background: url(treeview-sprite.gif) 0 -8822px no-repeat; } .ygtvcancel:hover { background: url(treeview-sprite.gif) 0 -8866px no-repeat; } .ygtv-label-editor { background-color: #f2f2f2; border: 1px solid silver; position: absolute; display: none; overflow: hidden; margin: auto; z-index: 9000; } .ygtv-edit-TextNode { width: 190px; } .ygtv-edit-TextNode .ygtvcancel, .ygtv-edit-TextNode .ygtvok { border: none; } .ygtv-edit-TextNode .ygtv-button-container { float: right; } .ygtv-edit-TextNode .ygtv-input input { width: 140px; } .ygtv-edit-DateNode .ygtvcancel { border: none; } .ygtv-edit-DateNode .ygtvok { display: none; } .ygtv-edit-DateNode .ygtv-button-container { text-align: right; margin: auto; } .ygtv-highlight .ygtv-highlight0, .ygtv-highlight .ygtv-highlight0 .ygtvlabel { } .ygtv-highlight .ygtv-highlight1, .ygtv-highlight .ygtv-highlight1 .ygtvlabel { background-color: blue; color: white; } .ygtv-highlight .ygtv-highlight2, .ygtv-highlight .ygtv-highlight2 .ygtvlabel { background-color: silver; } .ygtv-highlight .ygtv-highlight0 .ygtvfocus .ygtvlabel, .ygtv-highlight .ygtv-highlight1 .ygtvfocus .ygtvlabel, .ygtv-highlight .ygtv-highlight2 .ygtvfocus .ygtvlabel { background-color: #c0e0e0; } .ygtv-highlight .ygtvcontent { padding-right: 1em; } .ygtv-checkbox .ygtv-highlight0 .ygtvcontent { padding-left: 1em; background: url(check0.gif) no-repeat; } .ygtv-checkbox .ygtv-highlight0 .ygtvfocus.ygtvcontent, .ygtv-checkbox .ygtv-highlight1 .ygtvfocus.ygtvcontent, .ygtv-checkbox .ygtv-highlight2 .ygtvfocus.ygtvcontent { background-color: #c0e0e0; } .ygtv-checkbox .ygtv-highlight1 .ygtvcontent { padding-left: 1em; background: url(check1.gif) no-repeat; } .ygtv-checkbox .ygtv-highlight2 .ygtvcontent { padding-left: 1em; background: url(check2.gif) no-repeat; }
sysraj86/carnivalcrm
include/javascript/yui/build/treeview/assets/skins/sam/treeview-skin.css
CSS
agpl-3.0
5,694
/** * This file is part of mycollab-scheduler. * * mycollab-scheduler is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * mycollab-scheduler is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with mycollab-scheduler. If not, see <http://www.gnu.org/licenses/>. */ package com.esofthead.mycollab.schedule.email.project.service import com.esofthead.mycollab.common.domain.SimpleRelayEmailNotification import com.esofthead.mycollab.common.i18n.GenericI18Enum import com.esofthead.mycollab.common.{MonitorTypeConstants, NotificationType} import com.esofthead.mycollab.core.utils.StringUtils import com.esofthead.mycollab.html.FormatUtils._ import com.esofthead.mycollab.html.LinkUtils import com.esofthead.mycollab.module.mail.MailUtils import com.esofthead.mycollab.module.project.domain._ import com.esofthead.mycollab.module.project.i18n.{BugI18nEnum, OptionI18nEnum} import com.esofthead.mycollab.module.project.service.{MilestoneService, ProjectMemberService, ProjectNotificationSettingService, ProjectService} import com.esofthead.mycollab.module.project.{ProjectLinkGenerator, ProjectResources, ProjectTypeConstants} import com.esofthead.mycollab.module.tracker.domain.{BugWithBLOBs, SimpleBug} import com.esofthead.mycollab.module.tracker.service.BugService import com.esofthead.mycollab.module.user.AccountLinkGenerator import com.esofthead.mycollab.module.user.domain.SimpleUser import com.esofthead.mycollab.module.user.service.UserService import com.esofthead.mycollab.schedule.email.format._ import com.esofthead.mycollab.schedule.email.project.BugRelayEmailNotificationAction import com.esofthead.mycollab.schedule.email.{ItemFieldMapper, MailContext} import com.esofthead.mycollab.spring.ApplicationContextUtil import com.hp.gagawa.java.elements.{A, Img, Span, Text} import org.slf4j.LoggerFactory import org.springframework.beans.factory.annotation.Autowired import org.springframework.beans.factory.config.BeanDefinition import org.springframework.context.annotation.Scope import org.springframework.stereotype.Component /** * @author MyCollab Ltd. * @since 4.6.0 */ @Component @Scope(BeanDefinition.SCOPE_PROTOTYPE) class BugRelayEmailNotificationActionImpl extends SendMailToFollowersAction[SimpleBug] with BugRelayEmailNotificationAction { private val LOG = LoggerFactory.getLogger(classOf[BugRelayEmailNotificationActionImpl]) @Autowired var bugService: BugService = _ @Autowired var projectMemberService: ProjectMemberService = _ @Autowired var projectNotificationService: ProjectNotificationSettingService = _ private val mapper = new BugFieldNameMapper protected def buildExtraTemplateVariables(context: MailContext[SimpleBug]) { val currentProject = new WebItem(bean.getProjectname, ProjectLinkGenerator.generateProjectFullLink(siteUrl, bean.getProjectid)) val emailNotification: SimpleRelayEmailNotification = context.getEmailNotification val summary = "#" + bean.getBugkey + " - " + bean.getSummary val summaryLink: String = ProjectLinkGenerator.generateBugPreviewFullLink(siteUrl, bean.getBugkey, bean.getProjectShortName) val projectMember: SimpleProjectMember = projectMemberService.findMemberByUsername(emailNotification.getChangeby, bean.getProjectid, emailNotification.getSaccountid) val avatarId: String = if (projectMember != null) projectMember.getMemberAvatarId else "" val userAvatar: Img = LinkUtils.newAvatar(avatarId) val makeChangeUser: String = userAvatar.toString + emailNotification.getChangeByUserFullName val actionEnum: Enum[_] = emailNotification.getAction match { case MonitorTypeConstants.CREATE_ACTION => BugI18nEnum.MAIL_CREATE_ITEM_HEADING case MonitorTypeConstants.UPDATE_ACTION => BugI18nEnum.MAIL_UPDATE_ITEM_HEADING case MonitorTypeConstants.ADD_COMMENT_ACTION => BugI18nEnum.MAIL_COMMENT_ITEM_HEADING } contentGenerator.putVariable("actionHeading", context.getMessage(actionEnum, makeChangeUser)) contentGenerator.putVariable("titles", List(currentProject)) contentGenerator.putVariable("summary", summary) contentGenerator.putVariable("summaryLink", summaryLink) } protected def getBeanInContext(context: MailContext[SimpleBug]): SimpleBug = bugService.findById(context.getTypeid.toInt, context.getSaccountid) protected def getItemName: String = StringUtils.trim(bean.getSummary, 100) protected def getCreateSubject(context: MailContext[SimpleBug]): String = context.getMessage(BugI18nEnum.MAIL_CREATE_ITEM_SUBJECT, bean.getProjectname, context.getChangeByUserFullName, getItemName) protected def getUpdateSubject(context: MailContext[SimpleBug]): String = context.getMessage(BugI18nEnum.MAIL_UPDATE_ITEM_SUBJECT, bean.getProjectname, context.getChangeByUserFullName, getItemName) protected def getCommentSubject(context: MailContext[SimpleBug]): String = context.getMessage(BugI18nEnum.MAIL_COMMENT_ITEM_SUBJECT, bean.getProjectname, context.getChangeByUserFullName, getItemName) protected def getItemFieldMapper: ItemFieldMapper = mapper protected def getListNotifyUsersWithFilter(notification: ProjectRelayEmailNotification): Set[SimpleUser] = { import scala.collection.JavaConverters._ val notificationSettings: List[ProjectNotificationSetting] = projectNotificationService. findNotifications(notification.getProjectId, notification.getSaccountid).asScala.toList var notifyUsers: Set[SimpleUser] = notification.getNotifyUsers.asScala.toSet for (notificationSetting <- notificationSettings) { if (NotificationType.None.name == notificationSetting.getLevel) { notifyUsers = notifyUsers.filter(notifyUser => !(notifyUser.getUsername == notificationSetting.getUsername)) } else if (NotificationType.Minimal.name == notificationSetting.getLevel) { val findResult: Option[SimpleUser] = notifyUsers.find(notifyUser => notifyUser.getUsername == notificationSetting.getUsername); findResult match { case None => { val bug: SimpleBug = bugService.findById(notification.getTypeid.toInt, notification.getSaccountid) if (notificationSetting.getUsername == bug.getAssignuser) { val prjMember: SimpleUser = projectMemberService.getActiveUserOfProject(notificationSetting.getUsername, notificationSetting.getProjectid, notificationSetting.getSaccountid) if (prjMember != null) { notifyUsers += prjMember } } } case Some(user) => {} } } else if (NotificationType.Full.name == notificationSetting.getLevel) { val prjMember: SimpleUser = projectMemberService.getActiveUserOfProject(notificationSetting.getUsername, notificationSetting.getProjectid, notificationSetting.getSaccountid) if (prjMember != null) { notifyUsers += prjMember } } } notifyUsers } class BugFieldNameMapper extends ItemFieldMapper { put(BugWithBLOBs.Field.summary, BugI18nEnum.FORM_SUMMARY, isColSpan = true) put(BugWithBLOBs.Field.environment, BugI18nEnum.FORM_ENVIRONMENT, isColSpan = true) put(BugWithBLOBs.Field.description, GenericI18Enum.FORM_DESCRIPTION, isColSpan = true) put(BugWithBLOBs.Field.assignuser, new AssigneeFieldFormat(BugWithBLOBs.Field.assignuser.name, GenericI18Enum.FORM_ASSIGNEE)) put(BugWithBLOBs.Field.milestoneid, new MilestoneFieldFormat(BugWithBLOBs.Field.milestoneid.name, BugI18nEnum.FORM_PHASE)) put(BugWithBLOBs.Field.status, new I18nFieldFormat(BugWithBLOBs.Field.status.name, BugI18nEnum.FORM_STATUS, classOf[OptionI18nEnum.BugStatus])) put(BugWithBLOBs.Field.resolution, new I18nFieldFormat(BugWithBLOBs.Field.resolution.name, BugI18nEnum.FORM_RESOLUTION, classOf[OptionI18nEnum.BugResolution])) put(BugWithBLOBs.Field.severity, new I18nFieldFormat(BugWithBLOBs.Field.severity.name, BugI18nEnum.FORM_SEVERITY, classOf[OptionI18nEnum.BugSeverity])) put(BugWithBLOBs.Field.priority, new I18nFieldFormat(BugWithBLOBs.Field.priority.name, BugI18nEnum.FORM_PRIORITY, classOf[OptionI18nEnum.BugPriority])) put(BugWithBLOBs.Field.duedate, new DateFieldFormat(BugWithBLOBs.Field.duedate.name, BugI18nEnum.FORM_DUE_DATE)) put(BugWithBLOBs.Field.logby, new LogUserFieldFormat(BugWithBLOBs.Field.logby.name, BugI18nEnum.FORM_LOG_BY)) } class MilestoneFieldFormat(fieldName: String, displayName: Enum[_]) extends FieldFormat(fieldName, displayName) { def formatField(context: MailContext[_]): String = { val bug: SimpleBug = context.getWrappedBean.asInstanceOf[SimpleBug] if (bug.getMilestoneid == null || bug.getMilestoneName == null) { new Span().write } else { val img: Text = new Text(ProjectResources.getFontIconHtml(ProjectTypeConstants.MILESTONE)); val milestoneLink: String = ProjectLinkGenerator.generateMilestonePreviewFullLink(context.siteUrl, bug.getProjectid, bug.getMilestoneid) val link: A = newA(milestoneLink, bug.getMilestoneName) newLink(img, link).write } } def formatField(context: MailContext[_], value: String): String = { if (StringUtils.isBlank(value)) { new Span().write } else { try { val milestoneId: Int = value.toInt val milestoneService: MilestoneService = ApplicationContextUtil.getSpringBean(classOf[MilestoneService]) val milestone: SimpleMilestone = milestoneService.findById(milestoneId, context.getUser.getAccountId) if (milestone != null) { val img: Text = new Text(ProjectResources.getFontIconHtml(ProjectTypeConstants.MILESTONE)); val milestoneLink: String = ProjectLinkGenerator.generateMilestonePreviewFullLink(context.siteUrl, milestone .getProjectid, milestone.getId) val link: A = newA(milestoneLink, milestone.getName) return newLink(img, link).write } } catch { case e: Exception => LOG.error("Error", e) } value } } } class AssigneeFieldFormat(fieldName: String, displayName: Enum[_]) extends FieldFormat(fieldName, displayName) { def formatField(context: MailContext[_]): String = { val bug: SimpleBug = context.getWrappedBean.asInstanceOf[SimpleBug] if (bug.getAssignuser != null) { val userAvatarLink: String = MailUtils.getAvatarLink(bug.getAssignUserAvatarId, 16) val img: Img = newImg("avatar", userAvatarLink) val userLink: String = AccountLinkGenerator.generatePreviewFullUserLink(MailUtils.getSiteUrl(bug.getSaccountid), bug.getAssignuser) val link: A = newA(userLink, bug.getAssignuserFullName) newLink(img, link).write } else { new Span().write } } def formatField(context: MailContext[_], value: String): String = { if (org.apache.commons.lang3.StringUtils.isBlank(value)) { new Span().write } else { val userService: UserService = ApplicationContextUtil.getSpringBean(classOf[UserService]) val user: SimpleUser = userService.findUserByUserNameInAccount(value, context.getUser.getAccountId) if (user != null) { val userAvatarLink: String = MailUtils.getAvatarLink(user.getAvatarid, 16) val userLink: String = AccountLinkGenerator.generatePreviewFullUserLink(MailUtils.getSiteUrl(user.getAccountId), user.getUsername) val img: Img = newImg("avatar", userAvatarLink) val link: A = newA(userLink, user.getDisplayName) newLink(img, link).write } else value } } } class LogUserFieldFormat(fieldName: String, displayName: Enum[_]) extends FieldFormat(fieldName, displayName) { def formatField(context: MailContext[_]): String = { val bug: SimpleBug = context.getWrappedBean.asInstanceOf[SimpleBug] if (bug.getLogby != null) { val userAvatarLink: String = MailUtils.getAvatarLink(bug.getLoguserAvatarId, 16) val img: Img = newImg("avatar", userAvatarLink) val userLink: String = AccountLinkGenerator.generatePreviewFullUserLink(MailUtils.getSiteUrl(bug.getSaccountid), bug.getLogby) val link: A = newA(userLink, bug.getLoguserFullName) newLink(img, link).write } else new Span().write } def formatField(context: MailContext[_], value: String): String = { if (StringUtils.isBlank(value)) return new Span().write val userService: UserService = ApplicationContextUtil.getSpringBean(classOf[UserService]) val user: SimpleUser = userService.findUserByUserNameInAccount(value, context.getUser.getAccountId) if (user != null) { val userAvatarLink: String = MailUtils.getAvatarLink(user.getAvatarid, 16) val userLink: String = AccountLinkGenerator.generatePreviewFullUserLink(MailUtils.getSiteUrl(user.getAccountId), user.getUsername) val img: Img = newImg("avatar", userAvatarLink) val link: A = newA(userLink, user.getDisplayName) newLink(img, link).write } else value } } }
maduhu/mycollab
mycollab-scheduler/src/main/scala/com/esofthead/mycollab/schedule/email/project/service/BugRelayEmailNotificationActionImpl.scala
Scala
agpl-3.0
14,706
/* * Realmedia RTSP protocol (RDT) support. * Copyright (c) 2007 Ronald S. Bultje * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * @brief Realmedia RTSP protocol (RDT) support * @author Ronald S. Bultje <[email protected]> */ #include "avformat.h" #include "libavutil/avstring.h" #include "rtpdec.h" #include "rdt.h" #include "libavutil/base64.h" #include "libavutil/md5.h" #include "rm.h" #include "internal.h" #include "avio_internal.h" #include "libavcodec/get_bits.h" struct RDTDemuxContext { AVFormatContext *ic; /**< the containing (RTSP) demux context */ /** Each RDT stream-set (represented by one RTSPStream) can contain * multiple streams (of the same content, but with possibly different * codecs/bitrates). Each such stream is represented by one AVStream * in the AVFormatContext, and this variable points to the offset in * that array such that the first is the first stream of this set. */ AVStream **streams; int n_streams; /**< streams with identifical content in this set */ void *dynamic_protocol_context; DynamicPayloadPacketHandlerProc parse_packet; uint32_t prev_timestamp; int prev_set_id, prev_stream_id; }; RDTDemuxContext * ff_rdt_parse_open(AVFormatContext *ic, int first_stream_of_set_idx, void *priv_data, RTPDynamicProtocolHandler *handler) { RDTDemuxContext *s = av_mallocz(sizeof(RDTDemuxContext)); if (!s) return NULL; s->ic = ic; s->streams = &ic->streams[first_stream_of_set_idx]; do { s->n_streams++; } while (first_stream_of_set_idx + s->n_streams < ic->nb_streams && s->streams[s->n_streams]->id == s->streams[0]->id); s->prev_set_id = -1; s->prev_stream_id = -1; s->prev_timestamp = -1; s->parse_packet = handler ? handler->parse_packet : NULL; s->dynamic_protocol_context = priv_data; return s; } void ff_rdt_parse_close(RDTDemuxContext *s) { av_free(s); } struct PayloadContext { AVFormatContext *rmctx; int nb_rmst; RMStream **rmst; uint8_t *mlti_data; unsigned int mlti_data_size; char buffer[RTP_MAX_PACKET_LENGTH + FF_INPUT_BUFFER_PADDING_SIZE]; int audio_pkt_cnt; /**< remaining audio packets in rmdec */ }; void ff_rdt_calc_response_and_checksum(char response[41], char chksum[9], const char *challenge) { int ch_len = strlen (challenge), i; unsigned char zres[16], buf[64] = { 0xa1, 0xe9, 0x14, 0x9d, 0x0e, 0x6b, 0x3b, 0x59 }; #define XOR_TABLE_SIZE 37 const unsigned char xor_table[XOR_TABLE_SIZE] = { 0x05, 0x18, 0x74, 0xd0, 0x0d, 0x09, 0x02, 0x53, 0xc0, 0x01, 0x05, 0x05, 0x67, 0x03, 0x19, 0x70, 0x08, 0x27, 0x66, 0x10, 0x10, 0x72, 0x08, 0x09, 0x63, 0x11, 0x03, 0x71, 0x08, 0x08, 0x70, 0x02, 0x10, 0x57, 0x05, 0x18, 0x54 }; /* some (length) checks */ if (ch_len == 40) /* what a hack... */ ch_len = 32; else if (ch_len > 56) ch_len = 56; memcpy(buf + 8, challenge, ch_len); /* xor challenge bytewise with xor_table */ for (i = 0; i < XOR_TABLE_SIZE; i++) buf[8 + i] ^= xor_table[i]; av_md5_sum(zres, buf, 64); ff_data_to_hex(response, zres, 16, 1); /* add tail */ strcpy (response + 32, "01d0a8e3"); /* calculate checksum */ for (i = 0; i < 8; i++) chksum[i] = response[i * 4]; chksum[8] = 0; } static int rdt_load_mdpr (PayloadContext *rdt, AVStream *st, int rule_nr) { AVIOContext pb; int size; uint32_t tag; /** * Layout of the MLTI chunk: * 4: MLTI * 2: number of streams * Then for each stream ([number_of_streams] times): * 2: mdpr index * 2: number of mdpr chunks * Then for each mdpr chunk ([number_of_mdpr_chunks] times): * 4: size * [size]: data * we skip MDPR chunks until we reach the one of the stream * we're interested in, and forward that ([size]+[data]) to * the RM demuxer to parse the stream-specific header data. */ if (!rdt->mlti_data) return -1; ffio_init_context(&pb, rdt->mlti_data, rdt->mlti_data_size, 0, NULL, NULL, NULL, NULL); tag = avio_rl32(&pb); if (tag == MKTAG('M', 'L', 'T', 'I')) { int num, chunk_nr; /* read index of MDPR chunk numbers */ num = avio_rb16(&pb); if (rule_nr < 0 || rule_nr >= num) return -1; avio_seek(&pb, rule_nr * 2, SEEK_CUR); chunk_nr = avio_rb16(&pb); avio_seek(&pb, (num - 1 - rule_nr) * 2, SEEK_CUR); /* read MDPR chunks */ num = avio_rb16(&pb); if (chunk_nr >= num) return -1; while (chunk_nr--) avio_seek(&pb, avio_rb32(&pb), SEEK_CUR); size = avio_rb32(&pb); } else { size = rdt->mlti_data_size; avio_seek(&pb, 0, SEEK_SET); } if (ff_rm_read_mdpr_codecdata(rdt->rmctx, &pb, st, rdt->rmst[st->index], size) < 0) return -1; return 0; } /** * Actual data handling. */ int ff_rdt_parse_header(const uint8_t *buf, int len, int *pset_id, int *pseq_no, int *pstream_id, int *pis_keyframe, uint32_t *ptimestamp) { GetBitContext gb; int consumed = 0, set_id, seq_no, stream_id, is_keyframe, len_included, need_reliable; uint32_t timestamp; /* skip status packets */ while (len >= 5 && buf[1] == 0xFF /* status packet */) { int pkt_len; if (!(buf[0] & 0x80)) return -1; /* not followed by a data packet */ pkt_len = AV_RB16(buf+3); buf += pkt_len; len -= pkt_len; consumed += pkt_len; } if (len < 16) return -1; /** * Layout of the header (in bits): * 1: len_included * Flag indicating whether this header includes a length field; * this can be used to concatenate multiple RDT packets in a * single UDP/TCP data frame and is used to precede RDT data * by stream status packets * 1: need_reliable * Flag indicating whether this header includes a "reliable * sequence number"; these are apparently sequence numbers of * data packets alone. For data packets, this flag is always * set, according to the Real documentation [1] * 5: set_id * ID of a set of streams of identical content, possibly with * different codecs or bitrates * 1: is_reliable * Flag set for certain streams deemed less tolerable for packet * loss * 16: seq_no * Packet sequence number; if >=0xFF00, this is a non-data packet * containing stream status info, the second byte indicates the * type of status packet (see wireshark docs / source code [2]) * if (len_included) { * 16: packet_len * } else { * packet_len = remainder of UDP/TCP frame * } * 1: is_back_to_back * Back-to-Back flag; used for timing, set for one in every 10 * packets, according to the Real documentation [1] * 1: is_slow_data * Slow-data flag; currently unused, according to Real docs [1] * 5: stream_id * ID of the stream within this particular set of streams * 1: is_no_keyframe * Non-keyframe flag (unset if packet belongs to a keyframe) * 32: timestamp (PTS) * if (set_id == 0x1F) { * 16: set_id (extended set-of-streams ID; see set_id) * } * if (need_reliable) { * 16: reliable_seq_no * Reliable sequence number (see need_reliable) * } * if (stream_id == 0x3F) { * 16: stream_id (extended stream ID; see stream_id) * } * [1] https://protocol.helixcommunity.org/files/2005/devdocs/RDT_Feature_Level_20.txt * [2] http://www.wireshark.org/docs/dfref/r/rdt.html and * http://anonsvn.wireshark.org/viewvc/trunk/epan/dissectors/packet-rdt.c */ init_get_bits(&gb, buf, len << 3); len_included = get_bits1(&gb); need_reliable = get_bits1(&gb); set_id = get_bits(&gb, 5); skip_bits(&gb, 1); seq_no = get_bits(&gb, 16); if (len_included) skip_bits(&gb, 16); skip_bits(&gb, 2); stream_id = get_bits(&gb, 5); is_keyframe = !get_bits1(&gb); timestamp = get_bits_long(&gb, 32); if (set_id == 0x1f) set_id = get_bits(&gb, 16); if (need_reliable) skip_bits(&gb, 16); if (stream_id == 0x1f) stream_id = get_bits(&gb, 16); if (pset_id) *pset_id = set_id; if (pseq_no) *pseq_no = seq_no; if (pstream_id) *pstream_id = stream_id; if (pis_keyframe) *pis_keyframe = is_keyframe; if (ptimestamp) *ptimestamp = timestamp; return consumed + (get_bits_count(&gb) >> 3); } /**< return 0 on packet, no more left, 1 on packet, 1 on partial packet... */ static int rdt_parse_packet (AVFormatContext *ctx, PayloadContext *rdt, AVStream *st, AVPacket *pkt, uint32_t *timestamp, const uint8_t *buf, int len, int flags) { int seq = 1, res; AVIOContext pb; if (rdt->audio_pkt_cnt == 0) { int pos; ffio_init_context(&pb, buf, len, 0, NULL, NULL, NULL, NULL); flags = (flags & RTP_FLAG_KEY) ? 2 : 0; res = ff_rm_parse_packet (rdt->rmctx, &pb, st, rdt->rmst[st->index], len, pkt, &seq, flags, *timestamp); pos = url_ftell(&pb); if (res < 0) return res; if (res > 0) { if (st->codec->codec_id == CODEC_ID_AAC) { memcpy (rdt->buffer, buf + pos, len - pos); rdt->rmctx->pb = avio_alloc_context (rdt->buffer, len - pos, 0, NULL, NULL, NULL, NULL); } goto get_cache; } } else { get_cache: rdt->audio_pkt_cnt = ff_rm_retrieve_cache (rdt->rmctx, rdt->rmctx->pb, st, rdt->rmst[st->index], pkt); if (rdt->audio_pkt_cnt == 0 && st->codec->codec_id == CODEC_ID_AAC) av_freep(&rdt->rmctx->pb); } pkt->stream_index = st->index; pkt->pts = *timestamp; return rdt->audio_pkt_cnt > 0; } int ff_rdt_parse_packet(RDTDemuxContext *s, AVPacket *pkt, uint8_t **bufptr, int len) { uint8_t *buf = bufptr ? *bufptr : NULL; int seq_no, flags = 0, stream_id, set_id, is_keyframe; uint32_t timestamp; int rv= 0; if (!s->parse_packet) return -1; if (!buf && s->prev_stream_id != -1) { /* return the next packets, if any */ timestamp= 0; ///< Should not be used if buf is NULL, but should be set to the timestamp of the packet returned.... rv= s->parse_packet(s->ic, s->dynamic_protocol_context, s->streams[s->prev_stream_id], pkt, &timestamp, NULL, 0, flags); return rv; } if (len < 12) return -1; rv = ff_rdt_parse_header(buf, len, &set_id, &seq_no, &stream_id, &is_keyframe, &timestamp); if (rv < 0) return rv; if (is_keyframe && (set_id != s->prev_set_id || timestamp != s->prev_timestamp || stream_id != s->prev_stream_id)) { flags |= RTP_FLAG_KEY; s->prev_set_id = set_id; s->prev_timestamp = timestamp; } s->prev_stream_id = stream_id; buf += rv; len -= rv; if (s->prev_stream_id >= s->n_streams) { s->prev_stream_id = -1; return -1; } rv = s->parse_packet(s->ic, s->dynamic_protocol_context, s->streams[s->prev_stream_id], pkt, &timestamp, buf, len, flags); return rv; } void ff_rdt_subscribe_rule (char *cmd, int size, int stream_nr, int rule_nr) { av_strlcatf(cmd, size, "stream=%d;rule=%d,stream=%d;rule=%d", stream_nr, rule_nr * 2, stream_nr, rule_nr * 2 + 1); } static unsigned char * rdt_parse_b64buf (unsigned int *target_len, const char *p) { unsigned char *target; int len = strlen(p); if (*p == '\"') { p++; len -= 2; /* skip embracing " at start/end */ } *target_len = len * 3 / 4; target = av_mallocz(*target_len + FF_INPUT_BUFFER_PADDING_SIZE); av_base64_decode(target, p, *target_len); return target; } static int rdt_parse_sdp_line (AVFormatContext *s, int st_index, PayloadContext *rdt, const char *line) { AVStream *stream = s->streams[st_index]; const char *p = line; if (av_strstart(p, "OpaqueData:buffer;", &p)) { rdt->mlti_data = rdt_parse_b64buf(&rdt->mlti_data_size, p); } else if (av_strstart(p, "StartTime:integer;", &p)) stream->first_dts = atoi(p); else if (av_strstart(p, "ASMRuleBook:string;", &p)) { int n, first = -1; for (n = 0; n < s->nb_streams; n++) if (s->streams[n]->id == stream->id) { int count = s->streams[n]->index + 1; if (first == -1) first = n; if (rdt->nb_rmst < count) { RMStream **rmst= av_realloc(rdt->rmst, count*sizeof(*rmst)); if (!rmst) return AVERROR(ENOMEM); memset(rmst + rdt->nb_rmst, 0, (count - rdt->nb_rmst) * sizeof(*rmst)); rdt->rmst = rmst; rdt->nb_rmst = count; } rdt->rmst[s->streams[n]->index] = ff_rm_alloc_rmstream(); rdt_load_mdpr(rdt, s->streams[n], (n - first) * 2); if (s->streams[n]->codec->codec_id == CODEC_ID_AAC) s->streams[n]->codec->frame_size = 1; // FIXME } } return 0; } static void real_parse_asm_rule(AVStream *st, const char *p, const char *end) { do { /* can be either averagebandwidth= or AverageBandwidth= */ if (sscanf(p, " %*1[Aa]verage%*1[Bb]andwidth=%d", &st->codec->bit_rate) == 1) break; if (!(p = strchr(p, ',')) || p > end) p = end; p++; } while (p < end); } static AVStream * add_dstream(AVFormatContext *s, AVStream *orig_st) { AVStream *st; if (!(st = av_new_stream(s, orig_st->id))) return NULL; st->codec->codec_type = orig_st->codec->codec_type; st->first_dts = orig_st->first_dts; return st; } static void real_parse_asm_rulebook(AVFormatContext *s, AVStream *orig_st, const char *p) { const char *end; int n_rules = 0, odd = 0; AVStream *st; /** * The ASMRuleBook contains a list of comma-separated strings per rule, * and each rule is separated by a ;. The last one also has a ; at the * end so we can use it as delimiter. * Every rule occurs twice, once for when the RTSP packet header marker * is set and once for if it isn't. We only read the first because we * don't care much (that's what the "odd" variable is for). * Each rule contains a set of one or more statements, optionally * preceeded by a single condition. If there's a condition, the rule * starts with a '#'. Multiple conditions are merged between brackets, * so there are never multiple conditions spread out over separate * statements. Generally, these conditions are bitrate limits (min/max) * for multi-bitrate streams. */ if (*p == '\"') p++; while (1) { if (!(end = strchr(p, ';'))) break; if (!odd && end != p) { if (n_rules > 0) st = add_dstream(s, orig_st); else st = orig_st; if (!st) break; real_parse_asm_rule(st, p, end); n_rules++; } p = end + 1; odd ^= 1; } } void ff_real_parse_sdp_a_line (AVFormatContext *s, int stream_index, const char *line) { const char *p = line; if (av_strstart(p, "ASMRuleBook:string;", &p)) real_parse_asm_rulebook(s, s->streams[stream_index], p); } static PayloadContext * rdt_new_context (void) { PayloadContext *rdt = av_mallocz(sizeof(PayloadContext)); av_open_input_stream(&rdt->rmctx, NULL, "", &ff_rdt_demuxer, NULL); return rdt; } static void rdt_free_context (PayloadContext *rdt) { int i; for (i = 0; i < rdt->nb_rmst; i++) if (rdt->rmst[i]) { ff_rm_free_rmstream(rdt->rmst[i]); av_freep(&rdt->rmst[i]); } if (rdt->rmctx) av_close_input_stream(rdt->rmctx); av_freep(&rdt->mlti_data); av_freep(&rdt->rmst); av_free(rdt); } #if __STDC_VERSION >= 1999001L #define RDT_HANDLER(n, s, t) \ static RTPDynamicProtocolHandler ff_rdt_ ## n ## _handler = { \ .enc_name = s, \ .codec_type = t, \ .codec_id = CODEC_ID_NONE, \ .parse_sdp_a_line = rdt_parse_sdp_line, \ .open = rdt_new_context, \ .close = rdt_free_context, \ .parse_packet = rdt_parse_packet \ } #else #define RDT_HANDLER(n, s, t) \ static RTPDynamicProtocolHandler ff_rdt_ ## n ## _handler = { \ s, \ t, \ CODEC_ID_NONE, \ 0, \ rdt_parse_sdp_line, \ rdt_new_context, \ rdt_free_context, \ rdt_parse_packet \ , NULL \ } #endif RDT_HANDLER(live_video, "x-pn-multirate-realvideo-live", AVMEDIA_TYPE_VIDEO); RDT_HANDLER(live_audio, "x-pn-multirate-realaudio-live", AVMEDIA_TYPE_AUDIO); RDT_HANDLER(video, "x-pn-realvideo", AVMEDIA_TYPE_VIDEO); RDT_HANDLER(audio, "x-pn-realaudio", AVMEDIA_TYPE_AUDIO); void av_register_rdt_dynamic_payload_handlers(void) { ff_register_dynamic_payload_handler(&ff_rdt_video_handler); ff_register_dynamic_payload_handler(&ff_rdt_audio_handler); ff_register_dynamic_payload_handler(&ff_rdt_live_video_handler); ff_register_dynamic_payload_handler(&ff_rdt_live_audio_handler); }
ging/isabel
lib/ffmpeg/Win32/src/ffmpeg/libavformat/rdt.c
C
agpl-3.0
18,890
#!/usr/bin/env python # -*- coding: utf-8; tab-width: 4; indent-tabs-mode: t -*- # # NetProfile: Authentication routines # © Copyright 2013-2014 Alex 'Unik' Unigovsky # # This file is part of NetProfile. # NetProfile is free software: you can redistribute it and/or # modify it under the terms of the GNU Affero General Public # License as published by the Free Software Foundation, either # version 3 of the License, or (at your option) any later # version. # # NetProfile is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General # Public License along with NetProfile. If not, see # <http://www.gnu.org/licenses/>. from __future__ import ( unicode_literals, print_function, absolute_import, division ) import hashlib import random import string import time from zope.interface import implementer from pyramid.interfaces import IAuthenticationPolicy from pyramid.security import ( Authenticated, Everyone ) class PluginPolicySelected(object): def __init__(self, request, policy): self.request = request self.policy = policy @implementer(IAuthenticationPolicy) class PluginAuthenticationPolicy(object): def __init__(self, default, routes=None): self._default = default if routes is None: routes = {} self._routes = routes def add_plugin(self, route, policy): self._routes[route] = policy def match(self, request): if hasattr(request, 'auth_policy'): return request.auth_policy cur = None cur_len = 0 for route, plug in self._routes.items(): r_len = len(route) if r_len <= cur_len: continue path = request.path if route == path[:r_len]: if len(path) > r_len: if path[r_len:r_len + 1] != '/': continue cur = plug cur_len = r_len if cur: request.auth_policy = cur else: request.auth_policy = self._default request.registry.notify(PluginPolicySelected(request, request.auth_policy)) return request.auth_policy def authenticated_userid(self, request): return self.match(request).authenticated_userid(request) def unauthenticated_userid(self, request): return self.match(request).unauthenticated_userid(request) def effective_principals(self, request): return self.match(request).effective_principals(request) def remember(self, request, principal, **kw): return self.match(request).remember(request, principal, **kw) def forget(self, request): return self.match(request).forget(request) _TOKEN_FILTER_MAP = ( [chr(n) for n in range(32)] + [chr(127), '\\', '"'] ) _TOKEN_FILTER_MAP = dict.fromkeys(_TOKEN_FILTER_MAP, None) def _filter_token(tok): return str(tok).translate(_TOKEN_FILTER_MAP) def _format_kvpairs(**kwargs): return ', '.join('{0!s}="{1}"'.format(k, _filter_token(v)) for (k, v) in kwargs.items()) def _generate_nonce(ts, secret, salt=None, chars=string.hexdigits.upper()): # TODO: Add IP-address to nonce if not salt: try: rng = random.SystemRandom() except NotImplementedError: rng = random salt = ''.join(rng.choice(chars) for i in range(16)) ctx = hashlib.md5(('%s:%s:%s' % (ts, salt, secret)).encode()) return ('%s:%s:%s' % (ts, salt, ctx.hexdigest())) def _is_valid_nonce(nonce, secret): comp = nonce.split(':') if len(comp) != 3: return False calc_nonce = _generate_nonce(comp[0], secret, comp[1]) if nonce == calc_nonce: return True return False def _generate_digest_challenge(ts, secret, realm, opaque, stale=False): nonce = _generate_nonce(ts, secret) return 'Digest %s' % (_format_kvpairs( realm=realm, qop='auth', nonce=nonce, opaque=opaque, algorithm='MD5', stale='true' if stale else 'false' ),) def _add_www_authenticate(request, secret, realm): resp = request.response if not resp.www_authenticate: resp.www_authenticate = _generate_digest_challenge( round(time.time()), secret, realm, 'NPDIGEST' ) def _parse_authorization(request, secret, realm): authz = request.authorization if (not authz) or (len(authz) != 2) or (authz[0] != 'Digest'): _add_www_authenticate(request, secret, realm) return None params = authz[1] if 'algorithm' not in params: params['algorithm'] = 'MD5' for required in ('username', 'realm', 'nonce', 'uri', 'response', 'cnonce', 'nc', 'opaque'): if (required not in params) or ((required == 'opaque') and (params['opaque'] != 'NPDIGEST')): _add_www_authenticate(request, secret, realm) return None return params @implementer(IAuthenticationPolicy) class DigestAuthenticationPolicy(object): def __init__(self, secret, callback, realm='Realm'): self.secret = secret self.callback = callback self.realm = realm def authenticated_userid(self, request): params = _parse_authorization(request, self.secret, self.realm) if params is None: return None if not _is_valid_nonce(params['nonce'], self.secret): _add_www_authenticate(request, self.secret, self.realm) return None userid = params['username'] if self.callback(params, request) is not None: return 'u:%s' % userid _add_www_authenticate(request, self.secret, self.realm) def unauthenticated_userid(self, request): params = _parse_authorization(request, self.secret, self.realm) if params is None: return None if not _is_valid_nonce(params['nonce'], self.secret): _add_www_authenticate(request, self.secret, self.realm) return None return 'u:%s' % params['username'] def effective_principals(self, request): creds = [Everyone] params = _parse_authorization(request, self.secret, self.realm) if params is None: return creds if not _is_valid_nonce(params['nonce'], self.secret): _add_www_authenticate(request, self.secret, self.realm) return creds groups = self.callback(params, request) if groups is None: return creds creds.append(Authenticated) creds.append('u:%s' % params['username']) creds.extend(groups) return creds def remember(self, request, principal, *kw): return [] def forget(self, request): return [('WWW-Authenticate', _generate_digest_challenge( round(time.time()), self.secret, self.realm, 'NPDIGEST' ))]
annndrey/npui-unik
netprofile/netprofile/common/auth.py
Python
agpl-3.0
6,265