/* -*- mode: c; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 4 -*-
 * ex: set softtabstop=4 tabstop=8 expandtab shiftwidth=4: *
 * Editor Settings: expandtabs and use 4 spaces for indentation */

/*
 * Copyright Likewise Software
 * All rights reserved.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or (at
 * your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * for more details.  You should have received a copy of the GNU General
 * Public License along with this program.  If not, see
 * <http://www.gnu.org/licenses/>.
 *
 * LIKEWISE SOFTWARE MAKES THIS SOFTWARE AVAILABLE UNDER OTHER LICENSING
 * TERMS AS WELL.  IF YOU HAVE ENTERED INTO A SEPARATE LICENSE AGREEMENT
 * WITH LIKEWISE SOFTWARE, THEN YOU MAY ELECT TO USE THE SOFTWARE UNDER THE
 * TERMS OF THAT SOFTWARE LICENSE AGREEMENT INSTEAD OF THE TERMS OF THE GNU
 * GENERAL PUBLIC LICENSE, NOTWITHSTANDING THE ABOVE NOTICE.  IF YOU
 * HAVE QUESTIONS, OR WISH TO REQUEST A COPY OF THE ALTERNATE LICENSING
 * TERMS OFFERED BY LIKEWISE SOFTWARE, PLEASE CONTACT LIKEWISE SOFTWARE AT
 * license@likewisesoftware.com
 */

/*
 * Copyright (C) Likewise Software. All rights reserved.
 *
 * Module Name:
 *
 *        irpctx.c
 *
 * Abstract:
 *
 *        Likewise Posix File System Driver (PVFS)
 *
 *        Pvfs IRP Context routines
 *
 * Authors: Gerald Carter <gcarter@likewise.com>
 */

#include "pvfs.h"


/***********************************************************************
 **********************************************************************/

static
VOID
PvfsFreeIrpContext(
	PPVFS_IRP_CONTEXT *ppIrpContext
    )
{
    PPVFS_IRP_CONTEXT pIrpCtx = NULL;

    if (ppIrpContext && *ppIrpContext)
    {
        pIrpCtx = *ppIrpContext;

        if (pIrpCtx->pIrp &&
            PvfsIrpContextCheckFlag(pIrpCtx, PVFS_IRP_CTX_FLAG_PENDED))
        {
            pIrpCtx->pIrp->IoStatusBlock.Status = STATUS_FILE_CLOSED;
            PvfsCompleteIrpContext(pIrpCtx);
        }

        if (pIrpCtx->pScb)
        {
            PvfsReleaseSCB(&pIrpCtx->pScb);
        }

        PVFS_FREE(ppIrpContext);

        InterlockedDecrement(&gPvfsDriverState.Counters.IrpContext);
    }
}


/***********************************************************************
 **********************************************************************/

NTSTATUS
PvfsAllocateIrpContext(
	PPVFS_IRP_CONTEXT *ppIrpContext,
    PIRP pIrp
    )
{
    NTSTATUS ntError = STATUS_UNSUCCESSFUL;
    PPVFS_IRP_CONTEXT pIrpContext = NULL;

    *ppIrpContext = NULL;

    ntError = PvfsAllocateMemory(
                  OUT_PPVOID(&pIrpContext),
                  sizeof(PVFS_IRP_CONTEXT),
                  FALSE);
    BAIL_ON_NT_STATUS(ntError);

    pIrpContext->RefCount = 1;

    pIrpContext->Flags = PVFS_IRP_CTX_FLAG_NONE;
    pIrpContext->QueueType = PVFS_QUEUE_TYPE_NONE;
    pIrpContext->pScb = NULL;
    pIrpContext->Callback = NULL;

    pIrpContext->pIrp = pIrp;

    *ppIrpContext = pIrpContext;

    InterlockedIncrement(&gPvfsDriverState.Counters.IrpContext);

cleanup:
    return ntError;

error:
    goto cleanup;
}

/***********************************************************************
 ***********************************************************************/

VOID
PvfsIrpMarkPending(
    IN PPVFS_IRP_CONTEXT pIrpContext,
    IN PIO_IRP_CALLBACK CancelCallback,
    IN OPTIONAL PVOID CancelCallbackContext
    )
{
    BOOLEAN bPendIrp = FALSE;

    bPendIrp = PvfsIrpContextMarkIfNotSetFlag(
                   pIrpContext,
                   PVFS_IRP_CTX_FLAG_PENDED,
                   PVFS_IRP_CTX_FLAG_PENDED);

    if (bPendIrp)
    {
        IoIrpMarkPending(
            pIrpContext->pIrp,
            CancelCallback,
            CancelCallbackContext);
    }
}

////////////////////////////////////////////////////////////////////////

VOID
PvfsCompleteIrpContext(
    PPVFS_IRP_CONTEXT pIrpContext
    )
{
    BOOLEAN bComplete = FALSE;

    bComplete = PvfsIrpContextMarkIfSetMask(
                    pIrpContext,
                    (PVFS_IRP_CTX_FLAG_PENDED | PVFS_IRP_CTX_FLAG_COMPLETE),
                    PVFS_IRP_CTX_FLAG_PENDED,
                    PVFS_IRP_CTX_FLAG_COMPLETE);

    if (bComplete)
    {
        IoIrpComplete(pIrpContext->pIrp);
        pIrpContext->pIrp = NULL;
    }
}

////////////////////////////////////////////////////////////////////////

static
NTSTATUS
PvfsScheduleIrpContextCallback(
    IN PPVFS_IRP_CONTEXT pIrpContext,
    IN BOOLEAN Priority,
    PPVFS_IRP_PROCESS_CONTEXT_CALLBACK Callback
    );

static
VOID
PvfsProcessIrpContextCompletion(
    PVOID
    );


VOID
PvfsAsyncCompleteIrpContext(
    PPVFS_IRP_CONTEXT pIrpContext
    )
{
    BOOLEAN bComplete = FALSE;

    // Schedule a completion if pended and not already complete.
    bComplete = PvfsIrpContextCheckMask(
                    pIrpContext,
                   (PVFS_IRP_CTX_FLAG_PENDED | PVFS_IRP_CTX_FLAG_COMPLETE), 
                    PVFS_IRP_CTX_FLAG_PENDED);

    if (bComplete)
    {
        PvfsScheduleIrpContextCallback(
                pIrpContext, 
                TRUE, 
                PvfsProcessIrpContextCompletion);

        // Ignore the error.  It has already been dealt with as best
        // as possible
    }
}


/***********************************************************************
 ***********************************************************************/

PPVFS_IRP_CONTEXT
PvfsReferenceIrpContext(
    PPVFS_IRP_CONTEXT pIrpContext
    )
{
    InterlockedIncrement(&pIrpContext->RefCount);

    return pIrpContext;
}

/***********************************************************************
 ***********************************************************************/

VOID
PvfsReleaseIrpContext(
    PPVFS_IRP_CONTEXT *ppIrpContext
    )
{
    PPVFS_IRP_CONTEXT pIrpContext = *ppIrpContext;

    if (InterlockedDecrement(&pIrpContext->RefCount) == 0)
    {
        PvfsFreeIrpContext(&pIrpContext);
    }

    *ppIrpContext = NULL;
}

////////////////////////////////////////////////////////////////////////

static
VOID
PvfsProcessIrpContext(
    PVOID
    );


NTSTATUS
PvfsScheduleIrpContext(
    IN PPVFS_IRP_CONTEXT pIrpContext,
    IN BOOLEAN Priority
    )
{
    return PvfsScheduleIrpContextCallback(
                pIrpContext, 
                Priority, 
                PvfsProcessIrpContext);
}

static
NTSTATUS
PvfsScheduleIrpContextCallback(
    IN PPVFS_IRP_CONTEXT pIrpContext,
    IN BOOLEAN Priority,
    PPVFS_IRP_PROCESS_CONTEXT_CALLBACK Callback)
{
    NTSTATUS ntError = STATUS_UNSUCCESSFUL;
    PPVFS_IRP_CONTEXT pIrpCtx = NULL;

    // Take a reference for the work queue
    pIrpCtx = PvfsReferenceIrpContext(pIrpContext);

    pIrpCtx->QueueType = PVFS_QUEUE_TYPE_IO;
    PvfsIrpMarkPending(pIrpCtx, PvfsQueueCancelIrp, pIrpCtx);

    ntError = LwRtlQueueWorkItem(
                  gPvfsDriverState.ThreadPool,
                  Callback,
                  pIrpCtx,
                  Priority?LW_SCHEDULE_HIGH_PRIORITY:0);
    BAIL_ON_NT_STATUS(ntError);

    ntError = STATUS_PENDING;

error:
    if (ntError != STATUS_PENDING)
    {
        if (!PvfsIrpContextCheckFlag(pIrpContext, PVFS_IRP_CTX_FLAG_COMPLETE))
        {
            // The IRP was not already complete and just awaiting the
            // IoIrpComplete call.  So set the IoStatusBlock
            pIrpCtx->pIrp->IoStatusBlock.Status = ntError;
        }
        PvfsCompleteIrpContext(pIrpCtx);

        if (pIrpCtx)
        {
            PvfsReleaseIrpContext(&pIrpCtx);
        }
    }

    return ntError;
}

////////////////////////////////////////////////////////////////////////

static
VOID
PvfsProcessIrpContext(
    IN PVOID Context
    )
{
    NTSTATUS ntError = STATUS_SUCCESS;
    PPVFS_IRP_CONTEXT pIrpCtx = NULL;
    BOOLEAN bActive = FALSE;

    // We were given a reference to the IrpContext when it was queued
    pIrpCtx = Context;

    LWIO_ASSERT(!PvfsIrpContextCheckFlag(pIrpCtx, PVFS_IRP_CTX_FLAG_COMPLETE));

    PvfsQueueCancelIrpIfRequested(pIrpCtx);

    bActive = PvfsIrpContextMarkIfNotSetFlag(
                  pIrpCtx,
                  PVFS_IRP_CTX_FLAG_CANCELLED,
                  PVFS_IRP_CTX_FLAG_ACTIVE);

    if (bActive)
    {
        ntError = pIrpCtx->Callback(pIrpCtx);
    }
    else
    {
        ntError = STATUS_CANCELLED;
    }

    if (ntError != STATUS_PENDING)
    {
        pIrpCtx->pIrp->IoStatusBlock.Status = ntError;

        PvfsCompleteIrpContext(pIrpCtx);
    }

    PvfsReleaseIrpContext(&pIrpCtx);

    return;
}

static
VOID
PvfsProcessIrpContextCompletion(
    IN PVOID Context
    )
{
    PPVFS_IRP_CONTEXT pIrpCtx = NULL;

    // We were given a reference to the IrpContext when it was queued
    pIrpCtx = Context;

    // The IrpContext was marked for an async completion so that IoIrpComplete
    // would be called from the context of another thread.  Just complete and
    // exit
    PvfsCompleteIrpContext(pIrpCtx);

    PvfsReleaseIrpContext(&pIrpCtx);

    return;
}

////////////////////////////////////////////////////////////////////////

NTSTATUS
PvfsIrpContextMakePendedCancellable(
    PPVFS_IRP_CONTEXT pIrpContext,
    IN PIO_IRP_CALLBACK CancelCallback,
    IN OPTIONAL PVOID CancelCallbackContext,
    PVFS_QUEUE_TYPE Qtype)
{
    NTSTATUS    ntError = STATUS_SUCCESS;

    pIrpContext->QueueType = Qtype;
    PvfsIrpMarkPending(pIrpContext, CancelCallback, CancelCallbackContext);

    /* May schedule a cancel; caller must be able to handle */
    ntError = PvfsQueueCancelIrpIfRequestedElseDeactivate(pIrpContext);

    return ntError;
}
