Revision: 15699
Author: baranowb
Date: Fri Dec 10 00:49:19 2010
Log: Fixes Issue 2172
As in issue desc: reduce byte[] creation and copy ops.
http://code.google.com/p/mobicents/source/detail?r=15699

Added:
/trunk/protocols/ss7/mtp/mtp-impl/src/main/java/org/mobicents/protocols/ss7/mtp/Mtp2Buffer.java
Modified:
 /trunk/protocols/ss7/mtp/.classpath
/trunk/protocols/ss7/mtp/mtp-impl/src/main/java/org/mobicents/protocols/ss7/mtp/Mtp2.java /trunk/protocols/ss7/mtp/mtp-impl/src/main/java/org/mobicents/protocols/ss7/mtp/Mtp3.java

=======================================
--- /dev/null
+++ /trunk/protocols/ss7/mtp/mtp-impl/src/main/java/org/mobicents/protocols/ss7/mtp/Mtp2Buffer.java Fri Dec 10 00:49:19 2010
@@ -0,0 +1,36 @@
+/*
+ * JBoss, Home of Professional Open Source
+ * Copyright XXXX, Red Hat Middleware LLC, and individual contributors as indicated
+ * by the @authors tag. All rights reserved.
+ * See the copyright.txt in the distribution for a full listing
+ * of individual contributors.
+ * This copyrighted material is made available to anyone wishing to use,
+ * modify, copy, or redistribute it subject to the terms and conditions
+ * of the GNU General Public License, v. 2.0.
+ * This program is distributed in the hope that it will be useful, but WITHOUT A + * 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,
+ * v. 2.0 along with this distribution; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
+ * MA 02110-1301, USA.
+ */
+package org.mobicents.protocols.ss7.mtp;
+
+/**
+ * @author baranowb
+ *
+ */
+class Mtp2Buffer {
+    /**
+     * data in this frame.
+     */
+    byte[] frame = new byte[272 + 7]; // +7 - 272 is max SIF part len,
+    /**
+     * length of actual data fram to be transmited.
+     */
+ int len = 0;//len pointer for this buffer, indicates how much data is there really.
+
+    int offset = 0; //offset from beggining of buffer.
+    // public boolean isFree()
+}
=======================================
--- /trunk/protocols/ss7/mtp/.classpath Thu Nov 25 10:22:10 2010
+++ /trunk/protocols/ss7/mtp/.classpath Fri Dec 10 00:49:19 2010
@@ -4,9 +4,9 @@
   <classpathentry kind="src" path="mtp-impl/src/test/java"/>
   <classpathentry kind="var" path="M2_REPO/junit/junit/4.1/junit-4.1.jar"/>
<classpathentry kind="var" path="M2_REPO/log4j/log4j/1.2.14/log4j-1.2.14.jar"/> - <classpathentry kind="var" path="M2_REPO/org/mobicents/protocols/ss7/m3ua/m3ua-api/1.0.0.BETA2/m3ua-api-1.0.0.BETA2.jar"/> - <classpathentry kind="var" path="M2_REPO/org/mobicents/protocols/ss7/m3ua/m3ua-impl/1.0.0.BETA2/m3ua-impl-1.0.0.BETA2.jar"/> - <classpathentry kind="var" path="M2_REPO/org/mobicents/protocols/stream/stream/1.0.0.BETA1/stream-1.0.0.BETA1.jar"/> + <classpathentry kind="var" path="M2_REPO/org/mobicents/protocols/ss7/m3ua/m3ua-api/1.0.0-SNAPSHOT/m3ua-api-1.0.0-SNAPSHOT.jar"/> + <classpathentry kind="var" path="M2_REPO/org/mobicents/protocols/ss7/m3ua/m3ua-impl/1.0.0-SNAPSHOT/m3ua-impl-1.0.0-SNAPSHOT.jar"/> + <classpathentry kind="var" path="M2_REPO/org/mobicents/protocols/stream/stream/1.0.0.BETA2/stream-1.0.0.BETA2.jar"/> <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
   <classpathentry kind="output" path="target/classes"/>
 </classpath>
=======================================
--- /trunk/protocols/ss7/mtp/mtp-impl/src/main/java/org/mobicents/protocols/ss7/mtp/Mtp2.java Wed Dec 1 06:29:20 2010 +++ /trunk/protocols/ss7/mtp/mtp-impl/src/main/java/org/mobicents/protocols/ss7/mtp/Mtp2.java Fri Dec 10 00:49:19 2010
@@ -185,20 +185,42 @@
     private FastHDLC hdlc = new FastHDLC();
     private HdlcState rxState = new HdlcState();
     private HdlcState txState = new HdlcState();
-    private int rxLen = 0;
-    private int txLen = 0;
-    private int txOffset = 0;
+    //private int rxLen = 0;
+    //private int txLen = 0;
+
     private byte[] txBuffer = new byte[RX_TX_BUFF_SIZE];
     private byte[] rxBuffer = new byte[RX_TX_BUFF_SIZE];
-    private int[] rxFrame = new int[279];
-    private byte[] txFrame = new byte[279];
+    //private int[] rxFrame = new int[279];
+    //private byte[] txFrame = new byte[279];
+    //private int txOffset = 0;
+    /**
+     * Buffer to store incoming frame.
+     */
+    private Mtp2Buffer rxFrame = new Mtp2Buffer();
+    /**
+ * Buffer to store frame to send, this ref will be set when next frame is scheduled, no copy&paste
+     */
+    private Mtp2Buffer txFrame;
+    /**
+     * frame used to create LSSU/FISU
+     */
+    private Mtp2Buffer stateFrame = new Mtp2Buffer();
+    /**
+ * frame used to create NEXT LSSU, it is used in case when link transits from NOT_ALIGNED to ALIGNED state
+     */
+    private Mtp2Buffer nextStateFrame = new Mtp2Buffer();
+    /**
+ * Indicates that there is something to send in {...@link #nextStateFrame}.
+     */
+    private boolean pendingLSSU = false;
+
     /**
* Last write timestamp, it is required for case when we must start sending but nothing comes on wire.
      */
     // private long lastWriteStamp = 0;
// Used only for LSSU, in some case we need to schedule LSSU frame, before
     // last is processed,
-    private TxQueue txQueue = new TxQueue();
+   //private TxQueue txQueue = new TxQueue();
     private int doCRC = 0;
     private int rxCRC = 0xffff;
     private int txCRC = 0xffff;
@@ -210,7 +232,7 @@
      * from when we send and retransmission is requested. FIXME: add this->
      * ACKED buffers will have len == 0(isFree() == true);
      */
-    private Mtp2SendBuffer[] transmissionBuffer = new Mtp2SendBuffer[128];
+    private Mtp2Buffer[] transmissionBuffer = new Mtp2Buffer[128];
     private static final int _OFF_RTR = -1;
     /**
* Determines posistion in transmissionBuffer. If != _OFF_RTR, it points
@@ -273,7 +295,7 @@

         // init buffer
         for (int i = 0; i < this.transmissionBuffer.length; i++) {
-            this.transmissionBuffer[i] = new Mtp2SendBuffer();
+            this.transmissionBuffer[i] = new Mtp2Buffer();
         }
     }

@@ -343,7 +365,7 @@
         if (started) {
             throw new IllegalStateException("Link already running");
         }
-
+
         channel.open();
         mtp3.registerLink(this);
         started = true;
@@ -353,12 +375,12 @@
         if(logger.isInfoEnabled()){
          logger.info("Is out of service now. Starting.");
        }
-
+        this.txFrame = stateFrame;
         //state = Mtp2.MTP2_OUT_OF_SERVICE;
         setState(MTP2_OUT_OF_SERVICE);
         //send Out of service indicator when link starts.
         queueLSSU(Mtp2.FRAME_STATUS_INDICATION_OS);
-        processTx(16);
+        processTx(RX_TX_BUFF_SIZE);
         startInitialAlignment();
     }

@@ -387,7 +409,8 @@
// Comment from Oleg: this is done initialy to setup correct spot in tx
         // buffer: dunno, I just believe, for now.
         if (resetTxOffset) {
-            txOffset = 3;
+            //txOffset = 3;
+               this.txFrame.offset = 3; // I really dont get this shift.
         }

         this.reset();
@@ -429,11 +452,11 @@
         this.retransmissionFSN = _OFF_RTR;
         this.retransmissionFSN_LastAcked = 0x7F;
         this.retransmissionFSN_LastSent = 0x7F;
+
     }

     public void fail() {
         cleanupTimers();
-        //this.state = MTP2_OUT_OF_SERVICE;

         if(logger.isDebugEnabled())
         {
@@ -444,6 +467,7 @@
     }

     public boolean send(byte[] msg, int len) {
+       //FIXME: this operation actually could be split into two....
                if (this.state != MTP2_INSERVICE) {
                        if (this.logger.isEnabledFor(Level.TRACE)) {
                                logger.trace("MTP3 scheduled MSU when not in 
service, discarding.");
@@ -488,20 +512,15 @@
     }

     private void queueLSSU(int indicator) {
-        if (this.txLen != txOffset) {
-            // we schedule in queue, this is for some special cases.
-            byte[] frame = new byte[4];
-            frame[0] = (byte) (this.sendBSN | (this.sendBIB << 7));
- frame[1] = (byte) (this.retransmissionFSN_LastSent | (this.sendFIB << 7));
-            frame[2] = 1;
-            frame[3] = (byte) indicator;
-            txQueue.offer(frame);
+        //if (this.txLen != txOffset) {
+       if (this.txFrame!=null && this.txFrame.len != this.txFrame.offset) {
+               fillLSSUBuffer(this.nextStateFrame,indicator);
+               this.pendingLSSU = true; //should we check on entering here?
+
         } else {
-            this.txLen = 4;
-            this.txFrame[0] = (byte) (this.sendBSN | (this.sendBIB << 7));
- this.txFrame[1] = (byte) (this.retransmissionFSN_LastSent | (this.sendFIB << 7));
-            this.txFrame[2] = 1;
-            this.txFrame[3] = (byte) indicator;
+               this.txFrame = this.stateFrame; //set proper frame
+               fillLSSUBuffer(this.txFrame,indicator);
+

         }

@@ -509,14 +528,24 @@
             logger.trace("Queue LSSU[" + FRAME_NAMES[indicator] + "]");
         }
     }
+    private void fillLSSUBuffer(Mtp2Buffer b, int indicator)
+    {
+       b.len = 4;
+       b.offset = 0;
+       b.frame[0] = (byte) (this.sendBSN | (this.sendBIB << 7));
+ b.frame[1] = (byte) (this.retransmissionFSN_LastSent | (this.sendFIB << 7));
+        b.frame[2] = 1;
+        b.frame[3] = (byte) indicator;
+
+    }

     private void queueFISU() {
-        this.txLen = 3;
-        this.txFrame[0] = (byte) (this.sendBSN | (this.sendBIB << 7));
- this.txFrame[1] = (byte) (this.retransmissionFSN_LastSent | (this.sendFIB << 7));
-        this.txFrame[2] = 0;
-
-        // txQueue.offer(frame);
+
+       this.txFrame = this.stateFrame;
+ this.txFrame.frame[0] = (byte) (this.sendBSN | (this.sendBIB << 7)); + this.txFrame.frame[1] = (byte) (this.retransmissionFSN_LastSent | (this.sendFIB << 7));
+        this.txFrame.frame[2] = 0;
+        this.txFrame.offset = 0;

         if(this.logger.isEnabledFor(Level.TRACE)){
             logger.trace("Queue FISU");
@@ -524,14 +553,10 @@
     }

     private void queueNextFrame() {
-        if (this.state != MTP2_INSERVICE && !this.txQueue.isEmpty()) {
-            byte[] b = txQueue.peak();
-            System.arraycopy(b, 0, txFrame, 0, b.length);
-            this.txLen = b.length;
-            if(logger.isTraceEnabled())
-            {
- logger.trace("Scheduling frame from queue: "+Utils.dump(txFrame, txLen, true));
-            }
+        if (this.state != MTP2_INSERVICE && this.pendingLSSU) {
+               this.txFrame = nextStateFrame;
+               this.pendingLSSU = false;
+
         } else {
             switch (state) {
                 case MTP2_OUT_OF_SERVICE:
@@ -558,27 +583,23 @@

// in service, we need to check buffer, otherwise its RTR
                     if (this.retransmissionFSN != _OFF_RTR) {
- Mtp2SendBuffer buffer = this.transmissionBuffer[this.retransmissionFSN]; + Mtp2Buffer buffer = this.transmissionBuffer[this.retransmissionFSN];
                         // we shoudl use getters, but its faster with "."
-
- System.arraycopy(buffer.frame, 0, txFrame, 0, buffer.len);
-                        this.txLen = buffer.len;
- this.txFrame[0] = (byte) (this.sendBSN | (this.sendBIB << 7)); - this.txFrame[1] = (byte) (this.retransmissionFSN | (this.sendFIB << 7));
-
+                        this.txFrame = buffer;
+                        this.txFrame.offset = 0;
+ this.txFrame.frame[0] = (byte) (this.sendBSN | (this.sendBIB << 7)); + this.txFrame.frame[1] = (byte) (this.retransmissionFSN | (this.sendFIB << 7));
+
if (this.retransmissionFSN == this.retransmissionFSN_LastSent) {
                             this.retransmissionFSN = _OFF_RTR;
                         } else {
                             // set up next :)
this.retransmissionFSN = NEXT_FSN(this.retransmissionFSN);
                         }
-                        // if (this.enabledL2Debug) {
-                        // trace("Scheduled next frame in tx buffer: "
-                        // + dump(this.txFrame, this.txLen, false));
-                        // }
+
                         if(logger.isTraceEnabled())
                         {
- logger.trace("Retransmiting frame: "+Utils.dump(txFrame, txLen, true)); + logger.trace("Retransmiting frame: "+Utils.dump(txFrame.frame, txFrame.len, true));
                         }
                         return;
                     }
@@ -593,9 +614,9 @@
         return ((fcs) >> 8) ^ fcstab[((fcs) ^ (c)) & 0xff];
     }

-    private void processLssu(int fsn, int bsn) {
-        int type = rxFrame[3] & 0x07;
-        //
+    private void processLssu() {
+       //Q703 Figure 4
+        int type = rxFrame.frame[3] & 0x07;

         switch (this.state) {
             case MTP2_NOT_ALIGNED:
@@ -612,7 +633,6 @@
                             queueLSSU(FRAME_STATUS_INDICATION_N);
                         }
                         start_T3();
-                        //this.state = MTP2_ALIGNED;

                         this.setState(MTP2_ALIGNED);
                         break;
@@ -631,13 +651,11 @@
                         // 4. start T3
                         start_T3();
                         // 5. set state
-                        //this.state = MTP2_ALIGNED;

                         this.setState(MTP2_ALIGNED);
                         break;
                     default:
-                    // logger.warn("Ingoring LSSU[" + _FRAME_NAMES[type]
-                    // + "] on state[" + _STATE_NAMES[state] + "]");
+
                 }
                 // BREAK For NOT_ALIGNED state
                 break;
@@ -666,7 +684,6 @@
                         // 6. cancel further proving.
                         this.futureProving = false;
                         // 7. set state
-                        //this.state = MTP2_PROVING;

                         this.setState(MTP2_PROVING);
                         break;
@@ -682,8 +699,7 @@

                         break;
                     default:
-                    // logger.warn("Ingoring LSSU[" + _FRAME_NAMES[type]
-                    // + "] on state[" + _STATE_NAMES[state] + "]");
+
                 }

                 // BREAK for ALIGNED state.
@@ -698,7 +714,6 @@
                         // 3. start T3
                         start_T3();
                         // 4. swithc state
-                        //this.state = MTP2_ALIGNED;

                         this.setState(MTP2_ALIGNED);
                         break;
@@ -794,47 +809,27 @@

     private void processMSU(int len) {
         if (this.mtp3 != null) {
-            int sio = rxFrame[3];
-            int realLength = 0;
-            if (len == 63) {
- // -5 = (FIB+FSN(1)) - (BIB+BSN(1)) - java(zero index: 1) -2(CRC)
-                realLength = rxLen - 5;
-            //was -4
-            } else {
-                realLength = len;
-            }
-
-            byte[] sif = new byte[realLength];
-            // for (int i = 0; i < len - 1; i++) {
-            // sif[i] = (byte) rxFrame[i + 4];
-            // }
-            for (int i = 0; i < realLength; i++) {
-                sif[i] = (byte) rxFrame[i + 3];
-            }
-            // FIXME: switch to this
-            // System.arraycopy(rxFrame, 4, sif, 0, realLength);
-
-            if (logger.isEnabledFor(Level.TRACE)) {
- logger.trace(String.format("(%s) Delivering MSU to layer 3 ", name));
-            }
-            mtp3.onMessage(sio, sif, this);
+               mtp3.onMessage(rxFrame,this);
         }
     }
-
+
     private void processFrame() {
-        int bsn = rxFrame[0] & 0x7F;
-        int bib = (rxFrame[0] >> 7) & 0x01;
-        int fsn = rxFrame[1] & 0x7F;
-        int fib = (rxFrame[1] >> 7) & 0x01;
-
-        int li = rxFrame[2] & 0x3f;
+
+
+        int bsn = rxFrame.frame[0] & 0x7F;
+        int bib = (rxFrame.frame[0] >> 7) & 0x01;
+        int fsn = rxFrame.frame[1] & 0x7F;
+        int fib = (rxFrame.frame[1] >> 7) & 0x01;
+
+        int li = rxFrame.frame[2] & 0x3f;

         if (logger.isTraceEnabled()) {
             String type = null;
             if (li == 0) {
                 type = "FISU";
             } else if (li == 1 || li == 2) {
-                int lssuType = rxFrame[3] & 0x07;
+                //int lssuType = rxFrame[3] & 0x07;
+               int lssuType = rxFrame.frame[3] & 0x07;
                 type = "LSSU(" + FRAME_NAMES[lssuType] + ")";
             } else {
                 type = "MSU";
@@ -845,21 +840,23 @@
         }

         //Why it was 5?
-        if (li + 3 > rxLen) {
+//        if (li + 3 > rxLen) {
+        if (li + 3 > rxFrame.len) {

                if(this.logger.isEnabledFor(Level.TRACE)){
- logger.trace("Discarding frame on wrong RX Len: " + rxLen + " > " + li); + logger.trace("Discarding frame on wrong RX Len: " + rxFrame.len + " > " + li);
                }
             return;
         }

         if (li == 1 || li == 2) {
-
+
             // LSSU does not count for IAM check for SU
-            processLssu(fsn, bsn);
+            processLssu();
// LSSU does not go into BSN/FSN check, its always static for this
             // part.
             // and if we get here from IN_SERVICE, everything is reset.
+
             return;
         }

@@ -894,8 +891,6 @@
                     this.sendBIB = fib;
                     this.retransmissionFSN_LastAcked = bsn;

-                    //this.state = MTP2_INSERVICE;
-
                     if (logger.isDebugEnabled()) {
logger.debug(String.format("(%s) MTP now IN_SERVICE, Notifing layer 3", name));
                     }
@@ -1012,6 +1007,7 @@
                 return;
             }
             processMSU(li);
+
         }

     }
@@ -1025,92 +1021,92 @@
      *            the number of received bytes.
      */
     private void processRx(byte[] buff, int len) {
-        // private void processRx(ByteBuffer bb, int len) {
-
-        int i = 0;
-
-        // start HDLC alg
-        while (i < len) {
-            while (rxState.bits <= 24 && i < len) {
-                int b = buff[i++] & 0xff;
-                hdlc.fasthdlc_rx_load_nocheck(rxState, b);
-                if (rxState.state == 0) {
-                    // octet counting mode
-                    nCount = (nCount + 1) % 16;
-                    if (nCount == 0) {
-                        countError("on receive");
-                    }
-                }
-            }
-
-            int res = hdlc.fasthdlc_rx_run(rxState);
-
-            switch (res) {
-                case FastHDLC.RETURN_COMPLETE_FLAG:
-                    // frame received and we count it
-                    countFrame();
-
-                    // checking length and CRC of the received frame
-                    if (rxLen == 0) {
-                    } else if (rxLen < 5) {
-                        // frame must be at least 5 bytes in length
-                        countError("hdlc error, frame LI<5");
-
-                    } else if (rxCRC == 0xF0B8) {
-                        // good frame received
-                        processFrame();
-                    } else {
-                        countError("hdlc complete, wrong terms.");
-
-                    }
-                    rxLen = 0;
-                    rxCRC = 0xffff;
-                    break;
-                case FastHDLC.RETURN_DISCARD_FLAG:
-                    // looking for next flag
-                    rxCRC = 0xffff;
-                    rxLen = 0;
-                    // eCount = 0;
-                    countFrame();
-                    // "on receive, hdlc discard"
-
-                    countError("hdlc discard.");
-
-                    break;
-                case FastHDLC.RETURN_EMPTY_FLAG:
-
-                    rxLen = 0;
-                    break;
-                default:
-                    if (rxLen > 279) {
-
-                        rxState.state = 0;
-                        rxLen = 0;
-                        rxCRC = 0xffff;
-                        eCount = 0;
-                        countFrame();
- countError("Overlong MTP frame, entering octet mode on link '" + name + "'");
-
-                    } else {
-
-                        rxFrame[rxLen++] = res;
-                        rxCRC = PPP_FCS(rxCRC, res & 0xff);
-                    }
-            }
-
-        }
+
+        int i = 0;
+
+         // start HDLC alg
+         while (i < len) {
+             while (rxState.bits <= 24 && i < len) {
+                 int b = buff[i++] & 0xff;
+                 hdlc.fasthdlc_rx_load_nocheck(rxState, b);
+                 if (rxState.state == 0) {
+                     // octet counting mode
+                     nCount = (nCount + 1) % 16;
+                     if (nCount == 0) {
+                         countError("on receive");
+                     }
+                 }
+             }
+
+             int res = hdlc.fasthdlc_rx_run(rxState);
+
+             switch (res) {
+                 case FastHDLC.RETURN_COMPLETE_FLAG:
+                     // frame received and we count it
+                     countFrame();
+
+                     // checking length and CRC of the received frame
+                     if (rxFrame.len == 0) {
+                     } else if (rxFrame.len < 5) {
+                         // frame must be at least 5 bytes in length
+                         countError("hdlc error, frame LI<5");
+
+                     } else if (rxCRC == 0xF0B8) {
+                         // good frame received
+                         processFrame();
+                     } else {
+                         countError("hdlc complete, wrong terms.");
+
+                     }
+                     rxFrame.len = 0;
+                     rxCRC = 0xffff;
+                     break;
+                 case FastHDLC.RETURN_DISCARD_FLAG:
+                     // looking for next flag
+                     rxCRC = 0xffff;
+                     rxFrame.len = 0;
+                     // eCount = 0;
+                     countFrame();
+                     // "on receive, hdlc discard"
+
+                     countError("hdlc discard.");
+
+                     break;
+                 case FastHDLC.RETURN_EMPTY_FLAG:
+
+                        rxFrame.len = 0;
+                     break;
+                 default:
+                     if (rxFrame.len > 279) {
+
+                         rxState.state = 0;
+                         rxFrame.len = 0;
+                         rxCRC = 0xffff;
+                         eCount = 0;
+                         countFrame();
+ countError("Overlong MTP frame, entering octet mode on link '" + name + "'");
+
+                     } else {
+
+                        rxFrame.frame[rxFrame.len++] = (byte)res;
+                         rxCRC = PPP_FCS(rxCRC, res & 0xff);
+                     }
+             }
+
+         }
     }

     private void processTx(int bytesRead) throws IOException {

-        for (int i = 0; i < bytesRead && i < RX_TX_BUFF_SIZE; i++) {
+
+       for (int i = 0; i < bytesRead && i < RX_TX_BUFF_SIZE; i++) {
             if (txState.bits < 8) {
                 // need more bits
-                if (doCRC == 0 && txOffset < txLen) {
-                    int data = txFrame[txOffset++] & 0xff;
+                if (doCRC == 0 && txFrame.offset < txFrame.len) {
+                    int data = txFrame.frame[txFrame.offset++] & 0xff;
                     hdlc.fasthdlc_tx_load(txState, data);
                     txCRC = PPP_FCS(txCRC, data);
-                    if (txOffset == txLen) {
+                    if (txFrame.offset == txFrame.len) {
                         doCRC = 1;
                         txCRC ^= 0xffff;
                     }
@@ -1125,9 +1121,7 @@

                     queueNextFrame();

-                    // txFrame = txQueue.peak();
-                    // txLen = txFrame.length;
-                    txOffset = 0;
+                    txFrame.offset = 0;
                     txCRC = 0xffff;
                     hdlc.fasthdlc_tx_frame_nocheck(txState);
                 }
@@ -1135,7 +1129,7 @@
// txBuffer.put(i, (byte) hdlc.fasthdlc_tx_run_nocheck(txState));
             txBuffer[i] = (byte) hdlc.fasthdlc_tx_run_nocheck(txState);
         }
-
+
     }

     public void doRead() {
@@ -1149,7 +1143,7 @@
                     processRx(rxBuffer, bytesRead);
                 }
             } catch (Exception e) {
-                //state = MTP2_OUT_OF_SERVICE;
+
                if(logger.isEnabledFor(Level.ERROR))
                {
logger.error(String.format("(%s) Can not read data from channel", name), e);
@@ -1171,7 +1165,6 @@
                logger.trace("Sending frame");
             }
         } catch (Exception e) {
-            //state = MTP2_OUT_OF_SERVICE;
                if(logger.isEnabledFor(Level.ERROR))
                {
logger.error(String.format("(%s) Can not write data to channel", name), e);
@@ -1205,7 +1198,6 @@
                 this.mtp3.linkFailed(this);
             }
         }
-        //this.state = MTP2_OUT_OF_SERVICE;
         this.setState(MTP2_OUT_OF_SERVICE);
         // NOTE: buffer is flushed on start alignment.
         start_T17();
@@ -1226,7 +1218,6 @@
             }
         }

-        //this.state = MTP2_OUT_OF_SERVICE;
         this.setState(MTP2_OUT_OF_SERVICE);
         // NOTE: buffer is flushed on start alignment.
         start_T17();
@@ -1250,7 +1241,6 @@
         stop_T2();
         stop_T3();
         stop_T4();
-        //this.state = MTP2_ALIGNED_READY;

         if (logger.isDebugEnabled()) {
             logger.debug(String.format("(%s) Aligned ready", name));
@@ -1271,7 +1261,7 @@
                     if (this.mtp3 != null) {
                         mtp3.linkFailed(this);
                     }
-                    //state = MTP2_OUT_OF_SERVICE;
+
                     this.setState(MTP2_OUT_OF_SERVICE);
                 }
                 break;
@@ -1281,7 +1271,7 @@
                         // start T17 ? check for alignemtn count;
                         // see Q.703 p.55
                         this.provingAttempts++;
-                        if (this.provingAttempts < 5) {
+ if (this.provingAttempts < PROVING_ATTEMPTS_THRESHOLD) {
                             this.futureProving = true;

                             if(this.logger.isEnabledFor(Level.WARN)){
@@ -1491,33 +1481,6 @@
         return !t17Action.isCanceled();
     }

-
-
-
-    // ////////////////////
-    // Some mtp classes //
-    // ////////////////////
-    private class Mtp2SendBuffer {
-        // FIXME: is 272 max data length?
-        /**
-         * data in this frame.
-         */
-        byte[] frame = new byte[272 + 7]; // +7 - 272 is max SIF part len,
-        /**
-         * length of actual data fram to be transmited.
-         */
-        int len = 0;        // public boolean isFree()
-    }
-
-//    private void log(String msg, Level level) {
-// // FIXME: yeah, I know, but in case of more links, logs will be a pain
-//        StringBuilder sb = new StringBuilder();
-//
-//        //
-// sb.append(" Link [").append(name).append("] [").append(" state = ").append( STATE_NAMES[state]).append(" ] ").append(msg);
-//        logger.log(level, sb.toString());
-//
-//    }

     private static final int NEXT_FSN(int x) {
         // kill FIB if present
=======================================
--- /trunk/protocols/ss7/mtp/mtp-impl/src/main/java/org/mobicents/protocols/ss7/mtp/Mtp3.java Tue Nov 30 02:16:54 2010 +++ /trunk/protocols/ss7/mtp/mtp-impl/src/main/java/org/mobicents/protocols/ss7/mtp/Mtp3.java Fri Dec 10 00:49:19 2010
@@ -65,8 +65,11 @@
     private int dpc;
     private int opc;
     private int ni=DEFAULT_NI << 2; // << cause its faster for checks.
-
-
+    /**
+     * Local byte[], in which we forge messages.
+     */
+    private byte[] localFrame = new byte[279];
+    private byte[][] localBuffers;
     /** List of signaling channels wrapped with MTP2*/
     private List<Mtp2> links = new ArrayList();

@@ -97,6 +100,11 @@
         } catch (Exception e) {
             e.printStackTrace();
         }
+        this.localBuffers = new byte[300][];
+        for(int i=0;i<300;i++)
+        {
+               this.localBuffers[i] = new byte[i];
+        }
     }

     /**
@@ -229,156 +237,159 @@
      * @param msg
      *            service information field;
      */
-    public void onMessage(int sio, byte[] sif, Mtp2 mtp2) {
-            int subserviceIndicator = (sio >> 4) & 0x0F;
-            int serviceIndicator = sio & 0x0F;
- int ni = (subserviceIndicator & 0x0C) ; //local NI(network Indicator) form msg., 0x0C, since we store it as shifted value.
-            // int dpc = (sif[0] & 0xff | ((sif[1] & 0x3f) << 8));
- // int opc = ((sif[1] & 0xC0) >> 6) | ((sif[2] & 0xff) << 2) | ((sif[3]
-            // & 0x0f) << 10);
-            // int sls = (sif[3] & 0xf0) >>> 4;
- int dpc = dpc(sif, 1); //1 - cause sif contains sio, even though its also passed as arg.
-            int opc = opc(sif, 1);
-            int sls = sls(sif, 1);
-
- //check SSI, Q.704 Figure 25, seems like if its bad, we discard.
-            if(this.ni!=ni)
-            {
-               if (logger.isTraceEnabled()) {
-                    logger.trace(
- String.format("(%s) Received MSSU with bad SSI, discarding! [si=" + serviceIndicator + ",ssi=" + subserviceIndicator + ", dpc=" + dpc + ", opc=" + opc + ", sls=" + sls + "] data: ", mtp2.getName()) + Arrays.toString(sif));
-                }
-               return;
-            }else if (logger.isTraceEnabled()) {
+
+    public void onMessage(Mtp2Buffer rxFrame, Mtp2 mtp2)
+    {
+ // | ----------------------- TO L4 --------------------------- | + // | --------------------- SIF ------------------------ |
+       //FSN   BSN   LEN    SIO    DPC/OPC,SLS    HEADING     LEN
+ //b1 b0 0e 01 01 80 00 00 21 70 01 02 03 04 05 06 0f CRC CRC
+       int sio = rxFrame.frame[3] & 0xFF;
+       int subserviceIndicator = (sio >> 4) & 0x0F;
+        int serviceIndicator = sio & 0x0F;
+ int ni = (subserviceIndicator & 0x0C) ; //local NI(network Indicator) form msg., 0x0C, since we store it as shifted value.
+        // int dpc = (sif[0] & 0xff | ((sif[1] & 0x3f) << 8));
+ // int opc = ((sif[1] & 0xC0) >> 6) | ((sif[2] & 0xff) << 2) | ((sif[3]
+        // & 0x0f) << 10);
+        // int sls = (sif[3] & 0xf0) >>> 4;
+ int dpc = dpc(rxFrame.frame, 4); //1 - cause sif contains sio, even though its also passed as arg.
+        int opc = opc(rxFrame.frame, 4);
+        int sls = sls(rxFrame.frame, 4);
+
+        //check SSI, Q.704 Figure 25, seems like if its bad, we discard.
+        if(this.ni!=ni)
+        {
+               if (logger.isTraceEnabled()) {
                 logger.trace(
- String.format("(%s) Received MSSU [si=" + serviceIndicator + ",ssi=" + subserviceIndicator + ", dpc=" + dpc + ", opc=" + opc + ", sls=" + sls + "] data: ", mtp2.getName()) + Arrays.toString(sif));
-            }
-
-
-            switch (serviceIndicator) {
-                case LINK_MANAGEMENT:
-                    int h0 = sif[5] & 0x0f;
-                    int h1 = (sif[5] & 0xf0) >>> 4;
-
+ String.format("(%s) Received MSSU with bad SSI, discarding! [si=" + serviceIndicator + ",ssi=" + subserviceIndicator + ", dpc=" + dpc + ", opc=" + opc + ", sls=" + sls + "] data: ", mtp2.getName()) + Arrays.toString(rxFrame.frame));
+            }
+               return;
+        }else if (logger.isTraceEnabled()) {
+            logger.trace(
+ String.format("(%s) Received MSSU [si=" + serviceIndicator + ",ssi=" + subserviceIndicator + ", dpc=" + dpc + ", opc=" + opc + ", sls=" + sls + "] data: ", mtp2.getName()) + Arrays.toString(rxFrame.frame));
+        }
+
+
+        switch (serviceIndicator) {
+            case LINK_MANAGEMENT:
+                int h0 = rxFrame.frame[8] & 0x0f;
+                int h1 = (rxFrame.frame[8] & 0xf0) >>> 4;
+
+                if (logger.isDebugEnabled()) {
+ logger.debug(String.format("(%s) Signalling network management", mtp2.getName()));
+                }
+
+                if (h0 == 0) {
                     if (logger.isDebugEnabled()) {
- logger.debug(String.format("(%s) Signalling network management", mtp2.getName()));
-                    }
-
-                    if (h0 == 0) {
-                        if (logger.isDebugEnabled()) {
- logger.debug(String.format("(%s) Changeover management", mtp2.getName()));
-                        }
-                    } else if (h0 == 7 && h1 == 1) {
-                        if (logger.isDebugEnabled()) {
- logger.debug(String.format("(%s) TRA received", mtp2.getName()));
-                        }
-                    }
-                    //FIX ME
-                    break;
-                case LINK_TESTING:
-                    h0 = sif[5] & 0x0f;
-                    h1 = (sif[5] & 0xf0) >>> 4;
-
-                    int len = (sif[6] & 0xf0) >>> 4;
-
-                    if (h0 == 1 && h1 == 1) {
-                       if (logger.isDebugEnabled()) {
- logger.debug(String.format("(%s) Received SLTM", mtp2.getName()));
-                        }
-                        // receive SLTM from remote end
-                        // create response
-                        byte[] slta = new byte[len + 7];
-
-
-                        //change order of opc/dpc in SLTA !
- writeRoutingLabel(slta, 0, this.ni << 2, sls, opc, dpc);
-                        slta[0] = (byte) sio;
-                        slta[5] = 0x021;
-                        // +1 cause we copy LEN byte also.
-                        System.arraycopy(sif, 6, slta, 6, len + 1);
-
-                        if (logger.isDebugEnabled()) {
- logger.debug(String.format("(%s) Responding with SLTA", mtp2.getName()));
-                        }
-                        mtp2.send(slta, slta.length);
-                    } else if (h0 == 1 && h1 == 2) {
-                        // receive SLTA from remote end
-                       if (logger.isDebugEnabled()) {
- logger.debug(String.format("(%s) Received SLTA", mtp2.getName()));
-                        }
-
-                        //checking pattern
-                        if (checkPattern(sif, SLTM_PATTERN)) {
-                            //test message is acknowledged
-                            mtp2.sltmTest.ack();
-
-                            //notify top layer that link is up
-                            if (!l4IsUp) {
-                                l4IsUp = true;
-                                linkUp(mtp2);
-                            }
-                        } else {
-                               if(logger.isEnabledFor(Level.WARN))
-                               {
- logger.warn("SLTA pattern does not match: \n"+Arrays.toString(sif)+"\n"+Arrays.toString(SLTM_PATTERN));
-                               }
+ logger.debug(String.format("(%s) Changeover management", mtp2.getName()));
+                    }
+                } else if (h0 == 7 && h1 == 1) {
+                    if (logger.isDebugEnabled()) {
+ logger.debug(String.format("(%s) TRA received", mtp2.getName()));
+                    }
+                }
+                //FIX ME
+                break;
+            case LINK_TESTING:
+                h0 = rxFrame.frame[8] & 0x0f;
+                h1 = (rxFrame.frame[8] & 0xf0) >>> 4;
+
+                int len = (rxFrame.frame[9] & 0xf0) >>> 4;
+
+                if (h0 == 1 && h1 == 1) {
+                       if (logger.isDebugEnabled()) {
+ logger.debug(String.format("(%s) Received SLTM", mtp2.getName()));
+                    }
+                    // receive SLTM from remote end
+                    // create response
+
+                    //change order of opc/dpc in SLTA !
+ writeRoutingLabel(this.localFrame, sio, this.ni << 2, sls, opc, dpc);
+                    //slta[0] = (byte) sio;
+                    this.localFrame[5] = 0x021;
+                    // +1 cause we copy LEN byte also.
+ System.arraycopy(rxFrame.frame, 9, this.localFrame, 6, len + 1);
+
+                    if (logger.isDebugEnabled()) {
+ logger.debug(String.format("(%s) Responding with SLTA", mtp2.getName()));
+                    }
+                    mtp2.send( this.localFrame, len+9);
+                } else if (h0 == 1 && h1 == 2) {
+                    // receive SLTA from remote end
+                       if (logger.isDebugEnabled()) {
+ logger.debug(String.format("(%s) Received SLTA", mtp2.getName()));
+                    }
+
+                    //checking pattern
+                    if (checkPattern(rxFrame,len, SLTM_PATTERN)) {
+                        //test message is acknowledged
+                        mtp2.sltmTest.ack();
+
+                        //notify top layer that link is up
+                        if (!l4IsUp) {
+                            l4IsUp = true;
+                            linkUp(mtp2);
                         }
                     } else {
                        if(logger.isEnabledFor(Level.WARN))
                        {
- logger.warn(String.format("(%s) Unexpected message type", mtp2.getName())); + logger.warn("SLTA pattern does not match: \n"+Arrays.toString(rxFrame.frame)+"\n"+Arrays.toString(SLTM_PATTERN));
                        }
                     }
-                    break;
-                case _SI_SERVICE_SCCP:
-                       if (logger.isDebugEnabled()) {
-                        logger.debug("Received SCCP MSU");
-
-                    }
-
-                    if (mtp3Listener != null) {
-
-                        byte[] message = new byte[sif.length + 1];
-                        System.arraycopy(sif, 0, message, 1, sif.length);
-                        message[0] = (byte) sio;
-                        try {
-                            mtp3Listener.receive(message);
-                        } catch (Exception e) {
-                            e.printStackTrace();
-                        }
-                    }
-                    break;
-                case _SI_SERVICE_ISUP:
-                       if (logger.isDebugEnabled()) {
-                        logger.debug("Received ISUP MSU");
-
-                    }
-                    if (mtp3Listener != null) {
-                        //baranowb: pushed this, unless someone can tell me
-                       //why there was diff in code for SCCP && ISUP
-                       byte[] message = new byte[sif.length + 1];
-                        System.arraycopy(sif, 0, message, 1, sif.length);
-                        message[0] = (byte) sio;
-                        try {
-                            mtp3Listener.receive(message);
-                        } catch (Exception e) {
-                            e.printStackTrace();
-                        }
-                    }
-                    break;
-                default:
-                    if (logger.isEnabledFor(Level.WARN) ) {
- logger.warn("Received MSU for UNKNOWN SERVICE!!!!!!!!!!!: " + Utils.dump(sif, sif.length, false));
-                    }
-                    break;
-            }
-        //creating handler for received message and schedule execution
-//        MessageHandler handler = new MessageHandler(sio, sif, mtp2);
-//        handler.run();
-//        processor.execute(handler);
-    }
-
-    /**
+                } else {
+                       if(logger.isEnabledFor(Level.WARN))
+                       {
+ logger.warn(String.format("(%s) Unexpected message type", mtp2.getName()));
+                       }
+                }
+                break;
+            case _SI_SERVICE_SCCP:
+               if (logger.isDebugEnabled()) {
+                    logger.debug("Received SCCP MSU");
+                }
+
+                if (mtp3Listener != null) {
+
+ // | ----------------------- TO L4 --------------------------- | + // | --------------------- SIF ------------------------ |
+                       //FSN   BSN   LEN    SIO    DPC/OPC,SLS    HEADING     
LEN
+ //b1 b0 0e 01 01 80 00 00 21 70 01 02 03 04 05 06 0f CRC CRC + byte[] messageBuffer = fetchBuffer(rxFrame.len-5); //-5 = FSN(1) + BSN(1) + LEN(1) +2xCRC(1) + System.arraycopy(rxFrame.frame, 3, messageBuffer, 0, rxFrame.len-5);
+                    //messageBuffer[0] = (byte) sio;
+                    try {
+                        mtp3Listener.receive(messageBuffer);
+                    } catch (Exception e) {
+                        e.printStackTrace();
+                    }
+                }
+                break;
+            case _SI_SERVICE_ISUP:
+               if (logger.isDebugEnabled()) {
+                    logger.debug("Received ISUP MSU");
+
+                }
+                if (mtp3Listener != null) {
+                       byte[] messageBuffer = fetchBuffer(rxFrame.len-5);
+ System.arraycopy(rxFrame.frame, 3, messageBuffer, 0, rxFrame.len-5);
+                     //messageBuffer[0] = (byte) sio;
+                    try {
+                        mtp3Listener.receive(messageBuffer);
+                    } catch (Exception e) {
+                        e.printStackTrace();
+                    }
+                }
+                break;
+            default:
+                if (logger.isEnabledFor(Level.WARN) ) {
+ logger.warn("Received MSU for UNKNOWN SERVICE!!!!!!!!!!!: " + Utils.dump(rxFrame.frame, rxFrame.len, false));
+                }
+                break;
+        }
+    }
+
+
+       /**
      * Selects link for transmission using link selection indicator.
      *
      * @param sls signaling link selection indicator.
@@ -486,39 +497,40 @@

     private void restartTraffic(Mtp2 link) {

-        byte[] buffer = new byte[6];
-        writeRoutingLabel(buffer, 0, this.ni, 0, dpc, opc);
+        writeRoutingLabel(this.localFrame, 0, this.ni, 0, dpc, opc);

         // H0 and H1, see Q.704 section 15.11.2+
-        buffer[5] = 0x17;
-        link.send(buffer, buffer.length);
- } // -6 cause we have in sif, sio+label+len of pattern - thats 1+4+1 = 6
-    private final static int SIF_PATTERN_OFFSET = 7;
-
-    /**
-     * Performs test message check.
-     *
-     * @param sif the response test message
-     * @param pattern expected message content
-     * @return true if message content matches to specfied pattern
-     */
-    private boolean checkPattern(byte[] sif, byte[] pattern) {
-        if (sif.length - SIF_PATTERN_OFFSET != pattern.length) {
+        this.localFrame[5] = 0x17;
+        link.send(this.localFrame, 6);
+    }
+
+    private final static int PATTERN_OFFSET = 10;
+ private final static int PATTERN_LEN_OFFSET = PATTERN_OFFSET+2; //+2 becuase frame.len contains 2B for CRC
+
+ private boolean checkPattern(Mtp2Buffer frame,int sltmLen, byte[] pattern) {
+        if (frame.len - PATTERN_LEN_OFFSET != pattern.length) {
             return false;
         }
         for (int i = 0; i < pattern.length; i++) {
-            if (sif[i + SIF_PATTERN_OFFSET] != pattern[i]) {
+            if (frame.frame[ i + PATTERN_OFFSET ] != pattern[i]) {
                 return false;
             }
         }
         return true;
     }
-
+
+    /**
+        * @param i
+        * @return
+        */
+       private byte[] fetchBuffer(int size) {
+               return this.localBuffers[size];
+       }
     protected class SLTMTest extends MTPTask {

         private Mtp2 link;
         private int tryCount;        //SLTM message buffer;
-        private byte[] sltm = new byte[7 + SLTM_PATTERN.length];
+ private byte[] sltm = new byte[7 + SLTM_PATTERN.length]; //this has to be separate, cause its async to Mtp3.send

         private SLTMTest(Mtp2 link) {
             this.link = link;
@@ -635,12 +647,16 @@

public static void writeRoutingLabel(byte[] data, int si, int ssi, int sls, int dpc, int opc) {
         //see Q.704.14.2
-        data[0] = (byte) (((ssi & 0x0F) << 4) | (si & 0x0F));
-        data[1] = (byte) dpc;
-        data[2] = (byte) (((dpc >> 8) & 0x3F) | ((opc & 0x03) << 6));
-        data[3] = (byte) (opc >> 2);
-        data[4] = (byte) (((opc >> 10) & 0x0F) | ((sls & 0x0F) << 4));
+        writeRoutingLabel(0,data, si, ssi, sls, dpc, opc);

     }
-
-}
+ public static void writeRoutingLabel(int shift, byte[] data, int si, int ssi, int sls, int dpc, int opc) {
+        //see Q.704.14.2
+        data[0+shift] = (byte) (((ssi & 0x0F) << 4) | (si & 0x0F));
+        data[1+shift] = (byte) dpc;
+        data[2+shift] = (byte) (((dpc >> 8) & 0x3F) | ((opc & 0x03) << 6));
+        data[3+shift] = (byte) (opc >> 2);
+ data[4+shift] = (byte) (((opc >> 10) & 0x0F) | ((sls & 0x0F) << 4));
+
+    }
+}

Reply via email to