/*static char *SCCSID = "@(#)gas.c	6.3 92/01/31";*/
#define ASWAP0 ASWAP0
#include <os2def.h>
#include <bse.h>

#include "const.h"
#include "misc.h"
#include "chain.h"
#include "buf.h"
#include "dir.h"
#include "volume.h"
#include "storage.h"
#include "tables.h"
#include "lw.h"
#include "pb_ifs.h"
#include "pbmacros.h"
#include "frame.h"
#include "fsdata.h"
#include "log.h"

#include "pr_ALLOC.h"
#include "pr_BITMP.h"
#include "pr_CACHE.h"
#include "pr_HEAP.h"
#include "pr_MISC.h"
#include "pr_debug.h"


/*	GAS - Get Allocation Sector
 *
 *	GAS is a captive of AddExt.  It allocates a single block, fetches
 *	it into memory, sets its fields to empty (leaf type) and returns
 *	its address.  Note that if the block is to be used for node
 *	records, the ABF_NODE bit must be set and the AB_FCNT field must
 *	be corrected.
 *
 *	BUGBUG - allocate 4 of them to pack?
 *
 *	ENTRY	lsnPrefer = starting location for search
 *
 *	EXIT	Returns the address of sector found
 *		  *ppbuf = header of cache buffer holding sector
 *		Returns NULL if none available
 *
 *	Yields CPU
 */

PVOID
GAS (lsnPrefer, ppbuf, pfrm)
LSN		lsnPrefer;
PBUFNODE far   *ppbuf;
PFRAME		pfrm;
{
    LSN		lsnAlloc;	/* lsn of allocated sector */
    ALSEC far	*pals;		/* pointer to sector allocated */
    PBUFNODE pbuf;

    /* Allocate freespace block */
    if (AFB (1L, lsnPrefer, &lsnAlloc, pfrm)) {
	/* mark sector allocated in bitmap */
                                                      //#85759
	   if (!ClrBit (lsnAlloc, 1L, FALSE,pfrm))
        return NULL;

#ifndef MINIFSD
   if ((pals = InitLzRd (lsnAlloc, &pbuf, pfrm)) == NULL)
	  pals = GetInBuf (lsnAlloc, 1, BP_KEEP, &pbuf,pfrm);
#else
	/* get the sector in a buffer */
	   pals = GetInBuf (lsnAlloc, 1, BP_KEEP, &pbuf,pfrm);
#endif

   *ppbuf = pbuf;

	if (pals != NULL) {

	    /* initialize ALSEC (as a leaf) */
	    pals->sig = ABSIGVAL;
	    pals->lsnSelf = lsnAlloc;
	    pals->alb.bFlag = 0;
	    pals->alb.cFree = LEAFPERSEC;
	    pals->alb.cUsed = 0;
	    pals->alb.oFree = sizeof (ALBLK);

#ifndef MINIFSD
       if (pbuf->fFlag & BFL_LZREAD)
     /* Correct lazy read map for FNODE */
         memset ((PBYTE)pbuf->pLzRdBitMap +
                ((lsnAlloc % SPB)*(SECSIZE/8)), 0x00,
                 SECSIZE / 8);
#endif

	}
#ifdef DEBUG
	else {
	    dprintf (__FILE__": GetInBuf returned NULL\n");
	}
#endif

	return (pals);
    }
    else
	return (NULL);
}
