Nucleus FILE - read.pudn.comread.pudn.com/downloads40/sourcecode/embed/140204/file/FILE.pdf ·...

64
Nucleus Nucleus FILE FILE Reference Manual Reference Manual 0001034-001 Copyright (c) 1999 Accelerated Technology, Inc. 720 Oak Circle Dr. E. Mobile, AL 36609 (334) 661-5770

Transcript of Nucleus FILE - read.pudn.comread.pudn.com/downloads40/sourcecode/embed/140204/file/FILE.pdf ·...

NucleusNucleusFILEFILE

Reference ManualReference Manual

0001034-001

Copyright (c) 1999Accelerated Technology, Inc.

720 Oak Circle Dr. E.Mobile, AL 36609

(334) 661-5770

Preface

ii

Nucleus FILE Reference Manual

iii

Related DocumentationRelated DocumentationNucleus PLUS Reference Manual, by Accelerated Technology, describes the operationand usage of the Nucleus PLUS kernel.

Nucleus PLUS Internals, by Accelerated Technology, describes, in considerable detail,the implementation of the Nucleus PLUS kernel.

Style and Symbol ConventionsStyle and Symbol ConventionsProgram listings, program examples, filenames, menu items/buttons and interactivedisplays are each shown in a special font.

Program listings and program examples - Courier NewFilenames - COURIER NEW, ALL CAPSInteractive Command Lines - Courier New, Bold

TrademarksTrademarksMS-DOS is a trademark of Microsoft CorporationUNIX is a trademark of X/OpenIBM PC is a trademark of International Business Machines, Inc.Intel is a trademark of Intel, Inc.

Additional AssistanceAdditional AssistanceFor additional assistance, please contact us at the following:

Accelerated Technology720 Oak Circle Drive, EastMobile, AL 36609800-468-6853334-661-5770334-661-5788 (fax)

[email protected]://www.atinucleus.com

Copyright (©) 1999, All Rights Reserved.Document Part Number : 0001034-001Last Revised: September 14, 1999

Preface

iv

v

Chapter 1 - Introduction ..........................................................................................1Introduction .................................................................................................................... 2File System Description .................................................................................................. 2Overview........................................................................................................................ 3

Chapter 2 - Getting Started ......................................................................................5Installation...................................................................................................................... 6

Diskette Installation: ................................................................................................... 6CD-ROM Installation:................................................................................................. 7

Building Nucleus FILE ................................................................................................... 7Nucleus RTX Users:.................................................................................................... 7Nucleus PLUS Users (Diskette Installation):................................................................ 8Nucleus PLUS Users (CD-ROM Installation): ............................................................. 8

Chapter 3 - Porting and Tuning................................................................................9Porting Nucleus FILE ................................................................................................... 10

Get the Date/Time (PC_UPDATE.C) ........................................................................ 10Printing Routines (PC_PRINT.C) .............................................................................. 10Printing Error Strings (PC_ERROR.C) ...................................................................... 10

Tuning Nucleus FILE ................................................................................................... 11Device Selection (DEVTABLE.C) ............................................................................ 11Tuning Memory Allocation (PC_MEMRY.C) ........................................................... 11File System Tuning (PCDISK.H)............................................................................... 12Intel Environment Tuning ......................................................................................... 12Device Driver Manifests............................................................................................ 12Nucleus PLUS RAM Disk Usage on Intel Platforms .................................................. 12RAM Disk Tuning .................................................................................................... 13Multitasking Definition ............................................................................................. 13File System Capacity Tuning..................................................................................... 14

Tuning Nucleus FILE for Nucleus RTX or Nucleus PLUS............................................. 14Modifying IN_DATA.C (Nucleus RTX).................................................................... 14Modifying IN_Fixed_Partitions................................................................................. 15Modifying IN_System_Event_Groups ....................................................................... 16Modifying IN_System_Resources.............................................................................. 16Modifying Nucleus FILE For Nucleus PLUS............................................................ 16Modifying NUFI.C.................................................................................................... 17

ContentsContents

Preface

vi

Modifying NUFP.C ...................................................................................................17Chapter 4 – User Interfaces................................................................................... 19Major Data Structures........................................................................................... 20

DDRIVE ...................................................................................................................20DOSINODE ..............................................................................................................20FINODE....................................................................................................................20BLKBUFF.................................................................................................................20DROBJ......................................................................................................................20PCFILE.....................................................................................................................21DSTAT .....................................................................................................................21

User Interfaces ..............................................................................................................21NU_Close..............................................................................................................22NU_Close_Disk.....................................................................................................23NU_Current_Dir....................................................................................................24NU_Delete.............................................................................................................25NU_Disk_Abort ....................................................................................................26NU_Flush..............................................................................................................29NU_Format ...........................................................................................................30NU_FreeSpace.......................................................................................................32NU_Get_Default_Drive .........................................................................................33NU_Get_First ........................................................................................................34NU_Get_Next........................................................................................................36NU_Make_Dir.......................................................................................................37NU_Open ..............................................................................................................38NU_Open_Disk .....................................................................................................40NU_Read...............................................................................................................41NU_Remove_Dir...................................................................................................42NU_Rename..........................................................................................................43NU_Seek ...............................................................................................................44NU_Set_Current_Dir .............................................................................................45NU_Set_Default_Drive..........................................................................................46NU_Set_Default_Drive_Number ...........................................................................47NU_Truncate.........................................................................................................48NU_Write..............................................................................................................49p_errno..................................................................................................................50

Appendix A – Programming Tips ......................................................................... 51Romming code ..........................................................................................................52Stack requirements ....................................................................................................52Error recovery ...........................................................................................................52

Appendix B - Tutorial........................................................................................... 53Getting Started ..........................................................................................................54Creating a Directory Entry On Disk ...........................................................................54Finishing Up..............................................................................................................57

1

1Chapter 1 - Introduction

IntroductionIntroduction

File System DescriptionFile System Description

OverviewOverview

IntroductionIntroduction

Chapter 1 - Introduction

2

IntroductionNucleus FILE provides the tools needed to maintain an MS-DOS compatible file system.It may be used in embedded applications or in applications requiring import/exportcapabilities to DOS based floppy disks or Winchester partitions. Nucleus FILE iscompatable with MS-DOS 4.

All of the file system routines you would expect are provided, including open, close,seek, read, write, lseek, mkdir, rmdir, rm, and format. Full path and Winchester disksupport is provided.

Special care has been taken to provide a robust environment for embedded applications.Programmers using the package for embedded applications are advised to study theexample program(s) to see how to use the package.

File System DescriptionThe file system consists of one or more identical File Allocation Tables (FATs), followedby a fixed size root directory and a "heap" area logically broken up into clusters. Acluster is simply one or more contiguous sectors. A file or subdirectory consists of adirectory entry plus a linked list of clusters, called a chain, which contains its data. Thedirectory entry contains the number of the first cluster in the chain.

The FAT contains one 12 or 16 bit entry per cluster in the heap area. If the entry containsa zero, the cluster it maps to is free and may be used; otherwise, the entry is eitherreserved or it is part of a "chain". Each entry in a chain marks a cluster by virtue of itsposition and its contents link it to the next cluster in the file or subdirectory. A specialmagic number marks the end of a chain. So, to get at the contents of a file you simply getthe first cluster from the directory entry and read its contents from the software media,then look in the FAT for the next entry in the chain. If the entry contains a number lessthan the end-of-file marker, read its contents from the software media and get the nextcluster from the FAT.

The primary access to the file system is the root directory. The root directory containsroom for a fixed number of directory entries. The number is determined by the formatprogram and is stored in block zero. As described below, subdirectories (those lower inthe hierarchy) can contain an unlimited number of entries.

Directory or subdirectory entries contain a filename, creation date and time, an attributebyte, a size and a pointer to the first cluster (if there is one) reserved by the entry. Asubdirectory is a special case of a directory entry, the subdirectory attribute is set in theattribute byte and its clusters contain more directory entries.

Sub-directories can grow by claiming more clusters from the disk. Every subdirectorycontains the two special entries '.' and '..'. The '..' points to the first cluster inthe chain of the directory's parent, while '.' points to the beginning of thesubdirectory.

Nucleus FILE Reference Manual

3

OverviewEach program package of Nucleus FILE is tailored to the target environment. Thedirectory structure of the program package includes a main directory of source files andone or more subdirectories (e.g., \RAMDEMO) which contain sample program(s)depending on the target. See the Nucleus FILE chapter of your Nucleus Target SpecificNotes for your particular program package.

The process required to build Nucleus FILE will depend on which version of the Nucleuskernel you are using. Throughout this document there will be references to using NucleusRTX and Nucleus PLUS. If you are using Nucleus RTX, you will need to move theobject files built in your Nucleus RTX working directory. These files will be combinedwith the Nucleus FILE object files to build your system. If you are using Nucleus PLUSand it was shipped on diskettes, you will need to copy the Nucleus PLUS library file inyour Nucleus PLUS working directory into your Nucleus FILE working directory inorder to build your system. In some cases, additional files may be required from yourNucleus PLUS working directory in order to build your system. If the Nucleus productsare shipped on a CD-ROM, the installation program creates all of the files, and placesthem in the correct directories. Please see the Nucleus Target Specific Notes for yourparticular program package for details.

Chapter 1 - Introduction

4

5

InstallationInstallation

Building Nucleus FILEBuilding Nucleus FILE

Chapter 2 - Getting Started

2

GettingGettingStartedStarted

Chapter 2 – Getting Started

6

InstallationThe Nucleus FILE distribution software contains the source files, and at least onesubdirectory that contains a demonstration program. The following installationinstructions assume a working knowledge of MS-DOS.

Diskette Installation:The representation "D:" refers to the hard disk drive designator on which Nucleus FILEis being installed. The following is a set of commands that are assumed to be entered atthe drive letter prompt (i.e., "C" prompt, "D" prompt, etc.) to which Nucleus FILE is tobe loaded.

D> md nucleus.filD> cd nucleus.fil<<< Insert Nucleus FILE Disk into drive a: >>>D> xcopy a:\ /e/s

The foregoing process will build a directory tree as illustrated in Figure 1. The '<' and'>' indicate optional directories based on the target system.

NUCLEUS.FIL

RAMDEMO <BIOSDEMO> ... <otherdemo>

Figure 1 - Nucleus FILE Directory Tree

Nucleus FILE Reference Manual

7

CD-ROM Installation:

Execute SETUP.EXE to install Nucleus FILE to your system. After installation, thedirectory structure should resemble:

The Nucleus FILE library and demo rely on this structure and will not build correctlyunless the batch files are modified. There may be additional subdirectories under FILE,so please refer to your Target Specific Notes for further instructions.

Building Nucleus FILEBuilding Nucleus FILE is generally a target specific activity. There is a batch file namedeither BUILD_FI.BAT or FILE.BAT that creates the Nucleus FILE library. It can befound in the directory with the Nucleus FILE source code. This batch file assumes thatthe PLUS library already exists. However, for RTX users this may be a new conceptsince RTX is delivered with a batch file, which simply builds object files and links themtogether. For those users, the file MAKENLIB.BAT is provided so that you can build alibrary file of Nucleus RTX objects.

If you installed FILE from diskettes, we recommend that you create a working directoryon your drive separate from where the directories Nucleus FILE, Nucleus RTX orNucleus PLUS are loaded, before starting to build the Nucleus FILE system. Once thisdirectory is created (for our instructions, we will assume a directory of the name\FILEWORK), follow the directions below based on the kernel you are using. NOTE:Instructions for building the library or an application do not apply to Nucleus EDE ports.Refer to your Nucleus EDE Online Help for more information.

Nucleus RTX Users:1. Copy the file MAKENLIB.BAT from your main Nucleus FILE directory into your

Nucleus RTX working directory.2. Execute MAKENLIB in the Nucleus RTX working directory (we are assuming that

you have already built Nucleus RTX for your target system).3. Copy the resulting NUCLEUS.LIB file into your \FILEWORK directory.4. Copy the NU_DEFS.H, NU_EXTR.H, and IN_DEFS.H files from your Nucleus

RTX working directory into your \FILEWORK directory.5. Copy all of the files from your main Nucleus FILE directory into your \FILEWORK

directory.6. Execute the BUILD_FI.BAT file in your \FILEWORK directory.

Chapter 2 – Getting Started

8

Nucleus PLUS Users (Diskette Installation):1. Copy the NUCLEUS.LIB directory from your Nucleus PLUS working directory

(we are assuming that you have already built Nucleus PLUS for your target) intoyour \FILEWORK directory.

2. Copy the file NUCLEUS.H from your Nucleus PLUS working directory into your\FILEWORK directory.

3. Copy all of the files from your main Nucleus FILE directory into your \FILEWORKdirectory.

4. Execute the BUILD_FI.BAT file in your \FILEWORK directory.

The result of the preceding operations is a complete library (minus a few target specificfiles that are discussed in your Target Specific Notes for Nucleus FILE) that can be usedto build applications which include Nucleus FILE file-system access. To complete thebuild process with a pre-defined application, please consult your Target Specific Notesfor Nucleus FILE.

Nucleus PLUS Users (CD-ROM Installation):Please consult your Target Specific Notes for specific instructions on building theNucleus FILE library and the Nucleus FILE demo.

9

Porting Nucleus FILEPorting Nucleus FILE

Tuning Nucleus FILETuning Nucleus FILE

Tuning Nucleus FILE for NucleusTuning Nucleus FILE for NucleusRTX or Nucleus PLUSRTX or Nucleus PLUS

Chapter 3 - Porting and Tuning

3

Porting andPorting andTuningTuning

Chapter 3 - Porting and Tuning

10

Porting Nucleus FILESince there is such a wide variety of host platforms and target file devices, it is notpossible for Nucleus FILE to include interfaces for all of them. Therefore, a simple wayhas been provided to port the lowest level routines in Nucleus FILE. These routines areused for the following purposes and each is described in the paragraphs that follow.

§ Get the Date/Time§ Printing Routines§ Printing Error Strings

Get the Date/Time (PC_UPDATE.C)This routine will return the current date and time to the file system. It must be written tointerface with the target system's date/time clock.

An implementation of the Get the Date/Time routine can be found in PC_UDATE.C. Youmust modify this routine for your target environment.

Printing Routines (PC_PRINT.C)If your compiler does not support the standard printing routines (printf, etc.), NucleusFILE provides some routines to perform these functions.

An implementation of the Printing routines can be found in PC_PRINT.C. You mustmodify this routine for your target environment.

Printing Error Strings (PC_ERROR.C)The file PC_ERROR.C contains a routine that will print out any errors detected whilethe file system is executing. If you do not have a printf function or if you do not wish theerrors to be printed, you must modify this file. Modification to the file is self-explanatory.

Nucleus FILE Reference Manual

11

Tuning Nucleus FILENucleus FILE has been designed as a flexible system to accommodate many differenttypes of embedded environments from the most full featured to a small system thatsimply needs RAM Disk support. In order to accommodate such a wide variety ofsystems, Nucleus FILE includes certain manifest constants and preset variables that canbe modified to tune Nucleus FILE to your environment. This section describes each ofthe files within Nucleus FILE that contains these constants and variables.

Device Selection (DEVTABLE.C)Nucleus FILE can accommodate any number of drives that you require. The file systemaccesses the drives via a set of interfaces that are defined in the table pc_bdevsw in fileDEVTABLE.C. In order for any driver, whether supplied by ATI or developed by you, tointerface to the file system, it must have an entry in this table. For now, we are interestedin configuring your system once the device drivers have been developed and aretherefore only concerned with entries in the table, not the make up of those entries.

There should be one entry in pc_bdevsw per drive specified in PCDISK.H by themanifest constant NDRIVES. The first entry represents drive A:, the second drive B:, andso on. Based on the target version of Nucleus FILE that you purchased, there is at leastone demonstration program that uses a tailored version of DEVTABLE.C. On yourdistribution software, in the main directory, the file DEVTABLE.C contains a number ofdifferent configurations based on the drivers you have purchased. Please reviewDEVTABLE.C from the main directory to see some alternatives.

Tuning Memory Allocation (PC_MEMRY.C)PC_MEMRY.C is responsible for the actual allocation of many of the primary datastructures used by Nucleus FILE. The size of these data structures is dictated by manifestconstants in PCDISK.H. Some of these are discussed in the following section, FileSystem Tuning (PCDISK.H). A number of these data structures are fully specified by themanifests in PCDISK.H. However, some are optional. Those that are optional pertain tothe management of the FAT on each disk. You only need one FAT structure for each diskyou are using. The file PC_MEMRY.C that is in your main directory of the releasecontains a switch statement in the function pc_memory_fat_blocks_alloc for fiveFATs (for drives A: - E:).

If your system is using less than 5 disks, the code for each case in the switch statementcan be removed for those drives that you do not use.

As with DEVTABLE.C, a special version of PC_MEMRY.C is included with thedemonstration files for your particular target. There may be more than one demonstrationfile. In any case, the PC_MEMRY.C found with the demonstration program(s) containsonly those FAT allocations that are required for the specific demonstration. Pleaseconsult this file to determine how you might modify PC_MEMRY.C for your application.

Chapter 3 - Porting and Tuning

12

In addition to the changes required in PC_MEMRY.C, you may also need to makechanges to some Nucleus RTX or Nucleus PLUS configuration files. Please refer toTuning Nucleus FILE for Nucleus RTX or Nucleus PLUS for a description of thesemodifications.

NOTE: You must make modifications to the Nucleus RTX and Nucleus PLUSconfiguration files if you modify PC_MEMRY.C to include fewer drives than arecurrently provided in the main release.

File System Tuning (PCDISK.H)The number of tasks, directories, and files, as well as buffer sizes, affect the operation ofthe file system. The more tasks that are used and files or subdirectories that are openedwill increase contention for the file system and possibly affect the overall throughput ofthe system. Small buffers will require more access to the file medium while large buffersreduce the amount of access yet increase the overall memory usage in the system. Thesetradeoffs can be controlled by tuning various manifest constants and preset variables inthe file PCDISK.H. This section describes each manifest constant that can be modifiedin order to tune the file system to your specifications.

Intel Environment TuningFor those users of Nucleus FILE whose target environment is a real-mode 80x86processor, the manifest constant FAR must be modified to indicate the far designator foryour compiler. For Microsoft and Borland compilers, the keyword is `far'. For the properdesignator for other compilers, please consult the compiler manuals

Device Driver ManifestsFor those customers using the IDE, FLOPPY, or RAMDISK drivers from AcceleratedTechnology, the appropriate manifests `IDE', `FLOPPY', and `RAMDISK' must bemodified. If you purchased the driver, change the manifest value from 0 to 1.

Nucleus PLUS RAM Disk Usage on Intel PlatformsIf you purchased the RAM Disk driver, are using Nucleus PLUS, and you need toallocate a RAM Disk greater than 64Kbytes, you must modify the manifestRAMDISK_FROMPOOL. Setting this manifest to 0 will cause the RAM Disk code toallocate memory by using the DOS based malloc service. If you need a RAM Disk ofgreater than 64Kbytes in an Intel real-mode 80x86 environment, you must setRAMDISK_FROMPOOL to 0.

Nucleus FILE Reference Manual

13

RAM Disk TuningThere are three manifest constants that determine the size of a RAM Disk. If youpurchased the RAM Disk and you wish to change the size from the default size, you willneed to modify one or all of these manifests.

NUM_RAMDISK_PAGES - This manifest is the number of RAM Disk pages that the systemwill use. Each page is 512 bytes in length. The size of the RAM Disk is determined bymultiplying this value times the RAMDISK_PAGE_SIZE manifest.

RAMDISK_PAGE_SIZE - This manifest is the number of RAM Disk Pages that will beused in the RAM Disk.

NRAMDISKBLOCKS - This manifest combines the NUM_RAMDISK_PAGES and theRAMDISK_PAGE_SIZE to determine the total number of blocks in the RAM Disk.

To determine how large a RAM Disk you will be using, multiply the number of pagestimes the page size times 512 bytes. The following example allocates a 64Kbyte RAMDisk.

#define NUM_RAMDISK_PAGES 16#define RAMDISK_PAGE_SIZE 8#define NRAMDISKBLOCKS (NUM_RAMDISK_PAGES*RAMDISK_PAGE_SIZE)

Multitasking DefinitionYou must indicate to the system how many tasks will be accessing Nucleus FILE. This isdone to enable the bounds of certain internal tablesto be set. In order to inform the systemof how many tasks will be used, modify the manifest constant NUM_USERS.

Chapter 3 - Porting and Tuning

14

File System Capacity TuningNucleus FILE can handle multiple tasks accessing multiple drives. The amount ofmemory necessary for doing so can be tuned so that you can optimize between theamount of memory used and the throughput that you require. The following manifestsprovide this tuning capability.

Tasks DescriptionNDRIVES This manifest designates the number of drives that will be

supported by Nucleus FILE. For example: a value of 1 equals A:only, 2 equals A: and B:, 3 equals A:, B: and C:. etc. This effectsthe amount of storage allocated in PC_MEMRY.C. The device tablein DEVTABLE.C must have one entry per drive.

NBLKBUFFS This manifest designates the block buffer pool size. Set this to thenumber of disk block buffers you desire. This is the number ofdisk blocks that will be buffered for directory traversal routines.The buffer pool is shared by all drives in the system. Setting thisvery high will improve disk traversal performance. Each buffertakes 536 bytes.

NUSERFILES This manifest designates the maximum number of files. Set this tothe maximum number of simultaneous files you will have open.This is the number of files that may be opened at one time. Thereis a fixed cost - approximately 100 bytes per file.

EMAXPATH This manifest designates the maximum path string. Set this to thelongest supported path name. This is the maximum path stringlength supported. If it is set high Nucleus FILE will use slightlymore stack. It is set to 148 in the generic PCDISK.H file. This isenough for a path that is 10 subdirectories deep. On memory leansystems you may want to change this. Beware of making themaximum string length too small for your application.

Tuning Nucleus FILE for Nucleus RTX or Nucleus PLUSNucleus FILE uses the multitasking capabilities of Nucleus RTX and Nucleus PLUS topermit multi-task access to file services. These capabilities include events, semaphores(called resources in Nucleus RTX), and fixed memory partition management. In order tosupply Nucleus FILE with these resources, certain files are supplied with the file system.These files depend on the kernel being used. For Nucleus RTX the file is IN_DATA.C,for Nucleus PLUS, two files, NUFI.C and NUFP.C are supplied. This sectiondiscusses the portions of these files that may need to be modified for your installation ofNucleus FILE.

Modifying IN_DATA.C (Nucleus RTX)There are at least two versions of IN_DATA.C supplied with each delivery of NucleusFILE. One version is maintained in the main directory of the distribution software. Theother(s) is maintained in the demonstration directory(s).

Nucleus FILE Reference Manual

15

How IN_DATA.C is modified depends on the configuration of your file systemenvironment. Primarily, changes center around the number of drives that you will beusing. A few other considerations are mentioned at the end of this section that mayconcern your system. First, however, we will discuss the implication of reducing orincreasing the number of disks that your file system will support.

Modifying IN_Fixed_PartitionsIN_Fixed_Partitions is a table included in Nucleus RTX deliveries in the fileIN_DATA.C. This table contains information that Nucleus RTX uses to determine thememory and system requirements for fixed memory partitions. The special version ofIN_DATA.C found in the main directory of the Nucleus FILE software contains aversion of IN_Fixed_Partitions which, in addition to the standard partitions that arerequired regardless of how many disks are used, also contains entries for five FileAllocation Table (FAT) partitions. These are named NUF_FAT_PARTITION_x_SIZE,where x is equal to the drive letters A: through E:. In addition, a special entry is suppliedfor the RAM Disk partition.

Depending on the number of drives that you require in your system, you will be requiredto modify DEVTABLE.C, PC_MEMRY.C, and PCDISK.H. In these files, you willdeclare one FAT partition for each drive your system will support. You must ensure thatthere is an entry for each of these in IN_Fixed_Partitions. Use the files in your maindirectory for an example of the correlation between these four files. In addition, you mustensure that the indices for the partitions are declared properly in PCDISK.H. This isdone by ensuring that the manifest NUF_USER_PARTITION is equal to the numbercorresponding to the first file system partition (NUF_USER_PARTITION_SIZE entry) inthe table IN_Fixed_Partitions.

Further, you will want to ensure that your application does not use any indices for apartition, which falls between the value of NUF_USER_PARTITION and the last partitionused by the file system.

Chapter 3 - Porting and Tuning

16

Modifying IN_System_Event_GroupsNucleus FILE uses at least three event groups per drive plus one for each INODE entry(NDRIVES * 3 + NFINODES) plus any that are required by ATI disk drivers. Pleasesee the definition in the PCDISK.H file included in the main directory of the file systemrelease for the manifest NUF_NUM_EVENTS.

This value should be used in defining IN_System_Event_Groups in IN_DATA.C.Unless you change the value of the manifest NUF_FIRST_EVENT_NUMBER inPCDISK.H, your system usage of events should begin at the index ofNUF_NUM_EVENTS (the index is 0 based, since NUF_FIRST_EVENT_NUMBER is definedas 0, the first non-file system event should be NUF_NUM_EVENTS). If you modifyNUF_FIRST_EVENT_NUMBER, be aware of the affect on any additional event groups thatyour system uses which are defined after the event groups for Nucleus FILE.

Modifying IN_System_ResourcesNucleus FILE only uses one resource identified by the manifestNUF_FILE_SYSTEM_MUTEX defined in file PCDISK.H. This resource is declared asindex 0, which means that any other resources used by your system should be indexedstarting at NUF_NUM_RESOURCES (for the same reason as stated in section above). Onceagain, if you modify NUF_FILE_SYSTEM_MUTEX, you should consider its new valuewhen adding resources in your system.

Modifying Nucleus FILE For Nucleus PLUSThere are two additional files which must be modified when using Nucleus FILE withNucleus PLUS. NUFI.C is primarily the initialization file for the demonstrationprogram. However, it does invoke NUFP_Initialize, which must be invoked by yourapplication. NUFP.C contains the initialization of the Nucleus PLUS componentsrequired by Nucleus FILE. The following sections describe in more detail the functionsand required modifications for each of these files.

Nucleus FILE Reference Manual

17

Modifying NUFI.CNUFI.C contains Application_Initialize. This is the function that receives controldirectly from Nucleus PLUS at initialization. It is normally used to start the primary tasksin your system. The NUFI.C file shipped in the main directory of the file systemrelease contains the initialization of a number of tasks that are used in one of thedemonstration files shipped with some versions of Nucleus FILE. This file is used as astarting point, since there are five initialized tasks. However, in most situations, this filewill need to be modified. Not only to remove tasks that your system does not use, butalso to make sure that memory allocations are performed properly.

The removal of tasks from Application_Initialize is a straightforward processand will not be discussed here. But, the allocation of system memory is very importantand needs to be discussed. When Application_Initialize is called by NucleusPLUS, it is passed a pointer to the first available memory address known to NucleusPLUS. However, Nucleus PLUS has no way of knowing how much memory is availablebeyond this address. That is an application specific detail. (In the version of NUFI.Cthat you receive, it was based on the MS-DOS port in which case Nucleus PLUSallocated the memory using malloc and therefore knows the size. This is the exceptionrather than the rule.). You will need to be aware of how much memory is available afterthis point and ensure that enough memory is available for Nucleus FILE.Application_Initialize in NUFI.C uses the memory pool System_Memory toassign a control pointer to the memory it allocates for system usage. If you do not usethis name, you must change the places in NUFI.C and NUFP.C that use it.

One final note regarding NUFI.C. There is a table in NUFI.C which converts NucleusRTX based task indices into Nucleus PLUS task pointers. This table was only installed tomake the demonstration programs work with both Nucleus RTX and Nucleus PLUS. Ifyou are not using the demonstration program, you can ignore this table.

Modifying NUFP.CNUFP.C contains the initialization of Nucleus PLUS objects that are necessary for thefile system to run. As with modifying IN_DATA.C for Nucleus RTX, NUFP.C ismodified based on the configuration of your file system. However, since Nucleus PLUSis not constrained by specific indexes for fixed partitions, events, and semaphores, thereis less coordination required with the rest of the system when using Nucleus PLUS.

All required modification for Nucleus FILE requirements are made to the routineNUFP_Initialize. For each fixed memory partition used by Nucleus FILE, there is acall to NU_Allocate_Memory and NU_Create_Partition_Pool.

Chapter 3 - Porting and Tuning

18

NOTE: It is important that there is available memory in the system memory pool whenallocating memory for Nucleus PLUS objects associated with Nucleus FILE. Currently,the routine Application_Initialize, located in file NUFI.C receives a pointerfrom Nucleus PLUS at invocation and allocates enough memory for use by the filesystem and the few tasks used in the demonstration programs. If you are going to changethe way that the system first allocates memory in Application_Initialize, you willneed to make sure to make the appropriate changes in NUFP.C. Namely, change thelocation that memory is allocated from, if it is different than the area currently used bythe demonstration programs.

If you alter the number of drives used by the system, you should remove the calls toNU_Allocate_Memory and NU_Create_Partition_Pool in NUFP_Initializefor the File Allocation Tables that are not required. Further, if you do not use the RAMDisk, you should move the associated calls to NU_Allocate_Memory andNU_Create_Partition_Pool. Since there is only one Semaphore required byNucleus FILE, no further modification is necessary in NUFP_Initialize, which isassociated with creating the semaphore.

The number of event groups required by Nucleus FILE, as defined in PCDISK.H (seeprevious section - Modifying NUFI.C), controls the allocation of event groups inNUFP_Initialize. Therefore, no modification to NUFP_Initialize is required forevent groups as long as the value in PCDISK.H is correct.

19

Chapter 4 – User Interfaces

4

UserUserInterfacesInterfaces

User InterfacesUser Interfaces

Chapter 4 - User Interfaces

20

Major Data StructuresThe following section discusses the major data structures used in Nucleus FILE.

DDRIVEContains drive specific information, such as the location of the FAT, the size of the rootdirectory, the total size of the volume, the number of duplicate FATs, and the number ofblocks per cluster. Also, the packages in memory FAT buffers are accessed via pointersin this structure.

DOSINODEThis is an exact image of a DOS directory entry. Fields include filename, creation date,file attributes, file size and the cluster number for the start of data.

This structure is used to access the directory entries in the data buffers. pc_ino2dos()and pc_dos2inode are used to transfer data from the package's internal view to the diskimage and back.

FINODEThis contains information for individual file or subdirectory entries. The structurecontains the "DOSINODE" information stored in native byte order. It also contains otheruseful information such as a pointer to the drive's DDRIVE structure and enoughinformation to locate the directory entry on disk.

FINODES are stored in a common pool and may be "opened" by several files at once; thisfeature should allow integration of multi-tasking features.

BLKBUFFAll subdirectory and root directory access is through a write through buffer pool based onthis structure. A buffer pool provides tunable memory usage, usable buffer managementin multi-tasking systems, and higher performance due to reduced disk activity forfrequently accessed paths. The least recently used (LRU) algorithm is used to determinewhat buffers to discard when a new buffer is to be read in. Buffers are locked duringcritical operations.

The structure is allocated and initialized by calling NU_Open_Disk() all neededinformation is read from block zero. Calling NU_Close_Disk causes the FAT buffers tobe flushed and all storage associated with the DDRIVE structure to be freed.

DROBJThis object is a self-contained representation of a file, volume label or sub-directoryentry. It provides access to the DDRIVE structure for drive specific information, theFINODE structure for file/sub-directory content and position information and it providesconvenient access to the BLKBUFF structure that contains the DOS directory entry.

(This is only meaningful when the buffer is locked.) The DROBJ structure is common toall code that manipulates directory entries (files & subdirectories). DROBJ'S are createdby calling pc_fndnode() and they are freed by calling pc_freeobj().

Nucleus FILE Reference Manual

21

PCFILEThis structure is used to implement the random access file capability. It contains a clustersized read/write buffer, a file pointer, and a link to the DROBJ structure controlling thedirectory entry. File descriptors (FDs) are indices into an array of pointers to thesestructures. PCFILE structures are created by calling NU_Open() and destroyed bycalling NU_Close().

DSTATThis structure is used by NU_Get_Next and NU_Done to traverse the file system. Itcontains private information used to keep track of where the next directory entry residesand public information used to report the status of a directory entry back to the user.DSTAT structures are created by calling NU_Get_First() and destroyed by callingNU_Done().

User InterfacesNucleus FILE has the most common user interfaces isolated to one source file(NU_FILE.C ). The following section describes all of the interfaces, their invocation,return status and examples. This should serve as the primary reference manual forNucleus FILE. All routines can be accessed if the Nucleus library is linked with the userapplication. It is also advisable to include PCDISK.H in the source files that accessNucleus FILE services so that warnings and possible errors can be avoided.

Chapter 4 - User Interfaces

22

NU_Close

INT NU_Close(fd)

This will close the file updating the disk, freeing all core associated with fd.

ParametersParameter Meaningfd (PCFD) The file descriptor of the file to be closed.

Return Value

Status Meaning0 If all went well.-1 If not successful.p_errno Set to PENBADF, Invalid file descriptor.

Example#include <posix.h>

PCFD fd;IMPORT INT p_errno;

if (pc_close(fd) < 0) printf("Error closing file:%i\n", p_errno)

Nucleus FILE Reference Manual

23

NU_Close_Disk

BOOL NU_Close_Disk(path)

Given a path name containing a valid drive specifier, this will flush the file allocationtable and purge any buffers or objects associated with the drive.

ParametersParameter Meaningpath (*TEXT) Specifies the drive letter for the disk to be closed.

Return ValueStatus MeaningYES DiskClose request completed successfully.

Example#include <pcdisk.h>

NU_Close_Disk("A:");

Chapter 4 - User Interfaces

24

NU_Current_Dir

BOOL NU_Current_Dir (drive, path)

This fills in a string with the full path name of the current working directory. It returnsNO if is unable to fill in the string. If the pointer to the drive structure is null or an invaliddrive specifier the default drive is used.

ParametersParameter Meaningdrive (*TEXT) The letter of the drive for which the current directory is requested.path (*TEXT) Specifies the drive letter for the disk to be opened.

Return ValueStatus MeaningYES If successful.NO If not successful.path The path name of the current directory.

ExampleTEXT pwd[MAXPATH];

if (NU_Current_Dir("A:", pwd)) printf ("Working dir is %s", pwd);else printf ("Can't find working dir for A:");

Nucleus FILE Reference Manual

25

NU_Delete

BOOL NU_Delete(name)

This will delete the file specified in name. It will fail if the file is not a simple file, if it isopen, if it does not exist, or if it is read only.

ParametersParameter Meaningname (*TEXT) Pathname of the file to be deleted.

Return ValueStatus MeaningYES If it successfully deleted the file.

Example#include <pcdisk.h>

if (! NU_Delete("B:\USR\TEMP\TMP001.PRN")) printf("Cant delete file \n")

Chapter 4 - User Interfaces

26

NU_Disk_Abort

VOID NU_Disk_Abort(path)

This will abort all operations on a disk. If an application senses that there are problemswith a disk, it should call NU_Disk_Abort("D:"). This will cause all resourcesassociated with that drive to be freed, and no disk writes will be attempted. All filedescriptors associated with the drive become invalid. After correcting the problem callNU_Open_Disk("D:") to re-mount the disk and re-open your files.

ParameterParameter Meaningpath (*TEXT) Specifies the drive letter on which to abort the operation.

Return ValueNone

Nucleus FILE Reference Manual

27

Example#include <posix.h>

unsigned int trying;PCFD pcfd;

trying = YES;

while (trying){ if (pcfd = NU_Open("A:\USR\MYFILE", (PO_CREAT|PO_WRONLY), PS_IWRITE) < 0)) { /* Get out at next opportunity */ trying = NO;

/* Display error message */ printf("Cant create file error:%i\n",p_errno);

/* See if there is a disk error. */ if (ask_driver_if_there_is_a_problem("A:")) { /* Clear everything so we can get a fresh start */ NU_Disk_Abort("A:");

/* Try to fix it */ if (driver_fix_it("A:"))) { /* Reopen it */ if (pc_diskopen("A:")) trying = YES; } } }

}

Chapter 4 - User Interfaces

28

NU_Done

VOID NU_Done(statobj)

This will free internal resources used by NU_Get_Next and NU_Get_First. Given apointer to a DSTAT structure that has been set up by a call to NU_Get_First() freeinternal elements used by the statobj.

NOTE: You MUST call this function when done searching through a directory.

ParameterParameter Meaningstatobj (*DSTAT) Pointer to a data structure, which maintains

file/subdirectory information useful in traversing adirectory tree.

Return ValueNone

Example#include <pcdisk.h>

DSTAT statobj;

A simple directory list subroutine.if (NU_Get_First(&statobj, path)){ while (YES) { if (statobj.fattribute & AVOLUME) dirstr = "<VOL>"; else if (statobj.fattribute & ADIRENT) dirstr = "<DIR>"; else dirstr = " ";

printf("%-8s.%-3s %7ld %5s \n", statobj.fname, statobj.fext,statobj.fsize,dirstr);

if (!NU_Get_Next(&statobj)) break; }}

/* Call gdone to free up internal resources used by statobj */NU_Done(&statobj);

Nucleus FILE Reference Manual

29

NU_Flush

BOOL NU_Flush(PCFD fd)

This interface moves all data in a file's buffer onto the disk.

ParametersParameter Meaningfd (PCFD) File descriptor for the file to be flushed.

Return ValueStatus MeaningYES Operation successful.NO Error occurred; p_errno will be modified.

p_errnoThe following table summarizes the possible values for the p_errno parameter.

Value MeaningPENBADF Invalid file descriptor.PENOSPC IO error occurred.

Chapter 4 - User Interfaces

30

NU_Format

BOOL NU_Format(driveno, pfmt)

Given a drive number and a format parameter block, this function will put an MS-DOSfile system on the drive. The disk MUST already have a low-level format. All blocks onthe drive should be initialized with E5's or zeros.

NOTE: Nucleus FILE will perform a low-level format of a floppy disk.

Some common parameters are listed below. For other drive types, use debug to get theparameters from block zero after running FORMAT.

Parameter Drive Size360 720 20M

oemname N/A N/A N/Asecpalloc 2 2 4secreserved 1 1 1numfats 2 2 2numroot 0x70 0x70 0x200mediadesc 0xFD 0xF9 0xF8secpfat 2 3 44secptrk 9 9 0x11numhead 2 2 4numtrk 40 80 612

oemname is user definable up to 8 chars, space padded to the left.

ParametersParameter Meaningdriveno (COUNT) The physical drive number of the drive to be formatted.pfmt (*FMTPARMS) A pointer to a data structure that contains the parameters

Return ValueStatus MeaningYES If the file system disk was successfully initialized.

Nucleus FILE Reference Manual

31

Example#include <pcdisk.h>

FMTPARMS fmt;

/* Make a file system on a 360 K floppy drive. (assumed to be drive 0) */

strcpy(&fmt.oemname[0], "EBS");fmt.secpalloc = (UTINY) 2;fmt.secreserved = (UCOUNT) 1;fmt.numfats = (UTINY) 2;fmt.numroot = (UCOUNT) 0x70;fmt.mediadesc = (UTINY) 0xFD;fmt.secptrk = (UCOUNT) 9;fmt.secpfat = (UTINY) 2;fmt.numhead = (UCOUNT) 2;fmt.numtrk = (UCOUNT) 40;

if (!NU_Format(0, &fmt )) printf("Format failed \n");

Chapter 4 - User Interfaces

32

NU_FreeSpace

LONG NU_FreeSpace(path)

Given a path containing a valid drive specified, this will count the number of free byteson the drive.

ParametersParameter Meaningpath (*TEXT) Specifies the drive letter for the disk for calculating available

bytes.

Return ValueStatus MeaningLONG Number of free bytes.0 If the drive is full, not open, or out of range.

Example#include <pcdisk.h>

printf("%l bytes remaining \n",NU_FreeSpace("A:") );

Nucleus FILE Reference Manual

33

NU_Get_Default_Drive

COUNT NU_Get_Default_Drive()

Use this function to get the current default drive when a path specifier does not contain adrive specifier. (See also NU_Set_Default_Drive().)

Return ValueThe current default drive.

Example#include <pcdisk.h>

if (path[1] != ':') driveno = NU_Get_Default_Drive();else driveno = path[0] - 'A';

Chapter 4 - User Interfaces

34

NU_Get_First

BOOL NU_Get_First(statobj, pattern)

This gets the first entry in a directory to match a pattern. Given a pattern that containsboth a path specifier and a search pattern, this will fill in the structure at statobj withinformation about the file and set up internal parts of statobj to supply appropriateinformation for calls to NU_Get_Next.

Examples of patterns are:

"D:\USR\RELEASE\NETWORK\*.C""D:\USR\BIN\UU*.*""D:MEMO_?.*""D:*.*"

ParametersParameter Meaningstatobj (*DSTAT) Pointer to a data structure which maintains file/

sub-directory information useful in traversing a directorytree.

pattern (*TEXT) A string that represents the first directory entry searchedfor. See the previous examples.

Return ValueStatus MeaningYES If a match was found.NO All other cases.

Nucleus FILE Reference Manual

35

Example#include <pcdisk.h>

DSTAT statobj;

/* A simple directory list subroutine. */

if (NU_Get_First(&statobj, path)){ while (YES) { if (statobj.fattribute & AVOLUME) dirstr = "<VOL>"; else if (statobj.fattribute & ADIRENT) dirstr = "<DIR>"; else dirstr = " ";

printf("%-8s.%-3s %7ld %5s \n", statobj.fname, statobj.fext,statobj.fsize,dirstr);

if (!NU_Get_Next(&statobj)) break; }}

/* Call gdone to free up internal resources used by statobj */NU_Done(&statobj);

Chapter 4 - User Interfaces

36

NU_Get_Next

BOOL NU_Get_Next(statobj)

This gets the next entry in a directory that matches a pattern. Given a pointer to aDSTAT structure that has been set up by a call to NU_Get_First(), this will search forthe next match of the original pattern in the original path. It will return yes if found andupdate STATOBJ for subsequent calls to NU_Get_Next.

ParametersParameter Meaningstatobj (*DSTAT) Pointer to a data structure, which maintains

file/subdirectory information useful in traversing adirectory tree.

Return ValueStatus MeaningYES If a match was found.NO All other cases.

Example#include <pcdisk.h>

DSTAT statobj;

/* A simple directory list subroutine. */if (NU_Get_First(&statobj, path)){ while (YES) { if (statobj.fattribute & AVOLUME) dirstr = "<VOL>"; else if (statobj.fattribute & ADIRENT) dirstr = "<DIR>"; else dirstr = " ";

printf("%-8s.%-3s %7ld %5s \n", statobj.fname, statobj.fext,statobj.fsize,dirstr);

if (!NU_Get_Next(&statobj)) break; }}

/* Call gdone to free up internal resources used by statobj */NU_Done(&statobj);

Nucleus FILE Reference Manual

37

NU_Make_Dir

BOOL NU_Make_Dir(name)

This interface will create a subdirectory in the path specified by name. It will fail if a fileor directory of the same name already exists or if the path is not found.

ParametersParameter Meaningname (*TEXT) Specifies the name of the new directory.

Return ValueStatus MeaningYES If it was able to create the directory.NO All other cases.

Example#include <pcdisk.h>

if (!NU_Make_Dir("\USR\LIB\HDRS\SYS") printf("Cant create subdirectory\n");

Chapter 4 - User Interfaces

38

NU_Open

PCFD NU_Open(name, flag, mode)

This will open the file for access as specified in flag. If creating, it will use mode toset the access permissions on the file.

ParametersParameter Meaningname (*TEXT) The path name of the file to be opened.flag (UCOUNT) Specifies the access type to associate with this file descriptor.mode (UCOUNT) Specifies the read/write mode to associate with this file descriptor.

Access TypeThe following table summarizes the possible values for the flag parameter.

Parameter MeaningPO_APPEND Seek to end of file before all writes.PO_BINARY Ignored. All file access is binary.PO_TEXT Ignored.PO_RDONLY Open for read only.PO_RDWR Read/write access allowed.PO_WRONLY Open for write only.PO_CREAT Create the file if it does not exist. Use mode to specify the

permission on the file.PO_EXCL If flag contains (PO_CREAT | PO_EXCL) and the file already

exists, fail and set p_errno to EEXIST.PO_TRUNC Truncate the file if it already exists

Read/WriteThe following table summarizes the possible values for the mode parameter.

Parameter MeaningPS_IWRITE Write permitted.PS_IREAD Read permitted. (Always true)

Return ValueStatus MeaningPCFD A non-negative integer to be used as a file descriptor for calling

read/write/seek/close.-1 Error occurred; p_errno will be modified.

Nucleus FILE Reference Manual

39

p_errno

The following table summarizes the possible values for p_errno.

Value MeaningPENOENT File not found or path to file not found.PEMFILE No file descriptors available. (Too many files open.)PEEXIST Exclusive access requested but file already exists.PEACCESS Attempt to open a read only file or a special (directory) file.

Example#include <POSIX.H>

PCFD fd;IMPORT INT p_errno;

if (fd = NU_Open("\USR\MYFILE", (PO_CREAT|PO_EXCL|PO_WRONLY), PS_IWRITE)<0)) printf("Cant create file error:%i\n",p_errno)

Chapter 4 - User Interfaces

40

NU_Open_Disk

BOOL NU_Open_Disk(path)

Given a path spec containing a valid drive specifier, this will open the disk by reading allof the block zero information and converting it to native byte order; then, reading the fileallocation table.

NOTE: This routine must be called after pc_memory_init and before any others. Seethe tutorial for details.

ParametersParameter Meaningpath (*TEXT) Specifies the drive letter for the disk to be opened.

Return ValueStatus MeaningYES If the disk was successfully initialized.

Example#include <pcdisk.h>

NU_Open_Disk("A:");

or

NU_Open_Disk("A:\USR\FOO");

Nucleus FILE Reference Manual

41

NU_Read

COUNT NU_Read(fd, buf, count)

This will attempt to read count bytes from the current file pointer of file at fd and putthem in buffer. The file pointer is updated.

ParametersParameter Meaningfd (PCFD) File descriptor for the file to be read from.buf (UTINY) Buffer to be filled by the read.count (COUNT) Number of bytes to be read.

Return ValueStatus MeaningCOUNT The number of bytes read.-1 If an error occurs.p_errno Set to PENBADF, File descriptor invalid.

Example#include <posix.h>

PCFD fd;PCFD fd2;IMPORT INT p_errno;

if((fd=pc_open("FROM.FIL",PO_RDONLY,0)) >= 0) if((fd2=pc_open("TO.FIL", PO_CREAT|PO_WRONLY, PS_IWRITE)) >= 0) while(NU_Read(fd, buff, 512) > 0) NU_Write(fd2, buff, 512);

Chapter 4 - User Interfaces

42

NU_Remove_Dir

BOOL NU_Remove_Dir(name)

This deletes the directory specified in name. It will fail if name is not a directory, is readonly, or contains more than the entries.

ParametersParameter Meaningname (*TEXT) A string representing the pathname of the directory to be

removed.

Return ValueStatus MeaningYES If the directory was successfully removed.NO If the directory was not successfully removed.

Example#include <pcdisk.h>

if (!NU_Remove_Dir("D:\USR\TEMP") printf("Cant delete directory\n");

Nucleus FILE Reference Manual

43

NU_Rename

BOOL NU_Rename(name, newname)

This renames the file in path (name) to newname. It will fail if new name is invalid, newname already exists, or its path not found. It does not test if name is a simple file.

ParametersParameter Meaningname (*TEXT) The pathname of the file to be renamed.newname (*TEXT) The new pathname for the file being renamed.

Return ValueStatus MeaningYES If the file was renamed.NO If the name not found.

Example#include <pcdisk.h>

if (!NU_Rename("\USR\TXT\LETTER.TXT", "LETTER.OLD")) printf("Cant rename LETTER.TXT");

Chapter 4 - User Interfaces

44

NU_Seek

LONG NU_Seek(fd, offset, origin)

This will move the file pointer offset bytes from the origin specified. The file pointer isset according to the following rules. Attempting to seek beyond end of file puts the filepointer one byte past eof.

ParametersParameter Meaningfd (PCFD) File descriptor for the file, which is having its pointer

moved.offset (LONG) Number of bytes the pointer is to be moved.origin (COUNT) Location in the file to begin processing.

OriginThe following table summarizes the possible values for the origin parameter.

Parameter MeaningPSEEK_SET Offset from beginning of file.PSEEK_CUR Offset from current file pointer.PSEEK_END Offset from end of file.

Return ValueStatus MeaningNew offset If successful.-1 If not successful.p_errno Error occurred; p_errno will be modified.

p_errnoThe following table summarizes the possible values for thep_errno parameter.

Value MeaningPENBADF File descriptor invalidPEINVAL Seek to negative file pointer attempted.

Example#include <posix.h>

PCFD fd;

if ((fd = pc_open("FROM.FIL",PO_RDWR,0)) >= 0) if (NU_Seek(fd, (recsize*recno), PSEEK_SET) != (recsize*recno)) printf("Cant find record %i\n",recno);

Nucleus FILE Reference Manual

45

NU_Set_Current_Dir

BOOL NU_Set_Current_Dir(path)

This interface finds path specified. If the path is a subdirectory, it will make it the currentworking directory for the drive.

ParametersParameter Meaningpath (*TEXT) A string representing the path name of the directory that is

to become the current working directory.

Return ValueStatus MeaningYES If the current working directory was changed.

Exampleif (!NU_Set_Current_Dir("D:\USR\DATA\FINANCE")) printf("Can't change working directory\n");

Chapter 4 - User Interfaces

46

NU_Set_Default_Drive

BOOL NU_Set_Default_Drive(TEXT *drive)

This function sets the current default drive that will be used when a path specifier doesnot contain a drive specifier. NOTE: The default is zero (drive A:)

ParametersParameter Meaningdrive (*TEXT) The drive letter of the drive to become the default.

Return ValueStatus MeaningNO If the specified drive is out of range.

Nucleus FILE Reference Manual

47

NU_Set_Default_Drive_Number

BOOL NU_Set_Default_Drive(driveno)

Use this function to set the current default drive that will be used when a path specifierdoes not contain a drive.

NOTE: The default is zero (drive A:) See also NU_Get_Default_Drive().

ParametersParameter Meaningdriveno (COUNT) The number of the drive to become the current default

drive.

Return ValueStatus MeaningNO If the drive is out of range.

Example#include <pcdisk.h>

In a shell program respond to:

SETDFLT D:if (command == SETDFLT)if (cmd[2] == '\0')if (cmd[1] != ':')NU_Set_Default_Drive( cmd[0] - 'A');

Chapter 4 - User Interfaces

48

NU_Truncate

BOOL NU_Truncate(fd, offset)

This interface moves the file pointer offset bytes from the beginning of the file andtruncates the file beyond that point by adjusting the file size and freeing the cluster chainpast the file pointer.

ParametersParameter Meaningfd (PCFD) File descriptor for the file to be flushed.offset (LONG) The place within the file at which the truncation is to

begin.

Return ValueStatus MeaningYES Operation SuccessfulNO Error occurred; p_errno will be modified.

p_errnoThe following table summarizes the possible values for the p_errno parameter.

Value MeaningPENBADF File descriptor invalid or open read only.PENOSPC IO error.PEINVAL Invalid offset.PESHARE Can not truncate a file open by more than one handle.

Nucleus FILE Reference Manual

49

NU_Write

COUNT NU_Write(fd, buf, count)

This will attempt to write count bytes from buffer specified to the current file pointer offile at fd. The file pointer is updated.

ParametersParameter Meaningfd (PCFD) File descriptor for the file to be written to.buf (UTINY) Buffer to be used to write from.count (COUNT) Number of bytes to be written.

Return Value

Status MeaningCOUNT The number of bytes written.-1 If an error occurs.p_errno Error occurred; p_errno will be modified.

p_errnoThe following table summarizes the possible values for the p_errno parameter.

Value MeaningPENBADF File descriptor invalid.PENOSPC Write failed. Presumably because of no space in the file.

Example#include <posix.h>

PCFD fd;IMPORT INT p_errno;

if (NU_Write(fd, buff, 512) < 0) printf("Cant write to file error:%i\n",p_errno)

Chapter 4 - User Interfaces

50

p_errno

IMPORT INT p_errno;

This will return error values from posix style functions.

Return ValueStatus Value MeaningPEBADF 9 Invalid file descriptorPENOENT 2 File not found or path to file not found.PEMFILE 24 No file descriptors available. (Too many files open.)PEEXIST 17 Exclusive access requested but file already exists.PEACCES 13 Attempt to open a read only file or a special directory.PEINVAL 22 Seek to negative file pointer attempted.PENOSPC 28 Write failed, presumably because of no space.

Example#include <pcdisk.h> printf (Error: %I\n, f_user -> p_errno);

51

A

Appendix A – Programming TipsThis appendix provides programming information for the Nucleus FILE system.

Programming TipsProgramming Tips

AppendixAppendix

Appendix A – Programming Tips

52

Romming codeThe package does not rely on a lot of statics. Copying the statics into ram should workfine at startup. If you use the supplied malloc/free routines you should change the waythe heap is initially allocated.

Stack requirementsSee the Target Specific Notes for Nucleus FILE for information on stack usage in theexample programs shipped with your package.

Error recoveryIf an application senses that there are problems with a disk, it should callNU_Disk_Abort("D:"). This will cause all resources associated with that drive to befreed, but no disk writes will be attempted. All file descriptors associated with the drivebecome invalid. After correcting the problem call NU_Open_Disk("D:") to re-mountthe disk and re-open your files.

NOTE: During this process it is possible for some data to be lost since the FATS will notbe flushed. To force FAT flushes more often you may close and reopen a file on the drivein question, or you may cheat by looking at the flushfat code directly (notrecommended).

53

B

Appendix B - Tutorial

TutorialTutorial

AppendixAppendix

Appendix B – Tutorial

54

This appendix provides a tutorial for the Nucleus FILE system.

We will study the flow of code for creating a subdirectory. This will hopefully providesome insight into the flow of the package and augment the individual functiondescriptions. The code described here contains the logic for manipulating directory trees.The code for implementing read/write/seek and buffer management is not described sinceits purpose is clearer and its flow should be derived from the source.

WARNING: This description is given to provide users with an overview of how thesystem works. Most of this code is at a lower level than you probably will need. Becareful that you are not re-inventing the wheel if you are coding in this area. Thisdocument is intended to document the flow of the software, not the implementationdetails, so some poetic license has been taken to throw away details where they wouldgum up the presentation. Beware !!

Getting Startedpc_memory_init() is called to initialize all of the memory necessary for systemoperation. This routine is found in the FILE PC_MEMRY.C and calls various routinesthat may need to be ported to your environment.

NU_Open_Disk("D:xxxxxx") is called.

NU_Open_Disk takes a string containing the drive letter as an argument and preparesthe drive for access. Block zero is read in and interesting drive constants such as thelocation the root directory are calculated and placed in the DDRIVE structure. The FATbuffer pool is initialized as well.

Creating a Directory Entry On DiskNU_Make_Dir("D:PATH\NEWSUBDIR") will call both pc_fndnode() andpc_mknode(). These routines eventually touch almost all of the code in the package sowe will discuss them and hopefully, in the process, explain the inner workings.

First NU_Make_Dir() needs to fail if the directory entry already exists, so it callspc_fndnode(). If this routine returns an initialized object then there is a problem.

pc_fndnode() is also used by the file open utilities, NU_Get_First(), andNU_Get_Next().pc_fndnode("D:PATH\DIREENTNAME") works as follows.

Parsedrive is called to convert the drive specifier to a drive number. If the drive specifierdoes not exist the current default drive is used.

Nucleus FILE Reference Manual

55

The drive number is converted to a pdrive structure via a lookup function.

If PATH does not begin with "\", NU_Current_Dir() is called to get an initializedDROBJ structure, which represents the current directory. If PATH does begin with "\",pc_get_root() retrieves the root directory. This DROBJ is now the root of the directorytree for searching.

pc_fndnode() now nibbles entry names off the path from left to right callingpc_get_inode() to find the name in the current entry. If the name is found the returnedDROBJ becomes the current starting point for subsequent searches.

When the path string is exhausted, the entry has been found. One minor detail. if the pathcontains '..\', pc_getmom() is called. This function essentially climbs the directorytree.

Let's look at pc_get_inode() since it takes us lower into the package:

pc_get_inode()'s arguments are a DROBJ (subdirectory) and a file name or wild cardpattern to find. If a second DROBJ is supplied (NON-NULL) it is assumed to represent alocation in the subdirectory to search from; otherwise pc_mkchild() is called toallocate space and clone the DROBJ, and searches begin from the beginning of thedirectory. Once the search object is established pc_findin() is called. pc_findin()takes the match pattern and the search object and tries to find pattern. If Pattern is found,the search object is updated to represent the entry that was matched. The search object isreturned if match was found, otherwise NULL is returned.

pc_mkchild() calls pc_allocobj() to allocate a DROBJ structure and a FINODEstructure that is linked to it. It then copies most of the parent information over. The "firstblock" field in the new DROBJ (The DROBJ'S view of what block chain its directoryentry is in) is ascertained from the parent DROBJ. The block information comes from thecluster information if the parent is a subdirectory or it is derived if the parent is root.

Note that we are talking about blocks, not clusters. The routines pc_firstblock(),pc_nextblock() and their subordinates provide the block abstraction. This allows mostof the code to view the root directory and subdirectories as the simultaneously, eventhough the root is a fixed contiguous block entity and subdirectories are dynamicallyallocated cluster entities.

pc_findin() looks through the blocks of a directory searching for a filename or patternmatch. The block numbers come from the firstblock/nextblock scheme as describedabove. Block numbers and offsets are stored in the DROBJ structure, so at any time it ispossible to tell what directory entry is represented.

At this point blocks need to be read from the disk. Block reads are done through thebuffer pool (pc_read_obj()). If the block exists in the pool there is no need to read itfrom disk. NOTE: the buffer pool read routine "locks" the buffer guaranteeing that it willnot be swapped out. This allows direct surgery on the buffer without causing problems.But the buffer must be manually unlocked.

Appendix B – Tutorial

56

The blocks are searched for the pattern. If it is found, the block number and index intothe block (and drive) are noted and the FINODE list is searched (pc_scani() ) to see ifthat very entry is being used by another file or directory traversal routine.

If it is being used, the FINODE's opencount is increased so the FINODE will not bedestroyed until the last user frees it. If it is not being used, a new FINODE structure iscreated (pc_alloci()) and the raw disk info is copied over (pc_dos2inode()) andthe FINODE is added to the list of open directory entries with an open count of one.

Once the FINODE is found and stitched into the DROBJ, the DROBJ is fully defined andis a useful entity for the user level code.

Now, back to NU_Make_Dir().

If pc_findnode() failed NU_Make_Dir() can now create a node by callingpc_mknode().

pc_mknode()'s job is to create a new directory entry in the root or in a subdirectory. Ifthe entry is a subdirectory it also creates the '.' and '..' entries; if the entry is a file,it zeroes the file size.

First, pc_mknode() calls pc_parsepath() to separate the path argument intofilename, extension and path. pc_fndnode() is called to find the subdirectory in path(it may be root), and return an initialized DROBJ structure representing the path.

A new DROBJ structure is created by calling pc_allocobj(). The DROBJ is initialized( pc_initinode() ) with the filename, extension, size, attributes and user supplieddate stamp info (pc_getsysdate() ). If the new entry is a subdirectory, someadditional processing is done to create a "file" containing '.' and '..'. The directoryattribute will be set later if the insertion succeeds.

The new DROBJ structure is inserted into the directory by calling pc_insert_inode().pc_insert_inode() works as follows:

It is called with two arguments, the parent DROBJ and the DROBJ to be inserted. Firstthe parent is searched for slots containing deleted or unused entries. The search is doneby scanning the directory blocks.

pc_firstblock() and pc_nextblock() provide a common interface for both the rootand subdirectories. The actual reading of the blocks is done with pc_readobj() whichuses the block buffer pool. If no slot is found and the parent is the root, it is an error (rootdirectory full).

Otherwise the subdirectory is extended by allocating a new cluster for the subdirectorywith pc_clgrow() and initializing an entry in the buffer pool for the first sector in thenew cluster.Once a directory entry slot has been found or created, the dirent information is copiedfrom the DROBJ's FINODE to the buffer pool (pc_ino2dos()) and the block in thebuffer pool is flushed.

The FINODE now represents an in-use directory entry so it is added to the activeshareable FINODE list with pc_marki().

Nucleus FILE Reference Manual

57

If the directory attribute needs to be set, it is, and the DROBJ is re-written to disk withpc_update_inode(). The file allocation table is flushed and we are done.

We have now completed making a directory.

Finishing UpNU_Close_Disk() is called.

NU_Close_Disk() takes a string containing the drive letter as an argument. It flushesthe file allocation table, purges the blockbuffer bool, the shared FINODE table, the openfile table, and releases all memory used by that drive. NOTE: Well behaved programsshould close all files on the drive before calling NU_Close_Disk() since no attempt ismade to flush the file's buffers.

Appendix B – Tutorial

58