]> git.proxmox.com Git - mirror_edk2.git/blobdiff - MdeModulePkg/Universal/Network/IScsiDxe/IScsiProto.c
Re-execute the failed SCSI command if iSCSI driver could reinstates the session succe...
[mirror_edk2.git] / MdeModulePkg / Universal / Network / IScsiDxe / IScsiProto.c
index b88ea1c2f6ff35608b7cf6fc0f8b6d946b4d6100..60131b32db9891f384bfe4253143c7eab4205690 100644 (file)
@@ -1,8 +1,8 @@
 /** @file\r
-  The implementation of IScsi protocol based on RFC3720\r
+  The implementation of iSCSI protocol based on RFC3720.\r
 \r
-Copyright (c) 2004 - 2008, Intel Corporation\r
-All rights reserved. This program and the accompanying materials\r
+Copyright (c) 2004 - 2014, Intel Corporation. All rights reserved.<BR>\r
+This program and the accompanying materials\r
 are licensed and made available under the terms and conditions of the BSD License\r
 which accompanies this distribution.  The full text of the license may be found at\r
 http://opensource.org/licenses/bsd-license.php\r
@@ -10,33 +10,22 @@ http://opensource.org/licenses/bsd-license.php
 THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,\r
 WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.\r
 \r
-Module Name:\r
-\r
-  IScsiProto.c\r
-\r
-Abstract:\r
-  The implementation of IScsi protocol based on RFC3720\r
-\r
 **/\r
 \r
 #include "IScsiImpl.h"\r
 \r
-static UINT32 mDataSegPad = 0;\r
+UINT32 mDataSegPad = 0;\r
 \r
 /**\r
   Attach the iSCSI connection to the iSCSI session. \r
 \r
-  @param  Session[in] The iSCSI session.\r
-\r
-  @param  Conn[in]    The iSCSI connection.\r
-\r
-  @retval None.\r
-\r
+  @param[in, out]  Session The iSCSI session.\r
+  @param[in, out]  Conn    The iSCSI connection.\r
 **/\r
 VOID\r
 IScsiAttatchConnection (\r
-  IN ISCSI_SESSION     *Session,\r
-  IN ISCSI_CONNECTION  *Conn\r
+  IN OUT ISCSI_SESSION     *Session,\r
+  IN OUT ISCSI_CONNECTION  *Conn\r
   )\r
 {\r
   InsertTailList (&Session->Conns, &Conn->Link);\r
@@ -47,14 +36,11 @@ IScsiAttatchConnection (
 /**\r
   Detach the iSCSI connection from the session it belongs to. \r
 \r
-  @param  Conn[in] The iSCSI connection.\r
-\r
-  @retval None.\r
-\r
+  @param[in, out]  Conn The iSCSI connection.\r
 **/\r
 VOID\r
 IScsiDetatchConnection (\r
-  IN ISCSI_CONNECTION  *Conn\r
+  IN OUT ISCSI_CONNECTION  *Conn\r
   )\r
 {\r
   RemoveEntryList (&Conn->Link);\r
@@ -65,17 +51,17 @@ IScsiDetatchConnection (
 /**\r
   Check the sequence number according to RFC3720. \r
 \r
-  @param  ExpSN[in]   The currently expected sequence number.\r
-\r
-  @param  NewSN[in]   The sequence number to check.\r
-\r
-  @retval EFI_SUCCESS The check passed and the ExpSN is increased.\r
+  @param[in, out]  ExpSN   The currently expected sequence number.\r
+  @param[in]       NewSN   The sequence number to check.\r
 \r
+  @retval EFI_SUCCESS         The check passed and the ExpSN is increased.\r
+  @retval EFI_NOT_READY       Response was sent due to a retransmission request.\r
+  @retval EFI_PROTOCOL_ERROR  Some kind of iSCSI protocol error happened.\r
 **/\r
 EFI_STATUS\r
 IScsiCheckSN (\r
-  IN UINT32  *ExpSN,\r
-  IN UINT32  NewSN\r
+  IN OUT UINT32  *ExpSN,\r
+  IN UINT32      NewSN\r
   )\r
 {\r
   if (!ISCSI_SEQ_EQ (NewSN, *ExpSN)) {\r
@@ -99,20 +85,15 @@ IScsiCheckSN (
 /**\r
   Update the sequence numbers for the iSCSI command.\r
 \r
-  @param  Session[in]  The iSCSI session.\r
-\r
-  @param  MaxCmdSN[in] Maximum CmdSN from the target.\r
-\r
-  @param  ExpCmdSN[in] Next expected CmdSN from the target.\r
-\r
-  @retval None.\r
-\r
+  @param[in, out]  Session  The iSCSI session.\r
+  @param[in]       MaxCmdSN Maximum CmdSN from the target.\r
+  @param[in]       ExpCmdSN Next expected CmdSN from the target.\r
 **/\r
 VOID\r
 IScsiUpdateCmdSN (\r
-  IN ISCSI_SESSION  *Session,\r
-  IN UINT32         MaxCmdSN,\r
-  IN UINT32         ExpCmdSN\r
+  IN OUT ISCSI_SESSION  *Session,\r
+  IN UINT32             MaxCmdSN,\r
+  IN UINT32             ExpCmdSN\r
   )\r
 {\r
   if (ISCSI_SEQ_LT (MaxCmdSN, ExpCmdSN - 1)) {\r
@@ -131,18 +112,15 @@ IScsiUpdateCmdSN (
 /**\r
   This function does the iSCSI connection login.\r
 \r
-  @param  Conn[in]           The iSCSI connection to login.\r
+  @param[in, out]  Conn      The iSCSI connection to login.\r
 \r
   @retval EFI_SUCCESS        The iSCSI connection is logged into the iSCSI target.\r
-\r
   @retval EFI_TIMEOUT        Timeout happened during the login procedure.\r
-\r
-  @retval EFI_PROTOCOL_ERROR Some kind of iSCSI protocol error happened.\r
-\r
+  @retval Others             Other errors as indicated.  \r
 **/\r
 EFI_STATUS\r
 IScsiConnLogin (\r
-  IN ISCSI_CONNECTION  *Conn\r
+  IN OUT ISCSI_CONNECTION  *Conn\r
   )\r
 {\r
   EFI_STATUS  Status;\r
@@ -186,14 +164,11 @@ IScsiConnLogin (
 /**\r
   Reset the iSCSI connection.\r
 \r
-  @param  Conn[in] The iSCSI connection to reset.\r
-\r
-  @retval None.\r
-\r
+  @param[in, out]  Conn The iSCSI connection to reset.\r
 **/\r
 VOID\r
 IScsiConnReset (\r
-  IN ISCSI_CONNECTION  *Conn\r
+  IN OUT ISCSI_CONNECTION  *Conn\r
   )\r
 {\r
   Tcp4IoReset (&Conn->Tcp4Io);\r
@@ -202,12 +177,10 @@ IScsiConnReset (
 /**\r
   Create a TCP connection for the iSCSI session.\r
 \r
-  @param  Private[in] The iSCSI driver data.\r
-\r
-  @param  Session[in] Maximum CmdSN from the target.\r
-\r
-  @retval The newly created iSCSI connection.\r
+  @param[in]  Private The iSCSI driver data.\r
+  @param[in]  Session Maximum CmdSN from the target.\r
 \r
+  @return The newly created iSCSI connection.\r
 **/\r
 ISCSI_CONNECTION *\r
 IScsiCreateConnection (\r
@@ -232,7 +205,7 @@ IScsiCreateConnection (
   Conn->ExpStatSN       = 0;\r
   Conn->PartialReqSent  = FALSE;\r
   Conn->PartialRspRcvd  = FALSE;\r
-  Conn->CID             = Session->NextCID++;\r
+  Conn->Cid             = Session->NextCid++;\r
 \r
   Status = gBS->CreateEvent (\r
                   EVT_TIMER,\r
@@ -242,7 +215,7 @@ IScsiCreateConnection (
                   &Conn->TimeoutEvent\r
                   );\r
   if (EFI_ERROR (Status)) {\r
-    gBS->FreePool (Conn);\r
+    FreePool (Conn);\r
     return NULL;\r
   }\r
 \r
@@ -251,9 +224,9 @@ IScsiCreateConnection (
   //\r
   // set the default connection-only parameters\r
   //\r
-  Conn->MaxRecvDataSegmentLength  = MAX_RECV_DATA_SEG_LEN_IN_FFP;\r
-  Conn->HeaderDigest              = ISCSI_DIGEST_NONE;\r
-  Conn->DataDigest                = ISCSI_DIGEST_NONE;\r
+  Conn->MaxRecvDataSegmentLength  = DEFAULT_MAX_RECV_DATA_SEG_LEN;\r
+  Conn->HeaderDigest              = IScsiDigestNone;\r
+  Conn->DataDigest                = IScsiDigestNone;\r
 \r
   CopyMem (&Tcp4IoConfig.LocalIp, &Session->ConfigData.NvData.LocalIp, sizeof (EFI_IPv4_ADDRESS));\r
   CopyMem (&Tcp4IoConfig.SubnetMask, &Session->ConfigData.NvData.SubnetMask, sizeof (EFI_IPv4_ADDRESS));\r
@@ -273,7 +246,7 @@ IScsiCreateConnection (
             );\r
   if (EFI_ERROR (Status)) {\r
     gBS->CloseEvent (Conn->TimeoutEvent);\r
-    gBS->FreePool (Conn);\r
+    FreePool (Conn);\r
     Conn = NULL;\r
   }\r
 \r
@@ -283,10 +256,7 @@ IScsiCreateConnection (
 /**\r
   Destroy an iSCSI connection.\r
 \r
-  @param  Conn[in] The connection to destroy.\r
-\r
-  @retval None.\r
-\r
+  @param[in]  Conn The connection to destroy.\r
 **/\r
 VOID\r
 IScsiDestroyConnection (\r
@@ -296,19 +266,18 @@ IScsiDestroyConnection (
   Tcp4IoDestroySocket (&Conn->Tcp4Io);\r
   NetbufQueFlush (&Conn->RspQue);\r
   gBS->CloseEvent (Conn->TimeoutEvent);\r
-  gBS->FreePool (Conn);\r
+  FreePool (Conn);\r
 }\r
 \r
 /**\r
   Login the iSCSI session.\r
 \r
-  @param  Private[in]          The iSCSI driver data.\r
+  @param[in]  Private          The iSCSI driver data.\r
 \r
   @retval EFI_SUCCESS          The iSCSI session login procedure finished.\r
-\r
   @retval EFI_OUT_OF_RESOURCES Failed to allocate memory.\r
-\r
-  @retval EFI_PROTOCOL_ERROR   Some kind of iSCSI protocol error happened.\r
+  @retval EFI_NO_MEDIA         There was a media error.\r
+  @retval Others               Other errors as indicated.\r
 \r
 **/\r
 EFI_STATUS\r
@@ -320,9 +289,24 @@ IScsiSessionLogin (
   ISCSI_SESSION     *Session;\r
   ISCSI_CONNECTION  *Conn;\r
   EFI_TCP4_PROTOCOL *Tcp4;\r
+  BOOLEAN           MediaPresent;\r
 \r
   Session = &Private->Session;\r
 \r
+  //\r
+  // Check media status before session login\r
+  //\r
+  MediaPresent = TRUE;\r
+  NetLibDetectMedia (Private->Controller, &MediaPresent);\r
+  if (!MediaPresent) {\r
+    return EFI_NO_MEDIA;\r
+  }\r
+\r
+  //\r
+  // Set session identifier\r
+  //\r
+  CopyMem (Session->Isid, Session->ConfigData.NvData.IsId, 6);\r
+\r
   //\r
   // Create a connection for the session.\r
   //\r
@@ -361,15 +345,12 @@ IScsiSessionLogin (
   Build and send the iSCSI login request to the iSCSI target according to\r
   the current login stage.\r
 \r
-  @param  Conn[in]             The connection in the iSCSI login phase.\r
+  @param[in]  Conn             The connection in the iSCSI login phase.\r
 \r
   @retval EFI_SUCCESS          The iSCSI login request PDU is built and sent on this\r
                                connection.\r
-\r
   @retval EFI_OUT_OF_RESOURCES Failed to allocate memory.\r
-\r
-  @retval EFI_PROTOCOL_ERROR   Some kind of iSCSI protocol error happened.\r
-\r
+  @retval EFI_DEVICE_ERROR     Some kind of device error happened.\r
 **/\r
 EFI_STATUS\r
 IScsiSendLoginReq (\r
@@ -399,14 +380,10 @@ IScsiSendLoginReq (
 /**\r
   Receive and process the iSCSI login response.\r
 \r
-  @param  Conn[in]             The connection in the iSCSI login phase.\r
-\r
+  @param[in]  Conn             The connection in the iSCSI login phase.\r
+  \r
   @retval EFI_SUCCESS          The iSCSI login response PDU is received and processed.\r
-\r
-  @retval EFI_OUT_OF_RESOURCES Failed to allocate memory.\r
-\r
-  @retval EFI_PROTOCOL_ERROR   Some kind of iSCSI protocol error happened.\r
-\r
+  @retval Others               Other errors as indicated.\r
 **/\r
 EFI_STATUS\r
 IScsiReceiveLoginRsp (\r
@@ -426,6 +403,7 @@ IScsiReceiveLoginRsp (
   //\r
   // A Login Response is received, process it.\r
   //\r
+  ASSERT (Pdu != NULL);\r
   Status = IScsiProcessLoginRsp (Conn, Pdu);\r
 \r
   NetbufFree (Pdu);\r
@@ -438,23 +416,19 @@ IScsiReceiveLoginRsp (
   The DataSegmentLength and the actual size of the net buffer containing this PDU will be\r
   updated.\r
 \r
-  @param  Pdu[in]              The iSCSI PDU whose data segment the key-value pair will\r
+  @param[in, out]  Pdu         The iSCSI PDU whose data segment the key-value pair will\r
                                be added to.\r
-\r
-  @param  Key[in]              The key name string.\r
-\r
-  @param  Value[in]            The value string.\r
+  @param[in]       Key         The key name string.\r
+  @param[in]       Value       The value string.\r
 \r
   @retval EFI_SUCCESS          The key-valu pair is added to the PDU's datasegment and\r
                                the correspondence length fields are updated.\r
-\r
   @retval EFI_OUT_OF_RESOURCES There is not enough space in the PDU to add the key-value\r
                                pair.\r
-\r
 **/\r
 EFI_STATUS\r
 IScsiAddKeyValuePair (\r
-  IN NET_BUF          *Pdu,\r
+  IN OUT NET_BUF      *Pdu,\r
   IN CHAR8            *Key,\r
   IN CHAR8            *Value\r
   )\r
@@ -467,6 +441,9 @@ IScsiAddKeyValuePair (
   CHAR8               *Data;\r
 \r
   LoginReq    = (ISCSI_LOGIN_REQUEST *) NetbufGetByte (Pdu, 0, NULL);\r
+  if (LoginReq == NULL) {\r
+    return EFI_PROTOCOL_ERROR;\r
+  }\r
   DataSegLen  = NTOH24 (LoginReq->DataSegmentLength);\r
 \r
   KeyLen      = (UINT32) AsciiStrLen (Key);\r
@@ -513,14 +490,14 @@ IScsiAddKeyValuePair (
 /**\r
   Prepare the iSCSI login request to be sent according to the current login status.\r
 \r
-  @param  Conn[in] The connection in the iSCSI login phase.\r
-\r
-  @retval The pointer to the net buffer containing the iSCSI login request built.\r
+  @param[in, out]  Conn The connection in the iSCSI login phase.\r
 \r
+  @return The pointer to the net buffer containing the iSCSI login request built.\r
+  @retval Others    Other errors as indicated.\r
 **/\r
 NET_BUF *\r
 IScsiPrepareLoginReq (\r
-  IN ISCSI_CONNECTION  *Conn\r
+  IN OUT ISCSI_CONNECTION  *Conn\r
   )\r
 {\r
   ISCSI_SESSION       *Session;\r
@@ -536,6 +513,7 @@ IScsiPrepareLoginReq (
   }\r
 \r
   LoginReq = (ISCSI_LOGIN_REQUEST *) NetbufAllocSpace (Nbuf, sizeof (ISCSI_LOGIN_REQUEST), NET_BUF_TAIL);\r
+  ASSERT (LoginReq != NULL);\r
   ZeroMem (LoginReq, sizeof (ISCSI_LOGIN_REQUEST));\r
 \r
   //\r
@@ -545,9 +523,9 @@ IScsiPrepareLoginReq (
   ISCSI_SET_STAGES (LoginReq, Conn->CurrentStage, Conn->NextStage);\r
   LoginReq->VersionMax        = ISCSI_VERSION_MAX;\r
   LoginReq->VersionMin        = ISCSI_VERSION_MIN;\r
-  LoginReq->TSIH              = HTONS (Session->TSIH);\r
+  LoginReq->Tsih              = HTONS (Session->Tsih);\r
   LoginReq->InitiatorTaskTag  = HTONL (Session->InitiatorTaskTag);\r
-  LoginReq->CID               = HTONS (Conn->CID);\r
+  LoginReq->Cid               = HTONS (Conn->Cid);\r
   LoginReq->CmdSN             = HTONL (Session->CmdSN);\r
 \r
   //\r
@@ -558,7 +536,7 @@ IScsiPrepareLoginReq (
   // with their increasing StatSN values.\r
   //\r
   LoginReq->ExpStatSN = HTONL (Conn->ExpStatSN);\r
-  CopyMem (LoginReq->ISID, Session->ISID, sizeof (LoginReq->ISID));\r
+  CopyMem (LoginReq->Isid, Session->Isid, sizeof (LoginReq->Isid));\r
 \r
   if (Conn->PartialRspRcvd) {\r
     //\r
@@ -605,19 +583,18 @@ IScsiPrepareLoginReq (
 /**\r
   Process the iSCSI Login Response.\r
 \r
-  @param  Conn[in] The connection on which the iSCSI login response is received.\r
-\r
-  @param  Pdu[in]  The iSCSI login response PDU.\r
+  @param[in, out]  Conn The connection on which the iSCSI login response is received.\r
+  @param[in, out]  Pdu  The iSCSI login response PDU.\r
 \r
   @retval EFI_SUCCESS        The iSCSI login response PDU is processed and all check are passed.\r
-\r
   @retval EFI_PROTOCOL_ERROR Some kind of iSCSI protocol error happened.\r
-\r
+  @retval EFI_MEDIA_CHANGED  Target is redirected.\r
+  @retval Others             Other errors as indicated.\r
 **/\r
 EFI_STATUS\r
 IScsiProcessLoginRsp (\r
-  IN ISCSI_CONNECTION  *Conn,\r
-  IN NET_BUF           *Pdu\r
+  IN OUT ISCSI_CONNECTION  *Conn,\r
+  IN OUT NET_BUF           *Pdu\r
   )\r
 {\r
   EFI_STATUS            Status;\r
@@ -633,6 +610,9 @@ IScsiProcessLoginRsp (
   Session   = Conn->Session;\r
 \r
   LoginRsp  = (ISCSI_LOGIN_RESPONSE *) NetbufGetByte (Pdu, 0, NULL);\r
+  if (LoginRsp == NULL) {\r
+    return EFI_PROTOCOL_ERROR;\r
+  }\r
   if (!ISCSI_CHECK_OPCODE (LoginRsp, ISCSI_OPCODE_LOGIN_RSP)) {\r
     //\r
     // It's not a Login Response\r
@@ -700,7 +680,7 @@ IScsiProcessLoginRsp (
       (CurrentStage != Conn->CurrentStage) ||\r
       (!Conn->TransitInitiated && Transit) ||\r
       (Transit && (NextStage != Conn->NextStage)) ||\r
-      (CompareMem (Session->ISID, LoginRsp->ISID, sizeof (LoginRsp->ISID)) != 0) ||\r
+      (CompareMem (Session->Isid, LoginRsp->Isid, sizeof (LoginRsp->Isid)) != 0) ||\r
       (LoginRsp->InitiatorTaskTag != Session->InitiatorTaskTag)\r
       ) {\r
     //\r
@@ -719,6 +699,14 @@ IScsiProcessLoginRsp (
   LoginRsp->MaxCmdSN  = NTOHL (LoginRsp->MaxCmdSN);\r
 \r
   if ((Conn->CurrentStage == ISCSI_SECURITY_NEGOTIATION) && (Conn->CHAPStep == ISCSI_CHAP_INITIAL)) {\r
+    //\r
+    // If the Login Request is a leading Login Request, the target MUST use\r
+    // the value presented in CmdSN as the target value for ExpCmdSN.\r
+    //\r
+    if ((Session->State == SESSION_STATE_FREE) && (Session->CmdSN != LoginRsp->ExpCmdSN)) {\r
+      return EFI_PROTOCOL_ERROR;\r
+    }\r
+\r
     //\r
     // It's the initial Login Response, initialize the local ExpStatSN, MaxCmdSN\r
     // and ExpCmdSN.\r
@@ -767,14 +755,14 @@ IScsiProcessLoginRsp (
     //\r
     // In security negotiation stage, let CHAP module handle it.\r
     //\r
-    Status = IScsiCHAPOnRspReceived (Conn, Transit);\r
+    Status = IScsiCHAPOnRspReceived (Conn);\r
     break;\r
 \r
   case ISCSI_LOGIN_OPERATIONAL_NEGOTIATION:\r
     //\r
     // Response received with negotiation resonse on iSCSI parameters, check them.\r
     //\r
-    Status = IScsiCheckOpParams (Conn, Transit);\r
+    Status = IScsiCheckOpParams (Conn);\r
     break;\r
 \r
   default:\r
@@ -798,7 +786,7 @@ IScsiProcessLoginRsp (
       // CurrentStage is iSCSI Full Feature, it's the Login-Final Response,\r
       // get the TSIH from the Login Response.\r
       //\r
-      Session->TSIH = NTOHS (LoginRsp->TSIH);\r
+      Session->Tsih = NTOHS (LoginRsp->Tsih);\r
     }\r
   }\r
   //\r
@@ -813,25 +801,21 @@ IScsiProcessLoginRsp (
   Updated the target information according the data received in the iSCSI\r
   login response with an target redirection status.\r
 \r
-  @param  Session[in]          The iSCSI session.\r
-\r
-  @param  Data[in]             The data segment which should contain the\r
+  @param[in, out] Session      The iSCSI session.\r
+  @param[in]      Data         The data segment which should contain the\r
                                TargetAddress key-value list.\r
-\r
-  @param  Len[in]              Length of the data.\r
-\r
+  @param[in]      Len          Length of the data.\r
+  \r
   @retval EFI_SUCCESS          The target address is updated.\r
-\r
   @retval EFI_OUT_OF_RESOURCES Failed to allocate memory.\r
-\r
   @retval EFI_NOT_FOUND        The TargetAddress key is not found.\r
-\r
+  @retval Others               Other errors as indicated.\r
 **/\r
 EFI_STATUS\r
 IScsiUpdateTargetAddress (\r
-  IN ISCSI_SESSION  *Session,\r
-  IN CHAR8          *Data,\r
-  IN UINT32         Len\r
+  IN OUT ISCSI_SESSION  *Session,\r
+  IN CHAR8              *Data,\r
+  IN UINT32             Len\r
   )\r
 {\r
   LIST_ENTRY      *KeyValueList;\r
@@ -864,7 +848,7 @@ IScsiUpdateTargetAddress (
 \r
     IpStr = TargetAddress;\r
 \r
-    while (*TargetAddress && (*TargetAddress != ':') && (*TargetAddress != ',')) {\r
+    while ((*TargetAddress != 0) && (*TargetAddress != ':') && (*TargetAddress != ',')) {\r
       //\r
       // NULL, ':' or ',' ends the IPv4 string.\r
       //\r
@@ -913,12 +897,10 @@ IScsiUpdateTargetAddress (
 /**\r
   The callback function to free the net buffer list.\r
 \r
-  @param  Arg[in] The opaque parameter.\r
-\r
-  @retval None.\r
-\r
+  @param[in]  Arg The opaque parameter.\r
 **/\r
 VOID\r
+EFIAPI\r
 IScsiFreeNbufList (\r
   VOID *Arg\r
   )\r
@@ -926,18 +908,16 @@ IScsiFreeNbufList (
   ASSERT (Arg != NULL);\r
 \r
   NetbufFreeList ((LIST_ENTRY     *) Arg);\r
-  gBS->FreePool (Arg);\r
+  FreePool (Arg);\r
 }\r
 \r
 /**\r
   The callback function called in NetBufFree, it does nothing.\r
 \r
-  @param  Arg[in] The opaque parameter.\r
-\r
-  @retval None.\r
-\r
+  @param[in]   Arg  The opaque parameter.\r
 **/\r
 VOID\r
+EFIAPI\r
 IScsiNbufExtFree (\r
   VOID *Arg\r
   )\r
@@ -950,23 +930,18 @@ IScsiNbufExtFree (
   net buffer. The digest check will be conducted in this function if needed and the digests\r
   will be trimmed from the PDU buffer.\r
 \r
-  @param  Conn[in]         The iSCSI connection to receive data from.\r
-\r
-  @param  Pdu[out]         The received iSCSI pdu.\r
-\r
-  @param  Context[in]      The context used to describe information on the caller provided\r
+  @param[in]   Conn        The iSCSI connection to receive data from.\r
+  @param[out]  Pdu         The received iSCSI pdu.\r
+  @param[in]   Context     The context used to describe information on the caller provided\r
                            buffer to receive data segment of the iSCSI pdu, it's optional.\r
+  @param[in]  HeaderDigest Whether there will be header digest received.\r
+  @param[in]  DataDigest   Whether there will be data digest.\r
+  @param[in]  TimeoutEvent The timeout event, it's optional.\r
 \r
-  @param  HeaderDigest[in] Whether there will be header digest received.\r
-\r
-  @param  DataDigest[in]   Whether there will be data digest.\r
-\r
-  @param  TimeoutEvent[in] The timeout event, it's optional.\r
-\r
-  @retval EFI_SUCCESS      An iSCSI pdu is received.\r
-\r
-  @retval EFI_TIMEOUT      Timeout happenend.\r
-\r
+  @retval EFI_SUCCESS          An iSCSI pdu is received.\r
+  @retval EFI_OUT_OF_RESOURCES Failed to allocate memory.\r
+  @retval EFI_PROTOCOL_ERROR   Some kind of iSCSI protocol error happened.\r
+  @retval Others               Other errors as indicated.\r
 **/\r
 EFI_STATUS\r
 IScsiReceivePdu (\r
@@ -990,7 +965,7 @@ IScsiReceivePdu (
   NET_BUF         *DataSeg;\r
   UINT32          PadAndCRC32[2];\r
 \r
-  NbufList = AllocatePool (sizeof (LIST_ENTRY    ));\r
+  NbufList = AllocatePool (sizeof (LIST_ENTRY));\r
   if (NbufList == NULL) {\r
     return EFI_OUT_OF_RESOURCES;\r
   }\r
@@ -1003,11 +978,12 @@ IScsiReceivePdu (
   Len     = sizeof (ISCSI_BASIC_HEADER) + (HeaderDigest ? sizeof (UINT32) : 0);\r
   PduHdr  = NetbufAlloc (Len);\r
   if (PduHdr == NULL) {\r
-    Status = EFI_OUT_OF_RESOURCES;\r
-    goto ON_EXIT;\r
+    FreePool (NbufList);\r
+    return EFI_OUT_OF_RESOURCES;\r
   }\r
 \r
   Header = NetbufAllocSpace (PduHdr, Len, NET_BUF_TAIL);\r
+  ASSERT (Header != NULL);\r
   InsertTailList (NbufList, &PduHdr->List);\r
 \r
   //\r
@@ -1031,9 +1007,14 @@ IScsiReceivePdu (
   Len = ISCSI_GET_DATASEG_LEN (Header);\r
   if (Len == 0) {\r
     //\r
-    // No data segment.\r
+    // No data segment.Form the pdu from a list of pdu segments.\r
     //\r
-    goto FORM_PDU;\r
+    *Pdu = NetbufFromBufList (NbufList, 0, 0, IScsiFreeNbufList, NbufList);\r
+    if (*Pdu == NULL) {\r
+      Status = EFI_OUT_OF_RESOURCES;\r
+      goto ON_EXIT;\r
+    }\r
+    return Status;\r
   }\r
   //\r
   // Get the length of the padding bytes of the data segment.\r
@@ -1061,8 +1042,7 @@ IScsiReceivePdu (
       // The first to receive the useful data. The second to receive the padding.\r
       //\r
       Fragment[1].Len   = PadLen + (DataDigest ? sizeof (UINT32) : 0);\r
-      Fragment[1].Bulk  = (UINT8 *) ((UINTN) &PadAndCRC32[1] - PadLen);\r
-\r
+      Fragment[1].Bulk  = (UINT8 *)PadAndCRC32 + (4 - PadLen);\r
       FragmentCount     = 2;\r
     } else {\r
       FragmentCount = 1;\r
@@ -1127,7 +1107,6 @@ IScsiReceivePdu (
     NetbufTrim (DataSeg, PadLen, NET_BUF_TAIL);\r
   }\r
 \r
-FORM_PDU:\r
   //\r
   // Form the pdu from a list of pdu segments.\r
   //\r
@@ -1151,19 +1130,15 @@ ON_EXIT:
 /**\r
   Check and get the result of the prameter negotiation.\r
 \r
-  @param  Conn[in]           The connection in iSCSI login.\r
-\r
-  @param  Pdu[in]            The iSCSI response PDU containing the parameter list.\r
-\r
-  @retval EFI_SUCCESS        The parmeter check is passed and negotiation is finished.\r
-\r
-  @retval EFI_PROTOCOL_ERROR Some kind of iSCSI protocol error happened.\r
+  @param[in, out]  Conn          The connection in iSCSI login.\r
 \r
+  @retval EFI_SUCCESS          The parmeter check is passed and negotiation is finished.\r
+  @retval EFI_PROTOCOL_ERROR   Some kind of iSCSI protocol error happened.\r
+  @retval EFI_OUT_OF_RESOURCES Failed to allocate memory.\r
 **/\r
 EFI_STATUS\r
 IScsiCheckOpParams (\r
-  IN ISCSI_CONNECTION  *Conn,\r
-  IN BOOLEAN           Transit\r
+  IN OUT ISCSI_CONNECTION  *Conn\r
   )\r
 {\r
   EFI_STATUS      Status;\r
@@ -1193,7 +1168,7 @@ IScsiCheckOpParams (
   //\r
   KeyValueList = IScsiBuildKeyValueList (Data, Len);\r
   if (KeyValueList == NULL) {\r
-    gBS->FreePool (Data);\r
+    FreePool (Data);\r
     return Status;\r
   }\r
   //\r
@@ -1205,11 +1180,11 @@ IScsiCheckOpParams (
   }\r
 \r
   if (AsciiStrCmp (Value, "CRC32") == 0) {\r
-    if (Conn->HeaderDigest != ISCSI_DIGEST_CRC32) {\r
+    if (Conn->HeaderDigest != IScsiDigestCRC32) {\r
       goto ON_ERROR;\r
     }\r
   } else if (AsciiStrCmp (Value, ISCSI_KEY_VALUE_NONE) == 0) {\r
-    Conn->HeaderDigest = ISCSI_DIGEST_NONE;\r
+    Conn->HeaderDigest = IScsiDigestNone;\r
   } else {\r
     goto ON_ERROR;\r
   }\r
@@ -1222,11 +1197,11 @@ IScsiCheckOpParams (
   }\r
 \r
   if (AsciiStrCmp (Value, "CRC32") == 0) {\r
-    if (Conn->DataDigest != ISCSI_DIGEST_CRC32) {\r
+    if (Conn->DataDigest != IScsiDigestCRC32) {\r
       goto ON_ERROR;\r
     }\r
   } else if (AsciiStrCmp (Value, ISCSI_KEY_VALUE_NONE) == 0) {\r
-    Conn->DataDigest = ISCSI_DIGEST_NONE;\r
+    Conn->DataDigest = IScsiDigestNone;\r
   } else {\r
     goto ON_ERROR;\r
   }\r
@@ -1266,16 +1241,11 @@ IScsiCheckOpParams (
   Session->ImmediateData = (BOOLEAN) (Session->ImmediateData && (AsciiStrCmp (Value, "Yes") == 0));\r
 \r
   //\r
-  // MaxRecvDataSegmentLength, result function is Mininum.\r
+  // MaxRecvDataSegmentLength is declarative.\r
   //\r
   Value = IScsiGetValueByKeyFromList (KeyValueList, ISCSI_KEY_MAX_RECV_DATA_SEGMENT_LENGTH);\r
   if (Value != NULL) {\r
-    //\r
-    // MaxRecvDataSegmentLength is declarative.\r
-    //\r
-    NumericValue                    = AsciiStrDecimalToUintn (Value);\r
-\r
-    Conn->MaxRecvDataSegmentLength  = (UINT32) MIN (Conn->MaxRecvDataSegmentLength, NumericValue);\r
+    Conn->MaxRecvDataSegmentLength = (UINT32) AsciiStrDecimalToUintn (Value);\r
   }\r
   //\r
   // MaxBurstLength, result funtion is Mininum.\r
@@ -1291,9 +1261,10 @@ IScsiCheckOpParams (
   //\r
   // FirstBurstLength, result function is Minimum. Irrelevant when InitialR2T=Yes and\r
   // ImmediateData=No.\r
+  // This Key/Value is negotiation type.\r
   //\r
   Value = IScsiGetValueByKeyFromList (KeyValueList, ISCSI_KEY_FIRST_BURST_LENGTH);\r
-  if ((Value == NULL) && !(Session->InitialR2T && !Session->ImmediateData)) {\r
+  if (Value == NULL) {\r
     goto ON_ERROR;\r
   }\r
 \r
@@ -1400,7 +1371,7 @@ ON_ERROR:
 \r
   IScsiFreeKeyValueList (KeyValueList);\r
 \r
-  gBS->FreePool (Data);\r
+  FreePool (Data);\r
 \r
   return Status;\r
 }\r
@@ -1408,19 +1379,15 @@ ON_ERROR:
 /**\r
   Fill the oprational prameters.\r
 \r
-  @param  Conn[in]             The connection in iSCSI login.\r
-\r
-  @param  Pdu[in]              The iSCSI login request PDU to fill the parameters.\r
+  @param[in]       Conn        The connection in iSCSI login.\r
+  @param[in, out]  Pdu         The iSCSI login request PDU to fill the parameters.\r
 \r
   @retval EFI_SUCCESS          The parmeters are filled into the iSCSI login request PDU.\r
-\r
-  @retval EFI_OUT_OF_RESOURCES There is not enough space in the PDU to hold the parameters.\r
-\r
 **/\r
 EFI_STATUS\r
 IScsiFillOpParams (\r
   IN ISCSI_CONNECTION  *Conn,\r
-  IN NET_BUF           *Pdu\r
+  IN OUT NET_BUF       *Pdu\r
   )\r
 {\r
   ISCSI_SESSION *Session;\r
@@ -1428,10 +1395,10 @@ IScsiFillOpParams (
 \r
   Session = Conn->Session;\r
 \r
-  AsciiSPrint (Value, sizeof (Value), "%a", (Conn->HeaderDigest == ISCSI_DIGEST_CRC32) ? "None,CRC32" : "None");\r
+  AsciiSPrint (Value, sizeof (Value), "%a", (Conn->HeaderDigest == IScsiDigestCRC32) ? "None,CRC32" : "None");\r
   IScsiAddKeyValuePair (Pdu, ISCSI_KEY_HEADER_DIGEST, Value);\r
 \r
-  AsciiSPrint (Value, sizeof (Value), "%a", (Conn->DataDigest == ISCSI_DIGEST_CRC32) ? "None,CRC32" : "None");\r
+  AsciiSPrint (Value, sizeof (Value), "%a", (Conn->DataDigest == IScsiDigestCRC32) ? "None,CRC32" : "None");\r
   IScsiAddKeyValuePair (Pdu, ISCSI_KEY_DATA_DIGEST, Value);\r
 \r
   AsciiSPrint (Value, sizeof (Value), "%d", Session->ErrorRecoveryLevel);\r
@@ -1443,7 +1410,7 @@ IScsiFillOpParams (
   AsciiSPrint (Value, sizeof (Value), "%a", Session->ImmediateData ? "Yes" : "No");\r
   IScsiAddKeyValuePair (Pdu, ISCSI_KEY_IMMEDIATE_DATA, Value);\r
 \r
-  AsciiSPrint (Value, sizeof (Value), "%d", Conn->MaxRecvDataSegmentLength);\r
+  AsciiSPrint (Value, sizeof (Value), "%d", MAX_RECV_DATA_SEG_LEN_IN_FFP);\r
   IScsiAddKeyValuePair (Pdu, ISCSI_KEY_MAX_RECV_DATA_SEGMENT_LENGTH, Value);\r
 \r
   AsciiSPrint (Value, sizeof (Value), "%d", Session->MaxBurstLength);\r
@@ -1476,20 +1443,17 @@ IScsiFillOpParams (
 /**\r
   Pad the iSCSI AHS or data segment to an integer number of 4 byte words.\r
 \r
-  @param  Pdu[in]              The iSCSI pdu which contains segments to pad.\r
-\r
-  @param  Len[in]              The length of the last semgnet in the PDU.\r
+  @param[in, out]  Pdu         The iSCSI pdu which contains segments to pad.\r
+  @param[in]       Len         The length of the last semgnet in the PDU.\r
 \r
   @retval EFI_SUCCESS          The segment is padded or no need to pad it.\r
-\r
   @retval EFI_OUT_OF_RESOURCES There is not enough remaining free space to add the\r
                                padding bytes.\r
-\r
 **/\r
 EFI_STATUS\r
 IScsiPadSegment (\r
-  IN NET_BUF  *Pdu,\r
-  IN UINT32   Len\r
+  IN OUT NET_BUF  *Pdu,\r
+  IN UINT32       Len\r
   )\r
 {\r
   UINT32  PadLen;\r
@@ -1512,12 +1476,11 @@ IScsiPadSegment (
 /**\r
   Build a key-value list from the data segment.\r
 \r
-  @param  Data[in] The data segment containing the key-value pairs.\r
-\r
-  @param  Len[in]  Length of the data segment.\r
-\r
-  @retval The key-value list.\r
+  @param[in]  Data The data segment containing the key-value pairs.\r
+  @param[in]  Len  Length of the data segment.\r
 \r
+  @return The key-value list.\r
+  @retval NULL Other errors as indicated.\r
 **/\r
 LIST_ENTRY *\r
 IScsiBuildKeyValueList (\r
@@ -1528,7 +1491,7 @@ IScsiBuildKeyValueList (
   LIST_ENTRY            *ListHead;\r
   ISCSI_KEY_VALUE_PAIR  *KeyValuePair;\r
 \r
-  ListHead = AllocatePool (sizeof (LIST_ENTRY    ));\r
+  ListHead = AllocatePool (sizeof (LIST_ENTRY));\r
   if (ListHead == NULL) {\r
     return NULL;\r
   }\r
@@ -1556,7 +1519,7 @@ IScsiBuildKeyValueList (
       Data++;\r
       Len--;\r
     } else {\r
-      gBS->FreePool (KeyValuePair);\r
+      FreePool (KeyValuePair);\r
       goto ON_ERROR;\r
     }\r
 \r
@@ -1581,16 +1544,14 @@ ON_ERROR:
   Get the value string by the key name from the key-value list. If found,\r
   the key-value entry will be removed from the list.\r
 \r
-  @param  KeyValueList[in] The key-value list.\r
-\r
-  @param  Key[in]          The key name to find.\r
-\r
-  @retval The value string.\r
+  @param[in, out]  KeyValueList  The key-value list.\r
+  @param[in]       Key           The key name to find.\r
 \r
+  @return The value string.\r
 **/\r
 CHAR8 *\r
 IScsiGetValueByKeyFromList (\r
-  IN LIST_ENTRY      *KeyValueList,\r
+  IN OUT LIST_ENTRY  *KeyValueList,\r
   IN CHAR8           *Key\r
   )\r
 {\r
@@ -1607,7 +1568,7 @@ IScsiGetValueByKeyFromList (
       Value = KeyValuePair->Value;\r
 \r
       RemoveEntryList (&KeyValuePair->List);\r
-      gBS->FreePool (KeyValuePair);\r
+      FreePool (KeyValuePair);\r
       break;\r
     }\r
   }\r
@@ -1618,10 +1579,7 @@ IScsiGetValueByKeyFromList (
 /**\r
   Free the key-value list.\r
 \r
-  @param  KeyValueList[in] The key-value list.\r
-  \r
-  @retval None.\r
-\r
+  @param[in]  KeyValueList The key-value list.\r
 **/\r
 VOID\r
 IScsiFreeKeyValueList (\r
@@ -1635,28 +1593,25 @@ IScsiFreeKeyValueList (
     Entry         = NetListRemoveHead (KeyValueList);\r
     KeyValuePair  = NET_LIST_USER_STRUCT (Entry, ISCSI_KEY_VALUE_PAIR, List);\r
 \r
-    gBS->FreePool (KeyValuePair);\r
+    FreePool (KeyValuePair);\r
   }\r
 \r
-  gBS->FreePool (KeyValueList);\r
+  FreePool (KeyValueList);\r
 }\r
 \r
 /**\r
   Normalize the iSCSI name according to RFC.\r
 \r
-  @param  Name[in]           The iSCSI name.\r
-\r
-  @param  Len[in]            length of the iSCSI name.\r
+  @param[in, out]  Name       The iSCSI name.\r
+  @param[in]       Len        length of the iSCSI name.\r
 \r
   @retval EFI_SUCCESS        The iSCSI name is valid and normalized.\r
-\r
   @retval EFI_PROTOCOL_ERROR The iSCSI name is mal-formatted or not in the IQN format.\r
-\r
 **/\r
 EFI_STATUS\r
 IScsiNormalizeName (\r
-  IN CHAR8  *Name,\r
-  IN UINTN  Len\r
+  IN OUT CHAR8  *Name,\r
+  IN UINTN      Len\r
   )\r
 {\r
   UINTN Index;\r
@@ -1696,14 +1651,12 @@ IScsiNormalizeName (
 /**\r
   Create an iSCSI task control block.\r
 \r
-  @param  Conn[in]             The connection on which the task control block will be created.\r
-\r
-  @param  Tcb[out]             The newly created task control block.\r
+  @param[in]   Conn           The connection on which the task control block will be created.\r
+  @param[out]  Tcb            The newly created task control block.\r
 \r
   @retval EFI_SUCCESS          The task control block is created.\r
-\r
   @retval EFI_OUT_OF_RESOURCES Failed to allocate memory.\r
-\r
+  @retval EFI_NOT_READY        The target can not accept new commands.\r
 **/\r
 EFI_STATUS\r
 IScsiNewTcb (\r
@@ -1750,10 +1703,7 @@ IScsiNewTcb (
 /**\r
   Delete the tcb from the connection and destroy it.\r
 \r
-  @param  Tcb The tcb to delete.\r
-\r
-  @retval None.\r
-\r
+  @param[in]  Tcb The tcb to delete.\r
 **/\r
 VOID\r
 IScsiDelTcb (\r
@@ -1762,18 +1712,16 @@ IScsiDelTcb (
 {\r
   RemoveEntryList (&Tcb->Link);\r
 \r
-  gBS->FreePool (Tcb);\r
+  FreePool (Tcb);\r
 }\r
 \r
 /**\r
   Find the task control block by the initator task tag.\r
 \r
-  @param  TcbList[in]          The tcb list.\r
-\r
-  @param  InitiatorTaskTag[in] The initiator task tag.\r
-\r
-  @retval The task control block found.\r
+  @param[in]  TcbList         The tcb list.\r
+  @param[in]  InitiatorTaskTag The initiator task tag.\r
 \r
+  @return The task control block found.\r
 **/\r
 ISCSI_TCB *\r
 IScsiFindTcbByITT (\r
@@ -1802,14 +1750,11 @@ IScsiFindTcbByITT (
 /**\r
   Create a data segment, pad it and calculate the CRC if needed.\r
 \r
-  @param  Data[in]       The data to fill into the data segment.\r
-\r
-  @param  Len[in]        Length of the data.\r
-\r
-  @param  DataDigest[in] Whether to calculate CRC for this data segment.\r
-\r
-  @retval The net buffer wrapping the data segment.\r
+  @param[in]  Data       The data to fill into the data segment.\r
+  @param[in]  Len        Length of the data.\r
+  @param[in]  DataDigest Whether to calculate CRC for this data segment.\r
 \r
+  @return The net buffer wrapping the data segment.\r
 **/\r
 NET_BUF *\r
 IScsiNewDataSegment (\r
@@ -1845,14 +1790,12 @@ IScsiNewDataSegment (
   Create a iSCSI SCSI command PDU to encapsulate the command issued\r
   by SCSI through the EXT SCSI PASS THRU Protocol.\r
 \r
-  @param  Packet[in] The EXT SCSI PASS THRU request packet containing the SCSI command.\r
-\r
-  @param  Lun[in]    The LUN.\r
-\r
-  @param  Tcb[in]    The tcb assocated with this SCSI command.\r
-\r
-  @retval The created iSCSI SCSI command PDU.\r
+  @param[in]  Packet The EXT SCSI PASS THRU request packet containing the SCSI command.\r
+  @param[in]  Lun    The LUN.\r
+  @param[in]  Tcb    The tcb assocated with this SCSI command.\r
 \r
+  @return The  created iSCSI SCSI command PDU.\r
+  @retval NULL Other errors as indicated.\r
 **/\r
 NET_BUF *\r
 IScsiNewScsiCmdPdu (\r
@@ -1897,6 +1840,10 @@ IScsiNewScsiCmdPdu (
   }\r
 \r
   ScsiCmd = (SCSI_COMMAND *) NetbufAllocSpace (PduHeader, Length, NET_BUF_TAIL);\r
+  if (ScsiCmd == NULL) {\r
+    NetbufFree (PduHeader);\r
+    return NULL;\r
+  }    \r
   Header  = (ISCSI_ADDITIONAL_HEADER *) (ScsiCmd + 1);\r
 \r
   ZeroMem (ScsiCmd, Length);\r
@@ -1941,10 +1888,10 @@ IScsiNewScsiCmdPdu (
   ScsiCmd->CmdSN            = NTOHL (Tcb->CmdSN);\r
   ScsiCmd->ExpStatSN        = NTOHL (Tcb->Conn->ExpStatSN);\r
 \r
-  CopyMem (ScsiCmd->CDB, Packet->Cdb, sizeof (ScsiCmd->CDB));\r
+  CopyMem (ScsiCmd->Cdb, Packet->Cdb, sizeof (ScsiCmd->Cdb));\r
 \r
   if (Packet->CdbLength > 16) {\r
-    Header->Length  = NTOHS (Packet->CdbLength - 15);\r
+    Header->Length  = NTOHS ((UINT16) (Packet->CdbLength - 15));\r
     Header->Type    = ISCSI_AHS_TYPE_EXT_CDB;\r
 \r
     CopyMem (Header + 1, (UINT8 *) Packet->Cdb + 16, Packet->CdbLength - 16);\r
@@ -1978,7 +1925,7 @@ IScsiNewScsiCmdPdu (
       goto ON_EXIT;\r
     }\r
 \r
-    NbufList = AllocatePool (sizeof (LIST_ENTRY    ));\r
+    NbufList = AllocatePool (sizeof (LIST_ENTRY));\r
     if (NbufList == NULL) {\r
       NetbufFree (PduHeader);\r
       NetbufFree (DataSeg);\r
@@ -2003,7 +1950,7 @@ IScsiNewScsiCmdPdu (
       ) {\r
     //\r
     // Unsolicited data out sequence is not allowed,\r
-    // or FirstBustLength data is already sent out by immediate data\r
+    // or FirstBurstLength data is already sent out by immediate data\r
     // or all the OUT data accompany this SCSI packet is sent as\r
     // immediate data, the final flag should be set on this SCSI Command\r
     // PDU.\r
@@ -2019,18 +1966,14 @@ ON_EXIT:
 /**\r
   Create a new iSCSI SCSI Data Out PDU.\r
 \r
-  @param  Data[in]   The data to put into the Data Out PDU.\r
-\r
-  @param  Len[in]    Length of the data.\r
-\r
-  @param  DataSN[in] The DataSN of the Data Out PDU.\r
-\r
-  @param  Tcb[in]    The task control block of this Data Out PDU.\r
-\r
-  @param  Lun[in]    The LUN.\r
-\r
-  @retval The net buffer wrapping the Data Out PDU.\r
+  @param[in]  Data   The data to put into the Data Out PDU.\r
+  @param[in]  Len    Length of the data.\r
+  @param[in]  DataSN The DataSN of the Data Out PDU.\r
+  @param[in]  Tcb    The task control block of this Data Out PDU.\r
+  @param[in]  Lun    The LUN.\r
 \r
+  @return The net buffer wrapping the Data Out PDU.\r
+  @retval NULL Other errors as indicated.\r
 **/\r
 NET_BUF *\r
 IScsiNewDataOutPdu (\r
@@ -2048,7 +1991,7 @@ IScsiNewDataOutPdu (
   ISCSI_SCSI_DATA_OUT *DataOutHdr;\r
   ISCSI_XFER_CONTEXT  *XferContext;\r
 \r
-  NbufList = AllocatePool (sizeof (LIST_ENTRY    ));\r
+  NbufList = AllocatePool (sizeof (LIST_ENTRY));\r
   if (NbufList == NULL) {\r
     return NULL;\r
   }\r
@@ -2060,7 +2003,7 @@ IScsiNewDataOutPdu (
   //\r
   PduHdr = NetbufAlloc (sizeof (ISCSI_SCSI_DATA_OUT));\r
   if (PduHdr == NULL) {\r
-    gBS->FreePool (NbufList);\r
+    FreePool (NbufList);\r
     return NULL;\r
   }\r
   //\r
@@ -2069,6 +2012,7 @@ IScsiNewDataOutPdu (
   InsertTailList (NbufList, &PduHdr->List);\r
 \r
   DataOutHdr  = (ISCSI_SCSI_DATA_OUT *) NetbufAllocSpace (PduHdr, sizeof (ISCSI_SCSI_DATA_OUT), NET_BUF_TAIL);\r
+  ASSERT (DataOutHdr != NULL);\r
   XferContext = &Tcb->XferContext;\r
 \r
   ZeroMem (DataOutHdr, sizeof (ISCSI_SCSI_DATA_OUT));\r
@@ -2112,14 +2056,12 @@ IScsiNewDataOutPdu (
 /**\r
   Generate a consecutive sequence of iSCSI SCSI Data Out PDUs.\r
 \r
-  @param  Data[in] The data  which will be carried by the sequence of iSCSI SCSI Data Out PDUs.\r
-\r
-  @param  Tcb[in]  The task control block of the data to send out.\r
-\r
-  @param  Lun[in]  The LUN the data will be sent to.\r
-\r
-  @retval A list of net buffers with each of them wraps an iSCSI SCSI Data Out PDU.\r
+  @param[in]  Data The data  which will be carried by the sequence of iSCSI SCSI Data Out PDUs.\r
+  @param[in]  Tcb  The task control block of the data to send out.\r
+  @param[in]  Lun  The LUN the data will be sent to.\r
 \r
+  @return A list of net buffers with each of them wraps an iSCSI SCSI Data Out PDU.\r
+  @retval NULL Other errors as indicated.\r
 **/\r
 LIST_ENTRY *\r
 IScsiGenerateDataOutPduSequence (\r
@@ -2134,8 +2076,9 @@ IScsiGenerateDataOutPduSequence (
   NET_BUF             *DataOutPdu;\r
   ISCSI_CONNECTION    *Conn;\r
   ISCSI_XFER_CONTEXT  *XferContext;\r
+  UINT8               *DataOutPacket;\r
 \r
-  PduList = AllocatePool (sizeof (LIST_ENTRY    ));\r
+  PduList = AllocatePool (sizeof (LIST_ENTRY));\r
   if (PduList == NULL) {\r
     return NULL;\r
   }\r
@@ -2177,7 +2120,14 @@ IScsiGenerateDataOutPduSequence (
   //\r
   // Set the F bit for the last data out PDU in this sequence.\r
   //\r
-  ISCSI_SET_FLAG (NetbufGetByte (DataOutPdu, 0, NULL), ISCSI_BHS_FLAG_FINAL);\r
+  DataOutPacket = NetbufGetByte (DataOutPdu, 0, NULL);\r
+  if (DataOutPacket == NULL) {\r
+    IScsiFreeNbufList (PduList);\r
+    PduList = NULL;\r
+    goto ON_EXIT;\r
+  }\r
+\r
+  ISCSI_SET_FLAG (DataOutPacket, ISCSI_BHS_FLAG_FINAL);\r
 \r
 ON_EXIT:\r
 \r
@@ -2187,16 +2137,13 @@ ON_EXIT:
 /**\r
   Send the Data in a sequence of Data Out PDUs one by one.\r
 \r
-  @param  Data[in]             The data to carry by Data Out PDUs.\r
-\r
-  @param  Lun[in]              The LUN the data will be sent to.\r
-\r
-  @param  Tcb[in]              The task control block.\r
+  @param[in]  Data            The data to carry by Data Out PDUs.\r
+  @param[in]  Lun             The LUN the data will be sent to.\r
+  @param[in]  Tcb             The task control block.\r
 \r
   @retval EFI_SUCCES           The data is sent out to the LUN.\r
-\r
   @retval EFI_OUT_OF_RESOURCES Failed to allocate memory.\r
-\r
+  @retval Others               Other errors as indicated.\r
 **/\r
 EFI_STATUS\r
 IScsiSendDataOutPduSequence (\r
@@ -2240,17 +2187,15 @@ IScsiSendDataOutPduSequence (
 /**\r
   Process the received iSCSI SCSI Data In PDU.\r
 \r
-  @param  Pdu[in]            The Data In PDU received.\r
-\r
-  @param  Tcb[in]            The task control block.\r
-\r
-  @param  Packet[in][out]    The EXT SCSI PASS THRU request packet.\r
-\r
-  @retval EFI_SUCCES         The check on the Data IN PDU is passed and some update\r
-                             actions are taken.\r
-\r
-  @retval EFI_PROTOCOL_ERROR Some kind of iSCSI protocol errror happened.\r
+  @param[in]        Pdu      The Data In PDU received.\r
+  @param[in]        Tcb      The task control block.\r
+  @param[in, out]   Packet   The EXT SCSI PASS THRU request packet.\r
 \r
+  @retval EFI_SUCCES           The check on the Data IN PDU is passed and some update\r
+                               actions are taken.\r
+  @retval EFI_PROTOCOL_ERROR   Some kind of iSCSI protocol errror happened.\r
+  @retval EFI_BAD_BUFFER_SIZEE The buffer was not the proper size for the request.\r
+  @retval Others               Other errors as indicated.\r
 **/\r
 EFI_STATUS\r
 IScsiOnDataInRcvd (\r
@@ -2263,6 +2208,9 @@ IScsiOnDataInRcvd (
   EFI_STATUS          Status;\r
 \r
   DataInHdr                   = (ISCSI_SCSI_DATA_IN *) NetbufGetByte (Pdu, 0, NULL);\r
+  if (DataInHdr == NULL) {\r
+    return EFI_PROTOCOL_ERROR;\r
+  }\r
 \r
   DataInHdr->InitiatorTaskTag = NTOHL (DataInHdr->InitiatorTaskTag);\r
   DataInHdr->ExpCmdSN         = NTOHL (DataInHdr->ExpCmdSN);\r
@@ -2328,18 +2276,14 @@ IScsiOnDataInRcvd (
 /**\r
   Process the received iSCSI R2T PDU.\r
 \r
-  @param  Pdu[in]            The R2T PDU received.\r
-\r
-  @param  Tcb[in]            The task control block.\r
-\r
-  @param  Lun[in]            The Lun.\r
-\r
-  @param  Packet[in][out]    The EXT SCSI PASS THRU request packet.\r
+  @param[in]       Pdu       The R2T PDU received.\r
+  @param[in]       Tcb       The task control block.\r
+  @param[in]       Lun       The Lun.\r
+  @param[in, out]  Packet    The EXT SCSI PASS THRU request packet.\r
 \r
   @retval EFI_SUCCES         The R2T PDU is valid and the solicited data is sent out.\r
-\r
   @retval EFI_PROTOCOL_ERROR Some kind of iSCSI protocol errror happened.\r
-\r
+  @retval Others             Other errors as indicated.\r
 **/\r
 EFI_STATUS\r
 IScsiOnR2TRcvd (\r
@@ -2355,11 +2299,14 @@ IScsiOnR2TRcvd (
   UINT8                   *Data;\r
 \r
   R2THdr = (ISCSI_READY_TO_TRANSFER *) NetbufGetByte (Pdu, 0, NULL);\r
+  if (R2THdr == NULL) {\r
+    return EFI_PROTOCOL_ERROR;\r
+  }\r
 \r
   R2THdr->InitiatorTaskTag = NTOHL (R2THdr->InitiatorTaskTag);\r
   R2THdr->TargetTransferTag = NTOHL (R2THdr->TargetTransferTag);\r
   R2THdr->StatSN = NTOHL (R2THdr->StatSN);\r
-  R2THdr->R2TSN = NTOHL (R2THdr->R2TSN);\r
+  R2THdr->R2TSeqNum = NTOHL (R2THdr->R2TSeqNum);\r
   R2THdr->BufferOffset = NTOHL (R2THdr->BufferOffset);\r
   R2THdr->DesiredDataTransferLength = NTOHL (R2THdr->DesiredDataTransferLength);\r
 \r
@@ -2369,7 +2316,7 @@ IScsiOnR2TRcvd (
   //\r
   // Check the sequence number.\r
   //\r
-  Status = IScsiCheckSN (&Tcb->ExpDataSN, R2THdr->R2TSN);\r
+  Status = IScsiCheckSN (&Tcb->ExpDataSN, R2THdr->R2TSeqNum);\r
   if (EFI_ERROR (Status)) {\r
     return Status;\r
   }\r
@@ -2396,16 +2343,14 @@ IScsiOnR2TRcvd (
 /**\r
   Process the received iSCSI SCSI Response PDU.\r
 \r
-  @param  Pdu[in]            The Response PDU received.\r
-\r
-  @param  Tcb[in]            The task control block.\r
-\r
-  @param  Packet[in][out]    The EXT SCSI PASS THRU request packet.\r
+  @param[in]       Pdu      The Response PDU received.\r
+  @param[in]       Tcb      The task control block.\r
+  @param[in, out]  Packet   The EXT SCSI PASS THRU request packet.\r
 \r
   @retval EFI_SUCCES         The Response PDU is processed.\r
-\r
   @retval EFI_PROTOCOL_ERROR Some kind of iSCSI protocol errror happened.\r
-\r
+  @retval EFI_BAD_BUFFER_SIZEE The buffer was not the proper size for the request.\r
+  @retval Others             Other errors as indicated.\r
 **/\r
 EFI_STATUS\r
 IScsiOnScsiRspRcvd (\r
@@ -2420,6 +2365,9 @@ IScsiOnScsiRspRcvd (
   UINT32            DataSegLen;\r
 \r
   ScsiRspHdr                    = (SCSI_RESPONSE *) NetbufGetByte (Pdu, 0, NULL);\r
+  if (ScsiRspHdr == NULL) {\r
+    return EFI_PROTOCOL_ERROR;\r
+  }\r
 \r
   ScsiRspHdr->InitiatorTaskTag  = NTOHL (ScsiRspHdr->InitiatorTaskTag);\r
   if (ScsiRspHdr->InitiatorTaskTag != Tcb->InitiatorTaskTag) {\r
@@ -2482,6 +2430,9 @@ IScsiOnScsiRspRcvd (
   DataSegLen = ISCSI_GET_DATASEG_LEN (ScsiRspHdr);\r
   if (DataSegLen != 0) {\r
     SenseData               = (ISCSI_SENSE_DATA *) NetbufGetByte (Pdu, sizeof (SCSI_RESPONSE), NULL);\r
+    if (SenseData == NULL) {\r
+      return EFI_PROTOCOL_ERROR;\r
+    }\r
 \r
     SenseData->Length       = NTOHS (SenseData->Length);\r
 \r
@@ -2499,15 +2450,12 @@ IScsiOnScsiRspRcvd (
 /**\r
   Process the received NOP In PDU.\r
 \r
-  @param  Pdu[in]            The NOP In PDU received.\r
-\r
-  @param  Tcb[in]            The task control block.\r
+  @param[in]  Pdu            The NOP In PDU received.\r
+  @param[in]  Tcb            The task control block.\r
 \r
   @retval EFI_SUCCES         The NOP In PDU is processed and the related sequence\r
                              numbers are updated.\r
-\r
   @retval EFI_PROTOCOL_ERROR Some kind of iSCSI protocol errror happened.\r
-\r
 **/\r
 EFI_STATUS\r
 IScsiOnNopInRcvd (\r
@@ -2519,6 +2467,9 @@ IScsiOnNopInRcvd (
   EFI_STATUS    Status;\r
 \r
   NopInHdr            = (ISCSI_NOP_IN *) NetbufGetByte (Pdu, 0, NULL);\r
+  if (NopInHdr == NULL) {\r
+    return EFI_PROTOCOL_ERROR;\r
+  }\r
 \r
   NopInHdr->StatSN    = NTOHL (NopInHdr->StatSN);\r
   NopInHdr->ExpCmdSN  = NTOHL (NopInHdr->ExpCmdSN);\r
@@ -2543,20 +2494,18 @@ IScsiOnNopInRcvd (
 /**\r
   Execute the SCSI command issued through the EXT SCSI PASS THRU protocol.\r
 \r
-  @param  PassThru[in]     The EXT SCSI PASS THRU protocol.\r
-\r
-  @param  Target[in]       The target ID.\r
-\r
-  @param  Lun[in]          The LUN.\r
-\r
-  @param  Packet[in][out]  The request packet containing IO request, SCSI command\r
-                           buffer and buffers to read/write.\r
-\r
-  @retval EFI_SUCCES       The SCSI command is executed and the result is updated to \r
-                           the Packet.\r
-\r
-  @retval EFI_DEVICE_ERROR Some unexpected error happened.\r
-\r
+  @param[in]       PassThru  The EXT SCSI PASS THRU protocol.\r
+  @param[in]       Target    The target ID.\r
+  @param[in]       Lun       The LUN.\r
+  @param[in, out]  Packet    The request packet containing IO request, SCSI command\r
+                             buffer and buffers to read/write.\r
+                             \r
+  @retval EFI_SUCCES           The SCSI command is executed and the result is updated to \r
+                               the Packet.\r
+  @retval EFI_DEVICE_ERROR     Session state was not as required.\r
+  @retval EFI_OUT_OF_RESOURCES Failed to allocate memory.\r
+  @retval EFI_NOT_READY        The target can not accept new commands.\r
+  @retval Others               Other errors as indicated.\r
 **/\r
 EFI_STATUS\r
 IScsiExecuteScsiCommand (\r
@@ -2577,7 +2526,7 @@ IScsiExecuteScsiCommand (
   UINT8                   *Data;\r
   ISCSI_IN_BUFFER_CONTEXT InBufferContext;\r
   UINT64                  Timeout;\r
-  UINT8                   *Buffer;\r
+  UINT8                   *PduHdr;\r
 \r
   Private       = ISCSI_DRIVER_DATA_FROM_EXT_SCSI_PASS_THRU (PassThru);\r
   Session       = &Private->Session;\r
@@ -2587,7 +2536,8 @@ IScsiExecuteScsiCommand (
   Timeout       = 0;\r
 \r
   if (Session->State != SESSION_STATE_LOGGED_IN) {\r
-    return EFI_DEVICE_ERROR;\r
+    Status = EFI_DEVICE_ERROR;\r
+    goto ON_EXIT;\r
   }\r
 \r
   Conn = NET_LIST_USER_STRUCT_S (\r
@@ -2615,8 +2565,13 @@ IScsiExecuteScsiCommand (
   }\r
 \r
   XferContext         = &Tcb->XferContext;\r
-  Buffer              = NetbufGetByte (Pdu, 0, NULL);\r
-  XferContext->Offset = ISCSI_GET_DATASEG_LEN (Buffer);\r
+  PduHdr              = NetbufGetByte (Pdu, 0, NULL);\r
+  if (PduHdr == NULL) {\r
+    Status = EFI_PROTOCOL_ERROR;\r
+    NetbufFree (Pdu);\r
+    goto ON_EXIT;\r
+  }\r
+  XferContext->Offset = ISCSI_GET_DATASEG_LEN (PduHdr);\r
 \r
   //\r
   // Transmit the SCSI Command PDU.\r
@@ -2657,7 +2612,7 @@ IScsiExecuteScsiCommand (
     //\r
     // Start the timeout timer.\r
     //\r
-    if (Timeout) {\r
+    if (Timeout != 0) {\r
       Status = gBS->SetTimer (Conn->TimeoutEvent, TimerRelative, Timeout);\r
       if (EFI_ERROR (Status)) {\r
         goto ON_EXIT;\r
@@ -2672,7 +2627,13 @@ IScsiExecuteScsiCommand (
       goto ON_EXIT;\r
     }\r
 \r
-    switch (ISCSI_GET_OPCODE (NetbufGetByte (Pdu, 0, NULL))) {\r
+    PduHdr = NetbufGetByte (Pdu, 0, NULL);\r
+    if (PduHdr == NULL) {\r
+      Status = EFI_PROTOCOL_ERROR;\r
+      NetbufFree (Pdu);\r
+      goto ON_EXIT;\r
+    }\r
+    switch (ISCSI_GET_OPCODE (PduHdr)) {\r
     case ISCSI_OPCODE_SCSI_DATA_IN:\r
       Status = IScsiOnDataInRcvd (Pdu, Tcb, Packet);\r
       break;\r
@@ -2719,38 +2680,27 @@ ON_EXIT:
     IScsiDelTcb (Tcb);\r
   }\r
 \r
-  if ((Status != EFI_SUCCESS) && (Status != EFI_NOT_READY)) {\r
-    //\r
-    // Reinstate the session.\r
-    //\r
-    if (EFI_ERROR (IScsiSessionReinstatement (Private))) {\r
-      Status = EFI_DEVICE_ERROR;\r
-    }\r
-  }\r
-\r
   return Status;\r
 }\r
 \r
 /**\r
   Reinstate the session on some error.\r
 \r
-  @param  Private[in] The iSCSI driver data.\r
+  @param[in, out]  Private The iSCSI driver data.\r
 \r
   @retval EFI_SUCCES  The session is reinstated from some error.\r
-\r
-  @retval other       Reinstatement failed.\r
-\r
+  @retval Other       Reinstatement failed.\r
 **/\r
 EFI_STATUS\r
 IScsiSessionReinstatement (\r
-  IN ISCSI_DRIVER_DATA  *Private\r
+  IN OUT ISCSI_DRIVER_DATA  *Private\r
   )\r
 {\r
   ISCSI_SESSION *Session;\r
   EFI_STATUS    Status;\r
 \r
   Session = &Private->Session;\r
-  ASSERT (Session->State == SESSION_STATE_LOGGED_IN);\r
+  ASSERT (Session->State != SESSION_STATE_FREE);\r
 \r
   //\r
   // Abort the session and re-init it.\r
@@ -2769,43 +2719,28 @@ IScsiSessionReinstatement (
 /**\r
   Initialize some session parameters before login.\r
 \r
-  @param  Session[in]  The iSCSI session.\r
-\r
-  @param  Recovery[in] Whether the request is from a fresh new start or recovery.\r
-\r
-  @retval None.\r
-\r
+  @param[in, out]  Session  The iSCSI session.\r
+  @param[in]       Recovery Whether the request is from a fresh new start or recovery.\r
 **/\r
 VOID\r
 IScsiSessionInit (\r
-  IN ISCSI_SESSION  *Session,\r
-  IN BOOLEAN        Recovery\r
+  IN OUT ISCSI_SESSION  *Session,\r
+  IN BOOLEAN            Recovery\r
   )\r
 {\r
-  UINT32  Random;\r
-\r
   if (!Recovery) {\r
     Session->Signature  = ISCSI_SESSION_SIGNATURE;\r
     Session->State      = SESSION_STATE_FREE;\r
 \r
-    Random              = NET_RANDOM (NetRandomInitSeed ());\r
-\r
-    Session->ISID[0]    = ISID_BYTE_0;\r
-    Session->ISID[1]    = ISID_BYTE_1;\r
-    Session->ISID[2]    = ISID_BYTE_2;\r
-    Session->ISID[3]    = ISID_BYTE_3;\r
-    Session->ISID[4]    = (UINT8) Random;\r
-    Session->ISID[5]    = (UINT8) (Random >> 8);\r
-\r
     InitializeListHead (&Session->Conns);\r
     InitializeListHead (&Session->TcbList);\r
   }\r
 \r
-  Session->TSIH                 = 0;\r
+  Session->Tsih                 = 0;\r
 \r
   Session->CmdSN                = 1;\r
   Session->InitiatorTaskTag     = 1;\r
-  Session->NextCID              = 1;\r
+  Session->NextCid              = 1;\r
 \r
   Session->TargetPortalGroupTag = 0;\r
   Session->MaxConnections       = ISCSI_MAX_CONNS_PER_SESSION;\r
@@ -2825,14 +2760,13 @@ IScsiSessionInit (
   Abort the iSCSI session, that is, reset all the connection and free the\r
   resources.\r
 \r
-  @param  Session[in] The iSCSI session.\r
+  @param[in, out]  Session The iSCSI session.\r
 \r
   @retval EFI_SUCCES  The session is aborted.\r
-\r
 **/\r
 EFI_STATUS\r
 IScsiSessionAbort (\r
-  IN ISCSI_SESSION  *Session\r
+  IN OUT ISCSI_SESSION  *Session\r
   )\r
 {\r
   ISCSI_DRIVER_DATA *Private;\r