Revision: 201031 RCL_3
authorDremov Kirill (Nokia-D-MSW/Tampere) <kirill.dremov@nokia.com>
Thu, 19 Aug 2010 11:01:00 +0300
branchRCL_3
changeset 41 786b94c6f0a4
parent 40 14e240312f6f
child 43 5b153be919d4
Revision: 201031 Kit: 201033
atext/plugins/group/bld.inf
atext/plugins/limitedpdpplugin/group/bld.inf
atext/plugins/limitedpdpplugin/group/limitedpdpplugin.mmp
atext/plugins/limitedpdpplugin/inc/debug.h
atext/plugins/limitedpdpplugin/inc/debugconfig.h
atext/plugins/limitedpdpplugin/inc/limitedpdpplugin.h
atext/plugins/limitedpdpplugin/inc/limitedpdpplugincopiedkeys.h
atext/plugins/limitedpdpplugin/inc/prjconfig.h
atext/plugins/limitedpdpplugin/rom/limitedpdpplugin.iby
atext/plugins/limitedpdpplugin/src/20031617.rss
atext/plugins/limitedpdpplugin/src/limitedpdpplugin.cpp
atext/plugins/limitedpdpplugin/src/proxy.cpp
atext/server/inc/atextmetadata.h
atext/server/src/atextmetadata.cpp
bluetooth/btexample/example/btproperties/BTProperties.cpp
bluetooth/btexample/example/eir/teir.cpp
bluetooth/btsdp/server/epocsvr.cpp
bluetooth/btstack/avdtp/avdtpDirectChannel.cpp
bluetooth/btstack/avdtp/avdtpDirectChannel.h
bluetooth/btstack/avdtp/avdtpLogicalChannelFactory.cpp
bluetooth/btstack/avdtp/avdtpMediaSession.cpp
bluetooth/btstack/avdtp/avdtpMuxChannel.cpp
bluetooth/btstack/avdtp/avdtpMuxChannel.h
bluetooth/btstack/avdtp/avdtpStream.cpp
bluetooth/btstack/avdtp/avdtpStream.h
bluetooth/btstack/avdtp/avdtpStreamStates.cpp
bluetooth/btstack/avdtp/avdtpTransportChannel.cpp
bluetooth/btstack/avdtp/avdtpTransportChannel.h
bluetooth/btstack/l2cap/L2CapFecNegotiator.cpp
bluetooth/btstack/l2cap/L2CapFecNegotiator.h
bluetooth/btstack/l2cap/l2capSigStates.cpp
bluetooth/btstack/l2cap/l2sap.cpp
bluetooth/btstack/l2cap/l2signalmgr.cpp
bluetooth/btstack/linkmgr/hcifacade_commands.cpp
bluetooth/btstack/linkmgr/hostresolver.cpp
bluetooth/btstack/linkmgr/physicallinks.cpp
bluetooth/btstack/linkmgr/physicallinks.h
bluetooth/btstack/secman/pairingserver.cpp
bluetooth/btstack/secman/pairingserver.h
bluetooth/btstack/secman/public/pairingservershared.h
bluetooth/gavdp/inc/gavdpInternal.h
bluetooth/gavdp/source/gavdpHelpers.cpp
bluetooth/gavdp/source/gavdpImp.cpp
bluetoothcommsprofiles/btpan/refBnepPacketNotifier/src/refBnepPacketNotifier.cpp
bluetoothmgmt/bluetoothclientlib/btlib/btsynclink.cpp
bluetoothmgmt/bluetoothclientlib/btlib/btsynclinkhelpers.h
bluetoothmgmt/bluetoothclientlib/inc/bt_sock.h
bluetoothmgmt/btrom/bluetooth.iby
bthci/bthci2/group/hci_framework.iby
--- a/atext/plugins/group/bld.inf	Thu Jul 15 19:55:36 2010 +0300
+++ b/atext/plugins/group/bld.inf	Thu Aug 19 11:01:00 2010 +0300
@@ -24,5 +24,6 @@
 
 PRJ_MMPFILES
 #include "../legacymodemplugin/group/bld.inf"
+#include "../limitedpdpplugin/group/bld.inf"
 
 PRJ_TESTMMPFILES
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/atext/plugins/limitedpdpplugin/group/bld.inf	Thu Aug 19 11:01:00 2010 +0300
@@ -0,0 +1,29 @@
+/*
+* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  This file provides the information required for building the
+*               whole of limitedpdpplugin
+*
+*/
+
+#include <platform_paths.hrh>
+
+PRJ_PLATFORMS
+
+PRJ_EXPORTS
+../rom/limitedpdpplugin.iby     CORE_OS_LAYER_IBY_EXPORT_PATH(limitedpdpplugin.iby)
+
+PRJ_MMPFILES
+limitedpdpplugin.mmp
+
+PRJ_TESTMMPFILES
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/atext/plugins/limitedpdpplugin/group/limitedpdpplugin.mmp	Thu Aug 19 11:01:00 2010 +0300
@@ -0,0 +1,51 @@
+/*
+* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Project definition file for project limitedpdpplugin
+*
+*/
+
+
+#include <platform_paths.hrh>
+
+TARGET                  limitedpdpplugin.dll
+TARGETTYPE              PLUGIN
+UID                     0x10009D8D 0x20031617
+
+CAPABILITY              CAP_ECOM_PLUGIN
+VENDORID                VID_DEFAULT
+
+SOURCEPATH              ../src
+SOURCE                  proxy.cpp
+SOURCE                  limitedpdpplugin.cpp
+
+START RESOURCE          ../src/20031617.rss
+TARGET                  limitedpdpplugin.rsc
+END
+
+USERINCLUDE             ../inc
+
+OS_LAYER_SYSTEMINCLUDE
+
+// Note:
+// The only other SYSTEMINCLUDE should you shall add are Symbian specific ones.
+// If there is a S60 header in the subdirectory then that should be
+// added into the include statements (like #include <phonebook/header.h>)
+SYSTEMINCLUDE           /epoc32/include/ecom
+
+LIBRARY	ecom.lib
+LIBRARY euser.lib
+LIBRARY atextpluginbase.lib
+LIBRARY centralrepository.lib
+
+DEBUGLIBRARY flogger.lib
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/atext/plugins/limitedpdpplugin/inc/debug.h	Thu Aug 19 11:01:00 2010 +0300
@@ -0,0 +1,171 @@
+/*
+* Copyright (c) 2008 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Logging definitions
+*
+*/
+
+
+#ifndef PRJ_LOGGING_H
+#define PRJ_LOGGING_H
+
+#include <e32base.h>
+#include "debugconfig.h"
+
+#ifdef PRJ_ENABLE_TRACE
+
+#ifdef PRJ_FILE_TRACE
+#include <flogger.h>
+#else
+#include <e32debug.h>
+#endif
+
+NONSHARABLE_CLASS(TOverflowTruncate16) : public TDes16Overflow
+    {
+public:
+    void Overflow(TDes16& /*aDes*/) {}
+    };
+
+NONSHARABLE_CLASS(TOverflowTruncate8) : public TDes8Overflow
+    {
+public:
+    void Overflow(TDes8& /*aDes*/) {}
+    };
+
+inline void Trace(TRefByValue<const TDesC16> aFmt, ...)
+    {
+    VA_LIST list;
+    VA_START(list,aFmt);
+#ifdef PRJ_FILE_TRACE
+    RFileLogger::WriteFormat(KLogDir, KLogFile, EFileLoggingModeAppend, aFmt, list);
+#else
+    TBuf16<KMaxLogLineLength> theFinalString;
+    theFinalString.Append(KTracePrefix16);
+    TOverflowTruncate16 overflow;
+    theFinalString.AppendFormatList(aFmt,list,&overflow);
+    RDebug::Print(theFinalString);
+#endif
+    }
+
+inline void Trace(TRefByValue<const TDesC8> aFmt, ...)
+    {
+    VA_LIST list;
+    VA_START(list, aFmt);
+#ifdef PRJ_FILE_TRACE
+    RFileLogger::WriteFormat(KLogDir, KLogFile, EFileLoggingModeAppend, aFmt, list);
+#else
+    TOverflowTruncate8 overflow;
+    TBuf8<KMaxLogLineLength> buf8;
+    buf8.Append(KTracePrefix8);
+    buf8.AppendFormatList(aFmt, list, &overflow);
+    TBuf16<KMaxLogLineLength> buf16(buf8.Length());
+    buf16.Copy(buf8);
+    TRefByValue<const TDesC> tmpFmt(_L("%S"));
+    RDebug::Print(tmpFmt, &buf16);
+#endif
+    }
+
+inline void TracePanic(
+    char* aFile,
+    TInt aLine,
+    TInt aPanicCode,
+    const TDesC& aPanicCategory)
+    {
+    TPtrC8 fullFileName((const TUint8*)aFile);
+    TPtrC8 fileName(fullFileName.Ptr()+fullFileName.LocateReverse('\\')+1);
+    TBuf8<KMaxLogLineLength> buf;
+    buf.Append(KPanicPrefix8);
+    buf.AppendFormat(_L8("%d at line %d in file %S"), aPanicCode, aLine, &fileName);
+    Trace(buf);
+    User::Panic(aPanicCategory, aPanicCode);
+    }
+
+inline void TraceLeave(char* aFile, TInt aLine, TInt aReason)
+    {
+    TPtrC8 fullFileName((const TUint8*)aFile);
+    TPtrC8 fileName(fullFileName.Ptr()+fullFileName.LocateReverse('\\')+1);
+    TBuf8<KMaxLogLineLength> buf;
+    buf.Append(KLeavePrefix8);
+    buf.AppendFormat(_L8("%d at line %d in file %S"), aReason, aLine, &fileName);
+    Trace(buf);
+    User::Leave(aReason);
+    }
+
+#define TRACE_INFO(p) {if(KTraceMask & KPRINTINFO) Trace p;}
+
+#define TRACE_ERROR(p) {if(KTraceMask & KPRINTERROR) Trace p;}
+
+#define TRACE_STATE(p) {if(KTraceMask & KPRINTSTATE) Trace p;}
+
+#define TRACE_WARNING(p) {if(KTraceMask & KPRINTWARNING) Trace p;}
+
+#define TRACE_INFO_SEG(p) {if(KTraceMask & KPRINTINFO) p;}
+
+#define TRACE_ASSERT(GUARD, CODE) {if (!(GUARD)) TracePanic(__FILE__, __LINE__, CODE, KPanicCategory);}
+
+#define PANIC(CODE) TracePanic(__FILE__, __LINE__, CODE, KPanicCategory)
+
+#define LEAVE_IF_ERROR(REASON) {if (REASON) TraceLeave(__FILE__, __LINE__, REASON);}
+
+#define LEAVE_IF_NULL(PTR) {if (!PTR) TraceLeave(__FILE__, __LINE__, PTR);}
+
+#define LEAVE(REASON) {TraceLeave(__FILE__, __LINE__, REASON);}
+
+#define TRACE_STATIC_FUNC_ENTRY {if(KTraceMask & KPRINTINFO) { TPtrC8 ptr8((TUint8*)__PRETTY_FUNCTION__); Trace(KFuncEntryFormat8, &ptr8);}}
+
+#define TRACE_FUNC_ENTRY {if(KTraceMask & KPRINTINFO) { TPtrC8 ptr8((TUint8*)__PRETTY_FUNCTION__); Trace(KFuncEntryThisFormat8, &ptr8, this);}}
+
+#define TRACE_FUNC_EXIT {if(KTraceMask & KPRINTINFO) { TPtrC8 ptr8((TUint8*)__PRETTY_FUNCTION__); Trace(KFuncExitFormat8, &ptr8);}}
+
+#define TRACE_STATIC_FUNC {if(KTraceMask & KPRINTINFO) { TPtrC8 ptr8((TUint8*)__PRETTY_FUNCTION__); Trace(KFuncFormat8, &ptr8);}}
+
+#define TRACE_FUNC {if(KTraceMask & KPRINTINFO) { TPtrC8 ptr8((TUint8*)__PRETTY_FUNCTION__); Trace(KFuncThisFormat8, &ptr8, this);}}
+
+#define RETURN_IF_ERR(ERR) {if(ERR) {TPtrC8 ptr8((TUint8*)__FILE__); Trace(_L8(" RETURN %d at file %S line %d"), ERR, &ptr8, __LINE__); return ERR;}}
+
+#else // PRJ_ENABLE_TRACE not defined
+
+#define TRACE_INFO(p)
+
+#define TRACE_ERROR(p)
+
+#define TRACE_STATE(p)
+
+#define TRACE_WARNING(p)
+
+#define TRACE_INFO_SEG(p)
+
+#define TRACE_ASSERT(GUARD, CODE)
+
+#define PANIC(CODE) {User::Panic(KPanicCategory, CODE);}
+
+#define LEAVE_IF_ERROR(REASON) {static_cast<void>(User::LeaveIfError(REASON));}
+
+#define LEAVE_IF_NULL(PTR) {static_cast<void>(User::LeaveIfNull(PTR));}
+
+#define LEAVE(REASON) {static_cast<void>(User::Leave(REASON));}
+
+#define TRACE_STATIC_FUNC_ENTRY
+
+#define TRACE_FUNC_ENTRY
+
+#define TRACE_FUNC_EXIT
+
+#define TRACE_STATIC_FUNC
+
+#define TRACE_FUNC
+
+#define RETURN_IF_ERR(ERR) {if(ERR) return ERR;}
+#endif // PRJ_ENABLE_TRACE
+
+#endif // PRJ_LOGGING_H
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/atext/plugins/limitedpdpplugin/inc/debugconfig.h	Thu Aug 19 11:01:00 2010 +0300
@@ -0,0 +1,55 @@
+/*
+* Copyright (c) 2008 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Logging configure file
+*
+*/
+
+
+#ifndef LIMITEDPDPPLUGIN_DEBUGCONFIG_H
+#define LIMITEDPDPPLUGIN_DEBUGCONFIG_H
+
+#include "prjconfig.h"
+
+/**
+ * Custom logging variations.
+ */
+#ifdef PRJ_FILE_TRACE
+_LIT(KLogFile,"limitedpdpplugin.txt");
+_LIT(KLogDir,"LIMITEDPDPPLUGIN");
+#endif
+
+#ifdef PRJ_ENABLE_TRACE
+_LIT(KTracePrefix16, "[LIMITEDPDPPLUGIN] ");
+_LIT8(KTracePrefix8, "[LIMITEDPDPPLUGIN] ");
+_LIT8(KFuncFormat8, "><%S");
+_LIT8(KFuncThisFormat8, "><%S, [0x%08X]");
+_LIT8(KFuncEntryFormat8, ">%S");
+_LIT8(KFuncEntryThisFormat8, ">%S, [0x%08X]");
+_LIT8(KFuncExitFormat8, "<%S");
+
+_LIT(KPanicCategory, "limitedpdpplugin");
+_LIT8(KPanicPrefix8, "PANIC code ");
+_LIT8(KLeavePrefix8, "LEAVE code ");
+#endif
+
+const TInt KMaxLogLineLength = 512;
+
+#define KPRINTERROR        0x00000001 // Tracing level: error
+#define KPRINTINFO        0x00000002 // Tracing level: function trace
+#define KPRINTSTATE        0x00000004 // Tracing level: state machine info
+#define KPRINTWARNING   0x00000008 // Tracing level: warning
+
+const TInt KTraceMask = KPRINTERROR | KPRINTINFO | KPRINTSTATE | KPRINTWARNING;
+
+#endif // LIMITEDPDPPLUGIN_DEBUGCONFIG_H
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/atext/plugins/limitedpdpplugin/inc/limitedpdpplugin.h	Thu Aug 19 11:01:00 2010 +0300
@@ -0,0 +1,226 @@
+/*
+ * Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ * All rights reserved.
+ * This component and the accompanying materials are made available
+ * under the terms of "Eclipse Public License v1.0"
+ * which accompanies this distribution, and is available
+ * at the URL "http://www.eclipse.org/legal/epl-v10.html".
+ *
+ * Initial Contributors:
+ * Nokia Corporation - initial contribution.
+ *
+ * Contributors:
+ *
+ * Description:  Main handler for incoming requests
+ *
+ */
+
+#ifndef C_LIMITEDPDPPLUGIN_H
+#define C_LIMITEDPDPPLUGIN_H
+
+#include <atextpluginbase.h>
+#include <e32base.h>
+#include <e32property.h>
+
+/**
+ *  Class for selecting handlers for different AT commands
+ *
+ *  @since TB9.2
+ */
+NONSHARABLE_CLASS( CLimitedPdpPlugin ) : public CATExtPluginBase
+    {
+
+public:
+
+    /**
+     * Two-phased constructor.
+     * @return Instance of self
+     */
+    static CLimitedPdpPlugin* NewL();
+
+    /**
+     * Destructor.
+     */
+    virtual ~CLimitedPdpPlugin();
+
+private:
+
+    CLimitedPdpPlugin();
+
+    void ConstructL();
+
+    /**
+     * Reports connection identifier name to the extension plugin.
+     *
+     * @since TB9.2
+     * @param aName Connection identifier name
+     * @return None
+     */
+    void ReportConnectionName( const TDesC8& aName );
+
+    /**
+     * Reports the support status of an AT command. This is synchronous API.
+     *
+     * @since TB9.2
+     * @param aCmd The AT command. Its format may vary depending on the
+     *             specification. 
+     *             a character carriage return (<cr>) in the end.
+     * @return ETrue if the command is supported; EFalse otherwise.
+     */
+    TBool IsCommandSupported( const TDesC8& aCmd );
+
+    /**
+     * Handles an AT command. Cancelling of the pending request is done by
+     * HandleCommandCancel(). The implementation in the extension plugin
+     * should be asynchronous. However, in this case, WE MUST IMPLEMENT THE 
+     * PLUGIN synchronously and BLOCK ATEXT THREAD WHILE EXISTING CONNECTIONS
+     * ARE BEING CLOSED. This is due to the fact that this plugin is an 
+     * observer and the modem AT command handler is issued immediately after
+     * this command returns. This has a couple of drawbacks:
+     * 1. ATEXT thread is blocked, which is against the requirements
+     * 2. Cancelling of this operation is not supported.
+     * 
+     * The extension plugin which accepts this command is responsible to
+     * supply result codes and response and to format result codes properly.
+     *
+     * After an extension plugin has handled or decided to reject given AT
+     * command, it must inform ATEXT by HandleCommandCompleted() with proper
+     * error code.
+     *
+     * @since TB9.2
+     * @param aCmd The AT command to be handled. 
+     * @param aReply When passed in, contains the built in answer filled by
+     *               ATEXT if it is not empty; when command handling
+     *               completes successfully, contains the result codes and 
+     *               responses to this command 
+     * @param aReplyNeeded Reply needed if ETrue, no reply otherwise. 
+     * @return None
+     */
+    void
+            HandleCommand( const TDesC8& aCmd,
+                           RBuf8& aReply,
+                           TBool aReplyNeeded );
+
+    /**
+     * Cancels a pending HandleCommand request.
+     *
+     * @since TB9.2
+     * @return None
+     */
+    void HandleCommandCancel();
+
+    /**
+     * Next reply part's length.
+     * The value must be equal or less than KDefaultCmdBufLength.
+     * When the reply from this method is zero, ATEXT stops calling
+     * GetNextPartOfReply().
+     *
+     * @since TB9.2
+     * @return Next reply part's length if zero or positive
+     */
+    TInt NextReplyPartLength();
+
+    /**
+     * Gets the next part of reply initially set by HandleCommandComplete().
+     * Length of aNextReply must be equal or less than KDefaultCmdBufLength.
+     *
+     * @since TB9.2
+     * @param aNextReply Next reply
+     * @return Symbian error code on error, KErrNone otherwise
+     */
+    TInt GetNextPartOfReply( RBuf8& aNextReply );
+
+    /**
+     * Receives unsolicited results. Cancelling of pending request is done
+     * by ReceiveUnsolicitedResultCancel(). The implementation in extension
+     * plugin should be asynchronous.
+     *
+     * @since TB9.2
+     * @return None
+     */
+    void ReceiveUnsolicitedResult();
+
+    /**
+     * Cancels a pending ReceiveUnsolicitedResult request.
+     *
+     * @since TB9.2
+     * @return None
+     */
+    void ReceiveUnsolicitedResultCancel();
+
+    /**
+     * Reports NVRAM status change to the plugins.
+     *
+     * @since TB9.2
+     * @param aNvram New NVRAM status. Each call of this function is a result
+     *               of DUN extracting the form notified by
+     *               CATExtCommonBase::SendNvramStatusChange(). Each of the
+     *               settings from SendNvramStatusChange() is separated to
+     *               one call of ReportNvramStatusChange().
+     * @return None
+     */
+    void ReportNvramStatusChange( const TDesC8& aNvram );
+
+    /**
+     * Reports about external handle command error condition.
+     * This is for cases when for example DUN decided the reply contained an
+     * error condition but plugin is still handling the command internally.
+     * This solution keeps the pointer to the last AT command handling plugin
+     * inside ATEXT and calls this function there to report the error.
+     * It is to be noted that HandleCommandCancel() is not sufficient to stop
+     * the processing as the command handling has already finished.
+     *
+     * @since TB9.2
+     * @return None
+     */
+    void ReportExternalHandleCommandError();
+
+    /**
+     * Checks whether this feature is on or off. Reads the value from CenRep
+     * and stores it to the internal variable.
+     *
+     * @since TB9.2
+     * @return ETrue if enabled, EFalse otherwise
+     */
+    TBool CheckFeatureEnablement();
+
+    /**
+     * Closes existing connections by setting PS key to ConnMon
+     *
+     * @since TB9.2
+     * @return KErrNone if successful, otherwise Symbian error code
+     */
+    TInt CloseExistingConnections();
+
+    /**
+     * Blocks thread until ConnMon indicates that existing packet data
+     * connections are closed. Operation is guarded by a timeout.
+     *
+     * @since TB9.2
+     * @return KErrNone if successful, otherwise Symbian error code
+     */
+    TInt BlockThreadUntilConnectionsClosed();
+
+private:
+    // data
+
+    /**
+     * Property handle used for communication with Connection monitor
+     */
+    RProperty iProperty;
+
+    /**
+     * Timer handle used for timeouting the ongoinging operation. Used for
+     * cancelling the closing of existing PDP contexts in case the operation
+     * takes too long.
+     */
+    RTimer iCancelTimer;
+
+    /**
+     * Value indicating whether this feature is enabled
+     */
+    TBool iFeatureSupported;
+
+    };
+
+#endif  // C_LIMITEDPDPPLUGIN_H
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/atext/plugins/limitedpdpplugin/inc/limitedpdpplugincopiedkeys.h	Thu Aug 19 11:01:00 2010 +0300
@@ -0,0 +1,65 @@
+/*
+ * Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies). 
+ * All rights reserved.
+ * This component and the accompanying materials are made available
+ * under the terms of "Eclipse Public License v1.0"
+ * which accompanies this distribution, and is available
+ * at the URL "http://www.eclipse.org/legal/epl-v10.html".
+ *
+ * Initial Contributors:
+ * Nokia Corporation - initial contribution.
+ *
+ * Contributors:
+ *
+ * Description:  Redefinition of used CenRep and PS keys.
+ *
+ */
+
+#ifndef LIMITEDPDPPLUGINCOPYKEYS_H
+#define LIMITEDPDPPLUGINCOPYKEYS_H
+
+/**
+ * NOTE: THIS FILE CONTAINS COPIES OF CENREP AND PS KEYS DEFINED
+ *       IN IPCONNMGMT PACKAGE. DO NOT CHANGE!!!
+ * 
+ * These needs to be copied to avoid dependency from OS layer (this module)
+ * to middleware layer (ipconnmgmt). Bad design choices...
+ */
+
+/**
+ * UID of CmManager repository
+ */
+const TUid KCopyOfCRUidCmManager =
+    {
+    0x10207376
+    };
+
+/**
+ * Dial-up override setting.
+ */
+const TUint32 KCopyOfDialUpOverride = 0x00000002;
+
+/**
+ * Connection Monitor RProperty category.
+ */
+const TUid KCopyOfConnectionMonitorPS =
+    {
+    0x101F6CF0
+    };
+
+/**
+ * Dial-Up override key.
+ */
+const TUint KCopyOfDialUpConnection = 0x00000001;
+
+/**
+ * Values for KDialUpConnection key.
+ */
+enum TCopyOfDialUpStates
+    {
+    EConnMonDialUpClosed,
+    EConnMonDialUpInit,
+    EConnMonReady
+    };
+
+#endif // LIMITEDPDPPLUGINCOPYKEYS_H
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/atext/plugins/limitedpdpplugin/inc/prjconfig.h	Thu Aug 19 11:01:00 2010 +0300
@@ -0,0 +1,46 @@
+/*
+* Copyright (c) 2008 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Project configure file
+*
+*/
+
+
+#ifndef ATEXT_PRJCONFIG_H
+#define ATEXT_PRJCONFIG_H
+
+/**
+ * Traces are enabled in _DEBUG build, by default.
+ */
+#ifdef _DEBUG
+#define PRJ_ENABLE_TRACE
+#endif
+
+/**
+ * traces to file if this is defined.
+ */
+//#define PRJ_FILE_TRACE
+
+
+/**
+ * build the project for module test purpose if this is defined
+ */
+//#define PRJ_MODULETEST_BUILD
+
+/**
+ * build the project using stubs to replace the dependencies if this is defined
+ */
+//#define PRJ_USE_STUB
+
+
+#endif // ATEXT_PRJCONFIG_H
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/atext/plugins/limitedpdpplugin/rom/limitedpdpplugin.iby	Thu Aug 19 11:01:00 2010 +0300
@@ -0,0 +1,24 @@
+/*
+* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Image description file for project limitedpdpplugin
+*
+*/
+
+
+#ifndef __LIMITEDPDPPLUGIN_IBY__
+#define __LIMITEDPDPPLUGIN_IBY__
+
+ECOM_PLUGIN( limitedpdpplugin.dll, limitedpdpplugin.rsc )
+
+#endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/atext/plugins/limitedpdpplugin/src/20031617.rss	Thu Aug 19 11:01:00 2010 +0300
@@ -0,0 +1,47 @@
+/*
+* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Resource definitions for project limitedpdpplugin
+*
+*/
+
+
+#include <atext_interfaceuid.h>
+#include <registryinfo.rh>
+
+// Declares info for two implementations
+RESOURCE REGISTRY_INFO theInfo
+	{
+	// UID for the DLL
+    dll_uid = 0x20031617;
+	// Declare array of interface info
+	interfaces =
+		{
+		INTERFACE_INFO
+			{
+			// UID of interface that is implemented
+			interface_uid = ATEXT_INTERFACE_DUN_UID;
+			implementations =
+				{
+				IMPLEMENTATION_INFO
+					{
+					implementation_uid = 0x20031618;
+					version_no = 1;
+					display_name = "Limited PDP Plugin";
+					default_data=  "OATD*";
+					opaque_data = "";
+					}
+				};
+			}
+		};
+	}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/atext/plugins/limitedpdpplugin/src/limitedpdpplugin.cpp	Thu Aug 19 11:01:00 2010 +0300
@@ -0,0 +1,420 @@
+/*
+ * Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ * All rights reserved.
+ * This component and the accompanying materials are made available
+ * under the terms of "Eclipse Public License v1.0"
+ * which accompanies this distribution, and is available
+ * at the URL "http://www.eclipse.org/legal/epl-v10.html".
+ *
+ * Initial Contributors:
+ * Nokia Corporation - initial contribution.
+ *
+ * Contributors:
+ *
+ * Description:  Main handler for incoming requests
+ *
+ */
+
+#include "limitedpdpplugin.h"
+#include <centralrepository.h>
+#include "limitedpdpplugincopiedkeys.h"
+#include "debug.h"
+
+// Internal constants
+const TInt KDialupOverrideEnabled = 1;
+const TInt KCloseTimeoutInterval = 15000000; // 15 secs
+const TInt KCleanUpWaitTimeout = 300000; // 300 ms
+#ifdef _DEBUG 
+const TInt KUsecToMSecDivider = 1000;
+#endif
+
+// ---------------------------------------------------------------------------
+// Two-phased constructor.
+// ---------------------------------------------------------------------------
+//
+CLimitedPdpPlugin* CLimitedPdpPlugin::NewL()
+    {
+    CLimitedPdpPlugin* self = new ( ELeave ) CLimitedPdpPlugin();
+    CleanupStack::PushL( self );
+    self->ConstructL();
+    CleanupStack::Pop( self );
+    return self;
+    }
+
+// ---------------------------------------------------------------------------
+// Destructor.
+// ---------------------------------------------------------------------------
+//
+CLimitedPdpPlugin::~CLimitedPdpPlugin()
+    {
+    TRACE_FUNC_ENTRY
+
+    // Check validity of handles so that Cancel functions can be called
+    if ( iProperty.Handle() != NULL )
+        {
+        // Cancel just in case in spite of the fact that with current
+        // architecture cancelling of the operation is not possible
+        iProperty.Cancel();
+        iProperty.Close();
+        }
+    if ( iCancelTimer.Handle() != NULL )
+        {
+        iCancelTimer.Cancel();
+        iCancelTimer.Close();
+        }
+
+    TRACE_FUNC_EXIT
+    }
+
+// ---------------------------------------------------------------------------
+// CLimitedPdpPlugin::CLimitedPdpPlugin
+// ---------------------------------------------------------------------------
+//
+CLimitedPdpPlugin::CLimitedPdpPlugin() :
+    CATExtPluginBase()
+    {
+    // Nothing to do here, resources are initialized in ConstructL
+    }
+
+// ---------------------------------------------------------------------------
+// CLimitedPdpPlugin::ConstructL
+// ---------------------------------------------------------------------------
+//
+void CLimitedPdpPlugin::ConstructL()
+    {
+    TRACE_FUNC_ENTRY
+
+    // No need to use cleanup stack here, since these will be closed in
+    // destructor anyway.
+    User::LeaveIfError( iCancelTimer.CreateLocal() );
+    User::LeaveIfError( iProperty.Attach( KCopyOfConnectionMonitorPS,
+                                          KCopyOfDialUpConnection ) );
+    iFeatureSupported = EFalse;
+    iFeatureSupported = CheckFeatureEnablement();
+
+    TRACE_FUNC_EXIT
+    }
+
+// ---------------------------------------------------------------------------
+// Reports connection identifier name to the extension plugin.
+// ---------------------------------------------------------------------------
+//
+void CLimitedPdpPlugin::ReportConnectionName( const TDesC8& /*aName*/)
+    {
+    }
+
+// ---------------------------------------------------------------------------
+// Reports the support status of an AT command. This is a synchronous API.
+// ---------------------------------------------------------------------------
+//
+TBool CLimitedPdpPlugin::IsCommandSupported( const TDesC8& /*aCmd*/)
+    {
+    TRACE_FUNC_ENTRY
+    // Set the return value according to feature support
+    TRACE_INFO(( _L("Returning feature support value %d"),
+                    static_cast<TInt>(iFeatureSupported)));
+    TRACE_FUNC_EXIT
+    return iFeatureSupported;
+    }
+
+// ---------------------------------------------------------------------------
+// Handles an AT command. Cancelling of the pending request is done by
+// HandleCommandCancel(). The implementation in the extension plugin should
+// be asynchronous, but in this case we must use blocking behavior. This has
+// a couple of drawbacks. First, the ATEXT thread is blocked and possible,
+// which is against the requirements, and secondly and more importantly, the
+// cancelling of this operation is not supported.
+// ---------------------------------------------------------------------------
+//
+void CLimitedPdpPlugin::HandleCommand( const TDesC8& /*aCmd*/,
+                                       RBuf8& /*aReply*/,
+                                       TBool /*aReplyNeeded*/)
+    {
+    TRACE_FUNC_ENTRY
+
+    // Double check that we are actually supporting the feature
+    if ( iFeatureSupported )
+        {
+        // Request ConnMon to close existing packet data connections
+        TInt retTemp = CloseExistingConnections();
+        if ( retTemp == KErrNone )
+            {
+            retTemp = BlockThreadUntilConnectionsClosed();
+            if ( retTemp == KErrNone )
+                {
+                // Internal connections closed. We need to wait for a while
+                // to make sure that lower layer resources are properly 
+                // cleaned in order to avoid conflicts in resource
+                // allocation. Again thread needs to be blocked, therefore
+                // User::After.
+                // NOTE: This is definitely a bad workaround and unreliable
+                // approach, but there aren't too many options...
+                TRACE_INFO(( _L("Block for %d ms for resource cleanup"),
+                                ( KCleanUpWaitTimeout / KUsecToMSecDivider )));
+                User::After( KCleanUpWaitTimeout );
+                TRACE_INFO(( _L("Cleanup wait completed, exit")));
+                }
+            }
+        }
+
+    TRACE_FUNC_EXIT
+    }
+
+// ---------------------------------------------------------------------------
+// Cancels a pending HandleCommand request.
+// ---------------------------------------------------------------------------
+//
+void CLimitedPdpPlugin::HandleCommandCancel()
+    {
+    TRACE_FUNC_ENTRY
+    TRACE_FUNC_EXIT
+    }
+
+// ---------------------------------------------------------------------------
+// Next reply part's length.
+// The value must be equal or less than KDefaultCmdBufLength.
+// When the reply from this method is zero, ATEXT stops calling
+// GetNextPartOfReply().
+// ---------------------------------------------------------------------------
+//
+TInt CLimitedPdpPlugin::NextReplyPartLength()
+    {
+    TRACE_FUNC_ENTRY
+    TRACE_FUNC_EXIT
+    return KErrNotSupported;
+    }
+
+// ---------------------------------------------------------------------------
+// Gets the next part of reply initially set by HandleCommandComplete().
+// Length of aNextReply must be equal or less than KDefaultCmdBufLength.
+// ---------------------------------------------------------------------------
+//
+TInt CLimitedPdpPlugin::GetNextPartOfReply( RBuf8& /*aNextReply*/)
+    {
+    TRACE_FUNC_ENTRY
+    TRACE_FUNC_EXIT
+    return KErrNotSupported;
+    }
+
+// ---------------------------------------------------------------------------
+// Receives unsolicited results. Cancelling of the pending request is done by
+// by ReceiveUnsolicitedResultCancel(). The implementation in the extension
+// plugin should be asynchronous.
+// ---------------------------------------------------------------------------
+//
+void CLimitedPdpPlugin::ReceiveUnsolicitedResult()
+    {
+    TRACE_FUNC_ENTRY
+    TRACE_FUNC_EXIT
+    }
+
+// ---------------------------------------------------------------------------
+// Cancels a pending ReceiveUnsolicitedResult request.
+// ---------------------------------------------------------------------------
+//
+void CLimitedPdpPlugin::ReceiveUnsolicitedResultCancel()
+    {
+    TRACE_FUNC_ENTRY
+    TRACE_FUNC_EXIT
+    }
+
+// ---------------------------------------------------------------------------
+// Reports NVRAM status change to the plugins.
+// ---------------------------------------------------------------------------
+//
+void CLimitedPdpPlugin::ReportNvramStatusChange( const TDesC8& /*aNvram*/)
+    {
+    TRACE_FUNC_ENTRY
+    TRACE_FUNC_EXIT
+    }
+
+// ---------------------------------------------------------------------------
+// Reports about external handle command error condition.
+// This is for cases when for example DUN decided the reply contained an
+// error condition but the plugin is still handling the command internally.
+// Example: "AT+TEST;+TEST2" was given in command line; "AT+TEST" returns
+// non-EReplyTypeError condition and "AT+TEST2" returns EReplyTypeError.
+// As the plugin(s) returning the non-EReplyTypeError may still have some
+// ongoing operation then these plugins are notified about the external
+// EReplyTypeError in command line processing. It is to be noted that
+// HandleCommandCancel() is not sufficient to stop the processing as the
+// command handling has already finished.
+// ---------------------------------------------------------------------------
+//
+void CLimitedPdpPlugin::ReportExternalHandleCommandError()
+    {
+    TRACE_FUNC_ENTRY
+    TRACE_FUNC_EXIT
+    }
+
+// ---------------------------------------------------------------------------
+// Reads CenRep key to check whether requested functionality is active.
+// ---------------------------------------------------------------------------
+//
+TBool CLimitedPdpPlugin::CheckFeatureEnablement()
+    {
+    TRACE_FUNC_ENTRY
+    TBool enabled( EFalse );
+    CRepository* cmRepository = NULL;
+    TRAP_IGNORE( cmRepository = CRepository::NewL ( KCopyOfCRUidCmManager ) );
+    if ( cmRepository )
+        {
+        TInt overrideValue = KErrNotFound;
+        TInt retTemp = cmRepository->Get( KCopyOfDialUpOverride,
+                                          overrideValue );
+
+        if ( ( retTemp == KErrNone ) && ( overrideValue
+                == KDialupOverrideEnabled ) )
+            {
+            enabled = ETrue;
+            TRACE_INFO(( _L("Dialup override feature enabled")));
+            }
+        }
+    delete cmRepository;
+    TRACE_FUNC_EXIT
+    return enabled;
+    }
+
+// ---------------------------------------------------------------------------
+// Ask ConnMon to close all existing packet data connections
+// ---------------------------------------------------------------------------
+//
+TInt CLimitedPdpPlugin::CloseExistingConnections()
+    {
+    TRACE_FUNC_ENTRY
+
+    TInt dialupState( EConnMonReady );
+    TInt retVal( KErrNone );
+
+    retVal = iProperty.Get( dialupState );
+    if ( retVal == KErrNone )
+        {
+        TRACE_INFO(( _L("Current dialup connection PS key value %d"),
+                        dialupState ));
+        if ( dialupState != EConnMonDialUpInit )
+            {
+            TRACE_INFO(( _L("Setting dialup connection PS key to value %d"),
+                            EConnMonDialUpInit ));
+            retVal = iProperty.Set( EConnMonDialUpInit );
+            }
+        else
+            {
+            // Error situation, we should not end up to this function if
+            // the connection closing is already in init state.
+            retVal = KErrNotReady;
+            }
+        }
+    TRACE_INFO(( _L("Closing existing connections done with status %d"),
+                    retVal ));
+    TRACE_FUNC_EXIT
+    return retVal;
+    }
+
+// ---------------------------------------------------------------------------
+// Synchronously block thread until ConnMon indicates that connections are
+// closed or operation timeouts.
+// ---------------------------------------------------------------------------
+//
+TInt CLimitedPdpPlugin::BlockThreadUntilConnectionsClosed()
+    {
+    TRACE_FUNC_ENTRY
+
+    TInt dialupState( EConnMonDialUpInit );
+    TInt retVal( KErrNone );
+
+    // Read the dialup value just to check if ConnMon has been able to update
+    // it already to reflect correct state.
+    retVal = iProperty.Get( dialupState );
+
+    if ( retVal == KErrNone )
+        {
+        TRACE_INFO(( _L("Dialup connection PS key value before wait: %d"),
+                        dialupState ));
+        if ( dialupState == EConnMonDialUpInit )
+            {
+            // Block thread until value changes
+            TRequestStatus propertyStatus;
+            TRequestStatus timeoutStatus;
+            // Set operation to timeout if closing internal contexts fails.
+            // If timeout expires before PS key is updated, this plugin
+            // will pass the ATD*99# command to modem. Most probably
+            // that will fail due to lack of resources. However, if
+            // internal connections are not closed within this timeframe
+            // there will be problems anyway. So this is only to hasten
+            // end user feedback on error situation. 
+            iCancelTimer.After( timeoutStatus, KCloseTimeoutInterval );
+
+            // Loop for property subscription just in case the ConnMon does
+            // not set correct value in first attempt. The loop exiting is
+            // done separately below, but this condition is better than using
+            // while ( ETrue )
+            while ( dialupState != EConnMonReady )
+                {
+                iProperty.Subscribe( propertyStatus );
+
+                TRACE_INFO(( _L("Blocking thread to wait connection closing") ));
+                User::WaitForRequest( propertyStatus, timeoutStatus );
+
+                // Wait completed, check which condition was valid
+                if ( propertyStatus != KRequestPending )
+                    {
+                    if ( propertyStatus == KErrNone )
+                        {
+                        // ConnMon changed the value, check if it is valid
+                        TInt retVal = iProperty.Get( dialupState );
+                        if ( retVal == KErrNone )
+                            {
+                            if ( dialupState == EConnMonReady )
+                                {
+                                TRACE_INFO(( _L("Existing connections closed successfully") ));
+                                }
+                            else
+                                {
+                                // Otherwise retry
+                                TRACE_INFO(( _L("Wrong internal connection state (%d), retry"),
+                                                dialupState ));
+                                continue;
+                                }
+                            }
+                        }
+                    else
+                        {
+                        retVal = propertyStatus.Int();
+                        }
+                    // We should exit the loop, either due success of error
+                    // Cancel and wait for timeout request to complete
+                    TRACE_INFO((_L("Existing connections closed (status: %d), cancel timer"),
+                                    retVal ));
+                    iCancelTimer.Cancel();
+                    // Wait... If the completion of Cancel() is not waited
+                    // here, CActiveScheduler will panic due to stray signal
+                    // (E32USER-CBase panic code 46)
+                    User::WaitForRequest( timeoutStatus );
+                    TRACE_INFO(( _L("Timeout cancelled (timeoutStatus: %d), exit wait"),
+                                    timeoutStatus.Int() ));
+                    break;
+                    }
+                else if ( timeoutStatus != KRequestPending )
+                    {
+                    // Timeout or error, exit
+                    TRACE_INFO(( _L("Wait for existing connections timeouted (status: %d)"),
+                                    timeoutStatus.Int() ));
+                    // Cancel PS subscription and wait for its completion
+                    iProperty.Cancel();
+                    User::WaitForRequest( propertyStatus );
+                    retVal = iProperty.Set( EConnMonDialUpClosed );
+                    TRACE_INFO(( _L("Subscription cancelled (status: %d) and state reset, exit"),
+                                    propertyStatus.Int() ));
+                    retVal = KErrTimedOut;
+                    break;
+                    }
+                }
+            }
+        }
+    // All done, exit
+    TRACE_INFO(( _L("Exiting from wait with status %d"), retVal ));
+
+    TRACE_FUNC_EXIT
+    return retVal;
+    }
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/atext/plugins/limitedpdpplugin/src/proxy.cpp	Thu Aug 19 11:01:00 2010 +0300
@@ -0,0 +1,48 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description:  Export ECom interface implementations
+*
+*/
+
+
+#ifndef LIMITEDPDPPLUGIN_H
+#define LIMITEDPDPPLUGIN_H
+
+#include <e32base.h>
+#include <ecom/implementationproxy.h>
+#include "limitedpdpplugin.h"
+
+// ---------------------------------------------------------------------------
+// An array of TImplementationProxy objects which onnect each
+// implemeation with its instantiation function
+// ---------------------------------------------------------------------------
+//
+const TImplementationProxy ImplementationTable[] =
+	{
+	IMPLEMENTATION_PROXY_ENTRY(0x20031618, CLimitedPdpPlugin::NewL),  // DUN
+	};
+
+// ---------------------------------------------------------------------------
+// Exported proxy function to resolve instantiation methods for an Ecom
+// plug-in DLL
+// ---------------------------------------------------------------------------
+//
+EXPORT_C const TImplementationProxy* ImplementationGroupProxy(TInt& aTableCount)
+	{
+	aTableCount = sizeof(ImplementationTable) / sizeof(TImplementationProxy);
+
+	return ImplementationTable;
+	}
+
+#endif  // LIMITEDPDPPLUGIN_H
--- a/atext/server/inc/atextmetadata.h	Thu Jul 15 19:55:36 2010 +0300
+++ b/atext/server/inc/atextmetadata.h	Thu Aug 19 11:01:00 2010 +0300
@@ -324,7 +324,7 @@
 public:
 
     TATExtEntrySupport( TDesC8& aAtCmdFull,
-                        const RMessage2& aMessage,
+                        RMessage2& aMessage,
                         CArrayFixFlat<TATExtOneCmdSupport>* aSupport ) :
                         iAtCmdFull( aAtCmdFull ),
                         iMessage( aMessage ),
@@ -333,6 +333,8 @@
                         iStartIndex( KErrNotFound ),
                         iSupportFound( EFalse ){}
 
+    TATExtEntrySupport& operator=( TATExtEntrySupport& aEntrySupport );
+    
     /**
      * Full AT command for which to check the support
      * (base part + parameters)
@@ -342,7 +344,7 @@
     /**
      * Client request message for reading
      */
-    const RMessage2& iMessage;
+    RMessage2& iMessage;
 
     /**
      * AT command's plugin entry support data.
@@ -365,7 +367,7 @@
      * Found plugin support for HandlePartialAndMasterPluginSupportL().
      */
     TBool iSupportFound;
-
+    
     };
 
 /**
--- a/atext/server/src/atextmetadata.cpp	Thu Jul 15 19:55:36 2010 +0300
+++ b/atext/server/src/atextmetadata.cpp	Thu Aug 19 11:01:00 2010 +0300
@@ -2049,7 +2049,9 @@
         TRACE_FUNC_EXIT
         return;
         }
-    TATExtEntrySupport entrySupport( aAtCmdFull, aMessage, support );
+    TATExtEntrySupport entrySupport( aAtCmdFull,
+                                     const_cast<RMessage2&>(aMessage),
+                                     support );
     TInt i;
     aComplInfo.iProcessed = EFalse;
     TInt count = support->Count();
@@ -2141,11 +2143,14 @@
     HBufC8* atCmdFull = HBufC8::NewMaxLC( aEntrySupport.iAtCmdFull.Length() );
     TPtr8 atCmdFullPtr = atCmdFull->Des();
     atCmdFullPtr.Copy( aEntrySupport.iAtCmdFull );
+    // First send the entry to the observers
+    TATExtEntrySupport handleCommandEntry = aEntrySupport;
+    aEntrySupport.iStartIndex = aStartIndex;
+    SendToMultipleObserverL( aEntrySupport, atCmdFull );
+    aEntrySupport = handleCommandEntry;
     // Now execute the HandleCommand()
     iCmdData.iReplyExpected = ETrue;  // Set before HandleCommandL()
     HandleCommandL( aEntrySupport, ETrue );
-    aEntrySupport.iStartIndex = aStartIndex;
-    SendToMultipleObserverL( aEntrySupport, atCmdFull );
     CleanupStack::PopAndDestroy( atCmdFull );
     aReplyExpected = ETrue;
     TRACE_FUNC_EXIT
@@ -2187,8 +2192,8 @@
         TPtr8 atCmdFullPtr = atCmdFull->Des();
         atCmdFullPtr.Copy( aEntrySupport.iAtCmdFull );
         // Now execute the HandleCommand()
+        SendToMultipleObserverL( nextSupport, atCmdFull );
         HandleCommandL( aEntrySupport, EFalse );
-        SendToMultipleObserverL( nextSupport, atCmdFull );
         CleanupStack::PopAndDestroy( atCmdFull );
         }
     else
@@ -2727,3 +2732,22 @@
     TRACE_FUNC_EXIT
     return KErrNone;
     }
+
+// ---------------------------------------------------------------------------
+// Assignment operator for ease of usage
+// ---------------------------------------------------------------------------
+//
+TATExtEntrySupport& TATExtEntrySupport::operator=( TATExtEntrySupport& aEntrySupport )
+    {
+    if ( &aEntrySupport == this )
+        {
+        return aEntrySupport;
+        }
+    iAtCmdFull = aEntrySupport.iAtCmdFull;
+    iMessage = aEntrySupport.iMessage;
+    iSupport = aEntrySupport.iSupport;
+    iEntry = aEntrySupport.iEntry;
+    iStartIndex = aEntrySupport.iStartIndex;
+    iSupportFound = aEntrySupport.iSupportFound;
+    return *this;
+    }
--- a/bluetooth/btexample/example/btproperties/BTProperties.cpp	Thu Jul 15 19:55:36 2010 +0300
+++ b/bluetooth/btexample/example/btproperties/BTProperties.cpp	Thu Aug 19 11:01:00 2010 +0300
@@ -55,6 +55,56 @@
 		}
 	}
 
+void CreateSubscribersL(RPointerArray<CSubscriber>& aSubscribers)
+	{
+	CSubscriber* subscriber = CSubscriber::NewL(test, KPropertyKeyBluetoothGetPHYCount, KNumLinks);
+	
+	CleanupStack::PushL(subscriber);
+	aSubscribers.AppendL(subscriber);
+	CleanupStack::Pop(subscriber);
+	
+	subscriber = CSubscriber::NewL(test, KPropertyKeyBluetoothGetRegistryTableChange, KRegistry);
+	CleanupStack::PushL(subscriber);
+	aSubscribers.AppendL(subscriber);
+	CleanupStack::Pop(subscriber);
+	
+	subscriber = CSubscriber::NewL(test, KPropertyKeyBluetoothGetConnectingStatus, KConnecting);
+	CleanupStack::PushL(subscriber);
+	aSubscribers.AppendL(subscriber);
+	CleanupStack::Pop(subscriber);
+		
+	subscriber = CSubscriber::NewL(test, KPropertyKeyBluetoothGetScanningStatus, KScanning);
+	CleanupStack::PushL(subscriber);
+	aSubscribers.AppendL(subscriber);
+	CleanupStack::Pop(subscriber);
+
+	subscriber = CSubscriber::NewL(test, KPropertyKeyBluetoothGetLimitedDiscoverableStatus, KLimited);
+	CleanupStack::PushL(subscriber);
+	aSubscribers.AppendL(subscriber);
+	CleanupStack::Pop(subscriber);
+	
+	subscriber = CSubscriber::NewL(test, KPropertyKeyBluetoothGetDeviceClass, KDeviceClass);
+	CleanupStack::PushL(subscriber);
+	aSubscribers.AppendL(subscriber);
+	CleanupStack::Pop(subscriber);
+	
+	subscriber = CSubscriber::NewL(test, KPropertyKeyBluetoothGetCorruptRegistryResetIndication, KCorruptRegistry);
+	CleanupStack::PushL(subscriber);
+	aSubscribers.AppendL(subscriber);
+	CleanupStack::Pop(subscriber);
+	
+	subscriber = CDeviceNameSubscriber::NewL(test, KPropertyKeyBluetoothGetDeviceName, KDeviceName);
+	CleanupStack::PushL(subscriber);
+	aSubscribers.AppendL(subscriber);
+	CleanupStack::Pop(subscriber);
+	
+	subscriber = CSubscriber::NewL(test, KPropertyKeyBluetoothHostResolverActive, KDiscovering);
+	CleanupStack::PushL(subscriber);
+	aSubscribers.AppendL(subscriber);
+	CleanupStack::Pop(subscriber);
+	}
+
+
 void TestL()
 	{
 	// first do a sync test
@@ -62,27 +112,22 @@
 
 	RPointerArray<CSubscriber> subscribers;
 
-	//ignoring errors!
-	subscribers.Append(CSubscriber::NewL(test, KPropertyKeyBluetoothGetPHYCount, KNumLinks));
-	subscribers.Append(CSubscriber::NewL(test, KPropertyKeyBluetoothGetRegistryTableChange, KRegistry));
-	subscribers.Append(CSubscriber::NewL(test, KPropertyKeyBluetoothGetConnectingStatus, KConnecting));
-	subscribers.Append(CSubscriber::NewL(test, KPropertyKeyBluetoothGetScanningStatus, KScanning));
-	subscribers.Append(CSubscriber::NewL(test, KPropertyKeyBluetoothGetLimitedDiscoverableStatus, KLimited));
-	subscribers.Append(CSubscriber::NewL(test, KPropertyKeyBluetoothGetDeviceClass, KDeviceClass));
-	subscribers.Append(CSubscriber::NewL(test, KPropertyKeyBluetoothGetCorruptRegistryResetIndication, KCorruptRegistry));
-	subscribers.Append(CDeviceNameSubscriber::NewL(test, KPropertyKeyBluetoothGetDeviceName, KDeviceName));
- 	subscribers.Append(CSubscriber::NewL(test, KPropertyKeyBluetoothHostResolverActive, KDiscovering));
+	TRAPD(err, CreateSubscribersL(subscribers));
 
 	test.Printf(_L("%d Subscribers\n"), subscribers.Count());
 
-	for (TInt i=0; i<subscribers.Count(); i++)
-		subscribers[i]->Start();
-
-	CActiveScheduler::Start();
+	if (err == KErrNone)
+		{
+		// Only start if no errors when creating the subscribers
+		for (TInt i=0; i<subscribers.Count(); i++)
+			{
+			subscribers[i]->Start();
+			}
+		CActiveScheduler::Start();
+		}
 	subscribers.ResetAndDestroy();
 	}
 
-
 CSubscriber* CSubscriber::NewL(RTest& aTest, TUint aKey, const TDesC& aString)
 	{
 	CSubscriber* s = new(ELeave) CSubscriber(aTest, aString);
--- a/bluetooth/btexample/example/eir/teir.cpp	Thu Jul 15 19:55:36 2010 +0300
+++ b/bluetooth/btexample/example/eir/teir.cpp	Thu Aug 19 11:01:00 2010 +0300
@@ -143,8 +143,13 @@
 	switch(aTag)
 		{
 	case ETestDeviceName:
-		iResolvers.Append(CActiveInquirer::NewL(iConsole, *this, 0, EFalse, EFalse, EFalse, EFalse));
+		{
+		CActiveInquirer* inquirer = CActiveInquirer::NewL(iConsole, *this, 0, EFalse, EFalse, EFalse, EFalse);
+		CleanupStack::PushL(inquirer);
+		iResolvers.AppendL(inquirer);
+		CleanupStack::Pop(inquirer);
 		iNameRequester->SetLocalNameL();
+		}
 		break;
 
 	case ETestUuid16:
@@ -249,12 +254,18 @@
 
 void CEirApp::NewNameRequesterL(TBool aEirInstead, TBool aIgnoreCache)
 	{
-	iResolvers.Append(CActiveNameRequester::NewL(iConsole, *this, aEirInstead, aIgnoreCache));
+	CActiveNameRequester* requester = CActiveNameRequester::NewL(iConsole, *this, aEirInstead, aIgnoreCache);
+	CleanupStack::PushL(requester);
+	iResolvers.AppendL(requester);
+	CleanupStack::Pop(requester);
 	}
 
 void CEirApp::NewInquirerL(TUint aIAC, TBool aDoNames, TBool aIgnoreCache, TBool aDoEir, TBool forever)
 	{
-	iResolvers.Append(CActiveInquirer::NewL(iConsole, *this, aIAC, aDoNames, aIgnoreCache, aDoEir, forever));
+	CActiveInquirer* inquirer = CActiveInquirer::NewL(iConsole, *this, aIAC, aDoNames, aIgnoreCache, aDoEir, forever);
+	CleanupStack::PushL(inquirer);
+	iResolvers.AppendL(inquirer);
+	CleanupStack::Pop(inquirer);
 	}
 
 void CEirApp::CancelInquirer()
@@ -268,7 +279,10 @@
 
 void CEirApp::NewNameArrayRequesterL()
 	{
-	iResolvers.Append(CActiveNameArrayRequester::NewL(iConsole, *this, iDevicesFound));
+	CActiveNameArrayRequester* requester = CActiveNameArrayRequester::NewL(iConsole, *this, iDevicesFound);
+	CleanupStack::PushL(requester);
+	iResolvers.AppendL(requester);
+	CleanupStack::Pop(requester);
 	}
 
 void CEirApp::DeviceFound(TBTDevAddr aAddress)
@@ -276,7 +290,7 @@
 #if USE_SMALL_CONSOLE
 	iConsole.Printf(_L("App: Found device.\n"));
 #endif
-	iDevicesFound.Append(aAddress);
+	(void)iDevicesFound.Append(aAddress);
 	}
 
 void CEirApp::InquiryComplete()
--- a/bluetooth/btsdp/server/epocsvr.cpp	Thu Jul 15 19:55:36 2010 +0300
+++ b/bluetooth/btsdp/server/epocsvr.cpp	Thu Aug 19 11:01:00 2010 +0300
@@ -967,7 +967,12 @@
 				// we wouldn't want to remove the record if an error did occur,
 				// which is very unlikely as typically only 1 or 2 records are
 				// added per session.
-				iSessionRecords.Append(newRecord);
+				err = iSessionRecords.Append(newRecord);
+				if(err != KErrNone)
+				    {
+				    //if append fails delete the service record created above and return the error code
+				    Server().DeleteServiceRecord(newRecord);
+				    }
 				}
 			aMessage.Complete(err);
 			}
--- a/bluetooth/btstack/avdtp/avdtpDirectChannel.cpp	Thu Jul 15 19:55:36 2010 +0300
+++ b/bluetooth/btstack/avdtp/avdtpDirectChannel.cpp	Thu Aug 19 11:01:00 2010 +0300
@@ -45,15 +45,28 @@
 	LOG_FUNC
 	}
 		
-TInt CDirectChannel::AttachTransportSession(CUserPlaneTransportSession& aSession, TAvdtpTransportSessionType /*aType*/)
+TInt CDirectChannel::AttachTransportSession(CUserPlaneTransportSession& aSession, TAvdtpTransportSessionType /*aType*/, TL2CapConfig::TChannelPriority aPriority)
 	{
 	LOG_FUNC
 	__ASSERT_DEBUG(!iTransportSession, Panic(EAVDTPBadSessionAttachToTransportChannel));
-	// don't care about session type for direct channels
 	iTransportSession = &aSession;
+	iChannelPriority = aPriority;
+	UpdateChannelPriority();
 	return KErrNone;
 	}
 	
+void CDirectChannel::UpdateChannelPriority()
+	{
+	LOG_FUNC
+	
+	if(iLogicalChannel)
+		{
+		TPckgBuf<TL2CapConfig> configBuf;
+		configBuf().ConfigureChannelPriority(iChannelPriority);
+		(void)iLogicalChannel->SetOption(KSolBtL2CAP, KL2CAPUpdateChannelConfig, configBuf);
+		}
+	}
+
 TBool CDirectChannel::CouldAttachSession(const TAvdtpSockAddr& /*aAddr*/)
 	{
 	LOG_FUNC
@@ -136,6 +149,10 @@
 	LOG_FUNC
 	__ASSERT_DEBUG(&aSession == iTransportSession, Panic(EAVDTPBadSessionDetachFromTransportChannel));
 	iTransportSession = NULL;
+	iChannelPriority = TL2CapConfig::ELow;
+	
+	UpdateChannelPriority();
+	
 	// closing logical channel is async - we die on CanClose
 	// but we're invalid, so tell protocol
 	Protocol().TransportChannelClosing(*this);
--- a/bluetooth/btstack/avdtp/avdtpDirectChannel.h	Thu Jul 15 19:55:36 2010 +0300
+++ b/bluetooth/btstack/avdtp/avdtpDirectChannel.h	Thu Aug 19 11:01:00 2010 +0300
@@ -37,7 +37,7 @@
 // can just forward down to L2CAP...
 
 	virtual void DetachTransportSession(CUserPlaneTransportSession& aSession, TAvdtpTransportSessionType aType);
-	virtual TInt AttachTransportSession(CUserPlaneTransportSession& aSession, TAvdtpTransportSessionType aType);
+	virtual TInt AttachTransportSession(CUserPlaneTransportSession& aSession, TAvdtpTransportSessionType aType, TL2CapConfig::TChannelPriority aPriority = TL2CapConfig::ELow);
 	virtual TBool CouldAttachSession(const TAvdtpSockAddr& aAddr);
 	virtual TTCID TCID() const;
 	CServProviderBase* ObtainSAP();
@@ -48,7 +48,8 @@
 	
 private:
 	CDirectChannel(CAvdtpProtocol& aProtocol, const TBTDevAddr& aRemoteDevice);
- 
+	void UpdateChannelPriority();
+	
 private:
 // interesting stuff from l2cap
 	virtual void NewData(TUint aCount);
@@ -59,6 +60,7 @@
 private:
 	CUserPlaneTransportSession*	iTransportSession;			// non-owned
 	TBool						iTransportSessionBlocked;
+	TL2CapConfig::TChannelPriority iChannelPriority;
 	};
 	
 #endif //AVDTPDIRECTCHANNEL_H
--- a/bluetooth/btstack/avdtp/avdtpLogicalChannelFactory.cpp	Thu Jul 15 19:55:36 2010 +0300
+++ b/bluetooth/btstack/avdtp/avdtpLogicalChannelFactory.cpp	Thu Aug 19 11:01:00 2010 +0300
@@ -1296,13 +1296,7 @@
 	
 	TPckgBuf<TL2CapConfig> configBuf;
 	iLogicalChannelSAP->GetOption(KSolBtL2CAP, KL2CAPUpdateChannelConfig, configBuf);
-
-	if(iSequenceNumber != KInitialSequenceNumber)
-		{
-		configBuf().ConfigureChannelPriority(TL2CapConfig::EHigh);
-		iLogicalChannelSAP->SetOption(KSolBtL2CAP, KL2CAPUpdateChannelConfig, configBuf);
-		}
-	else if(!aPrecreatedSAP)
+	if(!aPrecreatedSAP)
 		{
 		// FIXME consider value of rtx timer, should consider Tgavdp
 		// Note: The 'rtx timer' actually sets max retransmit count instead [Piotr].
--- a/bluetooth/btstack/avdtp/avdtpMediaSession.cpp	Thu Jul 15 19:55:36 2010 +0300
+++ b/bluetooth/btstack/avdtp/avdtpMediaSession.cpp	Thu Aug 19 11:01:00 2010 +0300
@@ -76,7 +76,7 @@
 	__ASSERT_DEBUG(iStream, Panic(EAvdtpTransportSessionBaseNotCheckStream));
 	TInt ret = KErrGeneral; // may be OOM or notfound
 
-	ret = iStream->AddSession(EMedia,*this,iTransportChannel);
+	ret = iStream->AddSession(EMedia,*this,iTransportChannel,TL2CapConfig::EHigh);
 	if (ret!=KErrNone)
 		{
 		// not erroring the stream, as it's not it's fault
--- a/bluetooth/btstack/avdtp/avdtpMuxChannel.cpp	Thu Jul 15 19:55:36 2010 +0300
+++ b/bluetooth/btstack/avdtp/avdtpMuxChannel.cpp	Thu Aug 19 11:01:00 2010 +0300
@@ -295,7 +295,7 @@
 	#pragma message("is there n pools for eg media, or just one?")
 	}
 */	
-TInt CMuxChannel::AttachTransportSession(CUserPlaneTransportSession& aSession, TAvdtpTransportSessionType aType)
+TInt CMuxChannel::AttachTransportSession(CUserPlaneTransportSession& aSession, TAvdtpTransportSessionType aType, TL2CapConfig::TChannelPriority aPriority)
 /**
 Protocol must ensure it has found appropriate muxchannel for
 Recovery packets
@@ -321,7 +321,45 @@
 	
 	__ASSERT_DEBUG(sessionArray, Panic(EAVDTPBadSessionAttachToTransportChannel));
 	
-	return sessionArray->Append(TUserPlaneTransportSessionState(aSession));
+	TInt err = sessionArray->Append(TUserPlaneTransportSessionState(aSession, aPriority));
+	if(err == KErrNone)
+		{
+		UpdateChannelPriority();
+		}
+	return err;
+	}
+
+void CMuxChannel::UpdateChannelPriority()
+	{
+	LOG_FUNC
+	
+	TL2CapConfig::TChannelPriority maxPriority = TL2CapConfig::ELow;
+	
+	MaxChannelPriority(maxPriority, iMediaSessions);
+	MaxChannelPriority(maxPriority, iReportingSessions);
+	MaxChannelPriority(maxPriority, iRecoverySessions);
+	
+	if(iLogicalChannel)
+		{
+		TPckgBuf<TL2CapConfig> configBuf;
+		configBuf().ConfigureChannelPriority(maxPriority);
+		(void)iLogicalChannel->SetOption(KSolBtL2CAP, KL2CAPUpdateChannelConfig, configBuf);
+		}
+	}
+
+
+void CMuxChannel::MaxChannelPriority(TL2CapConfig::TChannelPriority& aMaxPriority, const RArray<TUserPlaneTransportSessionState>& aSessions)
+	{
+	LOG_STATIC_FUNC
+	
+	for(TInt i=0; i < aSessions.Count(); ++i)
+		{
+		TL2CapConfig::TChannelPriority priority = aSessions[i].iChannelPriority;
+		if(aMaxPriority < priority)
+			{
+			aMaxPriority = priority;
+			}
+		}
 	}
 
 /**
@@ -419,6 +457,7 @@
 		}
 	__ASSERT_DEBUG(found==1, Panic(EAVDTPBadSessionDetachFromTransportChannel));
 
+	UpdateChannelPriority();
 	CheckForClose();
 	}
 
--- a/bluetooth/btstack/avdtp/avdtpMuxChannel.h	Thu Jul 15 19:55:36 2010 +0300
+++ b/bluetooth/btstack/avdtp/avdtpMuxChannel.h	Thu Aug 19 11:01:00 2010 +0300
@@ -134,7 +134,7 @@
 								TTCID aRemotelyAssignedTCID);
 
 // management path
-	virtual TInt AttachTransportSession(CUserPlaneTransportSession& aSession, TAvdtpTransportSessionType aType);
+	virtual TInt AttachTransportSession(CUserPlaneTransportSession& aSession, TAvdtpTransportSessionType aType, TL2CapConfig::TChannelPriority aPriority = TL2CapConfig::ELow);
 	virtual void DetachTransportSession(CUserPlaneTransportSession& aSession, TAvdtpTransportSessionType aType);
 	virtual TBool CouldAttachSession(const TAvdtpSockAddr& aAddr);
 	virtual TTCID TCID() const;
@@ -153,7 +153,9 @@
 
 private:	
 	CMuxChannel(CAvdtpProtocol& aProtocol, const TBTDevAddr& aRemoteDevice);
-						 
+	
+	void UpdateChannelPriority();
+	
 	static TInt MuxSendIntervalCb(TAny* aCMuxChannel);
 	void CheckForClose();
 	TUint DoSend();
@@ -171,13 +173,15 @@
 	// receive path	
 	struct TUserPlaneTransportSessionState
 		{
-		inline TUserPlaneTransportSessionState(CUserPlaneTransportSession& aSession);
+		inline TUserPlaneTransportSessionState(CUserPlaneTransportSession& aSession, TL2CapConfig::TChannelPriority aChannelPriority);
 		
 		CUserPlaneTransportSession& iSession;
 		TBool iIsBlocked;
-		
+		TL2CapConfig::TChannelPriority iChannelPriority;
 		};
 		
+	static void MaxChannelPriority(TL2CapConfig::TChannelPriority& aMaxPriority, const RArray<TUserPlaneTransportSessionState>& aSessions);
+	
 	RArray<TUserPlaneTransportSessionState>	iMediaSessions;
 	RArray<TUserPlaneTransportSessionState>	iReportingSessions;
 	RArray<TUserPlaneTransportSessionState>	iRecoverySessions; // recall not from same streams as other sessions
@@ -202,8 +206,10 @@
 	};
 
 inline CMuxChannel::TUserPlaneTransportSessionState::TUserPlaneTransportSessionState(
-	CUserPlaneTransportSession& aSession)
-: iSession(aSession)
+	CUserPlaneTransportSession& aSession,
+	TL2CapConfig::TChannelPriority aChannelPriority)
+	: iSession(aSession)
+	, iChannelPriority(aChannelPriority)
 	{
 	}
 
--- a/bluetooth/btstack/avdtp/avdtpStream.cpp	Thu Jul 15 19:55:36 2010 +0300
+++ b/bluetooth/btstack/avdtp/avdtpStream.cpp	Thu Aug 19 11:01:00 2010 +0300
@@ -343,10 +343,11 @@
 
 TInt CAVStream::AddSession(TAvdtpTransportSessionType aType,
 						   CUserPlaneTransportSession& aSession,
-						   CTransportChannel*& aChannel)
+						   CTransportChannel*& aChannel,
+						   TL2CapConfig::TChannelPriority aPriority)
 	{
 	LOG_FUNC
-	return iState->AddSession(*this, aType, aSession, aChannel);
+	return iState->AddSession(*this, aType, aSession, aChannel, aPriority);
 	}
 	
 void CAVStream::DropSession(TAvdtpTransportSessionType aType, CUserPlaneTransportSession& aSession)
--- a/bluetooth/btstack/avdtp/avdtpStream.h	Thu Jul 15 19:55:36 2010 +0300
+++ b/bluetooth/btstack/avdtp/avdtpStream.h	Thu Aug 19 11:01:00 2010 +0300
@@ -149,7 +149,8 @@
 	
 	TInt AddSession(TAvdtpTransportSessionType aType,
 					CUserPlaneTransportSession& aSession,
-					CTransportChannel*& aTransportChannel);
+					CTransportChannel*& aTransportChannel,
+					TL2CapConfig::TChannelPriority aPriority = TL2CapConfig::ELow);
 	void DropSession(TAvdtpTransportSessionType aType, CUserPlaneTransportSession& aSession);
 	void ClearSession(CUserPlaneTransportSession& aSession);
 
@@ -303,7 +304,8 @@
 	virtual TInt AddSession(CAVStream& aStream, 
 							TAvdtpTransportSessionType aType,
 							CUserPlaneTransportSession& aSession,
-							CTransportChannel*& aTransportChannel) const;
+							CTransportChannel*& aTransportChannel,
+							TL2CapConfig::TChannelPriority aPriority) const;
 	virtual void DropSession(CAVStream& aStream, TAvdtpTransportSessionType aType,
 							 CUserPlaneTransportSession& aSession) const;
 	
@@ -398,7 +400,8 @@
 	virtual TInt AddSession(CAVStream& aStream,
 					TAvdtpTransportSessionType aType,
 					CUserPlaneTransportSession& aSession,
-					CTransportChannel*& aChannel) const;
+					CTransportChannel*& aChannel,
+					TL2CapConfig::TChannelPriority aPriority) const;
 	virtual void DropSession(CAVStream& aStream, TAvdtpTransportSessionType aType,
 					 CUserPlaneTransportSession& aSession) const;
 	virtual void SetConfigurationL(CAVStream& aStream, 
@@ -419,7 +422,8 @@
 	TInt AddSession(CAVStream& aStream, 
 							TAvdtpTransportSessionType aType,
 							CUserPlaneTransportSession& aSession,
-							CTransportChannel*& aTransportChannel) const;
+							CTransportChannel*& aTransportChannel,
+							TL2CapConfig::TChannelPriority aPriority) const;
 	virtual void Enter(CAVStream& aStream) const;
 private:
 	void TryToOpen(CAVStream& aStream) const;
@@ -440,7 +444,8 @@
 	virtual TInt AddSession(CAVStream& aStream,
 					TAvdtpTransportSessionType aType,
 					CUserPlaneTransportSession& aSession,
-					CTransportChannel*& aChannel) const;
+					CTransportChannel*& aChannel,
+					TL2CapConfig::TChannelPriority aPriority) const;
 				
 	virtual TInt StartReceived(CAVStream& aStream) const;
 	virtual void Enter(CAVStream& aStream) const;
@@ -454,7 +459,8 @@
 	virtual TInt AddSession(CAVStream& aStream,
 					TAvdtpTransportSessionType aType,
 					CUserPlaneTransportSession& aSession,
-					CTransportChannel*& aChannel) const;
+					CTransportChannel*& aChannel,
+					TL2CapConfig::TChannelPriority aPriority) const;
 	
 	virtual TInt StartReceived(CAVStream& aStream) const;
 	virtual void Enter(CAVStream& aStream) const;
@@ -494,7 +500,8 @@
 	virtual TInt AddSession(CAVStream& aStream,
 			TAvdtpTransportSessionType aType,
 			CUserPlaneTransportSession& aSession,
-			CTransportChannel*& aChannel) const;
+			CTransportChannel*& aChannel,
+			TL2CapConfig::TChannelPriority aPriority) const;
 	// next pertains to reconfiguration
 	void SetConfigurationL(CAVStream& aStream, 
 									RBuf8& aPacketBuffer,
--- a/bluetooth/btstack/avdtp/avdtpStreamStates.cpp	Thu Jul 15 19:55:36 2010 +0300
+++ b/bluetooth/btstack/avdtp/avdtpStreamStates.cpp	Thu Aug 19 11:01:00 2010 +0300
@@ -254,7 +254,8 @@
 TInt TAVStreamState::AddSession(CAVStream& /*aStream*/, 
 							TAvdtpTransportSessionType /*aType*/,
 							CUserPlaneTransportSession& /*aSession*/,
-							CTransportChannel*& /*aTransportChannel*/) const
+							CTransportChannel*& /*aTransportChannel*/,
+							TL2CapConfig::TChannelPriority /*aPriority*/) const
 	{
 	LOG_FUNC
 	DEBUGPANICINSTATE(EAvdtpUnexpectedAddSessionEvent);
@@ -490,7 +491,8 @@
 TInt TAVStreamStateINTConfigured::AddSession(CAVStream& aStream,
 									TAvdtpTransportSessionType aType,
 						   			CUserPlaneTransportSession& aSession,
-						   			CTransportChannel*& aChannel) const
+						   			CTransportChannel*& aChannel,
+						   			TL2CapConfig::TChannelPriority aPriority) const
 	{
 	LOG_FUNC
 	TInt ret = KErrNone;
@@ -513,7 +515,7 @@
 		if (aChannel)
 			{
 			// bind session to channel
-			ret = aChannel->AttachTransportSession(aSession, aType);
+			ret = aChannel->AttachTransportSession(aSession, aType, aPriority);
 			if (ret==KErrNone)
 				{
 				// keep a copy of this binding
@@ -774,7 +776,8 @@
 TInt TAVStreamStateACPConfigured::AddSession(CAVStream& /*aStream*/, 
 							TAvdtpTransportSessionType /*aType*/,
 							CUserPlaneTransportSession& /*aSession*/,
-							CTransportChannel*& /*aTransportChannel*/) const
+							CTransportChannel*& /*aTransportChannel*/,
+							TL2CapConfig::TChannelPriority /*aPriority*/) const
 	{
 	LOG_FUNC
 	return KErrNotReady;
@@ -828,7 +831,8 @@
 TInt TAVStreamStateReady::AddSession(CAVStream& /*aStream*/, 
 		TAvdtpTransportSessionType /*aType*/,
 		CUserPlaneTransportSession& /*aSession*/,
-		CTransportChannel*& /*aTransportChannel*/) const
+		CTransportChannel*& /*aTransportChannel*/,
+		TL2CapConfig::TChannelPriority /*aPriority*/) const
 {
 LOG_FUNC
 #ifdef _DEBUG
@@ -919,7 +923,6 @@
 			sigch->SendAbort(aStream, aStream.RemoteSEID());
 			}
 	
-		// no need to tell signalling session as Opening is not available to RGavdp
 		// Opening is performed when the necessary sockets are created and connected in a stream
 		aStream.NotifyUserPlaneTransportSessionsError(NULL, aResult);
 		}
@@ -1194,7 +1197,8 @@
 TInt TAVStreamStateWaitForSessions::AddSession(CAVStream& aStream,
 									TAvdtpTransportSessionType aType,
 						   			CUserPlaneTransportSession& aSession,
-						   			CTransportChannel*& aChannel) const
+						   			CTransportChannel*& aChannel,
+						   			TL2CapConfig::TChannelPriority aPriority) const
 	{
 	LOG_FUNC
 	TInt ret = KErrNone;
@@ -1237,7 +1241,7 @@
 	
 	if (ret == KErrNone)
 		{
-		ret = b->iChannel->AttachTransportSession(aSession, aType);
+		ret = b->iChannel->AttachTransportSession(aSession, aType, aPriority);
 		if (ret==KErrNone)
 			{
 			// stream needs to remember binding
@@ -1277,11 +1281,12 @@
 TInt TAVStreamStateWaitForSessionsStartReceived::AddSession(CAVStream& aStream,
 												TAvdtpTransportSessionType aType,
 						   						CUserPlaneTransportSession& aSession,
-						   						CTransportChannel*& aChannel) const
+						   						CTransportChannel*& aChannel,
+						   						TL2CapConfig::TChannelPriority aPriority) const
 	{
 	LOG_FUNC
 	// Call the function from the parent class to bind the session
-	TInt ret = TAVStreamStateWaitForSessions::AddSession(aStream,aType,aSession,aChannel);
+	TInt ret = TAVStreamStateWaitForSessions::AddSession(aStream,aType,aSession,aChannel, aPriority);
 	
 	// if that worked, and all the channels are bound, we can now issue the delayed start
 	if((ret == KErrNone) && (!aStream.iNumSessionsRequired))
--- a/bluetooth/btstack/avdtp/avdtpTransportChannel.cpp	Thu Jul 15 19:55:36 2010 +0300
+++ b/bluetooth/btstack/avdtp/avdtpTransportChannel.cpp	Thu Aug 19 11:01:00 2010 +0300
@@ -99,6 +99,7 @@
 		// take ownership
 		iLogicalChannel = aLogicalChannelRecord.iLogicalChannelSAP;
 		iLogicalChannel->SetNotify(this);
+		UpdateChannelPriority();
 		// drain any data
 		if (aLogicalChannelRecord.iDataCount)
 			{
--- a/bluetooth/btstack/avdtp/avdtpTransportChannel.h	Thu Jul 15 19:55:36 2010 +0300
+++ b/bluetooth/btstack/avdtp/avdtpTransportChannel.h	Thu Aug 19 11:01:00 2010 +0300
@@ -59,7 +59,7 @@
 
 // management path
 	virtual void DetachTransportSession(CUserPlaneTransportSession& aSession, TAvdtpTransportSessionType aType)=0;
-	virtual TInt AttachTransportSession(CUserPlaneTransportSession& aSession, TAvdtpTransportSessionType aType)=0;
+	virtual TInt AttachTransportSession(CUserPlaneTransportSession& aSession, TAvdtpTransportSessionType aType, TL2CapConfig::TChannelPriority aPriority)=0;
 	virtual TBool CouldAttachSession(const TAvdtpSockAddr& aAddr)=0;
 	virtual TTCID TCID() const=0;
 	inline const TBTDevAddr& RemoteAddress() const;
@@ -101,6 +101,9 @@
 	void CloseLogicalChannel();
 	inline CAvdtpProtocol& Protocol() const;
 
+private:
+	virtual void UpdateChannelPriority() = 0;
+
 protected:
 	RTCID				iTCID;
 	CServProviderBase*	iLogicalChannel;
--- a/bluetooth/btstack/l2cap/L2CapFecNegotiator.cpp	Thu Jul 15 19:55:36 2010 +0300
+++ b/bluetooth/btstack/l2cap/L2CapFecNegotiator.cpp	Thu Aug 19 11:01:00 2010 +0300
@@ -558,6 +558,14 @@
 	ProcessPeerValue(response, EFalse);
 	}
 
+void TL2CapIncomingFecNegotiator::DowngradeToBasic()
+	{
+	LOG_FUNC
+	iPreferred = TRetransmissionAndFlowControlOption();
+	iConfigStatus = EOptionConfigComplete;
+	}
+
+
 void TL2CapIncomingFecNegotiator::BuildRequest(TL2CapChannelMode aMode, TRetransmissionAndFlowControlOption& aFecOption)
     {
     LOG_FUNC
@@ -761,9 +769,7 @@
 		iIncomingNegotiator.Preferred().LinkMode() != EL2CAPBasicMode)
 		{
 		LOG(_L("\tReceived Basic mode Config Request, downgrading incoming channel mode to Basic"));
-		// Downgrade incoming FEC to be basic mode.
-  		TRetransmissionAndFlowControlOption basicFec;
-  		iIncomingNegotiator.SetPreferred(basicFec);
+		iIncomingNegotiator.DowngradeToBasic();
 		}
 	}
 
--- a/bluetooth/btstack/l2cap/L2CapFecNegotiator.h	Thu Jul 15 19:55:36 2010 +0300
+++ b/bluetooth/btstack/l2cap/L2CapFecNegotiator.h	Thu Aug 19 11:01:00 2010 +0300
@@ -207,6 +207,7 @@
 	void ProcessPeerValue(const TRetransmissionAndFlowControlOption& aFecOption,
 						  TBool aIsUnacceptableParameters);
 	void ProcessImplicitPeerValue();
+	void DowngradeToBasic();
     void Setup();
 protected:
     void BuildRequest(TL2CapChannelMode aMode, TRetransmissionAndFlowControlOption& aFecOption);
--- a/bluetooth/btstack/l2cap/l2capSigStates.cpp	Thu Jul 15 19:55:36 2010 +0300
+++ b/bluetooth/btstack/l2cap/l2capSigStates.cpp	Thu Aug 19 11:01:00 2010 +0300
@@ -898,6 +898,9 @@
 void TL2CAPSigStateWaitConfig::Enter(CL2CapSAPSignalHandler& aSignalHandler) const
 	{
 	LOG_FUNC
+	// Cancel the Config timer if it's running
+	aSignalHandler.CancelTimer();
+	
 	// First start the ConfigReq sending delay timer (see DelayConfigRequest() for why).
 	// It's short lived, we'll start the proper L2CAP config timer when it expires.
 	aSignalHandler.StartConfigRequestDelayTimer();
--- a/bluetooth/btstack/l2cap/l2sap.cpp	Thu Jul 15 19:55:36 2010 +0300
+++ b/bluetooth/btstack/l2cap/l2sap.cpp	Thu Aug 19 11:01:00 2010 +0300
@@ -435,7 +435,7 @@
 		case KL2CAPUpdateChannelConfig:
 			{
 			const TL2CapConfig apiConf = *reinterpret_cast<const TL2CapConfig*>(aOption.Ptr());
-			return iL2CapSAPSignalHandler->UpdateChannelConfig(apiConf);
+            return UpdateChannelConfig(apiConf);
 			}
 			
 		// Can't set these
@@ -1084,6 +1084,11 @@
 
 	if(dataConfig)
 		{
+		// if UpdateChannelConfig was called before iL2CapDataQueue was created we update the priority now
+		if (iChannelPriority != 0)
+			{
+			dataConfig->SetChannelPriority(iChannelPriority);
+			}
 		TRAP(rerr, iL2CapDataQueue = CL2CapSDUQueue::NewL(*this,
 		                                                  aLocalPort,
 		                                                  aRemotePort,
--- a/bluetooth/btstack/l2cap/l2signalmgr.cpp	Thu Jul 15 19:55:36 2010 +0300
+++ b/bluetooth/btstack/l2cap/l2signalmgr.cpp	Thu Aug 19 11:01:00 2010 +0300
@@ -1177,11 +1177,11 @@
 		else
 			{
 			TBool controllerAdded = EFalse;
-			while((handler = iter++) != NULL && !controllerAdded)
+			while(!controllerAdded && (handler = iter++) != NULL)
 				{
 				if(channelPriority > handler->Config().ChannelPriority())
 					{
-					handler->iLink.AddBefore(&(aDataController.iLink));
+					aDataController.iLink.AddBefore(&handler->iLink);
 					controllerAdded = ETrue;
 					}
 				}
--- a/bluetooth/btstack/linkmgr/hcifacade_commands.cpp	Thu Jul 15 19:55:36 2010 +0300
+++ b/bluetooth/btstack/linkmgr/hcifacade_commands.cpp	Thu Aug 19 11:01:00 2010 +0300
@@ -559,7 +559,7 @@
 	
 	for (TInt count = 0; count < aNumCurrentIAC; count++)
 		{
-		iacLap.Append(aIAC_LAP[count]);
+		iacLap.AppendL(aIAC_LAP[count]);
 		}
 		
 	CWriteCurrentIACLAPCommand* cmd = CWriteCurrentIACLAPCommand::NewL(aNumCurrentIAC, iacLap);
--- a/bluetooth/btstack/linkmgr/hostresolver.cpp	Thu Jul 15 19:55:36 2010 +0300
+++ b/bluetooth/btstack/linkmgr/hostresolver.cpp	Thu Aug 19 11:01:00 2010 +0300
@@ -2284,7 +2284,7 @@
 		TInquiryCacheAge ageInfo;
 		ageInfo.iIAC = aIAC;
 		ageInfo.iCacheAge = aAge;
-		iCacheAge.Append(ageInfo);
+		(void)iCacheAge.Append(ageInfo);
 		// If we can't append, there's not a lot we can do - we'll just have
 		// to return KMaxTInt when someone asks for the age
 		}
--- a/bluetooth/btstack/linkmgr/physicallinks.cpp	Thu Jul 15 19:55:36 2010 +0300
+++ b/bluetooth/btstack/linkmgr/physicallinks.cpp	Thu Aug 19 11:01:00 2010 +0300
@@ -58,7 +58,7 @@
 static const THCIErrorCode KDefaultRejectReason = EHostSecurityRejection; // see spec Error Codes
 
 #ifdef _DEBUG
-#define __CHECK_CONNECTION_HANDLE(aHandle) __ASSERT_DEBUG(aHandle==iHandle, Panic(EBTLinkMgrConnectionEventInWrongSAP));
+#define __CHECK_CONNECTION_HANDLE(aHandle) __ASSERT_DEBUG(HasHandle(aHandle), Panic(EBTLinkMgrConnectionEventInWrongSAP));
 #else
 #define __CHECK_CONNECTION_HANDLE(aHandle) aHandle=aHandle; // to suppress warnings
 #endif
@@ -1826,63 +1826,36 @@
 		return KErrNone;
 		}
 	
-	TBTLinkMode nextMode = EActiveMode;
+	TBTLinkMode targetMode = EActiveMode;
 	// Determine which LPM we should be in (if any)
 	if(modeChangeMask & KExplicitActiveMode)
 		{
-		nextMode = EActiveMode;
+		targetMode = EActiveMode;
 		}
 	else if(modeChangeMask & EHoldMode)
 		{
-		nextMode = EHoldMode;
+		targetMode = EHoldMode;
 		}
 	else if(modeChangeMask & ESniffMode)
 		{
-		nextMode = ESniffMode;
+		targetMode = ESniffMode;
 		}
 	else if(modeChangeMask & EParkMode)
 		{
-		nextMode = EParkMode;
+		targetMode = EParkMode;
 		}
-	LOG2(_L8("Arbitration: Arbitrating mode 0x%02x -> 0x%02x"), currentMode, nextMode);
+	LOG2(_L8("Arbitration: Arbitrating mode 0x%02x -> 0x%02x"), currentMode, targetMode);
 	
-	if(nextMode != currentMode)
-		{
-		if(currentMode != EActiveMode)
-			{
-			LOG(_L8("Arbitration: Exiting existing LPM mode..."));
-			TInt err = RequestActive();
-			if(err != KErrNone)
-				{
-				return err;
-				}
-			}
-		if(nextMode == EHoldMode)
-			{
-			LOG(_L8("Arbitration: Entering Hold mode..."));
-			return RequestHold();
-			}
-		else if(nextMode == ESniffMode)
-			{
-			LOG(_L8("Arbitration: Entering Sniff mode..."));
-			return RequestSniff();
-			}
-		else if(nextMode == EParkMode)
-			{
-			LOG(_L8("Arbitration: Entering Park mode..."));
-			return RequestPark();
-			}
-		else if(nextMode == EActiveMode)
-			{
-			LOG(_L8("Arbitration: Staying in Active mode..."));
-			return KErrNone;
-			}
-		// Shouldn't reach here, we have a strange mode
-		DEBUG_PANIC_LINENUM;
-		}
-
-	LOG(_L8("Arbitration: Already in correct LPM, not doing anything"));
-	return KErrNone;
+	if(IsConnected())
+	    {
+        TInt err = iLowPowModeCtrl.ExecuteModeChange(targetMode);
+        LOG1(_L8("Arbitration: iLowPowModeCtrl.ExecuteModeChange: err:%d"), err);
+        return err;
+	    }
+	else
+	    {
+        return KErrDisconnected;
+	    }
 	}
 
 void CPhysicalLink::SetPassKey(const TDesC8& aPassKey)
@@ -2613,29 +2586,6 @@
 	return rerr;
 	}
 
-TInt CPhysicalLink::ExitMode(TBTLinkMode aMode)
-	{
-	LOG_FUNC
-	return iLowPowModeCtrl.ExitMode(aMode, iHandle);
-	}
-
-TInt CPhysicalLink::RequestMode(TBTLinkMode aMode)
-	{
-	LOG_FUNC
-	if (!IsConnected())
-		return KErrDisconnected;
-
-	// if active mode is required, try to exit whatever Low Power mode we are in -
-	// if neither sniff nor park nothing will happen.
-	if(aMode == EActiveMode)
-		{
-		return ExitMode(iLinkState.LinkMode());
-		}
-
-	// now request this connection goes to requested mode
-	return iLowPowModeCtrl.ChangeMode(aMode, iHandle);
-	}
-
 TInt CPhysicalLink::RequestChangeRole(TBTBasebandRole aRole)
 	{
 	LOG_FUNC
@@ -3143,29 +3093,14 @@
 	AuthenticationComplete(EPinRequestPending);
 	}
 
-
 TInt CPhysicalLink::RequestHold()
 	{
 	LOG_FUNC
-	return RequestMode(EHoldMode);
-	}
-
-TInt CPhysicalLink::RequestSniff()
-	{
-	LOG_FUNC
-	return RequestMode(ESniffMode);
-	}
-
-TInt CPhysicalLink::RequestPark()
-	{
-	LOG_FUNC
-	return RequestMode(EParkMode);
-	}
-
-TInt CPhysicalLink::RequestActive()
-	{
-	LOG_FUNC
-	return RequestMode(EActiveMode);
+	if (!IsConnected())
+        {
+        return KErrDisconnected;
+        }
+	 return iLowPowModeCtrl.ChangeMode(EHoldMode, iHandle);
 	}
 
 void CPhysicalLink::ReadNewPhysicalLinkMetricValue(TUint aIoctlName, CBTProxySAP& aSAP, TInt aCurrentValue)
@@ -3433,21 +3368,21 @@
 	LOG_FUNC
 	// Work out what the local priority will be now
 	iLocalPriority = iLocalPriority || aLocalPriority;
-	LOG1(_L8("Arbitraion: Local Priority now %d"), iLocalPriority);
+	LOG1(_L8("Arbitration: Local Priority now %d"), iLocalPriority);
 	if(aImmediate)
 		{
-		LOG(_L8("Arbitraion: Immediate Arbitration Requested..."));
+		LOG(_L8("Arbitration: Immediate Arbitration Requested..."));
 		CancelButPreserveLocalPriority();
 		return DoArbitrate();
 		}
 	else if(!IsActive())
 		{
-		LOG(_L8("Arbitraion: Arbitration requested, will execute after delay timer..."));
+		LOG(_L8("Arbitration: Arbitration requested, will execute after delay timer..."));
 		After(KBTArbitrationDelay);
 		}
 	else // timer is already on its way
 		{
-		LOG(_L8("Arbitraion: Arbitration delay timer still pending..."));
+		LOG(_L8("Arbitration: Arbitration delay timer still pending..."));
 		}
 	return KErrNone;
 	}
@@ -3455,7 +3390,7 @@
 void CArbitrationDelayTimer::Restart()
 	{
 	LOG_FUNC
-	LOG(_L8("Arbitraion: Arbitration timer restarted..."));
+	LOG(_L8("Arbitration: Arbitration timer restarted..."));
 	CancelButPreserveLocalPriority();
 	After(KBTArbitrationDelay);
 	}
@@ -3475,7 +3410,7 @@
 **/
 	{
 	LOG_FUNC
-	LOG(_L8("Arbitraion: Delayed Arbitration executing..."));
+	LOG(_L8("Arbitration: Delayed Arbitration executing..."));
 	static_cast<void>(DoArbitrate()); // ignore the error (always has been...)
 	}
 
@@ -4013,6 +3948,46 @@
 	return err;
 	}
 
+TInt TLowPowModeCmdController::ExecuteModeChange(TBTLinkMode aTargetMode)
+	{
+	LOG_FUNC
+	iTargetMode = aTargetMode;
+	if(iTargetMode != iParent.LinkState().LinkMode())
+		{
+		if(iParent.LinkState().LinkMode() != EActiveMode)
+			{
+			//the current mode is not in Active Mode, therefore the mode need to change to active first before change to other mode.
+			LOG(_L8("ExecuteModeChange: Exiting existing LPM mode..."));
+			return ExitMode(iParent.LinkState().LinkMode(), iParent.Handle());
+			}
+		//the current mode is in Active mode, therefore the mode is ready to go other mode.
+		if(iTargetMode == EHoldMode)
+			{
+			LOG(_L8("ExecuteModeChange: Entering Hold mode..."));
+			return ChangeMode(EHoldMode, iParent.Handle());
+			}
+		else if(iTargetMode == ESniffMode)
+			{
+			LOG(_L8("ExecuteModeChange: Entering Sniff mode..."));
+			return ChangeMode(ESniffMode, iParent.Handle());
+			}
+		else if(iTargetMode == EParkMode)
+			{
+			LOG(_L8("ExecuteModeChange: Entering Park mode..."));
+			return ChangeMode(EParkMode, iParent.Handle());
+			}
+		else if(iTargetMode == EActiveMode)
+			{
+			LOG(_L8("ExecuteModeChange: Staying in Active mode..."));
+			return KErrNone;
+			}
+		// Shouldn't reach here, we have a strange mode
+		DEBUG_PANIC_LINENUM;
+		}
+	LOG(_L8("ExecuteModeChange: Already in correct LPM, not doing anything"));
+	return KErrNone;
+	}
+
 void TLowPowModeCmdController::SniffL(THCIConnHandle aHandleToRemote)
 	{
 	LOG_FUNC
@@ -4082,29 +4057,36 @@
 		LOG2(_L("TLowPowModeCmdController::MhcqcCommandEventReceived: event:%d opcode:0x%x"), code, aRelatedCommand->Opcode());
 
 		const TModeChangeEvent& modeChangeEvent = TModeChangeEvent::Cast(aEvent);
-		TBTLinkMode mode = EActiveMode;
+		TBTLinkMode currentmode = EActiveMode;
 		switch(modeChangeEvent.CurrentMode())
 			{
 			// Mode 0, as defined for the Mode Change Event, is Active Mode
 			case 0:
 				break;
 			case 1:
-				mode = EHoldMode;
+				currentmode = EHoldMode;
 				break;
 			case 2:
-				mode = ESniffMode;
+				currentmode = ESniffMode;
 				break;
 			case 3:
-				mode = EParkMode;
+				currentmode = EParkMode;
 				break;
 			default:
 				__ASSERT_ALWAYS(EFalse, Panic(EHCICommandBadArgument));
 				break;
 			}
-			// In the HCI_Facade, in this situation, CPhysicalLinksManager::ModeChanged() is called.
-			// Since this methods find the CPhysicalLink object (that is iParent) and then call its
-			// ModeChange method, we can call it directly.
-			iParent.ModeChange(aEvent.ErrorCode(), modeChangeEvent.ConnectionHandle(), mode, modeChangeEvent.Interval());
+		// In the HCI_Facade, in this situation, CPhysicalLinksManager::ModeChanged() is called.
+		// Since this methods find the CPhysicalLink object (that is iParent) and then call its
+		// ModeChange method, we can call it directly.
+		iParent.ModeChange(aEvent.ErrorCode(), modeChangeEvent.ConnectionHandle(), currentmode, modeChangeEvent.Interval());
+		//pass the current mode into Gear box. let gear box to decide if the mode is on the target mode. 
+		//if it is, the gear box returns KErrNone, if it is not, the gear box will make another request for the target mode
+		if (aEvent.ErrorCode() == EOK)
+			{
+            TInt err = ExecuteModeChange(iTargetMode);
+			LOG1(_L("TLowPowModeCmdController::ExecuteModeChange: err:%d"), err);
+			}
 		}
 	}
 
--- a/bluetooth/btstack/linkmgr/physicallinks.h	Thu Jul 15 19:55:36 2010 +0300
+++ b/bluetooth/btstack/linkmgr/physicallinks.h	Thu Aug 19 11:01:00 2010 +0300
@@ -113,6 +113,8 @@
 	
 	TInt ExitMode(TBTLinkMode aMode, THCIConnHandle aHandle);
 	TInt ChangeMode(TBTLinkMode aMode, THCIConnHandle aHandle);
+	
+	TInt ExecuteModeChange(TBTLinkMode aTargetMode);
 
 private:	// events from MHCICommandQueueClient
 	virtual void MhcqcCommandEventReceived(const THCIEventBase& aEvent, const CHCICommandBase* aRelatedCommand);
@@ -127,11 +129,12 @@
 	void HoldL(THCIConnHandle aHandle);
 	void ParkL(THCIConnHandle aHandleToRemote);
 	void ExitParkL(THCIConnHandle aHandleToRemote);
-
+	
 private:
 	CPhysicalLink&		iParent;
 	MHCICommandQueue&	iCmdController;
 	TBool				iOutstandingCmd;
+	TBTLinkMode			iTargetMode;
 	};
 
 /**
@@ -332,11 +335,7 @@
 
 	TInt ChangeConnectionPacketType(TUint16 aType);
 
-	TInt ExitMode(TBTLinkMode aMode);
 	TInt RequestHold();
-	TInt RequestSniff();
-	TInt RequestPark();
-	TInt RequestActive();
 	TInt RequestChangeRole(TBTBasebandRole aRole);
 
 	void ReadNewPhysicalLinkMetricValue(TUint aIoctlName, CBTProxySAP& aSAP, TInt aCurrentValue);
@@ -490,7 +489,6 @@
 	void NotifyStateChange(TBTBasebandEventNotification & aEvent);
 
 	TBool IsPhysicalLinkIdle() const;
-	TInt RequestMode(TBTLinkMode aMode);
 	TBasebandTime CalculatePageTimeout(TBasebandPageTimePolicy aPolicy, TUint8 aRepMode, TBool aValidClockOffset);
 	TBool IsPasskeyMinLengthOK();
 	TBool PeerSupportsLinkKeyRegeneration() const;
--- a/bluetooth/btstack/secman/pairingserver.cpp	Thu Jul 15 19:55:36 2010 +0300
+++ b/bluetooth/btstack/secman/pairingserver.cpp	Thu Aug 19 11:01:00 2010 +0300
@@ -639,7 +639,6 @@
 		}
 	}
 
-
 void COobDataSession::XoldoLocalOobDataRetrieved(TInt aResult, const TBluetoothSimplePairingHash& aHash, const TBluetoothSimplePairingRandomizer& aRandomizer)
 	{
 	LOG_FUNC
@@ -702,8 +701,8 @@
 	{
 	LOG_FUNC
 	iPhysicalLinksManager.SecMan().CancelRequest(*this);
-	delete iProxySap;
-	if(iStartBondingMsg.Handle())
+	delete iProxySap; // cannot do an immediate shutdown as the semantics for that kill the phy
+	if(!iStartBondingMsg.IsNull())
 		{
 		iStartBondingMsg.Complete(KErrCancel);
 		}
@@ -718,6 +717,7 @@
 	case EPairingServerStartDedicatedBond:
 		StartBondingL(aMessage);
 		break;
+		
 	default:
 		CPairingSubSession::DispatchSubSessMessageL(aMessage);
 		break;
@@ -727,9 +727,18 @@
 void CDedicatedBondingSession::Complete(TInt aError)
 	{
 	LOG_FUNC
-	iState = EShutdown;
-	iAsyncShutdown->CallBack();
-	iStartBondingMsg.Complete(aError);
+	if(!iStartBondingMsg.IsNull())
+		{
+		__ASSERT_DEBUG(!ShuttingDown(), PANIC(KPairingServerFaultCat, EPairingServerBadShutdownState));
+		iState = EShutdownRequested;
+		iAsyncShutdown->CallBack();
+		iPhysicalLinksManager.SecMan().CancelRequest(*this); // we don't want the result anymore (if it's still pending).
+		iStartBondingMsg.Complete(aError); 
+		}
+	else
+		{
+		__ASSERT_DEBUG(ShuttingDown(), PANIC(KPairingServerFaultCat, EPairingServerBadShutdownState));
+		}
 	}
 
 TInt CDedicatedBondingSession::StaticShutdown(TAny* aDedBond)
@@ -742,42 +751,49 @@
 void CDedicatedBondingSession::Shutdown()
 	{
 	LOG_FUNC
-	__ASSERT_DEBUG(iState == EShutdown, PANIC(KPairingServerFaultCat, EPairingServerBadShutdownState));
-	iState = EInvalid;
+	__ASSERT_DEBUG(iState == EShutdownRequested, PANIC(KPairingServerFaultCat, EPairingServerBadShutdownState));
+	__ASSERT_DEBUG(iStartBondingMsg.IsNull(), PANIC(KPairingServerFaultCat, EPairingServerMessageShouldBeNull));
+	iState = EShutdownPending;
 	iProxySap->Shutdown(CServProviderBase::ENormal);
 	}
+	
+TBool CDedicatedBondingSession::ShuttingDown() const
+	{
+	return iState == EShutdownRequested || iState == EShutdownPending;
+	}
 
 void CDedicatedBondingSession::StartBondingL(const RMessage2& aMessage)
 	{
 	LOG_FUNC
 
-	if(!iStartBondingMsg.IsNull() || iState != EInvalid)
+	if(iState != EMintCondition)
 		{
 		aMessage.Panic(KPairingServerPanicCat, EPairingServerDedicatedBondAlreadyInProgress);
 		return;
 		}
-
+	__ASSERT_DEBUG(iStartBondingMsg.IsNull(), PANIC(KPairingServerFaultCat, EPairingServerMessageShouldBeNull));
+	
+	// Now we've been initiated, no turning back for this object.
+	iState = EInitiated;
+	
 	TPckgBuf<TBTDevAddr> addrBuf;
 	TInt addrLen = aMessage.GetDesLengthL(0);
 	if(addrLen != sizeof(TBTDevAddr))
 		{
-		// If the length is correct then the address has been packaged incorrect for the
+		// If the length is incorrect then the address has been packaged incorrectly for the
 		// IPC operation.
 		LEAVEL(KErrBadDescriptor);
 		}
 	aMessage.ReadL(0, addrBuf);
 
-	iStartBondingMsg = aMessage;
-	CleanupStack::PushL(TCleanupItem(CleanupStartMessage, this));
-
 	TBTSockAddr addr;
 	addr.SetBTAddr(addrBuf());
 	iProxySap = CBTProxySAP::NewL(iPhysicalLinksManager, NULL);
-
-	CleanupStack::Pop(this); // the start message cleaner
 	
+	iStartBondingMsg = aMessage;
 	// Now we've entered the realm of not leaving with an error, since the connection
 	// process has started.  Errors from now on must be via the Error() function call.
+	
 	iState = EInitialConnectionPending;
 	iProxySap->SetNotify(this);
 	iProxySap->SetRemName(addr);
@@ -789,13 +805,6 @@
 		}
 	}
 
-void CDedicatedBondingSession::CleanupStartMessage(TAny* aPtr)
-	{
-	LOG_STATIC_FUNC
-	CDedicatedBondingSession* session = reinterpret_cast<CDedicatedBondingSession*>(aPtr);
-	session->iStartBondingMsg = RMessage2(); // blat the old one
-	}
-
 void CDedicatedBondingSession::DoAccessRequestL()
 	{
 	LOG_FUNC
@@ -833,7 +842,7 @@
 		// fall-through...
 	case EInitialConnection:
 		ASSERT_DEBUG(aResult != EBTSecManAccessDeferred); // Should have been disconnected if we receive
-													// this - I don't expect this to happen.
+														  // this - I don't expect this to happen.
 		// fall-through...
 	case EFinalConnection:
 		completed = ETrue; // in the final connection any complete is errored.
@@ -842,12 +851,15 @@
 			err = KErrAccessDenied;
 			}
 		break;
+		
 	case EInitialConnectionPending:
+		// fall-through deliberate
 	case EFinalConnectionPending:
 		// Access request shouldn't successfully complete if the connection is still pending
 		__ASSERT_DEBUG(aResult != EBTSecManAccessGranted,  PANIC(KPairingServerFaultCat, EPairingServerUnexpectedAccessCallback));
 		// We should get the MSocketNotify::Error callback, so don't do anything else
 		break;
+		
 	default:
 		LOG1(_L("Unexpected Access Request Complete in state %d"), iState);
 		__ASSERT_DEBUG(EFalse, PANIC(KPairingServerFaultCat, EPairingServerUnexpectedAccessCallback));
@@ -885,15 +897,21 @@
 	case EFinalConnectionPending:
 		iState = EFinalConnection;
 		break;
+		
 	case EInitialConnection:
+		// fall-through deliberate
 	case EFinalConnection:
 		// Apparently multiple connect completes are allowed by CSocket
 		break;
-	case EShutdown:
+		
+	case EShutdownRequested:
+		// fall-through deliberate
+	case EShutdownPending:
 		// If an error occurred just after the connection request then we
 		// might receive a connection complete before the async shutdown request
-		// has been executed.
+		// has been executed or completed.
 		break;
+		
 	default:
 		LOG1(_L("Unexpected Connect Complete in state %d"), iState);
 		__ASSERT_DEBUG(EFalse, PANIC(KPairingServerFaultCat, EPairingServerUnexpectedSocketCallback));
@@ -924,6 +942,9 @@
 void CDedicatedBondingSession::CanClose(TDelete aDelete)
 	{
 	LOG_FUNC
+	__ASSERT_DEBUG(iState == EShutdownPending, PANIC(KPairingServerFaultCat, EPairingServerUnexpectedSocketCallback));
+	__ASSERT_DEBUG(iStartBondingMsg.IsNull(), PANIC(KPairingServerFaultCat, EPairingServerMessageShouldBeNull));
+	iState = EShutdown;
 	if (aDelete == EDelete)
 		{
 		delete iProxySap; iProxySap = NULL;
@@ -951,12 +972,17 @@
 		// enter the zombie state and wait for the access requester to complete.
 		iState = EZombie;
 		break;
+		
 	case EFinalConnection:
 		Error(KErrDisconnected);
 		break;
-	case EShutdown:
+		
+	case EShutdownRequested:
+		// fall-through deliberate
+	case EShutdownPending:
 		// Already closing down.
 		break;
+		
 	default:
 		LOG1(_L("Unexpected Disconnect in state %d"), iState);
 		__ASSERT_DEBUG(EFalse, PANIC(KPairingServerFaultCat, EPairingServerUnexpectedSocketCallback));
--- a/bluetooth/btstack/secman/pairingserver.h	Thu Jul 15 19:55:36 2010 +0300
+++ b/bluetooth/btstack/secman/pairingserver.h	Thu Aug 19 11:01:00 2010 +0300
@@ -218,8 +218,8 @@
 
 	void Complete(TInt aError);
 
-	static void CleanupStartMessage(TAny* aPtr);
 	static TInt StaticShutdown(TAny* aPtr);
+	TBool ShuttingDown() const;
 
 private: // from CPairingSubSession
 	void DispatchSubSessMessageL(const RMessage2& aMessage);
@@ -246,12 +246,15 @@
 private:
 	enum TState
 		{
-		EInvalid,
+		EMintCondition,
+		EInitiated,
 		EInitialConnectionPending,
 		EInitialConnection,
 		EZombie,
 		EFinalConnectionPending,
 		EFinalConnection,
+		EShutdownRequested,
+		EShutdownPending,
 		EShutdown,
 		};
 
--- a/bluetooth/btstack/secman/public/pairingservershared.h	Thu Jul 15 19:55:36 2010 +0300
+++ b/bluetooth/btstack/secman/public/pairingservershared.h	Thu Aug 19 11:01:00 2010 +0300
@@ -71,6 +71,7 @@
 	EPairingServerUnexpectedSocketCallback,
 	EPairingServerUnexpectedAccessCallback,
 	EPairingServerBadShutdownState,
+	EPairingServerMessageShouldBeNull,
 	};
 
 #endif // PAIRINGSERVERSHARED_H
--- a/bluetooth/gavdp/inc/gavdpInternal.h	Thu Jul 15 19:55:36 2010 +0300
+++ b/bluetooth/gavdp/inc/gavdpInternal.h	Thu Aug 19 11:01:00 2010 +0300
@@ -1,4 +1,4 @@
-// Copyright (c) 2004-2009 Nokia Corporation and/or its subsidiary(-ies).
+// Copyright (c) 2004-2010 Nokia Corporation and/or its subsidiary(-ies).
 // All rights reserved.
 // This component and the accompanying materials are made available
 // under the terms of "Eclipse Public License v1.0"
@@ -301,16 +301,17 @@
 NONSHARABLE_CLASS(CGavdpConnector) : public CGavdpHelper
 	{
 public:
-	static CGavdpConnector* NewL(CGavdp& aGavdp, MGavdpUser& aUser, const TBTDevAddr& aAddr);
+	static CGavdpConnector* NewL(CGavdp& aGavdp, MGavdpUser& aUser, const TBTDevAddr& aAddr, TBool aPassive = EFalse);
 	
 	virtual void Begin();
 	~CGavdpConnector();
 private:
-	CGavdpConnector(CGavdp& aGavdp, MGavdpUser& aUser, const TBTDevAddr& aAddr);
+	CGavdpConnector(CGavdp& aGavdp, MGavdpUser& aUser, const TBTDevAddr& aAddr, TBool aPassive);
 	void RunL();
 	void DoCancel();
 private:
 	TAvdtpSockAddr	iSocketAddress;
+	TBool			iIsPassiveConnector;	//true when listening
 	};
 
 class CGavdpUPlaneConnector;
--- a/bluetooth/gavdp/source/gavdpHelpers.cpp	Thu Jul 15 19:55:36 2010 +0300
+++ b/bluetooth/gavdp/source/gavdpHelpers.cpp	Thu Aug 19 11:01:00 2010 +0300
@@ -1,4 +1,4 @@
-// Copyright (c) 2004-2009 Nokia Corporation and/or its subsidiary(-ies).
+// Copyright (c) 2004-2010 Nokia Corporation and/or its subsidiary(-ies).
 // All rights reserved.
 // This component and the accompanying materials are made available
 // under the terms of "Eclipse Public License v1.0"
@@ -473,16 +473,17 @@
 
 	
 
-CGavdpConnector* CGavdpConnector::NewL(CGavdp& aGavdp, MGavdpUser& aUser, const TBTDevAddr& aAddr)
+CGavdpConnector* CGavdpConnector::NewL(CGavdp& aGavdp, MGavdpUser& aUser, const TBTDevAddr& aAddr, TBool aPassive)
 	{
-	return new (ELeave) CGavdpConnector(aGavdp, aUser, aAddr);
+	return new (ELeave) CGavdpConnector(aGavdp, aUser, aAddr, aPassive);
 	}
-	
-CGavdpConnector::CGavdpConnector(CGavdp& aGavdp, MGavdpUser& aUser, const TBTDevAddr& aAddr)
+
+CGavdpConnector::CGavdpConnector(CGavdp& aGavdp, MGavdpUser& aUser, const TBTDevAddr& aAddr, TBool aPassive)
 : CGavdpHelper(aGavdp, aUser)
 	{
 	iSocketAddress.SetBTAddr(aAddr);
 	iSocketAddress.SetSession(ESignalling);
+	iIsPassiveConnector = aPassive;
 	}
 
 CGavdpConnector::~CGavdpConnector()
@@ -492,10 +493,13 @@
 
 void CGavdpConnector::DoCancel()
 	{
-	AvdtpRequester().CancelAll(); // ESOCK has better semantics to SAP than CancelConnect.
+	//don't call cancel on the socket for passive connectors to prevent cancelling a listening socket
+	if (!iIsPassiveConnector)
+		{
+		AvdtpRequester().CancelAll(); // ESOCK has better semantics to SAP than CancelConnect.
+		}
 	}
 
-
 void CGavdpConnector::Begin()
 	{
 	// Ensure that once this is completed the RunL is scheduled
@@ -507,7 +511,6 @@
 
 void CGavdpConnector::RunL()
 	{
-		
 	// Do not call CGavdpHelper::CheckFailedL() here - avdtp will indicate a failure to connect, 
 	// and GAVDP is informed via CGavdpIndicator::RunL().
 	
@@ -751,14 +754,14 @@
 				}
 			};
 		}
+	
+	// This service is never complete, reissue ioctl.  We do this once we have finished using
+	// the iIndication data as once the ioctl has been issued the data may be overwritten.
+	// If AVDTP has an indication to pass to us and an ioctl has not been issued the
+	// indication will be queued within AVDTP until we have issued the ioctl again.
+	Begin();
+	}
 
-		// This service is never complete, reissue ioctl.  We do this once we have finished using
-		// the iIndication data as once the ioctl has been issued the data may be overwritten.
-		// If AVDTP has an indication to pass to us and an ioctl has not been issued the
-		// indication will be queued within AVDTP until we have issued the ioctl again.
-		Begin();
-	}
-	
 /**
 RunError overriden for CGavdpIndicator only. This GAVDP helper is used in its own right by GAVDP.
 It is not treated as a 'general' GAVDP helper, and, unlike a 'general' GAVDP helper,
--- a/bluetooth/gavdp/source/gavdpImp.cpp	Thu Jul 15 19:55:36 2010 +0300
+++ b/bluetooth/gavdp/source/gavdpImp.cpp	Thu Aug 19 11:01:00 2010 +0300
@@ -1,4 +1,4 @@
-// Copyright (c) 2004-2009 Nokia Corporation and/or its subsidiary(-ies).
+// Copyright (c) 2004-2010 Nokia Corporation and/or its subsidiary(-ies).
 // All rights reserved.
 // This component and the accompanying materials are made available
 // under the terms of "Eclipse Public License v1.0"
@@ -445,12 +445,37 @@
 	
 void CGavdp::Error(TInt aError)
 	{
-	// helper tells user - here we do whatever we need to tidy ourselves
+	//here we do whatever we need to tidy ourselves
 	delete iRequesterHelper;
 	iRequesterHelper = NULL;
-	iState = EIdle;
-	// and tell the user
-	iServiceUser.GAVDP_Error(aError, KNullDesC8);
+	
+	if (iState == EListening)
+		{
+		//if we're in the listening state and we get a KErrDisconnected error, this is
+		//because a connection completed and was disconnected straight away before we got
+		//the chance to pickup the connection indicator. We need to re-listen and throw
+		//away this error. Let's replace the error with the result of the re-listen.
+		if (aError == KErrDisconnected)
+			{
+			aError = Listen();
+			}
+		
+		//when listening, it doesn't make sense to pass this error to the user
+		if (aError == KErrCouldNotConnect)
+			{
+			aError = KErrNone;
+			}
+		}
+	
+	//the error might have been replaced due to the condition mentioned above so
+	//this needs to be checked.
+	if (aError != KErrNone)
+		{
+		iServiceUser.GAVDP_Error(aError, KNullDesC8);
+		
+		//update the state because an error did occur
+		iState = EIdle;
+		}
 	}
 
 void CGavdp::FatalError()
@@ -476,10 +501,12 @@
 		// eg Abort, Config
 		User::Leave(KErrInUse);
 		}
-	iRequesterHelper = CGavdpConnector::NewL(*this, iServiceUser, aRemoteAddress);
+	
+	//create a passive connector helper
+	iRequesterHelper = CGavdpConnector::NewL(*this, iServiceUser, aRemoteAddress, ETrue);
 	iRequesterHelper->Begin();
 	}
-	
+
 /*
 Forms the binding between passively created transport sessions and sockets
 */
--- a/bluetoothcommsprofiles/btpan/refBnepPacketNotifier/src/refBnepPacketNotifier.cpp	Thu Jul 15 19:55:36 2010 +0300
+++ b/bluetoothcommsprofiles/btpan/refBnepPacketNotifier/src/refBnepPacketNotifier.cpp	Thu Aug 19 11:01:00 2010 +0300
@@ -82,7 +82,7 @@
 	devByteCount.iByteCount=0;
 	devByteCount.iTickCount=0;
 	devByteCount.iAddr=aAddr;
-	iCounter.Append(devByteCount);
+	(void)iCounter.Append(devByteCount);
 	}
 
 void CRefBnepPacketNotifier::MbpnDeviceRemoved(const TBTDevAddr& aAddr)
--- a/bluetoothmgmt/bluetoothclientlib/btlib/btsynclink.cpp	Thu Jul 15 19:55:36 2010 +0300
+++ b/bluetoothmgmt/bluetoothclientlib/btlib/btsynclink.cpp	Thu Aug 19 11:01:00 2010 +0300
@@ -160,7 +160,6 @@
 
 // This needs to be a macro or the 'return' won't return properly
 #define CLOSE_RETURN_IF_ERROR(error) if (error) { LinkDown(); SCOSocket().Close(); ESCOSocket().Close(); return error; }
-#define CLOSE_LISTENER_RETURN_IF_ERROR(error) if (error) { ListeningSCOSocket().Close(); ListeningESCOSocket().Close(); return error; }
 
 EXPORT_C TInt CBluetoothSynchronousLink::SetupConnection(const TBTDevAddr& aBDAddr, const TBTSyncPackets& aPacketTypes)
 	{
@@ -191,23 +190,17 @@
 	if (packetsESCO) 
 		{
 		iSCOTypes |= EeSCO;
-		openESCO = ETrue;	
+		openESCO = ETrue;
 		}
 		
 	// but must be one		
 	__ASSERT_ALWAYS(packetsSCO || packetsESCO, Panic(EBadSyncPacketTypes));
 
-	if (iBTSynchronousLinkAttacherSCO->IsActive())
+	if (iBTSynchronousLinkAttacherSCO->IsActive() || iBTSynchronousLinkAttacherESCO->IsActive())
 		{
 		FLOG(_L("Link attacher already active"));
 		return KErrInUse;
 		}
-	
-	if (iBTSynchronousLinkAttacherESCO->IsActive())
-		{
-		FLOG(_L("Link attacher already active"));
-		return KErrInUse;
-		}	
 		
 	TInt linkState = LinkUp(aBDAddr);
 	if (linkState != KErrNone)
@@ -337,16 +330,12 @@
 */
 EXPORT_C TInt CBluetoothSynchronousLink::Disconnect()
 	{
-	if (!SCOSocket().SubSessionHandle())
+	if (!SCOSocket().SubSessionHandle() && !ESCOSocket().SubSessionHandle())
 		{
-		if(!ESCOSocket().SubSessionHandle())
-			{
-			return KErrDisconnected;
-			}
+		return KErrDisconnected;
 		}
 
-	if (iBTSynchronousLinkDetacherSCO->IsActive() ||
-	    iBTSynchronousLinkDetacherESCO->IsActive())
+	if (iBTSynchronousLinkDetacherSCO->IsActive() || iBTSynchronousLinkDetacherESCO->IsActive())
 		{
 		return KErrInUse;
 		}
@@ -499,6 +488,12 @@
 */
 EXPORT_C TInt CBluetoothSynchronousLink::AcceptConnection(const TBTSyncPackets& aPacketTypes)
 	{
+	TRAPD(err, AcceptConnectionL(aPacketTypes));
+	return err;
+	}
+	
+void CBluetoothSynchronousLink::AcceptConnectionL(const TBTSyncPackets& aPacketTypes)
+	{
 	TBool listenForSCO = EFalse;
 	TBool listenForESCO = EFalse;
 
@@ -506,41 +501,30 @@
 	
 	TBTSyncPacketTypes packets = aPacketTypes();
 	
-	
 	__ASSERT_ALWAYS(packets, Panic(EBadSyncPacketTypes));
 	packets &= (TBTSyncPackets::ESyncAnySCOPacket | TBTSyncPackets::ESyncAnyESCOPacket);
 	if (!packets)
 		{
-		return KErrNotSupported;
+		User::Leave(KErrNotSupported);
 		}
 
-	if (iBTSynchronousLinkAccepterSCO->IsActive())
+	if (iBTSynchronousLinkAccepterSCO->IsActive() || iBTSynchronousLinkAccepterESCO->IsActive())
 		{
-		return KErrInUse;
-		}
-		
-	if (iBTSynchronousLinkAccepterESCO->IsActive())
-		{
-		return KErrInUse;
+		User::Leave(KErrInUse);
 		}
 	
-	TInt err = ListeningSCOSocket().Open(iSockServer, KBTAddrFamily, KSockBluetoothTypeSCO, KBTLinkManager);
-	if(err)
-		{
-		return err;
-		}
+	User::LeaveIfError(ListeningSCOSocket().Open(iSockServer, KBTAddrFamily, KSockBluetoothTypeSCO, KBTLinkManager));
+	CleanupClosePushL(ListeningSCOSocket());
 		
-	err = ListeningESCOSocket().Open(iSockServer, KBTAddrFamily, KSockBluetoothTypeESCO, KBTLinkManager);
-	if(err)
-		{
-		ListeningSCOSocket().Close();
-		return err;
-		}
+	User::LeaveIfError(ListeningESCOSocket().Open(iSockServer, KBTAddrFamily, KSockBluetoothTypeESCO, KBTLinkManager));
+	CleanupClosePushL(ListeningESCOSocket());
+	
+	CleanupStack::PushL(TCleanupItem(StaticResetScoTypes, this)); // we want to clear any setting of SCO types upon leaving
 	
 	TBTSyncPacketTypes packetsSCO = packets & TBTSyncPackets::ESyncAnySCOPacket;
 	if (packetsSCO)
 		{
-		err = ListeningSCOSocket().SetOpt(ESyncUserPacketTypes, KSolBtSCO, packetsSCO);
+		TInt err = ListeningSCOSocket().SetOpt(ESyncUserPacketTypes, KSolBtSCO, packetsSCO);
 		if(!err)
 			{
 			iSCOTypes |= ESCO;
@@ -551,17 +535,15 @@
 	TBTSyncPacketTypes packetsESCO = packets & TBTSyncPackets::ESyncAnyESCOPacket;
 	if (packetsESCO) 
 		{
-		err = ListeningESCOSocket().SetOpt(ESyncUserPacketTypes, KSolBtSCO, packetsESCO);
+		TInt err = ListeningESCOSocket().SetOpt(ESyncUserPacketTypes, KSolBtSCO, packetsESCO);
 		if (!err)
 			{
 			iSCOTypes |= EeSCO;
 			listenForESCO = ETrue;
+			
+			TPckgC<TBTeSCOLinkParams> options(iRequestedLink);
+			User::LeaveIfError(ListeningESCOSocket().SetOpt(EeSCOExtOptions, KSolBtESCO, options));
 			}
-			
-		TPckgBuf<TBTeSCOLinkParams> options;
-		options() = iRequestedLink;
-		err = ListeningESCOSocket().SetOpt(EeSCOExtOptions, KSolBtESCO, options);
-		CLOSE_LISTENER_RETURN_IF_ERROR(err);	
 		}
 
 	__ASSERT_ALWAYS(listenForSCO || listenForESCO, Panic(EBadSyncPacketTypes));
@@ -580,62 +562,57 @@
 	
 	if (listenForSCO)
 		{
-		err = ListeningSCOSocket().Bind(sa);
-		CLOSE_LISTENER_RETURN_IF_ERROR(err);
-		
-		err = ListeningSCOSocket().Listen(KSCOListenQueSize);
-		CLOSE_LISTENER_RETURN_IF_ERROR(err);
-		
-		err = SCOSocket().Open(SocketServer());							    
-		if(err)
-			{
-			return err;
-			}
+		User::LeaveIfError(ListeningSCOSocket().Bind(sa));
+		User::LeaveIfError(ListeningSCOSocket().Listen(KSCOListenQueSize));
+		User::LeaveIfError(SCOSocket().Open(SocketServer()));
+		CleanupClosePushL(SCOSocket());
 		}
 	
 	if(listenForESCO)
 		{
-		err = ListeningESCOSocket().Bind(sa);
-		CLOSE_LISTENER_RETURN_IF_ERROR(err);
-	
-		err = ListeningESCOSocket().Listen(KSCOListenQueSize);
-		CLOSE_LISTENER_RETURN_IF_ERROR(err);
+		User::LeaveIfError(ListeningESCOSocket().Bind(sa));
+		User::LeaveIfError(ListeningESCOSocket().Listen(KSCOListenQueSize));
+		User::LeaveIfError(ESCOSocket().Open(SocketServer()));
+		}
+
+	// Now we can't fail synchronously, so we're ready to begin the accept.
+	if(listenForESCO)
+		{
+		iBTSynchronousLinkAccepterESCO->Accept();
+		}
 		
-		err = ESCOSocket().Open(SocketServer());	
-		if(err)
-			{
-			return err;
-			}
-		}	
-
 	if (listenForSCO)
 		{
-		iBTSynchronousLinkAccepterSCO->Accept(ListeningSCOSocket());
+		CleanupStack::Pop(&SCOSocket());
+		iBTSynchronousLinkAccepterSCO->Accept();
 		}
 	
-	if(listenForESCO)
-		{
-		iBTSynchronousLinkAccepterESCO->Accept(ListeningESCOSocket());
-		}
+	CleanupStack::Pop(3); // StaticResetScoTypes, ListeningESCOSocket(), ListeningSCOSocket()
+	}
 	
-	return err;
+void CBluetoothSynchronousLink::StaticResetScoTypes(TAny* aThis)
+	{
+	static_cast<CBluetoothSynchronousLink*>(aThis)->iSCOTypes = 0;
 	}
 
 
 /**
 Cancel ability to respond to a remote request to set up a synchronous link.
-It is possible for a race condition to mean that a connection has been established,
-but as this call consumes the callback, for this fact not to reach the caller.
-For this reason, it may be desirable to follow a call to CancelAccept with a call
-to Disconnect.
-@see CBluetoothSynchronousLink::Disconnect
+
+It is possible for a race condition to mean that a connection has been established
+but the notifier has not yet received the call-back.  In this case no call-back will
+be received and the link (if established) will be immediately shutdown.
 */
 EXPORT_C void CBluetoothSynchronousLink::CancelAccept()
 	{
 	iBTSynchronousLinkAccepterSCO->Cancel();
 	iBTSynchronousLinkAccepterESCO->Cancel();
 	iBTSynchronousLinkBaseband->StopAll();
-
+	
+	iSCOTypes = 0;
+	
+	LinkDown();
+	
 	ListeningSCOSocket().Close();
 	ListeningESCOSocket().Close();
 	SCOSocket().Close();
@@ -896,36 +873,48 @@
 		if (aSCOType & ESCO)
 			{
 			iBTSynchronousLinkAccepterESCO->Cancel();
+			ListeningESCOSocket().Close();
+			ESCOSocket().Close();
+			
 			SCOSocket().RemoteName(sockAddr);
 			}
 		else
 			{
 			iBTSynchronousLinkAccepterSCO->Cancel();
+			ListeningSCOSocket().Close();
+			SCOSocket().Close();
+			
 			ESCOSocket().RemoteName(sockAddr);
 			}
 		
 		if(sockAddr.Family() == KBTAddrFamily)
 			{
-			TBTSockAddr& btSockAddr = static_cast<TBTSockAddr&>(sockAddr);	// subclasses of TSockAddr are forbidden to add members
+			TBTSockAddr& btSockAddr = static_cast<TBTSockAddr&>(sockAddr);
 			TBTDevAddr da = btSockAddr.BTAddr();
-			TInt linkState = LinkUp(da);
-				
-			__ASSERT_ALWAYS((linkState == KErrNone), Panic(EBasebandFailedConnect));
-			
-			iBTSynchronousLinkBaseband->PreventPark();
-			iBTSynchronousLinkBaseband->CatchEvents();
-			UpdateLinkParams(aSCOType);
+			aErr = LinkUp(da);
+			if(aErr == KErrNone)
+				{
+				iBTSynchronousLinkBaseband->PreventPark();
+				iBTSynchronousLinkBaseband->CatchEvents();
+				UpdateLinkParams(aSCOType);
+				}
+			else
+				{
+				FTRACE(FPrint(_L("Failed to \"LinkUp\" the synchronous link (aErr %d)"), aErr));
+				}
 			}
 		else
 			{
 			// reading RemoteName has failed, probably socket state is already closed
 			// for example after quick disconnection initiated from remote side
-			aErr = KErrDisconnected;			
+			aErr = KErrDisconnected;
 			}
 		}
-	else
+	
+	if(aErr != KErrNone)
 		{
 		iNegotiatedLink = TBTeSCOLinkParams(0, 0, 0, 0);
+		CancelAccept(); // makes sure everything is cleaned up.
 		}
 
 #ifdef __FLOGGING__
@@ -935,9 +924,6 @@
 #else
 	Notifier().HandleAcceptConnectionCompleteL(aErr);
 #endif
-	
-	ListeningSCOSocket().Close();
-	ListeningESCOSocket().Close();
 	}
 
 
@@ -1034,24 +1020,16 @@
 CBTSynchronousLinkBaseband* CBTSynchronousLinkBaseband::NewL(CBluetoothSynchronousLink& aParent)
 	{
 	CBTSynchronousLinkBaseband* self = new(ELeave) CBTSynchronousLinkBaseband(aParent);
-	CleanupStack::PushL(self);
-	self->ConstructL();
-	CleanupStack::Pop(self);
 	return self;
 	}
 
 
 CBTSynchronousLinkBaseband::CBTSynchronousLinkBaseband(CBluetoothSynchronousLink& aParent)
 	: CActive(CActive::EPriorityStandard), iParent(aParent)
-	{}
-
-
-void CBTSynchronousLinkBaseband::ConstructL()
 	{
 	CActiveScheduler::Add(this);
 	}
 
-
 CBTSynchronousLinkBaseband::~CBTSynchronousLinkBaseband()
 	{
 	StopAll();
@@ -1093,7 +1071,7 @@
 	Cancel();
 	}
 
-
+	
 void CBTSynchronousLinkBaseband::DoCancel()
 	{
 	iParent.Baseband().CancelNextBasebandChangeEventNotifier();
@@ -1104,20 +1082,12 @@
 CBTSynchronousLinkAttacher* CBTSynchronousLinkAttacher::NewL(CBluetoothSynchronousLink& aParent, TSCOType aSCOType)
 	{
 	CBTSynchronousLinkAttacher* self = new (ELeave) CBTSynchronousLinkAttacher(aParent, aSCOType);
-	CleanupStack::PushL(self);
-	self->ConstructL();
-	CleanupStack::Pop(self);
 	return self;
 	}
 
-
 CBTSynchronousLinkAttacher::CBTSynchronousLinkAttacher(CBluetoothSynchronousLink& aParent, TSCOType aSCOType)
 	: CActive(CActive::EPriorityStandard), iParent(aParent), iSCOType(aSCOType)
 	{
-	}
-
-void CBTSynchronousLinkAttacher::ConstructL()
-	{
 	CActiveScheduler::Add(this);
 	}
 
@@ -1155,7 +1125,6 @@
 	return KErrNone;
 	}
 
-
 void CBTSynchronousLinkAttacher::DoCancel()
 	{
 	FLOG(_L("CBTSynchronousLinkAttacher cancel attach sync link"));
@@ -1174,20 +1143,12 @@
 CBTSynchronousLinkDetacher* CBTSynchronousLinkDetacher::NewL(CBluetoothSynchronousLink& aParent, TSCOType aSCOType)
 	{
 	CBTSynchronousLinkDetacher* self = new (ELeave) CBTSynchronousLinkDetacher(aParent, aSCOType);
-	CleanupStack::PushL(self);
-	self->ConstructL();
-	CleanupStack::Pop(self);
 	return self;
 	}
 
-
 CBTSynchronousLinkDetacher::CBTSynchronousLinkDetacher(CBluetoothSynchronousLink& aParent, TSCOType aSCOType)
 	: CActive(CActive::EPriorityStandard), iParent(aParent), iSCOType(aSCOType)
 	{
-	}
-
-void CBTSynchronousLinkDetacher::ConstructL()
-	{
 	CActiveScheduler::Add(this);
 	}
 
@@ -1240,9 +1201,6 @@
 CBTSynchronousLinkAccepter* CBTSynchronousLinkAccepter::NewL(CBluetoothSynchronousLink& aParent, TSCOType aSCOType)
 	{
 	CBTSynchronousLinkAccepter* self = new (ELeave) CBTSynchronousLinkAccepter(aParent, aSCOType);
-	CleanupStack::PushL(self);
-	self->ConstructL();
-	CleanupStack::Pop(self);
 	return self;
 	}
 
@@ -1250,10 +1208,6 @@
 CBTSynchronousLinkAccepter::CBTSynchronousLinkAccepter(CBluetoothSynchronousLink& aParent, TSCOType aSCOType)
 	: CActive(CActive::EPriorityStandard), iParent(aParent), iSCOType(aSCOType)
 	{
-	}
-
-void CBTSynchronousLinkAccepter::ConstructL()
-	{
 	CActiveScheduler::Add(this);
 	}
 
@@ -1262,7 +1216,7 @@
 	Cancel();
 	}
 
-void CBTSynchronousLinkAccepter::Accept(RSocket& aSocket)
+void CBTSynchronousLinkAccepter::Accept()
 
 	{
 	__ASSERT_ALWAYS(!IsActive(), Panic(EUnfinishedBusiness));
@@ -1270,11 +1224,11 @@
 	FLOG(_L("CBTSynchronousLinkAccepter accept sync link"));
 	if (iSCOType == ESCO)
 		{
-		aSocket.Accept(iParent.SCOSocket(), iStatus);
+		iParent.ListeningSCOSocket().Accept(iParent.SCOSocket(), iStatus);
 		}
 	else
 		{
-		aSocket.Accept(iParent.ESCOSocket(), iStatus);
+		iParent.ListeningESCOSocket().Accept(iParent.ESCOSocket(), iStatus);
 		}
 	SetActive();
 	}
@@ -1315,9 +1269,6 @@
 CBTSynchronousLinkSender* CBTSynchronousLinkSender::NewL(CBluetoothSynchronousLink& aParent, TSCOType aSCOType)
 	{
 	CBTSynchronousLinkSender* self = new (ELeave) CBTSynchronousLinkSender(aParent, aSCOType);
-	CleanupStack::PushL(self);
-	self->ConstructL();
-	CleanupStack::Pop(self);
 	return self;
 	}
 
@@ -1325,10 +1276,6 @@
 CBTSynchronousLinkSender::CBTSynchronousLinkSender(CBluetoothSynchronousLink& aParent, TSCOType aSCOType)
 	: CActive(CActive::EPriorityStandard), iParent(aParent), iSCOType(aSCOType)
 	{
-	}
-
-void CBTSynchronousLinkSender::ConstructL()
-	{
 	CActiveScheduler::Add(this);
 	}
 
@@ -1403,9 +1350,6 @@
 CBTSynchronousLinkReceiver* CBTSynchronousLinkReceiver::NewL(CBluetoothSynchronousLink& aParent, TSCOType aSCOType)
 	{
 	CBTSynchronousLinkReceiver* self = new (ELeave) CBTSynchronousLinkReceiver(aParent, aSCOType);
-	CleanupStack::PushL(self);
-	self->ConstructL();
-	CleanupStack::Pop(self);
 	return self;
 	}
 
@@ -1413,10 +1357,6 @@
 CBTSynchronousLinkReceiver::CBTSynchronousLinkReceiver(CBluetoothSynchronousLink& aParent, TSCOType aSCOType)
 	: CActive(CActive::EPriorityStandard), iParent(aParent), iSCOType(aSCOType)
 	{
-	}
-
-void CBTSynchronousLinkReceiver::ConstructL()
-	{
 	CActiveScheduler::Add(this);
 	}
 
--- a/bluetoothmgmt/bluetoothclientlib/btlib/btsynclinkhelpers.h	Thu Jul 15 19:55:36 2010 +0300
+++ b/bluetoothmgmt/bluetoothclientlib/btlib/btsynclinkhelpers.h	Thu Aug 19 11:01:00 2010 +0300
@@ -32,7 +32,6 @@
 	
 private:
 	CBTSynchronousLinkBaseband(CBluetoothSynchronousLink& aParent);
-	void ConstructL();
 	void DoCancel();
 	void RunL();
 	TInt RunError(TInt aError);
@@ -41,7 +40,7 @@
 	TBTBasebandEvent			iEvent;
 	};
 
-//CBluetoothSynchronousLink Active Objects...
+
 NONSHARABLE_CLASS(CBTSynchronousLinkAttacher) : public CActive
 	{
 public:
@@ -53,7 +52,6 @@
 
 private:
 	CBTSynchronousLinkAttacher(CBluetoothSynchronousLink& aParent, TSCOType aSCOTypes);
-	void ConstructL();
 	void DoCancel();
 	void RunL();
 	TInt RunError(TInt aError);
@@ -75,7 +73,6 @@
 
 private:
 	CBTSynchronousLinkDetacher(CBluetoothSynchronousLink& aParent, TSCOType aSCOTypes);
-	void ConstructL();
 	void DoCancel();
 	void RunL();
 	TInt RunError(TInt aError);
@@ -93,12 +90,11 @@
 	static CBTSynchronousLinkAccepter* NewL(CBluetoothSynchronousLink& aParent, TSCOType aSCOType);
 	~CBTSynchronousLinkAccepter();
 
-	void Accept(RSocket& aSocket);
+	void Accept();
 
 
 private:
 	CBTSynchronousLinkAccepter(CBluetoothSynchronousLink& aParent, TSCOType aSCOType);
-	void ConstructL();
 	void DoCancel();
 	void RunL();
 	TInt RunError(TInt aError);
@@ -120,7 +116,6 @@
 
 private:
 	CBTSynchronousLinkSender(CBluetoothSynchronousLink& aParent, TSCOType aSCOType);
-	void ConstructL();
 	void DoCancel();
 	void RunL();
 	TInt RunError(TInt aError);
@@ -142,7 +137,6 @@
 
 private:
 	CBTSynchronousLinkReceiver(CBluetoothSynchronousLink& aParent, TSCOType aSCOTypes);
-	void ConstructL();
 	void DoCancel();
 	void RunL();
 	TInt RunError(TInt aError);
--- a/bluetoothmgmt/bluetoothclientlib/inc/bt_sock.h	Thu Jul 15 19:55:36 2010 +0300
+++ b/bluetoothmgmt/bluetoothclientlib/inc/bt_sock.h	Thu Aug 19 11:01:00 2010 +0300
@@ -1424,6 +1424,8 @@
 	void UpdateLinkParams(TSCOType aSCOType);
 	TInt LinkUp(TBTDevAddr aAddr);
 	void LinkDown();
+	void AcceptConnectionL(const TBTSyncPackets& aPacketTypes);
+	static void StaticResetScoTypes(TAny* aThis);
 
 private:
 	CBTSynchronousLinkSender*			iBTSynchronousLinkSenderSCO;
--- a/bluetoothmgmt/btrom/bluetooth.iby	Thu Jul 15 19:55:36 2010 +0300
+++ b/bluetoothmgmt/btrom/bluetooth.iby	Thu Aug 19 11:01:00 2010 +0300
@@ -58,7 +58,7 @@
 file=ABI_DIR\BT_DIR\sdpagent.dll		System\Libs\sdpagent.dll
 
 REM Bluetooth AV user libraries
-file=ABI_DIR\BT_DIR\bluetoothAV.dll		System\Libs\bluetoothAV.dll
+file=ABI_DIR\BT_DIR\bluetoothav.dll		System\Libs\bluetoothAV.dll
 file=ABI_DIR\BT_DIR\gavdp.dll			System\Libs\gavdp.dll
 
 REM Generic Remote Control Framework
@@ -88,7 +88,7 @@
 data=ZPRIVATE\100069cc\backup_registration.xml	Private\100069cc\backup_registration.xml
 
 REM default is to run Esock_BT thread in DealerPlayer role
-data=ZPRIVATE\101F7988\esock_bt.cmi private\101F7988\esock_bt.cmi
+data=ZPRIVATE\101f7988\esock_bt.cmi private\101F7988\esock_bt.cmi
 
 file=ABI_DIR\BT_DIR\btcomm.csy			System\Libs\btcomm.csy
 
@@ -102,8 +102,8 @@
 REM Bluetooth using HCI API Version 2
 file=ABI_DIR\BT_DIR\bt_v2.prt							System\Libs\bt_v2.prt
 REM Stack configuration files
-data=ZPRIVATE\101f7989\ESock\bt.bt_v2.esk				Private\101f7989\ESock\bt.bt_v2.esk
-data=ZPRIVATE\101F7989\Bluetooth\bluetooth_stack.ini	Private\101F7989\Bluetooth\bluetooth_stack.ini
+data=ZPRIVATE\101f7989\esock\bt.bt_v2.esk				Private\101f7989\ESock\bt.bt_v2.esk
+data=ZPRIVATE\101f7989\bluetooth\bluetooth_stack.ini	Private\101F7989\Bluetooth\bluetooth_stack.ini
 
 REM HCI Shared binary
 file=ABI_DIR\BT_DIR\hcishared.dll			System\Libs\hcishared.dll
--- a/bthci/bthci2/group/hci_framework.iby	Thu Jul 15 19:55:36 2010 +0300
+++ b/bthci/bthci2/group/hci_framework.iby	Thu Aug 19 11:01:00 2010 +0300
@@ -32,6 +32,6 @@
 file=ABI_DIR\HCIF_DIR\hcicmdq.dll				System\Libs\hcicmdq.dll
 
 REM Command Queue configuration file
-data=ZPRIVATE\101F7989\Bluetooth\cmdq.ini	Private\101F7989\Bluetooth\cmdq.ini
+data=ZPRIVATE\101f7989\bluetooth\cmdq.ini	Private\101F7989\Bluetooth\cmdq.ini
 
 #endif //  HCI_FRAMEWORK_IBY