diff --git a/arch/m68k-all/include/gencall.c b/arch/m68k-all/include/gencall.c index 50cb01549c2..5319a3f80f4 100644 --- a/arch/m68k-all/include/gencall.c +++ b/arch/m68k-all/include/gencall.c @@ -515,6 +515,16 @@ static const char libextra[] = "#define __AROS_LC3LONG __AROS_LC3\n" "#define __AROS_LC4LONG __AROS_LC4\n" "#define __AROS_LC5LONG __AROS_LC5\n" +"/* 64-bit results are returned in d0/d1, which the plain call macros\n" +" already reassemble, so these map straight through */\n" +"#define __AROS_LC2QUAD __AROS_LC2\n" +"#define __AROS_LC3QUAD __AROS_LC3\n" +"#define __AROS_LC4QUAD __AROS_LC4\n" +"#define __AROS_LC5QUAD __AROS_LC5\n" +"#define __AROS_LC2UQUAD __AROS_LC2\n" +"#define __AROS_LC3UQUAD __AROS_LC3\n" +"#define __AROS_LC4UQUAD __AROS_LC4\n" +"#define __AROS_LC5UQUAD __AROS_LC5\n" "\n" "# define AROS_LDQUAD1(t,n,q1,bt,bn,o,s) \\\n" " __AROS_LD_PREFIX t AROS_SLIB_ENTRY(n,s,o) ( \\\n" diff --git a/arch/m68k-amiga/boot/mmakefile.src b/arch/m68k-amiga/boot/mmakefile.src index 82f84577cc3..a141ef59894 100644 --- a/arch/m68k-amiga/boot/mmakefile.src +++ b/arch/m68k-amiga/boot/mmakefile.src @@ -32,6 +32,7 @@ include $(SRCDIR)/config/aros.cfg #MM kernel-diag-kobj \ #MM kernel-disk-kobj \ #MM kernel-dos-kobj \ +#MM kernel-dos64-kobj \ #MM kernel-dosboot-kobj \ #MM kernel-expansion-kobj \ #MM kernel-filesystem-kobj \ @@ -165,7 +166,7 @@ AFILES := ext_entry # APOLLOROM = V4 -> Native V4 ifeq ($(APOLLOROM),V4) - KLIBS := keymap graphics layers intuition gadtools workbench mathffp mathieeesingbas freeanim lowlevel setpatch + KLIBS := keymap graphics layers intuition gadtools workbench mathffp mathieeesingbas freeanim lowlevel setpatch dos64 KDEVS := sagasd ata trackdisk KHNDLRS := con KHIDDS := bus storage system diff --git a/arch/m68k-amiga/filesys/afs/make.opts b/arch/m68k-amiga/filesys/afs/make.opts new file mode 100644 index 00000000000..bf62bfb68d6 --- /dev/null +++ b/arch/m68k-amiga/filesys/afs/make.opts @@ -0,0 +1,5 @@ +# Copyright (C) 2026, The AROS Development Team. All rights reserved. + +# Share requester wrappers to keep the Amiga filesystem handler within its +# ROM budget. Other targets use the generic inline default. +AFS_INLINE_REQUESTERS := 0 diff --git a/compiler/include/dos/dos.h b/compiler/include/dos/dos.h index 9fbb80fe511..cbbe3359372 100644 --- a/compiler/include/dos/dos.h +++ b/compiler/include/dos/dos.h @@ -60,10 +60,31 @@ struct DateStamp this value, as it may change in future versions. */ #define MAXCOMMENTLENGTH 80 +/* + * 64-bit integers in the DOS structures below follow the Amiga ABI, where + * they are only 2-byte aligned (the MorphOS headers use pack(2)). 32-bit + * ARM and PowerPC compilers align them to 8 bytes by default, which would + * move them away from the offsets other systems and binary handlers use. + * 64-bit AROS has no foreign layout to match and keeps natural alignment. + */ +#if (__WORDSIZE == 64) +#define AROS_DOS64_ALIGN +#else +#define AROS_DOS64_ALIGN __attribute__((__packed__, __aligned__(2))) +#endif + /* Structure used to describe a directory entry. Note that not all fields are supported by all filesystems. This structure should be allocated - with AllocDosObject(). */ -struct FileInfoBlock64 + with AllocDosObject(). + + The 64-bit size fields (fib_Size64, fib_NumBlocks64) overlay the reserved + area as defined by MorphOS (tm) V51. They are filled by the 64-bit examine + calls (dos64.library Examine64(), ExNext64(), ExamineFH64(), packets + ACTION_EXAMINE_OBJECT64, _NEXT64, _FH64). Everything before them keeps + the classic layout, so the block is the same size as before and the + 32-bit calls can use it as well. fib_DiskKey is IPTR as handlers may + store a pointer in it. */ +struct FileInfoBlock { IPTR fib_DiskKey; /* See for definitions. Generally: if this is >= 0 @@ -81,49 +102,47 @@ struct FileInfoBlock64 UBYTE fib_FileName[MAXFILENAMELENGTH]; LONG fib_Protection; /* The protection bits (see below). */ LONG fib_EntryType; - UQUAD fib_Size; /* The size of the file. */ - UQUAD fib_NumBlocks; /* Number of blocks used for file. */ - struct DateStamp fib_Date; /* Date of last change to file. */ - /* The filecomment. Follows the same BSTR/CSTR rules as fib_FileName */ - UBYTE fib_Comment[MAXCOMMENTLENGTH]; - UWORD fib_OwnerUID; /* UserID of fileowner. */ - UWORD fib_OwnerGID; /* GroupID of fileowner. */ - UBYTE fib_Reserved[32]; /* PRIVATE */ -}; - -struct FileInfoBlock32 -{ - IPTR fib_DiskKey; - /* See for definitions. Generally: if this is >= 0 - the file described is a directory, otherwise it is a plain file. */ - LONG fib_DirEntryType; - /* The filename. - * - * User applications should always treat this as ASCIIZ. - * - * NOTE: This is created as a BCPL string in the ACTION_EXAMINE_* - * filesystem handler code, but is converted to a C style - * '\0'-terminated string by the Dos/Examine???() functions. - * - */ - UBYTE fib_FileName[MAXFILENAMELENGTH]; - LONG fib_Protection; /* The protection bits (see below). */ - LONG fib_EntryType; - LONG fib_Size; /* The size of the file. */ + LONG fib_Size; /* The size of the file. 0 from the + 64-bit calls when it does not + fit; see fib_Size64. */ LONG fib_NumBlocks; /* Number of blocks used for file. */ struct DateStamp fib_Date; /* Date of last change to file. */ /* The filecomment. Follows the same BSTR/CSTR rules as fib_FileName */ UBYTE fib_Comment[MAXCOMMENTLENGTH]; UWORD fib_OwnerUID; /* UserID of fileowner. */ UWORD fib_OwnerGID; /* GroupID of fileowner. */ - UBYTE fib_Reserved[32]; /* PRIVATE */ + union + { + UBYTE fib_un_Reserved[32]; /* PRIVATE */ + struct + { + UQUAD fib_un_ext_Size64 AROS_DOS64_ALIGN; + UQUAD fib_un_ext_NumBlocks64 AROS_DOS64_ALIGN; + ULONG fib_un_ext_Pad0[3]; + UWORD fib_un_ext_Pad1; + UBYTE fib_un_ext_ActExtFlags; + UBYTE fib_un_ext_ReqExtFlags; + } fib_un_ext; + } fib_un; }; -#if (__DOS64) -#define FileInfoBlock FileInfoBlock64 -#else -#define FileInfoBlock FileInfoBlock32 -#endif +#define fib_Reserved fib_un.fib_un_Reserved +#define fib_Size64 fib_un.fib_un_ext.fib_un_ext_Size64 /* 64-bit size of the file */ +#define fib_NumBlocks64 fib_un.fib_un_ext.fib_un_ext_NumBlocks64 /* 64-bit number of blocks */ +/* Extensions the handler filled in (FIBEXTF_ flags). Must be 0 when an + ACTION_EXAMINE_*64 packet is sent. The 64-bit size and block count + do not need a flag; they are always filled. */ +#define fib_ActExtFlags fib_un.fib_un_ext.fib_un_ext_ActExtFlags +/* Extensions requested from the handler (FIBEXTF_ flags), or 0. */ +#define fib_ReqExtFlags fib_un.fib_un_ext.fib_un_ext_ReqExtFlags + +/* No FIBEXTF_ extensions are defined on AROS yet. Bit 0 is kept free + for compatibility: MorphOS uses it (FIBEXTB_POSIXDATE) for a POSIX + date in place of fib_Date. */ + +/* Former names: the 64-bit examine calls use the standard structure */ +#define FileInfoBlock32 FileInfoBlock +#define FileInfoBlock64 FileInfoBlock /* Protection bits for files (fib_Protection). */ /* Flags for owner (they are active-low, i.e. not set means the action is @@ -171,37 +190,41 @@ struct FileInfoBlock32 **********************************************************************/ /* Structure used in Info(). Must be longword-aligned. */ -struct InfoData64 +struct InfoData { LONG id_NumSoftErrors; /* Number of soft errors on device. */ LONG id_UnitNumber; /* Unit number of device. */ LONG id_DiskState; /* State the current volume is in (see below). */ - UQUAD id_NumBlocks; /* Number of blocks on device. */ - UQUAD id_NumBlocksUsed; /* Number of blocks in use. */ + LONG id_NumBlocks; /* Number of blocks on device. */ + LONG id_NumBlocksUsed; /* Number of blocks in use. */ LONG id_BytesPerBlock; /* Bytes per block. */ LONG id_DiskType; /* Type of disk (see below). */ BPTR id_VolumeNode; IPTR id_InUse; /* Set, if device is in use. */ }; -struct InfoData32 +/* AROS extension, used by dos64.library Info64() and ACTION_INFO64: the + standard InfoData followed by 64-bit block counts. The leading part is + identical to struct InfoData, so the block can also be filled by + ACTION_INFO; id_NumBlocks and id_NumBlocksUsed then hold the 32-bit + values. Allocate it with AllocDosObject64(DOS64_INFODATA, NULL). */ +struct InfoData64 { - LONG id_NumSoftErrors; /* Number of soft errors on device. */ - LONG id_UnitNumber; /* Unit number of device. */ - LONG id_DiskState; /* State the current volume is in (see below). */ - LONG id_NumBlocks; /* Number of blocks on device. */ - LONG id_NumBlocksUsed; /* Number of blocks in use. */ - LONG id_BytesPerBlock; /* Bytes per block. */ - LONG id_DiskType; /* Type of disk (see below). */ - BPTR id_VolumeNode; - IPTR id_InUse; /* Set, if device is in use. */ + LONG id_NumSoftErrors; + LONG id_UnitNumber; + LONG id_DiskState; + LONG id_NumBlocks; /* 32-bit count, may be clamped */ + LONG id_NumBlocksUsed; /* 32-bit count, may be clamped */ + LONG id_BytesPerBlock; + LONG id_DiskType; + BPTR id_VolumeNode; + IPTR id_InUse; + UQUAD id_NumBlocks64 AROS_DOS64_ALIGN; /* Number of blocks on device. */ + UQUAD id_NumBlocksUsed64 AROS_DOS64_ALIGN; /* Number of blocks in use. */ }; -#if (__DOS64) -#define InfoData InfoData64 -#else -#define InfoData InfoData32 -#endif +/* Former name */ +#define InfoData32 InfoData /* id_DiskState */ #define ID_WRITE_PROTECTED 80 /* Volume is write-protected. */ diff --git a/compiler/include/dos/dos64.h b/compiler/include/dos/dos64.h new file mode 100644 index 00000000000..14fcf55dec8 --- /dev/null +++ b/compiler/include/dos/dos64.h @@ -0,0 +1,144 @@ +#ifndef DOS_DOS64_H +#define DOS_DOS64_H + +/* + Copyright (C) 2026, The AROS Development Team. All rights reserved. + + Desc: 64-bit filesystem I/O support definitions, for use with + dos64.library and 64-bit aware filesystem handlers. +*/ + +#ifndef DOS_DOS_H +# include +#endif +#ifndef DOS_DOSEXTENS_H +# include +#endif +#ifndef DOS_RECORD_H +# include +#endif + +/********************************************************************** + ********************** 64-bit Packet types *************************** + **********************************************************************/ + +/* + * MorphOS (tm) compatible extensions (V51). 64-bit values are passed by + * pointer, so the packets are the same on 32-bit and 64-bit systems: + * + * ACTION_SEEK64 dp_Arg1 fh_Arg1, dp_Arg2 QUAD *position, + * dp_Arg3 mode, dp_Arg4 QUAD *oldposition + * ACTION_SET_FILE_SIZE64 dp_Arg1 fh_Arg1, dp_Arg2 QUAD *offset, + * dp_Arg3 mode, dp_Arg4 QUAD *newsize + * ACTION_LOCK_RECORD64 dp_Arg1 fh_Arg1, dp_Arg2 UQUAD *offset, + * dp_Arg3 UQUAD *length, dp_Arg4 mode, + * dp_Arg5 timeout + * ACTION_FREE_RECORD64 dp_Arg1 fh_Arg1, dp_Arg2 UQUAD *offset, + * dp_Arg3 UQUAD *length + * ACTION_QUERY_ATTR dp_Arg1 attribute (FQA_), dp_Arg2 APTR storage, + * dp_Arg3 storage size + * + * dp_Res1 is DOSTRUE on success, or DOSFALSE with the error in dp_Res2; + * the results are stored through the pointers. + * + * ACTION_EXAMINE_OBJECT64, ACTION_EXAMINE_NEXT64 and ACTION_EXAMINE_FH64 + * take the same arguments as the 32-bit packets (dp_Arg1 the lock, or + * fh_Arg1 for _FH64; dp_Arg2 a BPTR to a struct FileInfoBlock). The handler + * fills the standard fields and fib_Size64/fib_NumBlocks64 (see ), + * with fib_Size 0 for sizes above 2^31-1, and sets fib_ActExtFlags. The + * sender must set fib_ActExtFlags to 0 and fib_ReqExtFlags to the + * extensions it wants (or 0). + * + * A handler that does not know a packet answers DOSFALSE with + * ERROR_ACTION_NOT_KNOWN. + */ +#ifndef ACTION_SEEK64 +#define ACTION_SEEK64 26400 +#define ACTION_SET_FILE_SIZE64 26401 +#define ACTION_LOCK_RECORD64 26402 +#define ACTION_FREE_RECORD64 26403 +#define ACTION_QUERY_ATTR 26407 +#define ACTION_EXAMINE_OBJECT64 26408 +#define ACTION_EXAMINE_NEXT64 26409 +#define ACTION_EXAMINE_FH64 26410 +#endif + +/* ACTION_QUERY_ATTR attributes (MorphOS (tm) compatible) */ +#ifndef FQA_MaxFileNameLength +#define FQA_MaxFileNameLength 0 /* LONG */ +#define FQA_MaxVolumeNameLength 1 /* LONG */ +#define FQA_MaxFileSize 2 /* QUAD */ +#define FQA_IsCaseSensitive 3 /* LONG */ +#define FQA_DeviceType 4 /* LONG */ +#define FQA_NumBlocks 6 /* QUAD */ +#define FQA_NumBlocksUsed 7 /* QUAD */ +#endif + +/* + * AROS extension: 64-bit volume information. + * Arguments as for ACTION_INFO, but dp_Arg2 points (BPTR) to a + * struct InfoData64 (see ): the standard InfoData followed by + * the 64-bit block counts. + */ +#define ACTION_INFO64 2020 + +#if (__WORDSIZE != 64) +/* + * AmigaOS 4 (tm) compatible 64-bit packet layout, used on 32-bit + * systems for the ACTION_CHANGE_FILE_POSITION64, ACTION_GET_FILE_POSITION64, + * ACTION_CHANGE_FILE_SIZE64 and ACTION_GET_FILE_SIZE64 packets, where the + * standard DosPacket fields are too small to carry 64-bit values. + * + * This structure overlays the standard DosPacket. The originator must + * additionally store the object (fh_Arg1) in the *standard* packet's + * dp_Arg1 field, set dp_Res0 to DP64_INIT, and place the 64-bit + * argument(s) in the fields below. + * + * On 64-bit AROS builds this structure is not used (see below). + */ +struct DosPacket64 +{ + struct Message * dp_Link; /* Pointer to a standard exec message. */ + struct MsgPort * dp_Port; /* Reply-Port of that packet. */ + + LONG dp_Type; /* 8: Packet type (ACTION_...) */ + LONG dp_Res0; /* 12: Set to DP64_INIT by the originator */ + ULONG dp_Res2; /* 16: Secondary result (IoErr() value) */ + LONG dp_Pad0; /* 20: see the alignment note below */ + QUAD dp_Res1; /* 24: 64-bit primary result */ + LONG dp_Arg1; /* 32: the object (fh_Arg1) */ + LONG dp_Pad1; /* 36 */ + QUAD dp_Arg2; /* 40: 64-bit argument */ + ULONG dp_Arg3; /* 48: 32-bit argument (e.g. seek mode) */ + ULONG dp_Arg4; /* 52: struct FileHandle * */ + QUAD dp_Arg5; /* 56: must be zero to validate dp_Arg4 */ +}; + +/* + * On 64-bit AROS the standard DosPacket argument and result fields are + * already 64-bit wide (SIPTR), so these four packets carry their 64-bit + * values directly in dp_Arg2/dp_Res1 of a standard packet there. + * + * The padding above is deliberate and must not be removed. The 64-bit + * fields of this packet sit at fixed offsets (dp_Res1 at 24, dp_Arg2 at + * 40, dp_Arg5 at 56), which is what a handler on the other side reads + * and writes. Those offsets are what a compiler that gives a 64-bit type + * 8-byte alignment produces on its own - but m68k aligns them to 4, so + * without the padding every 64-bit field would sit 4 bytes early and the + * two sides would disagree about where the result is. Spelling the + * padding out keeps the layout identical whatever the ABI decides. + */ + +#define DP64_INIT (-3) +#endif + +/********************************************************************** + ******************* AllocDosObject64() types ************************* + **********************************************************************/ + +/* Objects allocatable with dos64.library/AllocDosObject64() */ +#define DOS64_FIB 1 /* struct FileInfoBlock */ +#define DOS64_INFODATA 2 /* struct InfoData64 */ +#define DOS64_RECORDLOCK 3 /* struct RecordLock64 */ + +#endif /* DOS_DOS64_H */ diff --git a/compiler/include/dos/dosextens.h b/compiler/include/dos/dosextens.h index 1367158e34e..e806f503bc3 100644 --- a/compiler/include/dos/dosextens.h +++ b/compiler/include/dos/dosextens.h @@ -290,29 +290,7 @@ struct DevProc should not use this structure in any way and only use library-calls to access files. Treat this structure as PRIVATE. If you want to create this structure nevertheless, use AllocDosObject(). */ -struct FileHandle64 -{ - /* The next three are used with packet-based filesystems */ - ULONG fh_Flags; - LONG fh_Interactive; /* interactive handle flag */ - struct MsgPort * fh_Type; /* port to send packets to */ - - BPTR fh_Buf; - UQUAD fh_Pos; - UQUAD fh_End; - - SIPTR fh_Funcs; - SIPTR fh_Func2; - SIPTR fh_Func3; - SIPTR fh_Args; - SIPTR fh_Arg2; - - /* v39+ */ - IPTR fh_BufSize; /* Size of buffered io buffer */ - BPTR fh_OrigBuf; /* Always the same as fh_Buf */ -}; - -struct FileHandle32 +struct FileHandle { /* The next three are used with packet-based filesystems */ ULONG fh_Flags; @@ -334,12 +312,6 @@ struct FileHandle32 BPTR fh_OrigBuf; /* Always the same as fh_Buf */ }; -#if (__DOS64) -#define FileHandle FileHandle64 -#else -#define FileHandle FileHandle32 -#endif - /* Original AmigaOS aliases */ #define fh_Port fh_Interactive #define fh_Func1 fh_Funcs diff --git a/compiler/include/dos/exall.h b/compiler/include/dos/exall.h index a12c1b5f70c..10b4398f6f1 100644 --- a/compiler/include/dos/exall.h +++ b/compiler/include/dos/exall.h @@ -15,19 +15,23 @@ #ifndef UTILITY_HOOKS_H # include #endif +#ifndef DOS_DOS_H +# include +#endif /* Structure (as used in ExAll()), containing information about a file. This structure is only as long as it need to be. If is for example ED_SIZE was specified, when calling ExAll(), this structure only consists of the fields ed_Name through ed_Size. Therefore you can use the ED_ definitions below as longword offsets into this structure. */ -struct ExAllData64 +struct ExAllData { - struct ExAllData64 * ed_Next; + struct ExAllData * ed_Next; UBYTE * ed_Name; /* Name of the file. */ LONG ed_Type; /* Type of file. See . */ - UQUAD ed_Size; /* Size of file. */ + ULONG ed_Size; /* Size of file. With ED_SIZE64, 0 when the size + does not fit in 31 bits (see ed_Size64). */ ULONG ed_Prot; /* Protection bits. */ /* The following three fields are de facto an embedded datestamp @@ -41,35 +45,13 @@ struct ExAllData64 UWORD ed_OwnerUID; /* The owner ID. */ UWORD ed_OwnerGID; /* The group-owner ID. */ -}; - -struct ExAllData32 -{ - struct ExAllData32 * ed_Next; - - UBYTE * ed_Name; /* Name of the file. */ - LONG ed_Type; /* Type of file. See . */ - ULONG ed_Size; /* Size of file. */ - ULONG ed_Prot; /* Protection bits. */ - - /* The following three fields are de facto an embedded datestamp - structure (see ), which describes the last modification - date. */ - ULONG ed_Days; - ULONG ed_Mins; - ULONG ed_Ticks; - UBYTE * ed_Comment; /* The file comment. */ - - UWORD ed_OwnerUID; /* The owner ID. */ - UWORD ed_OwnerGID; /* The group-owner ID. */ + /* MorphOS (tm) V51 compatible extension, filled for ED_SIZE64 */ + UQUAD ed_Size64 AROS_DOS64_ALIGN; /* 64-bit size of file. */ }; -#if (__DOS64) -#define ExAllData ExAllData64 -#else -#define ExAllData ExAllData32 -#endif +/* Former name */ +#define ExAllData32 ExAllData /* Type argument for ExAll(). Each number includes the information of all lower numbers, too. If you specify for example ED_SIZE, you will get @@ -85,6 +67,9 @@ struct ExAllData32 #define ED_DATE 5 /* Last modification date. */ #define ED_COMMENT 6 /* Addtional file comment. */ #define ED_OWNER 7 /* Owner information. */ +#define ED_SIZE64 8 /* 64-bit size of file (ed_Size64). MorphOS (tm) + compatible; handlers that do not support it + fail with ERROR_BAD_NUMBER. */ /* Structure as used for controlling ExAll(). Allocate this structure by using diff --git a/compiler/include/dos/record.h b/compiler/include/dos/record.h index 1099988fe42..a918417d267 100644 --- a/compiler/include/dos/record.h +++ b/compiler/include/dos/record.h @@ -24,28 +24,26 @@ /* Structure as passed to LockRecords() and UnLockRecords(). */ -struct RecordLock64 +struct RecordLock { BPTR rec_FH; /* (struct FileHandle *) The file to get the current record from. */ - UQUAD rec_Offset; /* The offset, the current record should start. */ - UQUAD rec_Length; /* The length of the current record. */ + ULONG rec_Offset; /* The offset, the current record should start. */ + ULONG rec_Length; /* The length of the current record. */ ULONG rec_Mode; /* The mode od locking (see above). */ }; -struct RecordLock32 +/* 64-bit version, as passed to dos64.library LockRecords64() and + UnLockRecords64(). Same layout as the MorphOS (tm) V51 structure. */ +struct RecordLock64 { - BPTR rec_FH; /* (struct FileHandle *) The file to get the current - record from. */ - ULONG rec_Offset; /* The offset, the current record should start. */ - ULONG rec_Length; /* The length of the current record. */ - ULONG rec_Mode; /* The mode od locking (see above). */ + BPTR rec_FH; /* The file (struct FileHandle *). */ + UQUAD rec_Offset AROS_DOS64_ALIGN; /* Start of the record. */ + UQUAD rec_Length AROS_DOS64_ALIGN; /* Length of the record. */ + ULONG rec_Mode; /* The mode of locking (see above). */ }; -#if (__DOS64) -#define RecordLock RecordLock64 -#else -#define RecordLock RecordLock32 -#endif +/* Former name */ +#define RecordLock32 RecordLock #endif /* DOS_RECORD_H */ diff --git a/compiler/posixc/__dos64.c b/compiler/posixc/__dos64.c new file mode 100644 index 00000000000..95ac5d8e7dd --- /dev/null +++ b/compiler/posixc/__dos64.c @@ -0,0 +1,209 @@ +/* + Copyright (C) 2026, The AROS Development Team. All rights reserved. + + Internal 64-bit file access helpers for posixc.library: use + dos64.library when available, otherwise delegate to the 32-bit + dos.library calls, widening/narrowing as needed. +*/ + +#include + +#include +#include + +#define __NOBLIBBASE__ + +#include "__posixc_intbase.h" +#include "__optionallibs.h" +#include "__dos64.h" + +#include + +/* Returns the dos64.library base, or NULL when it is not available */ +static struct Library *__dos64_base(void) +{ + struct PosixCIntBase *PosixCBase = + (struct PosixCIntBase *)__aros_getbase_PosixCBase(); + + if (__dos64_available(PosixCBase)) + return PosixCBase->PosixCDOS64Base; + + return NULL; +} + +/* The dos64.library base when the fcb's filesystem handles 64-bit + packets, NULL otherwise (32-bit path) */ +static struct Library *__dos64_base_for(fcb *fcb) +{ + if (!(fcb->privflags & _FCB_FS64)) + return NULL; + + return __dos64_base(); +} + +void __dos64_probe(fcb *fcb) +{ + struct Library *DOS64Base = __dos64_base(); + + if (DOS64Base != NULL && fcb->handle != BNULL + && IsFileSystem64(fcb->handle)) + fcb->privflags |= _FCB_FS64; +} + +QUAD __dos64_seek(fcb *fcb, QUAD position, LONG mode) +{ + struct Library *DOS64Base = __dos64_base_for(fcb); + BPTR fh = fcb->handle; + + if (DOS64Base != NULL) + return Seek64(fh, mode, position); + + if (position != (QUAD)(LONG)position) + { + SetIoErr(ERROR_OBJECT_TOO_LARGE); + return -1; + } + return Seek(fh, (LONG)position, mode); +} + +QUAD __dos64_getpos(fcb *fcb) +{ + struct Library *DOS64Base = __dos64_base_for(fcb); + BPTR fh = fcb->handle; + + if (DOS64Base != NULL) + return GetFilePosition64(fh); + + return Seek(fh, 0, OFFSET_CURRENT); +} + +QUAD __dos64_getsize(fcb *fcb) +{ + struct Library *DOS64Base = __dos64_base_for(fcb); + BPTR fh = fcb->handle; + + if (DOS64Base != NULL) + return GetFileSize64(fh); + + /* + * Seek() returns the previous position: seek to the end to learn + * nothing yet, then back to where we were - that second call + * reports the end position, i.e. the size. + */ + QUAD pos = Seek(fh, 0, OFFSET_END); + if (pos == -1) + return -1; + return Seek(fh, (LONG)pos, OFFSET_BEGINNING); +} + +QUAD __dos64_setfilesize(fcb *fcb, QUAD size, LONG mode) +{ + struct Library *DOS64Base = __dos64_base_for(fcb); + BPTR fh = fcb->handle; + + if (DOS64Base != NULL) + return SetFileSize64(fh, mode, size); + + if (size != (QUAD)(LONG)size) + { + SetIoErr(ERROR_OBJECT_TOO_LARGE); + return -1; + } + return SetFileSize(fh, (LONG)size, mode); +} + +QUAD __dos64_read(fcb *fcb, APTR buf, QUAD len) +{ + struct Library *DOS64Base = __dos64_base_for(fcb); + BPTR fh = fcb->handle; + + if (DOS64Base != NULL) + return Read64(fh, buf, len); + + /* Partial transfers are permitted, so simply clamp */ + if (len > 0x7FFFF000LL) + len = 0x7FFFF000LL; + return Read(fh, buf, (LONG)len); +} + +QUAD __dos64_write(fcb *fcb, CONST_APTR buf, QUAD len) +{ + struct Library *DOS64Base = __dos64_base_for(fcb); + BPTR fh = fcb->handle; + + if (DOS64Base != NULL) + return Write64(fh, buf, len); + + if (len > 0x7FFFF000LL) + len = 0x7FFFF000LL; + return Write(fh, buf, (LONG)len); +} + +/* Derive the 64-bit fields of a FileInfoBlock filled by a 32-bit examine */ +static void __dos64_fib32to64(struct FileInfoBlock *fib) +{ + UQUAD size = (UQUAD)(ULONG)fib->fib_Size; + + fib->fib_Size64 = size; + fib->fib_NumBlocks64 = (UQUAD)(ULONG)fib->fib_NumBlocks; + fib->fib_ActExtFlags = 0; + if (size > 0x7FFFFFFFULL) + fib->fib_Size = 0; +} + +LONG __dos64_examine(BPTR obj, struct FileInfoBlock *fib, int what) +{ + struct Library *DOS64Base = __dos64_base(); + LONG ret = DOSFALSE; + + if (DOS64Base != NULL) + { + switch (what) + { + case __DOS64_EXAMINE: + return Examine64(obj, fib, NULL); + case __DOS64_EXAMINE_FH: + return ExamineFH64(obj, fib, NULL); + case __DOS64_EXAMINE_NEXT: + return ExNext64(obj, fib, NULL); + } + return DOSFALSE; + } + + /* The 64-bit fields share the block, so examine into it directly */ + switch (what) + { + case __DOS64_EXAMINE: + ret = Examine(obj, fib); + break; + case __DOS64_EXAMINE_FH: + ret = ExamineFH(obj, fib); + break; + case __DOS64_EXAMINE_NEXT: + ret = ExNext(obj, fib); + break; + } + + if (ret) + __dos64_fib32to64(fib); + + return ret; +} + +LONG __dos64_info(BPTR lock, struct InfoData64 *id) +{ + struct Library *DOS64Base = __dos64_base(); + LONG ret; + + if (DOS64Base != NULL) + return Info64(lock, id); + + /* InfoData64 starts with a standard InfoData */ + ret = Info(lock, (struct InfoData *)id); + if (ret) + { + id->id_NumBlocks64 = (UQUAD)(ULONG)id->id_NumBlocks; + id->id_NumBlocksUsed64 = (UQUAD)(ULONG)id->id_NumBlocksUsed; + } + return ret; +} diff --git a/compiler/posixc/__dos64.h b/compiler/posixc/__dos64.h new file mode 100644 index 00000000000..ab077f5cf3d --- /dev/null +++ b/compiler/posixc/__dos64.h @@ -0,0 +1,40 @@ +#ifndef ___DOS64_H +#define ___DOS64_H + +/* + Copyright (C) 2026, The AROS Development Team. All rights reserved. + + Internal 64-bit file access helpers for posixc.library. They use + dos64.library when it is available and transparently fall back to + the 32-bit dos.library calls when it is not, so posixc keeps + working on systems without dos64.library. Values the 32-bit + fallback cannot express fail with IoErr() == ERROR_OBJECT_TOO_LARGE + (mapped to EOVERFLOW by the callers). +*/ + +#include +#include + +#include "__fdesc.h" + +/* Detect 64-bit filesystem support for an open fcb and cache it in + the fcb's _FCB_FS64 privflag; the helpers below then pick the + 64-bit or 32-bit path directly, without per-call probing. */ +void __dos64_probe(fcb *fcb); + +QUAD __dos64_seek(fcb *fcb, QUAD position, LONG mode); +QUAD __dos64_getpos(fcb *fcb); +QUAD __dos64_getsize(fcb *fcb); +QUAD __dos64_setfilesize(fcb *fcb, QUAD size, LONG mode); +QUAD __dos64_read(fcb *fcb, APTR buf, QUAD len); +QUAD __dos64_write(fcb *fcb, CONST_APTR buf, QUAD len); + +/* obj is a filehandle for __DOS64_EXAMINE_FH, otherwise a lock */ +#define __DOS64_EXAMINE 0 +#define __DOS64_EXAMINE_FH 1 +#define __DOS64_EXAMINE_NEXT 2 +LONG __dos64_examine(BPTR obj, struct FileInfoBlock *fib, int what); + +LONG __dos64_info(BPTR lock, struct InfoData64 *id); + +#endif /* ___DOS64_H */ diff --git a/compiler/posixc/__fdesc.c b/compiler/posixc/__fdesc.c index 35d004671b8..cae61fae795 100644 --- a/compiler/posixc/__fdesc.c +++ b/compiler/posixc/__fdesc.c @@ -24,6 +24,7 @@ #include #include #include "__fdesc.h" +#include "__dos64.h" #include "__upath.h" /* TODO: Add locking to make filedesc usage thread safe @@ -352,6 +353,10 @@ int __open(int wanted_fd, const char *pathname, int flags, int mode) currdesc->fcb->flags = flags; currdesc->fcb->opencount = 1; + /* Detect 64-bit filesystem support once, and cache it in the fcb */ + if (!(currdesc->fcb->privflags & _FCB_ISDIR)) + __dos64_probe(currdesc->fcb); + __setfdesc(wanted_fd, currdesc); D(bug("__open: exiting fd=%d\n", wanted_fd)); @@ -476,6 +481,11 @@ int __init_stdfiles(struct PosixCIntBase *PosixCBase) BADDR(me->pr_CES), BADDR(errfcb->handle) )); + /* Std streams may be redirected to files; detect 64-bit support */ + __dos64_probe(infcb); + __dos64_probe(outfcb); + __dos64_probe(errfcb); + PosixCBase->fd_array[STDIN_FILENO] = indesc; PosixCBase->fd_array[STDOUT_FILENO] = outdesc; PosixCBase->fd_array[STDERR_FILENO] = errdesc; diff --git a/compiler/posixc/__fseeko.c b/compiler/posixc/__fseeko.c index 1681b7175f1..50056194ad8 100644 --- a/compiler/posixc/__fseeko.c +++ b/compiler/posixc/__fseeko.c @@ -16,151 +16,36 @@ #include "__stdio.h" #include "__fdesc.h" +#include "__dos64.h" #include -#if (__WORDSIZE < 64) - /* - * 32bit version of fseeko. only handles <=2GB files. + * fseeko engine. Positions are handled in 64 bits throughout; the + * __dos64 helpers use dos64.library when it is available and fall + * back to the 32-bit dos.library calls (failing with + * ERROR_OBJECT_TOO_LARGE for unrepresentable positions) when not. */ - -int __fseeko ( - FILE * stream, - off_t offset, - int whence) +int __fseeko64 ( + FILE * stream, + off64_t offset, + int whence) { - off_t cnt = 0; - off_t finalseekposition = 0; - off_t eofposition = 0; - struct FileInfoBlock *fib = NULL; + QUAD cnt = 0; + QUAD finalseekposition = 0; + QUAD eofposition = 0; BPTR fh = BNULL; fdesc *fdesc = __getfdesc(stream->fd); if (!fdesc) { - errno = EBADF; - return -1; - } - - fh = fdesc->fcb->handle; - - /* This is buffered IO, flush the buffer before any Seek */ - Flush (fh); - - /* Handling for fseeko specific behaviour (not all cases handled) */ - /* Get current position */ - cnt = Seek (fh, 0, OFFSET_CURRENT); - if (cnt == -1) - { - errno = __stdc_ioerr2errno (IoErr ()); - return -1; - } - - /* Get file size */ - fib = AllocDosObject(DOS_FIB, NULL); - if (!fib) - { - errno = __stdc_ioerr2errno(IoErr()); - return -1; - } - - if (ExamineFH(fh, fib)) - eofposition = fib->fib_Size; - else - { - /* Does not happen on sfs/affs */ - FreeDosObject(DOS_FIB, fib); - fib = NULL; errno = EBADF; return -1; } - FreeDosObject(DOS_FIB, fib); - fib = NULL; - - switch(whence) - { - case SEEK_SET: finalseekposition = offset; break; - case SEEK_CUR: finalseekposition = cnt + offset; break; - case SEEK_END: finalseekposition = eofposition + offset; break; - default: - errno = EINVAL; - return -1; - } - - /* Check conditions */ - /* Seek before beginning of file */ - if (finalseekposition < 0) + if (fdesc->fcb->privflags & _FCB_ISDIR) { - errno = EINVAL; - return -1; - } - - /* Seek beyond end of file and in write mode */ - if (finalseekposition > eofposition) - { - if (fdesc->fcb->flags & O_WRITE) - { - /* Write '0' to fill up to requested size - * compatible fseeko does not write but allows write */ - int bytestowrite = finalseekposition - eofposition; - int chunkcount = (bytestowrite)/128; - int remainder = bytestowrite - (chunkcount * 128); - char zeroarray[128] = {0}; - - Seek (fh, 0, OFFSET_END); - if (chunkcount > 0) - FWrite (fh, zeroarray, 128, chunkcount); - if (remainder > 0) - FWrite (fh, zeroarray, remainder, 1); - Flush (fh); - } - } - - cnt = Seek (fh, finalseekposition, OFFSET_BEGINNING); - - if (cnt == -1) - errno = __stdc_ioerr2errno (IoErr ()); - else - { - /* It's specified that upon success fseeko should clear EOF flag - so here we go. - */ - stream->flags &= ~(__POSIXC_STDIO_EOF); - cnt = 0; - } - - return cnt; -} /* __fseeko */ -#endif - -/* - * 64bit version of fseeko. Must be able to hanlde both 32bit and 64bit filesystems ! - */ - -int __fseeko64 ( - FILE * stream, - off64_t offset, - int whence) -{ - off_t cnt = 0; - off_t finalseekposition = 0; - off_t eofposition = 0; - struct FileInfoBlock *fib = NULL; - BPTR fh = BNULL; - fdesc *fdesc = __getfdesc(stream->fd); - - if (!fdesc) - { - errno = EBADF; - return -1; - } - - if (((offset <= LONG_MIN) || (offset >= LONG_MAX)) && !(fdesc->fcb->privflags & _FCB_FS64)) - { - /* asked to seek too far on a 32bit filesystem.. */ - errno = EBADF; + errno = EISDIR; return -1; } @@ -171,7 +56,7 @@ int __fseeko64 ( /* Handling for fseeko specific behaviour (not all cases handled) */ /* Get current position */ - cnt = Seek (fh, 0, OFFSET_CURRENT); + cnt = __dos64_getpos (fdesc->fcb); if (cnt == -1) { errno = __stdc_ioerr2errno (IoErr ()); @@ -179,35 +64,22 @@ int __fseeko64 ( } /* Get file size */ - fib = AllocDosObject(DOS_FIB, NULL); - if (!fib) - { - errno = __stdc_ioerr2errno(IoErr()); - return -1; - } - - if (ExamineFH(fh, fib)) - eofposition = fib->fib_Size; - else + eofposition = __dos64_getsize (fdesc->fcb); + if (eofposition == -1) { /* Does not happen on sfs/affs */ - FreeDosObject(DOS_FIB, fib); - fib = NULL; errno = EBADF; return -1; } - FreeDosObject(DOS_FIB, fib); - fib = NULL; - switch(whence) { case SEEK_SET: finalseekposition = offset; break; case SEEK_CUR: finalseekposition = cnt + offset; break; case SEEK_END: finalseekposition = eofposition + offset; break; default: - errno = EINVAL; - return -1; + errno = EINVAL; + return -1; } /* Check conditions */ @@ -225,37 +97,54 @@ int __fseeko64 ( { /* Write '0' to fill up to requested size * compatible fseeko does not write but allows write */ - int bytestowrite = finalseekposition - eofposition; - int chunkcount = (bytestowrite)/128; - int remainder = bytestowrite - (chunkcount * 128); + QUAD bytestowrite = finalseekposition - eofposition; + QUAD chunkcount = bytestowrite / 128; + LONG remainder = bytestowrite - (chunkcount * 128); char zeroarray[128] = {0}; - Seek (fh, 0, OFFSET_END); - if (chunkcount > 0) - FWrite (fh, zeroarray, 128, chunkcount); + __dos64_seek (fdesc->fcb, 0, OFFSET_END); + while (chunkcount > 0) + { + LONG n = (chunkcount > 0x100000) ? 0x100000 : (LONG)chunkcount; + FWrite (fh, zeroarray, 128, n); + chunkcount -= n; + } if (remainder > 0) FWrite (fh, zeroarray, remainder, 1); Flush (fh); } } - cnt = Seek (fh, finalseekposition, OFFSET_BEGINNING); + cnt = __dos64_seek (fdesc->fcb, finalseekposition, OFFSET_BEGINNING); if (cnt == -1) - errno = __stdc_ioerr2errno (IoErr ()); - else { - /* It's specified that upon success fseeko should clear EOF flag - so here we go. - */ - stream->flags &= ~(__POSIXC_STDIO_EOF); - cnt = 0; + LONG ioerr = IoErr (); + errno = (ioerr == ERROR_OBJECT_TOO_LARGE) + ? EOVERFLOW : __stdc_ioerr2errno (ioerr); + return -1; } - return cnt; + /* It's specified that upon success fseeko should clear EOF flag + so here we go. + */ + stream->flags &= ~(__POSIXC_STDIO_EOF); + + return 0; } /* __fseeko64 */ -#if (__WORDSIZE==64) +#if (__WORDSIZE < 64) +/* + * 32-bit off_t variant: same engine, the offset simply widens. + */ +int __fseeko ( + FILE * stream, + off_t offset, + int whence) +{ + return __fseeko64 (stream, (off64_t)offset, whence); +} /* __fseeko */ +#else /* * on 64bit fseeko is an alias of fseeko64 */ diff --git a/compiler/posixc/__ftello.c b/compiler/posixc/__ftello.c index 23b751bc219..d82261727b6 100644 --- a/compiler/posixc/__ftello.c +++ b/compiler/posixc/__ftello.c @@ -3,34 +3,65 @@ $Id$ */ +#include #include +#include + #define POSIXC_NOSTDIO_DECL #include "__stdio.h" - -#if (__WORDSIZE < 64) +#include "__fdesc.h" +#include "__dos64.h" /* - * 32bit version of ftello. only handles <=2GB files. + * ftello engine: full 64-bit position via the __dos64 helpers. */ - -off_t __ftello(FILE *stream) +off64_t __ftello64(FILE *stream) { - return ftell(stream); + QUAD cnt; + BPTR fh; + fdesc *fdesc = __getfdesc(stream->fd); + + if (!fdesc) + { + errno = EBADF; + return -1; + } + + if (fdesc->fcb->privflags & _FCB_ISDIR) + { + errno = EISDIR; + return -1; + } + + fh = fdesc->fcb->handle; + + Flush (fh); + cnt = __dos64_getpos (fdesc->fcb); + + if (cnt == -1) + errno = __stdc_ioerr2errno (IoErr ()); + + return cnt; } -#endif +#if (__WORDSIZE < 64) /* - * 64bit version of ftello. Must be able to hanlde both 32bit and 64bit filesystems ! + * 32-bit off_t variant: positions beyond off_t range report EOVERFLOW. */ - -off64_t __ftello64(FILE *stream) +off_t __ftello(FILE *stream) { - return ftell(stream); -} + QUAD cnt = __ftello64(stream); -#if (__WORDSIZE==64) + if (cnt != (QUAD)(off_t)cnt) + { + errno = EOVERFLOW; + return (off_t)-1; + } + return (off_t)cnt; +} +#else /* * on 64bit ftello is an alias of ftello64 */ diff --git a/compiler/posixc/__optionallibs.c b/compiler/posixc/__optionallibs.c new file mode 100644 index 00000000000..b30eda95538 --- /dev/null +++ b/compiler/posixc/__optionallibs.c @@ -0,0 +1,28 @@ +/* + Copyright (C) 2025-2026, The AROS Development Team. All rights reserved. +*/ + +#include +#include + +#include "__posixc_intbase.h" +#include "__optionallibs.h" + +int __dos64_available(struct PosixCIntBase *PosixCBase) +{ + if (PosixCBase->PosixCDOS64Base == NULL) + PosixCBase->PosixCDOS64Base = OpenLibrary("dos64.library", 50); + + return PosixCBase->PosixCDOS64Base != NULL; +} + +/* Close the optional libraries opened by this base */ +static void __optionallibs_close(struct PosixCIntBase *PosixCBase) +{ + if (PosixCBase->PosixCDOS64Base) { + CloseLibrary(PosixCBase->PosixCDOS64Base); + PosixCBase->PosixCDOS64Base = NULL; + } +} + +ADD2CLOSELIB(__optionallibs_close, 0) diff --git a/compiler/posixc/__optionallibs.h b/compiler/posixc/__optionallibs.h new file mode 100644 index 00000000000..39ebe45797c --- /dev/null +++ b/compiler/posixc/__optionallibs.h @@ -0,0 +1,11 @@ +/* + Copyright (C) 2025-2026, The AROS Development Team. All rights reserved. +*/ + +/* Functions in this include should be used in rest of posixc.library to check + if an optional library is available; the library is opened on first use + and closed when posixc.library is closed. */ + +struct PosixCIntBase; + +int __dos64_available(struct PosixCIntBase *PosixCBase); diff --git a/compiler/posixc/__posixc_intbase.h b/compiler/posixc/__posixc_intbase.h index 5a264c2690f..b4ff10bc661 100644 --- a/compiler/posixc/__posixc_intbase.h +++ b/compiler/posixc/__posixc_intbase.h @@ -31,6 +31,9 @@ struct PosixCIntBase { struct PosixCBase PosixCBase; + /* __optionallibs.c */ + struct Library *PosixCDOS64Base; /* dos64.library, for 64-bit file I/O */ + /* common */ APTR internalpool; int32_t flags; diff --git a/compiler/posixc/__stat.c b/compiler/posixc/__stat.c index 1d5678a611d..04d60c0cda3 100644 --- a/compiler/posixc/__stat.c +++ b/compiler/posixc/__stat.c @@ -13,6 +13,7 @@ #include #include +#include "__dos64.h" #include "__stat.h" #include @@ -29,7 +30,7 @@ static mode_t __prot_a2u(ULONG protect); static uid_t __id_a2u(UWORD id); static void hashlittle2(const void *key, size_t length, uint32_t *pc, uint32_t *pb); -static void __fill_statbuffer( +static int __fill_statbuffer( struct stat *sb, char *buffer, struct FileInfoBlock *fib, @@ -45,12 +46,13 @@ static void __fill_stat64buffer( int __stat(BPTR lock, struct stat *sb, BOOL filehandle) { struct FileInfoBlock *fib; + int res; UBYTE *buffer; int buffersize = 256; int fallback_to_defaults = 0; BOOL Examined; - fib = AllocDosObject(DOS_FIB, NULL); + fib = AllocVec(sizeof(struct FileInfoBlock), MEMF_PUBLIC | MEMF_CLEAR); if (!fib) { @@ -60,8 +62,8 @@ int __stat(BPTR lock, struct stat *sb, BOOL filehandle) } Examined = filehandle - ? ExamineFH(lock, fib) - : Examine(lock, fib); + ? __dos64_examine(lock, fib, __DOS64_EXAMINE_FH) + : __dos64_examine(lock, fib, __DOS64_EXAMINE); if (!Examined) { if(IoErr() == ERROR_NOT_IMPLEMENTED || @@ -72,7 +74,7 @@ int __stat(BPTR lock, struct stat *sb, BOOL filehandle) else { errno = __stdc_ioerr2errno(IoErr()); - FreeDosObject(DOS_FIB, fib); + FreeVec(fib); return -1; } } @@ -86,7 +88,7 @@ int __stat(BPTR lock, struct stat *sb, BOOL filehandle) if(!(buffer = AllocVec(buffersize, MEMF_ANY))) { errno = ENOMEM; - FreeDosObject(DOS_FIB, fib); + FreeVec(fib); return -1; } @@ -109,7 +111,7 @@ int __stat(BPTR lock, struct stat *sb, BOOL filehandle) else if(IoErr() != ERROR_LINE_TOO_LONG) { errno = __stdc_ioerr2errno(IoErr()); - FreeDosObject(DOS_FIB, fib); + FreeVec(fib); FreeVec(buffer); return -1; } @@ -123,18 +125,18 @@ int __stat(BPTR lock, struct stat *sb, BOOL filehandle) if (filehandle) { BPTR filelock = DupLockFromFH(lock); - __fill_statbuffer(sb, (char*) buffer, fib, fallback_to_defaults, filelock); + res = __fill_statbuffer(sb, (char*) buffer, fib, fallback_to_defaults, filelock); UnLock(filelock); } else { - __fill_statbuffer(sb, (char*) buffer, fib, fallback_to_defaults, lock); + res = __fill_statbuffer(sb, (char*) buffer, fib, fallback_to_defaults, lock); } FreeVec(buffer); - FreeDosObject(DOS_FIB, fib); + FreeVec(fib); - return 0; + return res; } int __stat64(BPTR lock, struct stat64 *sb, BOOL filehandle) @@ -145,7 +147,7 @@ int __stat64(BPTR lock, struct stat64 *sb, BOOL filehandle) int fallback_to_defaults = 0; BOOL Examined; - fib = AllocDosObject(DOS_FIB, NULL); + fib = AllocVec(sizeof(struct FileInfoBlock), MEMF_PUBLIC | MEMF_CLEAR); if (!fib) { @@ -155,8 +157,8 @@ int __stat64(BPTR lock, struct stat64 *sb, BOOL filehandle) } Examined = filehandle - ? ExamineFH(lock, fib) - : Examine(lock, fib); + ? __dos64_examine(lock, fib, __DOS64_EXAMINE_FH) + : __dos64_examine(lock, fib, __DOS64_EXAMINE); if (!Examined) { if(IoErr() == ERROR_NOT_IMPLEMENTED || @@ -167,7 +169,7 @@ int __stat64(BPTR lock, struct stat64 *sb, BOOL filehandle) else { errno = __stdc_ioerr2errno(IoErr()); - FreeDosObject(DOS_FIB, fib); + FreeVec(fib); return -1; } } @@ -181,7 +183,7 @@ int __stat64(BPTR lock, struct stat64 *sb, BOOL filehandle) if(!(buffer = AllocVec(buffersize, MEMF_ANY))) { errno = ENOMEM; - FreeDosObject(DOS_FIB, fib); + FreeVec(fib); return -1; } @@ -204,7 +206,7 @@ int __stat64(BPTR lock, struct stat64 *sb, BOOL filehandle) else if(IoErr() != ERROR_LINE_TOO_LONG) { errno = __stdc_ioerr2errno(IoErr()); - FreeDosObject(DOS_FIB, fib); + FreeVec(fib); FreeVec(buffer); return -1; } @@ -227,7 +229,7 @@ int __stat64(BPTR lock, struct stat64 *sb, BOOL filehandle) } FreeVec(buffer); - FreeDosObject(DOS_FIB, fib); + FreeVec(fib); return 0; } @@ -313,7 +315,7 @@ int __stat_from_path(const char *path, struct stat *sb) strcpy(filepart, split); *split = '\0'; - if ( !(fib = AllocDosObject(DOS_FIB, NULL)) + if ( !(fib = AllocVec(sizeof(struct FileInfoBlock), MEMF_PUBLIC | MEMF_CLEAR)) || !(lock = Lock(abspath, SHARED_LOCK))) { errno = __stdc_ioerr2errno(IoErr()); @@ -321,7 +323,7 @@ int __stat_from_path(const char *path, struct stat *sb) } /* examine parent directory of object to stat */ - if (!Examine(lock, fib)) + if (!__dos64_examine(lock, fib, __DOS64_EXAMINE)) { if (IoErr() == ERROR_NOT_IMPLEMENTED || IoErr() == ERROR_ACTION_NOT_KNOWN) @@ -339,14 +341,13 @@ int __stat_from_path(const char *path, struct stat *sb) /* examine entries of parent directory until we find the object to stat */ do { - loop = ExNext(lock, fib); + loop = __dos64_examine(lock, fib, __DOS64_EXAMINE_NEXT); if (loop) { if (stricmp(fib->fib_FileName, filepart) == 0) { - __fill_statbuffer(sb, abspath, fib, 0, lock); - res = 0; + res = __fill_statbuffer(sb, abspath, fib, 0, lock); break; } @@ -373,7 +374,7 @@ int __stat_from_path(const char *path, struct stat *sb) FreeVec(filepart); if (fib) - FreeDosObject(DOS_FIB, fib); + FreeVec(fib); return res; } @@ -459,7 +460,7 @@ int __stat64_from_path(const char *path, struct stat64 *sb) strcpy(filepart, split); *split = '\0'; - if ( !(fib = AllocDosObject(DOS_FIB, NULL)) + if ( !(fib = AllocVec(sizeof(struct FileInfoBlock), MEMF_PUBLIC | MEMF_CLEAR)) || !(lock = Lock(abspath, SHARED_LOCK))) { errno = __stdc_ioerr2errno(IoErr()); @@ -467,7 +468,7 @@ int __stat64_from_path(const char *path, struct stat64 *sb) } /* examine parent directory of object to stat */ - if (!Examine(lock, fib)) + if (!__dos64_examine(lock, fib, __DOS64_EXAMINE)) { if (IoErr() == ERROR_NOT_IMPLEMENTED || IoErr() == ERROR_ACTION_NOT_KNOWN) @@ -485,7 +486,7 @@ int __stat64_from_path(const char *path, struct stat64 *sb) /* examine entries of parent directory until we find the object to stat */ do { - loop = ExNext(lock, fib); + loop = __dos64_examine(lock, fib, __DOS64_EXAMINE_NEXT); if (loop) { @@ -519,7 +520,7 @@ int __stat64_from_path(const char *path, struct stat64 *sb) FreeVec(filepart); if (fib) - FreeDosObject(DOS_FIB, fib); + FreeVec(fib); return res; } @@ -795,7 +796,7 @@ static void hashlittle2( *pc=c; *pb=b; } -static void __fill_statbuffer( +static int __fill_statbuffer( struct stat *sb, char *buffer, struct FileInfoBlock *fib, @@ -805,14 +806,21 @@ static void __fill_statbuffer( uint64_t hash; uint32_t pc = 1, pb = 1; /* initial hash values */ + /* The size does not fit the 32 bit st_size */ + if (!fallback_to_defaults && fib->fib_Size64 > 0x7FFFFFFF) + { + errno = EOVERFLOW; + return -1; + } + hashlittle2(buffer, strlen((char*) buffer), &pc, &pb); hash = pc + (((uint64_t)pb)<<32); if(fallback_to_defaults) { /* Empty file, not protected, as old as it can be... */ - fib->fib_Size = 0; - fib->fib_NumBlocks = 0; + fib->fib_Size64 = 0; + fib->fib_NumBlocks64 = 0; fib->fib_Date.ds_Days = 0; fib->fib_Date.ds_Minute = 0; fib->fib_Date.ds_Tick = 0; @@ -826,7 +834,7 @@ static void __fill_statbuffer( sb->st_dev = (dev_t) (lock ? ((struct FileLock *)BADDR(lock))->fl_Volume : BNULL); sb->st_ino = hash; /* hash value will be truncated if st_ino size is smaller than uint64_t, but it's ok */ - sb->st_size = (off_t)fib->fib_Size; + sb->st_size = (off_t)fib->fib_Size64; /* FIXME: Update to properly handle the struct timespec fields st_atim, st_mtim and st_ctim */ sb->st_atime = @@ -851,9 +859,9 @@ static void __fill_statbuffer( sb->st_blksize = 1024; } } - if(fib->fib_Size > 0 && sb->st_blksize > 0) + if(fib->fib_Size64 > 0 && sb->st_blksize > 0) sb->st_blocks = - (1 + ((long) fib->fib_Size - 1) / sb->st_blksize) * + (1 + ((QUAD) fib->fib_Size64 - 1) / sb->st_blksize) * (sb->st_blksize / 512); else sb->st_blocks = 0; @@ -883,6 +891,8 @@ static void __fill_statbuffer( sb->st_nlink = 1; sb->st_mode |= S_IFREG; } + + return 0; } static void __fill_stat64buffer( @@ -901,8 +911,8 @@ static void __fill_stat64buffer( if(fallback_to_defaults) { /* Empty file, not protected, as old as it can be... */ - fib->fib_Size = 0; - fib->fib_NumBlocks = 0; + fib->fib_Size64 = 0; + fib->fib_NumBlocks64 = 0; fib->fib_Date.ds_Days = 0; fib->fib_Date.ds_Minute = 0; fib->fib_Date.ds_Tick = 0; @@ -916,7 +926,7 @@ static void __fill_stat64buffer( sb->st_dev = (dev_t) (lock ? ((struct FileLock *)BADDR(lock))->fl_Volume : BNULL); sb->st_ino = hash; /* hash value will be truncated if st_ino size is smaller than uint64_t, but it's ok */ - sb->st_size = (off_t)fib->fib_Size; + sb->st_size = (off64_t)fib->fib_Size64; /* FIXME: Update to properly handle the struct timespec fields st_atim, st_mtim and st_ctim */ sb->st_atime = @@ -941,9 +951,9 @@ static void __fill_stat64buffer( sb->st_blksize = 1024; } } - if(fib->fib_Size > 0 && sb->st_blksize > 0) + if(fib->fib_Size64 > 0 && sb->st_blksize > 0) sb->st_blocks = - (1 + ((long) fib->fib_Size - 1) / sb->st_blksize) * + (1 + ((QUAD) fib->fib_Size64 - 1) / sb->st_blksize) * (sb->st_blksize / 512); else sb->st_blocks = 0; diff --git a/compiler/posixc/fgetpos64.c b/compiler/posixc/fgetpos64.c index 53e3471faf1..4c921e91093 100644 --- a/compiler/posixc/fgetpos64.c +++ b/compiler/posixc/fgetpos64.c @@ -12,6 +12,8 @@ NAME */ #include +#include "__stdio.h" + int fgetpos64 ( /* SYNOPSIS */ @@ -51,7 +53,7 @@ return -1; } - *pos = ftell (stream); + *pos = __ftello64 (stream); if ( *pos < 0L ) { diff --git a/compiler/posixc/fseek.c b/compiler/posixc/fseek.c index df822336cd3..768681a144f 100644 --- a/compiler/posixc/fseek.c +++ b/compiler/posixc/fseek.c @@ -60,110 +60,6 @@ ******************************************************************************/ { - int cnt = 0; - int finalseekposition = 0; - int eofposition = 0; - struct FileInfoBlock *fib = NULL; - BPTR fh = BNULL; - fdesc *fdesc = __getfdesc(stream->fd); - - if (!fdesc) - { - errno = EBADF; - return -1; - } - - if (fdesc->fcb->privflags & _FCB_ISDIR) - { - errno = EISDIR; - return -1; - } - - fh = fdesc->fcb->handle; - - /* This is buffered IO, flush the buffer before any Seek */ - Flush (fh); - - /* Handling for fseek specific behaviour (not all cases handled) */ - /* Get current position */ - cnt = Seek (fh, 0, OFFSET_CURRENT); - if (cnt == -1) - { - errno = __stdc_ioerr2errno (IoErr ()); - return -1; - } - - /* Get file size */ - fib = AllocDosObject(DOS_FIB, NULL); - if (!fib) - { - errno = __stdc_ioerr2errno(IoErr()); - return -1; - } - - if (ExamineFH(fh, fib)) - eofposition = fib->fib_Size; - else - { - /* Does not happen on sfs/affs */ - FreeDosObject(DOS_FIB, fib); - fib = NULL; - errno = EBADF; - return -1; - } - - FreeDosObject(DOS_FIB, fib); - fib = NULL; - - switch(whence) - { - case SEEK_SET: finalseekposition = offset; break; - case SEEK_CUR: finalseekposition = cnt + offset; break; - case SEEK_END: finalseekposition = eofposition + offset; break; - default: - errno = EINVAL; - return -1; - } - - /* Check conditions */ - /* Seek before beginning of file */ - if (finalseekposition < 0) - { - errno = EINVAL; - return -1; - } - - /* Seek beyond end of file and in write mode */ - if (finalseekposition > eofposition) - { - if (fdesc->fcb->flags & O_WRITE) - { - /* Write '0' to fill up to requested size - compatible fseek does not write but allows write */ - int i = 0; - int bytestowrite = finalseekposition - eofposition; - int chunkcount = (bytestowrite)/128; - char zeroarray[128] = {0}; - - Seek (fh, 0, OFFSET_END); - for (i = 0; i < chunkcount; i++) - FWrite(fh, (STRPTR)zeroarray, 128, 1); - FWrite(fh, (STRPTR)zeroarray, bytestowrite - (chunkcount * 128), 1); - Flush (fh); - } - } - - cnt = Seek (fh, finalseekposition, OFFSET_BEGINNING); - - if (cnt == -1) - errno = __stdc_ioerr2errno (IoErr ()); - else - { - /* It's specified that upon success fseek should clear EOF flag - so here we go. - */ - stream->flags &= ~(__POSIXC_STDIO_EOF); - cnt = 0; - } - - return cnt; + /* fseek is fseeko with a narrower offset; the engine handles 64-bit positions */ + return __fseeko64 (stream, (off64_t)offset, whence); } /* fseek */ diff --git a/compiler/posixc/fsetpos64.c b/compiler/posixc/fsetpos64.c index 76956391741..5f8c4f0dd10 100644 --- a/compiler/posixc/fsetpos64.c +++ b/compiler/posixc/fsetpos64.c @@ -12,6 +12,8 @@ NAME */ #include +#include "__stdio.h" + int fsetpos64 ( /* SYNOPSIS */ @@ -53,7 +55,7 @@ return -1; } - retval = fseek (stream, *pos, SEEK_SET); + retval = __fseeko64 (stream, (off64_t)*pos, SEEK_SET); return retval; } /* fsetpos64 */ diff --git a/compiler/posixc/ftell.c b/compiler/posixc/ftell.c index 415fcf1c72a..375a7c8292d 100644 --- a/compiler/posixc/ftell.c +++ b/compiler/posixc/ftell.c @@ -10,6 +10,7 @@ #include #include "__stdio.h" #include "__fdesc.h" +#include "__dos64.h" /***************************************************************************** @@ -44,7 +45,7 @@ ******************************************************************************/ { - long cnt; + QUAD cnt; BPTR fh; fdesc *fdesc = __getfdesc(stream->fd); @@ -57,10 +58,15 @@ fh = fdesc->fcb->handle; Flush (fh); - cnt = Seek (fh, 0, OFFSET_CURRENT); + cnt = __dos64_getpos (fdesc->fcb); if (cnt == -1) errno = __stdc_ioerr2errno (IoErr ()); + else if (cnt != (QUAD)(long)cnt) + { + errno = EOVERFLOW; + cnt = -1; + } - return cnt; + return (long)cnt; } /* ftell */ diff --git a/compiler/posixc/ftruncate.c b/compiler/posixc/ftruncate.c index 5018936f21c..0f1c9f4f59f 100644 --- a/compiler/posixc/ftruncate.c +++ b/compiler/posixc/ftruncate.c @@ -10,6 +10,7 @@ #include #include #include "__fdesc.h" +#include "__dos64.h" /***************************************************************************** @@ -52,8 +53,8 @@ ******************************************************************************/ { - ULONG oldpos; - size_t size; + QUAD oldpos; + QUAD size; fdesc *fdesc = __getfdesc(fd); @@ -75,35 +76,38 @@ return -1; } - oldpos = Seek(fdesc->fcb->handle, 0, OFFSET_END); - size = Seek(fdesc->fcb->handle, 0, OFFSET_CURRENT); - Seek(fdesc->fcb->handle, oldpos, OFFSET_BEGINNING); + oldpos = __dos64_getpos(fdesc->fcb); + size = __dos64_getsize(fdesc->fcb); - if ((length = SetFileSize(fdesc->fcb->handle, length, OFFSET_BEGINNING)) == -1) + if (__dos64_setfilesize(fdesc->fcb, length, OFFSET_BEGINNING) == -1) { - errno = __stdc_ioerr2errno(IoErr()); + LONG ioerr = IoErr(); + errno = (ioerr == ERROR_OBJECT_TOO_LARGE) + ? EFBIG : __stdc_ioerr2errno(ioerr); return -1; } else - if (size < length) + if (size != -1 && size < length) { char buf[16]={0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; + QUAD left = length - size; - length -= size; + __dos64_seek(fdesc->fcb, size, OFFSET_BEGINNING); - oldpos = Seek(fdesc->fcb->handle, size, OFFSET_BEGINNING); - - while (length >= 16) + while (left >= 16) { FWrite(fdesc->fcb->handle, buf, 16, 1); - length -= 16; + left -= 16; } - if (length) - FWrite(fdesc->fcb->handle, buf, length, 1); + if (left) + FWrite(fdesc->fcb->handle, buf, left, 1); Flush(fdesc->fcb->handle); - Seek(fdesc->fcb->handle, oldpos, OFFSET_BEGINNING); } + /* Restore the original position */ + if (oldpos != -1) + __dos64_seek(fdesc->fcb, oldpos, OFFSET_BEGINNING); + return 0; } diff --git a/compiler/posixc/getfsstat.c b/compiler/posixc/getfsstat.c index f561ce5f4b8..44c7c37b740 100644 --- a/compiler/posixc/getfsstat.c +++ b/compiler/posixc/getfsstat.c @@ -9,6 +9,8 @@ #include #include #include + +#include "__dos64.h" #include #include #include "__upath.h" @@ -75,7 +77,7 @@ short getnixfilesystemtype(LONG id_DiskType) STRPTR name; BPTR lock; struct DosList *dlist; - struct InfoData data; + struct InfoData64 data; int fscount = 0; /* number of filesystems */ LONG ioerr = 0; @@ -112,7 +114,7 @@ short getnixfilesystemtype(LONG id_DiskType) /* Get filesystem data from lock */ if((lock = Lock(name, SHARED_LOCK))) { - if(Info(lock, &data)) + if(__dos64_info(lock, &data)) { /* Fill statfs structure */ buf[fscount - 1].f_type = getnixfilesystemtype( @@ -120,11 +122,11 @@ short getnixfilesystemtype(LONG id_DiskType) buf[fscount - 1].f_flags = 0; buf[fscount - 1].f_fsize = data.id_BytesPerBlock; buf[fscount - 1].f_bsize = data.id_BytesPerBlock; - buf[fscount - 1].f_blocks = data.id_NumBlocks; - buf[fscount - 1].f_bfree = data.id_NumBlocks - - data.id_NumBlocksUsed; - buf[fscount - 1].f_bavail = data.id_NumBlocks - - data.id_NumBlocksUsed; + buf[fscount - 1].f_blocks = data.id_NumBlocks64; + buf[fscount - 1].f_bfree = data.id_NumBlocks64 - + data.id_NumBlocksUsed64; + buf[fscount - 1].f_bavail = data.id_NumBlocks64 - + data.id_NumBlocksUsed64; buf[fscount - 1].f_files = 0; buf[fscount - 1].f_ffree = 0; buf[fscount - 1].f_fsid.val[0] = 0; diff --git a/compiler/posixc/lseek.c b/compiler/posixc/lseek.c index a6771ad3c50..0c6534cd6d2 100644 --- a/compiler/posixc/lseek.c +++ b/compiler/posixc/lseek.c @@ -11,6 +11,7 @@ #include #include #include "__fdesc.h" +#include "__dos64.h" /***************************************************************************** @@ -61,7 +62,7 @@ ******************************************************************************/ { - int cnt; + QUAD cnt; fdesc *fdesc = __getfdesc(filedes); if (!fdesc) @@ -89,7 +90,7 @@ return -1; } - cnt = Seek (fdesc->fcb->handle, offset, whence); + cnt = __dos64_seek (fdesc->fcb, offset, whence); if (cnt == -1) { @@ -102,40 +103,45 @@ is written there. Since implementing it would be rather difficult, we simply extend the file by writing zeros and hope for the best. */ - LONG abs_cur_pos = Seek(fdesc->fcb->handle, 0, OFFSET_CURRENT); + QUAD abs_cur_pos = __dos64_getpos(fdesc->fcb); if(abs_cur_pos == -1) goto error; - LONG file_size = Seek(fdesc->fcb->handle, 0, OFFSET_END); + QUAD file_size = __dos64_getsize(fdesc->fcb); if(file_size == -1) goto error; /* Now compute how much we have to extend the file */ - LONG abs_new_pos = 0; + QUAD abs_new_pos = 0; switch(whence) { case OFFSET_BEGINNING: abs_new_pos = offset; break; case OFFSET_CURRENT: abs_new_pos = abs_cur_pos + offset; break; case OFFSET_END: abs_new_pos = file_size + offset; break; } - if(abs_new_pos > abs_cur_pos) + if(abs_new_pos > file_size) { ULONG bufsize = 4096; APTR zeros = AllocMem(bufsize, MEMF_ANY | MEMF_CLEAR); if(!zeros) { /* Restore previous position */ - Seek(fdesc->fcb->handle, abs_cur_pos, OFFSET_BEGINNING); + __dos64_seek(fdesc->fcb, abs_cur_pos, OFFSET_BEGINNING); errno = ENOMEM; return -1; } - - LONG towrite = abs_new_pos - abs_cur_pos; + + if(__dos64_seek(fdesc->fcb, 0, OFFSET_END) == -1) + { + FreeMem(zeros, bufsize); + goto error; + } + QUAD towrite = abs_new_pos - file_size; do { Write(fdesc->fcb->handle, zeros, MIN(towrite, bufsize)); towrite -= bufsize; } while(towrite > 0); - + FreeMem(zeros, bufsize); } else @@ -150,8 +156,21 @@ goto error; } - return Seek(fdesc->fcb->handle, 0, OFFSET_CURRENT); + cnt = __dos64_getpos(fdesc->fcb); + if (cnt == -1) + goto error; + if (cnt != (QUAD)(off_t)cnt) + { + errno = EOVERFLOW; + return (off_t) -1; + } + + return (off_t) cnt; error: - errno = __stdc_ioerr2errno (IoErr ()); + { + LONG ioerr = IoErr (); + errno = (ioerr == ERROR_OBJECT_TOO_LARGE) + ? EOVERFLOW : __stdc_ioerr2errno (ioerr); + } return (off_t) -1; } /* __posixc_lseek */ diff --git a/compiler/posixc/lseek64.c b/compiler/posixc/lseek64.c index cd67b0c12e2..de44af377ab 100644 --- a/compiler/posixc/lseek64.c +++ b/compiler/posixc/lseek64.c @@ -11,6 +11,7 @@ #include #include #include "__fdesc.h" +#include "__dos64.h" /***************************************************************************** @@ -61,7 +62,7 @@ ******************************************************************************/ { - int cnt; + QUAD cnt; fdesc *fdesc = __getfdesc(filedes); if (!fdesc) @@ -89,7 +90,7 @@ return -1; } - cnt = Seek (fdesc->fcb->handle, offset, whence); + cnt = __dos64_seek (fdesc->fcb, offset, whence); if (cnt == -1) { @@ -102,40 +103,45 @@ is written there. Since implementing it would be rather difficult, we simply extend the file by writing zeros and hope for the best. */ - LONG abs_cur_pos = Seek(fdesc->fcb->handle, 0, OFFSET_CURRENT); + QUAD abs_cur_pos = __dos64_getpos(fdesc->fcb); if(abs_cur_pos == -1) goto error; - LONG file_size = Seek(fdesc->fcb->handle, 0, OFFSET_END); + QUAD file_size = __dos64_getsize(fdesc->fcb); if(file_size == -1) goto error; /* Now compute how much we have to extend the file */ - LONG abs_new_pos = 0; + QUAD abs_new_pos = 0; switch(whence) { case OFFSET_BEGINNING: abs_new_pos = offset; break; case OFFSET_CURRENT: abs_new_pos = abs_cur_pos + offset; break; case OFFSET_END: abs_new_pos = file_size + offset; break; } - if(abs_new_pos > abs_cur_pos) + if(abs_new_pos > file_size) { ULONG bufsize = 4096; APTR zeros = AllocMem(bufsize, MEMF_ANY | MEMF_CLEAR); if(!zeros) { /* Restore previous position */ - Seek(fdesc->fcb->handle, abs_cur_pos, OFFSET_BEGINNING); + __dos64_seek(fdesc->fcb, abs_cur_pos, OFFSET_BEGINNING); errno = ENOMEM; return -1; } - - LONG towrite = abs_new_pos - abs_cur_pos; + + if(__dos64_seek(fdesc->fcb, 0, OFFSET_END) == -1) + { + FreeMem(zeros, bufsize); + goto error; + } + QUAD towrite = abs_new_pos - file_size; do { Write(fdesc->fcb->handle, zeros, MIN(towrite, bufsize)); towrite -= bufsize; } while(towrite > 0); - + FreeMem(zeros, bufsize); } else @@ -150,8 +156,21 @@ goto error; } - return Seek(fdesc->fcb->handle, 0, OFFSET_CURRENT); + cnt = __dos64_getpos(fdesc->fcb); + if (cnt == -1) + goto error; + if (cnt != (QUAD)(__off64_t)cnt) + { + errno = EOVERFLOW; + return (__off64_t) -1; + } + + return (__off64_t) cnt; error: - errno = __stdc_ioerr2errno (IoErr ()); - return (off_t) -1; + { + LONG ioerr = IoErr (); + errno = (ioerr == ERROR_OBJECT_TOO_LARGE) + ? EOVERFLOW : __stdc_ioerr2errno (ioerr); + } + return (__off64_t) -1; } /* lseek64 */ diff --git a/compiler/posixc/mmakefile.src b/compiler/posixc/mmakefile.src index b1d30e2eabd..57187349e13 100644 --- a/compiler/posixc/mmakefile.src +++ b/compiler/posixc/mmakefile.src @@ -3,12 +3,14 @@ include $(SRCDIR)/config/aros.cfg #MM- AROS : compiler-posixc POSIXC := \ + __dos64 \ __env \ __exec \ __fdesc \ __fopen \ __fseeko \ __ftello \ + __optionallibs \ __posixc_assert \ __posixc_environ \ __posixc_init \ diff --git a/compiler/posixc/read.c b/compiler/posixc/read.c index 53547441b93..36903902eaf 100644 --- a/compiler/posixc/read.c +++ b/compiler/posixc/read.c @@ -11,6 +11,7 @@ #include #include #include "__fdesc.h" +#include "__dos64.h" /***************************************************************************** @@ -64,7 +65,7 @@ return -1; } - cnt = Read (fdesc->fcb->handle, buf, count); + cnt = __dos64_read (fdesc->fcb, buf, count); if (cnt == -1) errno = __stdc_ioerr2errno (IoErr ()); diff --git a/compiler/posixc/statfs.c b/compiler/posixc/statfs.c index 532b1c4125a..be99c4aff57 100644 --- a/compiler/posixc/statfs.c +++ b/compiler/posixc/statfs.c @@ -8,6 +8,8 @@ #include #include #include + +#include "__dos64.h" #include #include "__upath.h" @@ -51,7 +53,7 @@ short getnixfilesystemtype(LONG id_DiskType); { BPTR lock; LONG ioerr = 0; - struct InfoData data; + struct InfoData64 data; const char *apath; if (path == NULL) @@ -70,16 +72,16 @@ short getnixfilesystemtype(LONG id_DiskType); /* Get filesystem data from lock */ if(((lock = Lock(apath, SHARED_LOCK)))) { - if(Info(lock, &data)) + if(__dos64_info(lock, &data)) { /* Fill statfs structure */ buf->f_type = getnixfilesystemtype(data.id_DiskType); buf->f_flags = 0; buf->f_fsize = data.id_BytesPerBlock; buf->f_bsize = data.id_BytesPerBlock; - buf->f_blocks = data.id_NumBlocks; - buf->f_bfree = data.id_NumBlocks - data.id_NumBlocksUsed; - buf->f_bavail = data.id_NumBlocks - data.id_NumBlocksUsed; + buf->f_blocks = data.id_NumBlocks64; + buf->f_bfree = data.id_NumBlocks64 - data.id_NumBlocksUsed64; + buf->f_bavail = data.id_NumBlocks64 - data.id_NumBlocksUsed64; buf->f_files = 0; buf->f_ffree = 0; buf->f_fsid.val[0] = 0; diff --git a/compiler/posixc/write.c b/compiler/posixc/write.c index 94c28ac3895..c8cff053cf0 100644 --- a/compiler/posixc/write.c +++ b/compiler/posixc/write.c @@ -11,6 +11,7 @@ #include #include #include "__fdesc.h" +#include "__dos64.h" /***************************************************************************** @@ -56,7 +57,7 @@ return -1; } - cnt = Write (fdesc->fcb->handle, (void *)buf, count); + cnt = __dos64_write (fdesc->fcb, (void *)buf, count); if (cnt == -1) errno = __stdc_ioerr2errno (IoErr ()); diff --git a/compiler/stdc/__stdcio_dos64.c b/compiler/stdc/__stdcio_dos64.c new file mode 100644 index 00000000000..666fee4a4c2 --- /dev/null +++ b/compiler/stdc/__stdcio_dos64.c @@ -0,0 +1,85 @@ +/* + Copyright (C) 2026, The AROS Development Team. All rights reserved. + + Internal 64-bit seek helpers for stdcio.library: use dos64.library + when it is available, otherwise fall back to the 32-bit + dos.library calls. Positions the fallback cannot express fail with + IoErr() == ERROR_OBJECT_TOO_LARGE. +*/ + +#include + +#include +#include + +#include "__stdcio_intbase.h" +#include "__stdio.h" +#include "__stdcio_dos64.h" + +#include + +static struct Library *__stdcio_dos64base(void) +{ + struct StdCIOIntBase *StdCIOBase = + (struct StdCIOIntBase *)__aros_getbase_StdCIOBase(); + + if (StdCIOBase->StdCIODOS64Base == NULL) + StdCIOBase->StdCIODOS64Base = OpenLibrary("dos64.library", 50); + + return StdCIOBase->StdCIODOS64Base; +} + +/* Detect 64-bit filesystem support once per stream and cache it */ +void __stdcio_probe64(FILE *stream) +{ + struct Library *DOS64Base = __stdcio_dos64base(); + + if (DOS64Base != NULL && stream->fh != BNULL + && IsFileSystem64(stream->fh)) + stream->flags |= __STDCIO_STDIO_FS64; +} + +static struct Library *__stdcio_dos64base_for(FILE *stream) +{ + if (!(stream->flags & __STDCIO_STDIO_FS64)) + return NULL; + + return __stdcio_dos64base(); +} + +QUAD __stdcio_seek64(FILE *stream, QUAD position, LONG mode) +{ + struct Library *DOS64Base = __stdcio_dos64base_for(stream); + + if (DOS64Base != NULL) + return Seek64(stream->fh, mode, position); + + if (position != (QUAD)(LONG)position) + { + SetIoErr(ERROR_OBJECT_TOO_LARGE); + return -1; + } + return Seek(stream->fh, (LONG)position, mode); +} + +QUAD __stdcio_getpos64(FILE *stream) +{ + struct Library *DOS64Base = __stdcio_dos64base_for(stream); + + if (DOS64Base != NULL) + return GetFilePosition64(stream->fh); + + return Seek(stream->fh, 0, OFFSET_CURRENT); +} + +static int __close_stdcio_dos64(struct StdCIOIntBase *StdCIOBase) +{ + if (StdCIOBase->StdCIODOS64Base != NULL) + { + CloseLibrary(StdCIOBase->StdCIODOS64Base); + StdCIOBase->StdCIODOS64Base = NULL; + } + return 1; +} + +ADD2CLOSELIB(__close_stdcio_dos64, 0) diff --git a/compiler/stdc/__stdcio_dos64.h b/compiler/stdc/__stdcio_dos64.h new file mode 100644 index 00000000000..26caa2e1a07 --- /dev/null +++ b/compiler/stdc/__stdcio_dos64.h @@ -0,0 +1,24 @@ +#ifndef ___STDCIO_DOS64_H +#define ___STDCIO_DOS64_H + +/* + Copyright (C) 2026, The AROS Development Team. All rights reserved. + + Internal 64-bit seek helpers for stdcio.library (dos64.library when + available, 32-bit dos.library fallback otherwise). +*/ + +#include +#include + +#include + +/* Detect 64-bit filesystem support for a freshly opened stream and + cache it in the stream flags (__STDCIO_STDIO_FS64); the helpers + below then pick the 64-bit or 32-bit path directly. */ +void __stdcio_probe64(FILE *stream); + +QUAD __stdcio_seek64(FILE *stream, QUAD position, LONG mode); +QUAD __stdcio_getpos64(FILE *stream); + +#endif /* ___STDCIO_DOS64_H */ diff --git a/compiler/stdc/__stdcio_intbase.h b/compiler/stdc/__stdcio_intbase.h index 9e66af0e19f..356a92b1f68 100644 --- a/compiler/stdc/__stdcio_intbase.h +++ b/compiler/stdc/__stdcio_intbase.h @@ -18,6 +18,9 @@ struct StdCIOIntBase { struct StdCIOBase StdCIOBase; + /* __stdcio_dos64.c: optional dos64.library, for 64-bit file I/O */ + struct Library *StdCIODOS64Base; + /* getenv.c */ LONG varsize; char *envvar; diff --git a/compiler/stdc/__stdio.h b/compiler/stdc/__stdio.h index 3f5fa29f50e..8e5c0e1549f 100644 --- a/compiler/stdc/__stdio.h +++ b/compiler/stdc/__stdio.h @@ -28,6 +28,7 @@ struct __sFILE #define __STDCIO_STDIO_DONTCLOSE 0x0040L #define __STDCIO_STDIO_DONTFREE 0x0080L #define __STDCIO_STDIO_FLUSHONREAD 0x0100L +#define __STDCIO_STDIO_FS64 0x0200L /* Filesystem handles 64-bit packets */ #define __STDCIO_STDIO_RDWR __STDCIO_STDIO_WRITE | __STDCIO_STDIO_READ #endif /* ___STDIO_H */ diff --git a/compiler/stdc/fopen.c b/compiler/stdc/fopen.c index f71da1c9727..ea6b3da5289 100644 --- a/compiler/stdc/fopen.c +++ b/compiler/stdc/fopen.c @@ -12,6 +12,7 @@ #include #include "__stdio.h" +#include "__stdcio_dos64.h" #include "__stdcio_intbase.h" /***************************************************************************** @@ -125,6 +126,9 @@ if (!file->fh) goto error; + /* Detect 64-bit filesystem support once, and cache it */ + __stdcio_probe64(file); + if (file->flags & __STDCIO_STDIO_APPEND) { if (Seek(file->fh, 0, OFFSET_END) < 0) diff --git a/compiler/stdc/fseek.c b/compiler/stdc/fseek.c index 7357e1616c9..6da0cc8416e 100644 --- a/compiler/stdc/fseek.c +++ b/compiler/stdc/fseek.c @@ -9,6 +9,7 @@ #include #include "__stdio.h" +#include "__stdcio_dos64.h" #define DEBUG 0 #include @@ -61,7 +62,6 @@ ******************************************************************************/ { LONG mode; - BPTR fh = stream->fh; D(bug("[stdcio/fseek()] Entering stream=0x%x, offset=%d, whence=%d\n", stream, offset, whence @@ -86,11 +86,13 @@ return -1; } - if (Seek(fh, offset, mode) < 0) + if (__stdcio_seek64(stream, (QUAD)offset, mode) < 0) { D(bug("[stdcio/fseek()] Failed (IoErr()=%d)\n", IoErr())); if (IoErr() == ERROR_UNKNOWN) errno = EINVAL; + else if (IoErr() == ERROR_OBJECT_TOO_LARGE) + errno = EOVERFLOW; else errno = __stdc_ioerr2errno(IoErr()); return -1; diff --git a/compiler/stdc/ftell.c b/compiler/stdc/ftell.c index f13cc700f3b..e687d67fcc5 100644 --- a/compiler/stdc/ftell.c +++ b/compiler/stdc/ftell.c @@ -9,6 +9,7 @@ #include #include "__stdio.h" +#include "__stdcio_dos64.h" #define DEBUG 0 #include @@ -46,18 +47,23 @@ ******************************************************************************/ { - LONG cnt; + QUAD cnt; BPTR fh = stream->fh; D(bug("[stdcio/ftell()] Entering\n")); Flush (fh); - cnt = Seek (fh, 0, OFFSET_CURRENT); + cnt = __stdcio_getpos64 (stream); if (cnt == -1) errno = __stdc_ioerr2errno (IoErr ()); + else if (cnt != (QUAD)(long)cnt) + { + errno = EOVERFLOW; + cnt = -1; + } - D(bug("[stdcio/ftell()] Leaving cnt=%d\n", cnt)); + D(bug("[stdcio/ftell()] Leaving cnt=%ld\n", (long)cnt)); return (long int)cnt; } /* ftell */ diff --git a/compiler/stdc/include/aros/stdc/errno.h b/compiler/stdc/include/aros/stdc/errno.h index 485c00219a3..8f72646eaed 100644 --- a/compiler/stdc/include/aros/stdc/errno.h +++ b/compiler/stdc/include/aros/stdc/errno.h @@ -57,6 +57,7 @@ /* Codes used for error conversion of DOS error codes */ #define EACCES 13 /* Permission denied */ +#define EOVERFLOW 84 /* Value too large to be stored in data type */ #define ENOTBLK 15 /* Not a Block device */ #define EBUSY 16 /* Device busy */ #define EEXIST 17 /* File exists */ diff --git a/compiler/stdc/mmakefile.src b/compiler/stdc/mmakefile.src index cce93361611..e4c908265df 100644 --- a/compiler/stdc/mmakefile.src +++ b/compiler/stdc/mmakefile.src @@ -469,6 +469,7 @@ STDC_COMMON := \ STDCIO := \ __stdcio_assert \ + __stdcio_dos64 \ __stdcio_init \ __stdio \ clearerr \ diff --git a/developer/debug/test/dos/buffered_io_mock.py b/developer/debug/test/dos/buffered_io_mock.py new file mode 100644 index 00000000000..5e9946f79be --- /dev/null +++ b/developer/debug/test/dos/buffered_io_mock.py @@ -0,0 +1,146 @@ +# Copyright (C) 2026, The AROS Development Team. All rights reserved. +"""Host tests for DOS buffering, with controlled handler results. + +Run with Python 3 and a C compiler supporting AddressSanitizer and UBSan. +The actual FRead/FWrite/UnGetC/FGetC function bodies are compiled against +mock I/O callbacks to cover oversized requests and short/failed writes. +""" +from pathlib import Path +import re +import shutil +import subprocess +import tempfile + +root = Path(__file__).resolve().parents[4] +header=r''' +#include +#include +#include +#include +#include +typedef uint8_t UBYTE; +typedef uint32_t ULONG; +typedef int32_t LONG; +typedef uintptr_t BPTR; +typedef intptr_t SIPTR; +typedef void *APTR; +typedef const void *CONST_APTR; +#define CONST const +#define TRUE 1 +#define FALSE 0 +#define BNULL 0 +#define BADDR(x) ((void *)(uintptr_t)(x)) +#define MKBADDR(x) ((BPTR)(uintptr_t)(x)) +#define IOBUFSIZE 256 +#define OFFSET_CURRENT 0 +#define OFFSET_END 1 +#define ERROR_NO_FREE_STORE 103 +#define ERROR_SEEK_ERROR 219 +#define AROS_LIBFUNC_INIT +#define AROS_LIBFUNC_EXIT +#define AROS_LHA(t,n,r) t n +#define AROS_LH1(t,n,a,bt,bn,l,m) t Dos_##n(a,bt bn) +#define AROS_LH2(t,n,a,b,bt,bn,l,m) t Dos_##n(a,b,bt bn) +#define AROS_LH4(t,n,a,b,c,d,bt,bn,l,m) t Dos_##n(a,b,c,d,bt bn) +#define ASSERT(x) assert(x) +#define ASSERT_VALID_PTR(x) assert(x) +#define ASSERT_VALID_PROCESS(x) assert(x) +#define D(x) +struct DosLibrary {int unused;}; +struct Process {SIPTR pr_Result2;}; +struct FileHandle {LONG fh_Pos,fh_End;ULONG fh_Flags,fh_BufSize;BPTR fh_Buf,fh_OrigBuf;}; +#include "DOS_FHFLAGS_PATH" +struct Stream {struct FileHandle fh;UBYTE data[131072];ULONG pos,len;int reads,writes,flushes,shortwrite,zero_write,fail_write,fail_after,force_eof;LONG read_request,write_request;}; +static struct DosLibrary base; +static struct Process process; +static int fail_alloc; +static void *FindTask(void *x) {return &process;} +static void SetIoErr(LONG x) {process.pr_Result2=x;} +static LONG IoErr(void) {return process.pr_Result2;} +static void CopyMem(const void *src,void *dst,ULONG n) {memcpy(dst,src,n);} +static void *vbuf_alloc(struct FileHandle *f,char *buf,ULONG n) { + if(fail_alloc)return NULL; + if(n<208)n=208; + if(!buf){buf=malloc(n);f->fh_OrigBuf=MKBADDR(buf);f->fh_Flags|=FHF_OWNBUF;} + f->fh_Buf=MKBADDR(buf);f->fh_BufSize=n;f->fh_Flags|=FHF_BUF;f->fh_Pos=0;f->fh_End=(f->fh_Flags&FHF_WRITE)?n:0;return buf; +} +static LONG Read(BPTR file,void *b,LONG n) { + struct Stream *s=BADDR(file);assert(n>=0);s->reads++;s->read_request=n; + if(s->force_eof)return 0; + ULONG k=(ULONG)n;if(k>s->len-s->pos)k=s->len-s->pos; + memcpy(b,s->data+s->pos,k);s->pos+=k;return k; +} +static LONG Write(BPTR file,const void *b,LONG n) { + struct Stream *s=BADDR(file);assert(n>=0);s->writes++;s->write_request=n; + if(s->fail_write || (s->fail_after && s->writes>s->fail_after)){SetIoErr(222);return -1;} + if(s->zero_write)return 0; + ULONG k=(ULONG)n;if(s->shortwrite && k>(ULONG)s->shortwrite)k=s->shortwrite; + assert(s->pos+k<=sizeof(s->data));memcpy(s->data+s->pos,b,k);s->pos+=k;if(s->pos>s->len)s->len=s->pos;return k; +} +static LONG Flush(BPTR file) { + struct Stream *s=BADDR(file);struct FileHandle *f=&s->fh;s->flushes++; + if(f->fh_Flags&FHF_WRITE){ + if(f->fh_Flags&FHF_APPEND)s->pos=s->len; + ULONG done=0; + while(done<(ULONG)f->fh_Pos){LONG n=Write(file,(UBYTE*)BADDR(f->fh_Buf)+done,f->fh_Pos-done);if(n<=0)return 0;done+=n;} + f->fh_Pos=0; + }else if(f->fh_Posfh_End){s->pos-=f->fh_End-f->fh_Pos;f->fh_Pos=f->fh_End=0;} + return 1; +} +static LONG Seek(BPTR file,LONG n,LONG mode) { + struct Stream *s=BADDR(file);struct FileHandle *f=&s->fh; + if(f->fh_Flags&FHF_WRITE)assert(Flush(file)); + LONG old=s->pos-(f->fh_End-f->fh_Pos);f->fh_Pos=f->fh_End=0; + s->pos=mode==OFFSET_END?s->len+n:old+n;return old; +} +LONG vbuf_fetch(BPTR,UBYTE*,ULONG,struct DosLibrary*); +LONG FWriteChars(BPTR,const UBYTE*,ULONG,struct DosLibrary*); +static void init(struct Stream *s) {memset(s,0,sizeof(*s));fail_alloc=0;SetIoErr(0);} +static void end(struct Stream *s) {free(BADDR(s->fh.fh_Buf));s->fh.fh_Buf=0;} +''' +sources='' +for name in ('fread.c','fwrite.c','ungetc.c','fgetc.c'): + s=(root/'rom/dos'/name).read_text();sources+=re.sub(r'^#include[^\n]*\n','',s,flags=re.M)+'\n' +footer=r''' +int main(void) { + static struct Stream s;static UBYTE buf[65536],pattern[65536];BPTR f=MKBADDR(&s);int tests=0; + for(unsigned i=0;i1 && s.len==1000 && !memcmp(s.data,pattern,1000));end(&s);tests++; + init(&s);s.zero_write=1;assert(Dos_FWrite(f,pattern,1,1024,&base)==EOF && s.writes==1);end(&s);tests++; + init(&s);s.fail_write=1;assert(Dos_FWrite(f,pattern,0x80000000U,1,&base)==EOF && s.write_request==INT32_MAX && IoErr()==222);end(&s);tests++; + init(&s);s.fail_write=1;assert(Dos_FWrite(f,pattern,65536,65536,&base)==EOF && s.write_request==2147418112);end(&s);tests++; + init(&s);memcpy(s.data,"start",5);s.len=5;s.fh.fh_Flags=FHF_APPEND; + assert(Dos_FWrite(f,"pending",1,7,&base)==7 && s.fh.fh_Pos==7 && s.len==5); + assert(Dos_FWrite(f,pattern,1,8192,&base)==8192 && s.len==8204 && !memcmp(s.data,"startpending",12) && !memcmp(s.data+12,pattern,8192));end(&s);tests++; + init(&s);s.fh.fh_Flags=FHF_LINEBUF;assert(Dos_FWrite(f,pattern,1,1024,&base)==1024);assert(Flush(f));assert(s.writes>1 && s.len==1024 && !memcmp(s.data,pattern,1024));end(&s);tests++; + init(&s);s.fh.fh_Flags=FHF_NOBUF;s.shortwrite=13;assert(Dos_FWrite(f,pattern,1,1024,&base)==1024 && s.len==1024 && !memcmp(s.data,pattern,1024));end(&s);tests++; + init(&s);s.shortwrite=7;s.fail_after=2;assert(Dos_FWrite(f,pattern,1,1024,&base)==EOF && s.writes==3 && s.len==14 && IoErr()==222);end(&s);tests++; + printf("%d buffered-I/O cases PASS\n",tests);return 0; +} +''' +header = header.replace("DOS_FHFLAGS_PATH", + str(root / "rom/dos/dos_fhflags.h")) +compiler = shutil.which("clang") or shutil.which("cc") +if compiler is None: + raise SystemExit("A C compiler is required") +with tempfile.TemporaryDirectory(prefix="aros-buffered-io-") as directory: + p = Path(directory) + fixture = p / "buffered-io-mock.c" + fixture.write_text(header + sources + footer) + subprocess.run([compiler, "-std=c11", "-Wall", "-Wextra", "-Werror", + "-Wno-unused-parameter", "-Wno-sign-compare", + "-fsanitize=address,undefined", str(fixture), + "-o", str(p / "buffered-io-mock")], check=True) + subprocess.run([str(p / "buffered-io-mock")], check=True) diff --git a/developer/debug/test/dos/fread.c b/developer/debug/test/dos/fread.c index 90e1e3906ac..430913622b0 100644 --- a/developer/debug/test/dos/fread.c +++ b/developer/debug/test/dos/fread.c @@ -1,14 +1,28 @@ /* +<<<<<<< HEAD Copyright © 1995-2014, The AROS Development Team. All rights reserved. $Id$ +======= + Copyright (C) 1995-2026, The AROS Development Team. All rights reserved. +>>>>>>> ba40ca031a (dos: preserve pushback and complete direct buffered I/O requests) */ #include +#include +#include +#include +#include #include +#include +#include "../../../../rom/dos/dos_fhflags.h" #include "test.h" BPTR fh = BNULL; +static UBYTE *data = NULL; +static UBYTE *readbuf = NULL; +#define DATA_SIZE 65536 +#define LARGE_READ 8192 static void closehandles() { @@ -20,6 +34,7 @@ int main() LONG result = 0; LONG ioerr = 0; TEXT buffer[16]; + ULONG i; fh = Open("T:a", MODE_NEWFILE); @@ -30,6 +45,71 @@ int main() TEST((result == 0)); TEST((ioerr == 0)); + closehandles(); + data = AllocVec(DATA_SIZE, MEMF_ANY); + readbuf = AllocVec(DATA_SIZE, MEMF_ANY); + TEST(data != NULL && readbuf != NULL); + for (i = 0; i < DATA_SIZE; i++) + data[i] = i & 0xff; + fh = Open("T:a", MODE_NEWFILE); + TEST(fh != BNULL); + TEST(Write(fh, data, DATA_SIZE) == DATA_SIZE); + closehandles(); + + /* Direct reads must preserve the last byte for either UnGetC form. */ + fh = Open("T:a", MODE_OLDFILE); + TEST(fh != BNULL); + TEST(FRead(fh, readbuf, 1, LARGE_READ) == LARGE_READ); + TEST(memcmp(readbuf, data, LARGE_READ) == 0); + TEST(UnGetC(fh, -1) != 0); + TEST(FGetC(fh) == data[LARGE_READ - 1]); + TEST(FGetC(fh) == data[LARGE_READ]); + closehandles(); + + fh = Open("T:a", MODE_OLDFILE); + TEST(fh != BNULL); + TEST(FRead(fh, readbuf, 1, LARGE_READ) == LARGE_READ); + TEST(UnGetC(fh, 'X') != 0); + TEST(FGetC(fh) == 'X'); + TEST(FGetC(fh) == data[LARGE_READ]); + closehandles(); + + /* Unread buffered data and direct reads must agree on file position. */ + fh = Open("T:a", MODE_OLDFILE); + TEST(fh != BNULL); + TEST(FRead(fh, readbuf, 1, 17) == 17); + TEST(FRead(fh, readbuf + 17, 1, LARGE_READ) == LARGE_READ); + TEST(memcmp(readbuf, data, LARGE_READ + 17) == 0); + TEST(Seek(fh, 0, OFFSET_CURRENT) == LARGE_READ + 17); + TEST(FRead(fh, readbuf, 1, 23) == 23); + TEST(memcmp(readbuf, data + LARGE_READ + 17, 23) == 0); + TEST(Seek(fh, 0, OFFSET_CURRENT) == LARGE_READ + 40); + TEST(FRead(fh, readbuf, 1, LARGE_READ) == LARGE_READ); + TEST(memcmp(readbuf, data + LARGE_READ + 40, LARGE_READ) == 0); + TEST(Seek(fh, 0, OFFSET_CURRENT) == 2 * LARGE_READ + 40); + closehandles(); + + /* Append pending buffered bytes before a large byte-block write. */ + fh = Open("T:a", MODE_NEWFILE); + TEST(fh != BNULL); + TEST(Write(fh, "start", 5) == 5); + closehandles(); + fh = Open("T:a", MODE_READWRITE); + TEST(fh != BNULL); + TEST(SetVBuf(fh, NULL, BUF_FULL, 256) == 0); + ((struct FileHandle *)BADDR(fh))->fh_Flags |= FHF_APPEND; + TEST(FWrite(fh, "pending", 1, 7) == 7); + TEST(((struct FileHandle *)BADDR(fh))->fh_Pos == 7); + TEST(FWrite(fh, data, 1, LARGE_READ) == LARGE_READ); + TEST(Flush(fh) != 0); + closehandles(); + fh = Open("T:a", MODE_OLDFILE); + TEST(fh != BNULL); + TEST(Read(fh, readbuf, 12 + LARGE_READ) == 12 + LARGE_READ); + TEST(memcmp(readbuf, "startpending", 12) == 0); + TEST(memcmp(readbuf + 12, data, LARGE_READ) == 0); + TEST(Read(fh, buffer, 1) == 0); + /* EOF */ SetIoErr(0); result = FRead(fh, buffer, 1, 1); @@ -52,4 +132,8 @@ int main() void cleanup() { closehandles(); + if (data) FreeVec(data); + if (readbuf) FreeVec(readbuf); + data = readbuf = NULL; + DeleteFile("T:a"); } diff --git a/rom/dos/dos_fhflags.h b/rom/dos/dos_fhflags.h new file mode 100644 index 00000000000..6adba9bb019 --- /dev/null +++ b/rom/dos/dos_fhflags.h @@ -0,0 +1,21 @@ +#ifndef DOS_FHFLAGS_H +#define DOS_FHFLAGS_H + +/* + Copyright (C) 2026, The AROS Development Team. All rights reserved. + + Desc: FileHandle fh_Flags definitions, shared between dos.library + and dos64.library. The flags are AROS specific and therefore + PRIVATE - they describe dos.library's buffering state and + must not be interpreted by applications. +*/ + +#define FHF_WRITE 0x80000000 +#define FHF_BUF 0x00000001 +#define FHF_APPEND 0x00000002 +#define FHF_LINEBUF 0x00000004 +#define FHF_NOBUF 0x00000008 +#define FHF_OWNBUF 0x00000010 +#define FHF_FLUSHING 0x00000020 + +#endif /* DOS_FHFLAGS_H */ diff --git a/rom/dos/dos_intern.h b/rom/dos/dos_intern.h index 25afd52cd26..fd29408b5a9 100644 --- a/rom/dos/dos_intern.h +++ b/rom/dos/dos_intern.h @@ -94,13 +94,7 @@ struct vfp }; /* fh_Flags. The flags are AROS specific and therefore PRIVATE.. */ -#define FHF_WRITE 0x80000000 -#define FHF_BUF 0x00000001 -#define FHF_APPEND 0x00000002 -#define FHF_LINEBUF 0x00000004 -#define FHF_NOBUF 0x00000008 -#define FHF_OWNBUF 0x00000010 -#define FHF_FLUSHING 0x00000020 +#include "dos_fhflags.h" #define FPUTC(f,c) \ (((struct FileHandle *)BADDR(f))->fh_Flags&FHF_WRITE&& \ diff --git a/rom/dos/exall.c b/rom/dos/exall.c index 7e0abfc5eed..7e495f019e7 100644 --- a/rom/dos/exall.c +++ b/rom/dos/exall.c @@ -61,6 +61,7 @@ ED_DATE - date information (3 longwords) ED_COMMENT - file comment (NULL if no comment exists) ED_OWNER - owner user and group id + ED_SIZE64 - 64-bit size in bytes (ed_Size64) This is an incremental list, meaning that if you specify ED_OWNER you will get ALL attributes! @@ -150,7 +151,8 @@ offsetof(struct ExAllData,ed_Days), offsetof(struct ExAllData,ed_Comment), offsetof(struct ExAllData,ed_OwnerUID), - sizeof(struct ExAllData) + offsetof(struct ExAllData,ed_Size64), /* ED_OWNER: up to ed_OwnerGID */ + sizeof(struct ExAllData) /* ED_SIZE64 */ }; /* Reset the 'fake' error */ @@ -219,7 +221,7 @@ } while (0) - if (data > ED_OWNER) + if (data > ED_SIZE64) /* We don't have that many fields to fill in... */ err = ERROR_BAD_NUMBER; else @@ -247,6 +249,11 @@ /* Switch over the requested fields and fill them as appropriate. */ switch(data) { + case ED_SIZE64: + /* Only the 32-bit size is known here */ + curr->ed_Size64 = (UQUAD)(ULONG)icontrol->fib->fib_Size; + + /* Fall through */ case ED_OWNER: curr->ed_OwnerUID = icontrol->fib->fib_OwnerUID; curr->ed_OwnerGID = icontrol->fib->fib_OwnerGID; diff --git a/rom/dos/exnext.c b/rom/dos/exnext.c index 209d13529f9..9bdd14bf6e0 100644 --- a/rom/dos/exnext.c +++ b/rom/dos/exnext.c @@ -73,7 +73,7 @@ ASSERT_VALID_FILELOCK(lock); D(bug("[ExNext] lock=%x fib=%x\n", fl, fileInfoBlock)); - ret = dopacket2(DOSBase, NULL, fl->fl_Task, ACTION_EXAMINE_NEXT, lock, MKBADDR(fileInfoBlock)); + ret = dopacket2(DOSBase, NULL, fl ? fl->fl_Task : GetFileSysTask(), ACTION_EXAMINE_NEXT, lock, MKBADDR(fileInfoBlock)); if (ret) { fixfib(fileInfoBlock); D(bug("[ExNext] '%s'\n", fileInfoBlock->fib_FileName)); diff --git a/rom/dos/flush.c b/rom/dos/flush.c index 9d08e50f54f..40eec372580 100644 --- a/rom/dos/flush.c +++ b/rom/dos/flush.c @@ -78,7 +78,7 @@ fh->fh_Pos = fh->fh_End = 0; /* Read mode. Try to seek back to the current position. */ - if( InternalSeek( fh, offset, OFFSET_CURRENT, DOSBase ) < 0 ) + if( InternalSeek( fh, offset, OFFSET_CURRENT, DOSBase ) == -1 ) { return FALSE; } diff --git a/rom/dos/fread.c b/rom/dos/fread.c index a9b457d4973..0dcc0266456 100644 --- a/rom/dos/fread.c +++ b/rom/dos/fread.c @@ -1,6 +1,10 @@ /* +<<<<<<< HEAD Copyright © 1995-2014, The AROS Development Team. All rights reserved. $Id$ +======= + Copyright (C) 1995-2026, The AROS Development Team. All rights reserved. +>>>>>>> ba40ca031a (dos: preserve pushback and complete direct buffered I/O requests) Desc: Lang: english @@ -11,6 +15,8 @@ #define FETCHERR (-2) +static LONG direct_fetch(BPTR file, UBYTE *buffer, ULONG fetchsize, struct DosLibrary *DOSBase); + /***************************************************************************** NAME */ @@ -71,7 +77,9 @@ while(fetchsize > 0) { - res = vbuf_fetch(fh, ptr, fetchsize, DOSBase); + res = direct_fetch(fh, ptr, fetchsize, DOSBase); + if (res == 0) + res = vbuf_fetch(fh, ptr, fetchsize, DOSBase); if (res < 0) break; ptr += res; @@ -121,6 +129,56 @@ static LONG handle_write_mode(BPTR file, struct DosLibrary * DOSBase) return 0; } +/* + * A request at least one buffer long gains nothing from the buffer: once + * it is empty, read straight into the caller's memory with one packet. + * Returns 0 when the buffered path must be used instead, otherwise the + * same values as vbuf_fetch(). + */ +static LONG direct_fetch(BPTR file, UBYTE *buffer, ULONG fetchsize, struct DosLibrary *DOSBase) +{ + struct FileHandle *fh = (struct FileHandle *)BADDR(file); + ULONG bufsize; + LONG size; + + /* Buffered characters, a pushed back EOF, or a pending write */ + if (fh == NULL || fh->fh_Pos != fh->fh_End || (fh->fh_Flags & FHF_WRITE)) + return 0; + + if (fh->fh_Buf == BNULL) + bufsize = IOBUFSIZE; + else if (fh->fh_Buf != fh->fh_OrigBuf) + bufsize = 208; + else + bufsize = fh->fh_BufSize; + if (fetchsize < bufsize) + return 0; + + /* Keep room for the last character so UnGetC() remains valid. Allocate + * before reading, so allocation failure cannot consume input. + */ + if (fh->fh_Buf == BNULL && vbuf_alloc(fh, NULL, bufsize) == NULL) + { + SetIoErr(ERROR_NO_FREE_STORE); + return FETCHERR; + } + + /* Read() takes a signed 32-bit length, including on 64-bit targets. */ + if (fetchsize > 0x7FFFFFFFUL) + fetchsize = 0x7FFFFFFFUL; + + size = Read(file, buffer, fetchsize); + if (size > 0) + { + ((UBYTE *)BADDR(fh->fh_Buf))[0] = buffer[size - 1]; + fh->fh_Pos = fh->fh_End = 1; + } + else + fh->fh_Pos = fh->fh_End = 0; + + return (size > 0) ? size : EOF; +} + /* Fetches up to remaining buffer content from file buffer * Return values: * (-2) on error diff --git a/rom/dos/fwrite.c b/rom/dos/fwrite.c index c7770444bc3..fa87aa2e2c5 100644 --- a/rom/dos/fwrite.c +++ b/rom/dos/fwrite.c @@ -1,6 +1,10 @@ /* +<<<<<<< HEAD Copyright © 1995-2013, The AROS Development Team. All rights reserved. $Id$ +======= + Copyright (C) 1995-2026, The AROS Development Team. All rights reserved. +>>>>>>> ba40ca031a (dos: preserve pushback and complete direct buffered I/O requests) Lang: english */ @@ -8,6 +12,9 @@ #include +static LONG write_direct(BPTR file, CONST UBYTE *buffer, ULONG length, + struct DosLibrary *DOSBase); + /***************************************************************************** @@ -62,23 +69,46 @@ ASSERT(blocklen > 0); ASSERT(numblocks > 0); - ULONG written; + ULONG written = 0; const UBYTE *ptr; ptr = block; SetIoErr(0); - for(written = 0; written < numblocks; written++) + if (blocklen == 0 || numblocks == 0) + return 0; + + while (written < numblocks) { - if (FWriteChars(fh, ptr, blocklen, DOSBase) != blocklen) + ULONG blocks = numblocks - written; + ULONG length; + + /* Batch blocks without overflowing the product or the signed byte + * count. A single oversized block is split into smaller writes. + */ + if (blocklen <= 0x7FFFFFFFUL) { - return(EOF); + ULONG maxblocks = 0x7FFFFFFFUL / blocklen; + if (blocks > maxblocks) + blocks = maxblocks; + length = blocks * blocklen; } else { - ptr += blocklen; + blocks = 1; + length = blocklen; } + + while (length > 0) + { + ULONG chunk = length > 0x7FFFFFFFUL ? 0x7FFFFFFFUL : length; + if (FWriteChars(fh, ptr, chunk, DOSBase) != (LONG)chunk) + return EOF; + ptr += chunk; + length -= chunk; + } + written += blocks; } return written; @@ -105,7 +135,7 @@ FWriteChars(BPTR file, CONST UBYTE* buffer, ULONG length, struct DosLibrary *DOS if (fh->fh_Pos < fh->fh_End) { /* Read mode. Try to seek back to the current position. */ - if (Seek(file, fh->fh_Pos - fh->fh_End, OFFSET_CURRENT) < 0) + if (Seek(file, fh->fh_Pos - fh->fh_End, OFFSET_CURRENT) == -1) { fh->fh_Pos = fh->fh_End = 0; @@ -144,9 +174,16 @@ FWriteChars(BPTR file, CONST UBYTE* buffer, ULONG length, struct DosLibrary *DOS if (goOn) { - written = Write(file, buffer, length); + written = write_direct(file, buffer, length, DOSBase); } } + else if (!(fh->fh_Flags & FHF_LINEBUF) && length >= (ULONG)fh->fh_End) + { + /* At least a buffer's worth: write it with one packet. Flush() + * also moves an append-mode handle to the end of the file. */ + if ((fh->fh_Pos == 0 && !(fh->fh_Flags & FHF_APPEND)) || Flush(file)) + written = write_direct(file, buffer, length, DOSBase); + } else { for (written = 0; written < length; ++written) @@ -179,3 +216,25 @@ FWriteChars(BPTR file, CONST UBYTE* buffer, ULONG length, struct DosLibrary *DOS return(written); } + +static LONG write_direct(BPTR file, CONST UBYTE *buffer, ULONG length, + struct DosLibrary *DOSBase) +{ + ULONG written = 0; + + while (written < length) + { + ULONG chunk = length - written; + LONG size; + + if (chunk > 0x7FFFFFFFUL) + chunk = 0x7FFFFFFFUL; + size = Write(file, buffer + written, chunk); + /* A zero-length result makes no progress; do not loop forever. */ + if (size <= 0) + return EOF; + written += size; + } + + return written; +} diff --git a/rom/dos/matchnext.c b/rom/dos/matchnext.c index 66c5162b81d..ac9e2b18d74 100644 --- a/rom/dos/matchnext.c +++ b/rom/dos/matchnext.c @@ -156,7 +156,7 @@ { ac->an_Lock = DupLock(origdir); - if (!ac->an_Lock) + if (!ac->an_Lock && origdir) { error = IoErr(); goto done; diff --git a/rom/dos64/allocdosobject64.c b/rom/dos64/allocdosobject64.c new file mode 100644 index 00000000000..93cac1701be --- /dev/null +++ b/rom/dos64/allocdosobject64.c @@ -0,0 +1,75 @@ +/* + Copyright (C) 2026, The AROS Development Team. All rights reserved. + + Desc: Create 64-bit dos objects. +*/ + +#include +#include +#include "dos64_intern.h" + +/***************************************************************************** + + NAME */ +#include + + AROS_LH2(APTR, AllocDosObject64, + +/* SYNOPSIS */ + AROS_LHA(ULONG, type, D1), + AROS_LHA(const struct TagItem *, tags, D2), + +/* LOCATION */ + struct Dos64Base *, DOS64Base, 21, Dos64) + +/* FUNCTION + Creates a dos object of a given type, for use with the 64-bit + dos64.library functions. Free the object with FreeDosObject64() + when done. + + INPUTS + type - object type (DOS64_FIB, DOS64_INFODATA, DOS64_RECORDLOCK, + see ) + tags - future extensions, pass NULL + + RESULT + Pointer to the new object, or NULL on failure. IoErr() gives + additional information in that case. + + NOTES + + EXAMPLE + + BUGS + + SEE ALSO + FreeDosObject64(), dos.library/AllocDosObject() + + INTERNALS + +*****************************************************************************/ +{ + AROS_LIBFUNC_INIT + + ULONG size; + + switch (type) + { + case DOS64_FIB: + size = sizeof(struct FileInfoBlock); + break; + case DOS64_INFODATA: + size = sizeof(struct InfoData64); + break; + case DOS64_RECORDLOCK: + size = sizeof(struct RecordLock64); + break; + default: + SetIoErr(ERROR_BAD_NUMBER); + return NULL; + } + + return AllocVec(size, MEMF_PUBLIC | MEMF_CLEAR); + + AROS_LIBFUNC_EXIT +} /* AllocDosObject64 */ diff --git a/rom/dos64/changefileposition64.c b/rom/dos64/changefileposition64.c new file mode 100644 index 00000000000..d2633c0db28 --- /dev/null +++ b/rom/dos64/changefileposition64.c @@ -0,0 +1,60 @@ +/* + Copyright (C) 2026, The AROS Development Team. All rights reserved. + + Desc: Change the current 64-bit position in a file (boolean result). +*/ + +#include +#include "dos64_intern.h" + +/***************************************************************************** + + NAME */ +#include + + AROS_LH2QUAD1(LONG, ChangeFilePosition64, + +/* SYNOPSIS */ + AROS_LHA(BPTR, file, D1), + AROS_LHA(LONG, mode, D2), + AROS_LHAQUAD(QUAD, position, D3, D4), + +/* LOCATION */ + struct Dos64Base *, DOS64Base, 9, Dos64) + +/* FUNCTION + Changes the current read/write position in a file with full + 64-bit range. Behaves like Seek64() but returns a boolean + result instead of the previous position, matching the + AmigaOS 4 style API. + + INPUTS + file - filehandle + mode - Where to count from. Either OFFSET_BEGINNING, + OFFSET_CURRENT or OFFSET_END. + position - relative offset in bytes (positive, negative or 0). + + RESULT + Boolean success indicator; on DOSFALSE, IoErr() gives + additional information. + + NOTES + + EXAMPLE + + BUGS + + SEE ALSO + Seek64(), GetFilePosition64() + + INTERNALS + +*****************************************************************************/ +{ + AROS_LIBFUNC_INIT + + return (dos64_SeekBuffered(DOS64Base, file, position, mode) == -1) + ? DOSFALSE : DOSTRUE; + + AROS_LIBFUNC_EXIT +} /* ChangeFilePosition64 */ diff --git a/rom/dos64/changefilesize64.c b/rom/dos64/changefilesize64.c new file mode 100644 index 00000000000..84923d3629f --- /dev/null +++ b/rom/dos64/changefilesize64.c @@ -0,0 +1,66 @@ +/* + Copyright (C) 2026, The AROS Development Team. All rights reserved. + + Desc: Change the size of a file, 64-bit version (boolean result). +*/ + +#include +#include "dos64_intern.h" + +/***************************************************************************** + + NAME */ +#include + + AROS_LH2QUAD1(LONG, ChangeFileSize64, + +/* SYNOPSIS */ + AROS_LHA(BPTR, file, D1), + AROS_LHA(LONG, mode, D2), + AROS_LHAQUAD(QUAD, size, D3, D4), + +/* LOCATION */ + struct Dos64Base *, DOS64Base, 10, Dos64) + +/* FUNCTION + Change the size of a file with full 64-bit range. Behaves like + SetFileSize64() but returns a boolean result instead of the + new size, matching the AmigaOS 4 style API. + + INPUTS + file - filehandle + mode - OFFSET_BEGINNING, OFFSET_CURRENT or OFFSET_END + size - relative size + + RESULT + Boolean success indicator; on DOSFALSE, IoErr() gives + additional information. + + NOTES + + EXAMPLE + + BUGS + + SEE ALSO + SetFileSize64(), GetFileSize64() + + INTERNALS + +*****************************************************************************/ +{ + AROS_LIBFUNC_INIT + + struct FileHandle *fh = BADDR(file); + + if (fh == NULL) + { + SetIoErr(ERROR_INVALID_LOCK); + return DOSFALSE; + } + + return (dos64_SetFileSize(DOS64Base, fh, size, mode, FALSE) == -1) + ? DOSFALSE : DOSTRUE; + + AROS_LIBFUNC_EXIT +} /* ChangeFileSize64 */ diff --git a/rom/dos64/dos64.conf b/rom/dos64/dos64.conf new file mode 100644 index 00000000000..07e094810ac --- /dev/null +++ b/rom/dos64/dos64.conf @@ -0,0 +1,44 @@ +##begin config +version 51.0 +basename Dos64 +libbase DOS64Base +libbasetype struct Dos64Base +libbasetypeextern struct Library +residentpri -121 +options noexpunge +##end config + +##begin cdef +#include +#include +#include +#include +#include +##end cdef + +##begin cdefprivate +#include "dos64_intern.h" +##end cdefprivate + +##begin functionlist +QUAD Seek64(BPTR file, LONG mode, QUAD position) (D1, D2, D3/D4) +QUAD SetFileSize64(BPTR file, LONG mode, QUAD offset) (D1, D2, D3/D4) +QUAD GetFilePosition64(BPTR file) (D1) +QUAD GetFileSize64(BPTR file) (D1) +LONG ChangeFilePosition64(BPTR file, LONG mode, QUAD position) (D1, D2, D3/D4) +LONG ChangeFileSize64(BPTR file, LONG mode, QUAD size) (D1, D2, D3/D4) +QUAD Read64(BPTR file, APTR buffer, QUAD length) (D1, D2, D3/D4) +QUAD Write64(BPTR file, CONST_APTR buffer, QUAD length) (D1, D2, D3/D4) +LONG Examine64(BPTR lock, struct FileInfoBlock *fib, struct TagItem *tags) (D1, D2, D3) +LONG ExNext64(BPTR lock, struct FileInfoBlock *fib, struct TagItem *tags) (D1, D2, D3) +LONG ExamineFH64(BPTR fh, struct FileInfoBlock *fib, struct TagItem *tags) (D1, D2, D3) +LONG Info64(BPTR lock, struct InfoData64 *parameterBlock) (D1, D2) +BOOL LockRecord64(struct RecordLock64 *rec, ULONG timeout) (D1, D2) +BOOL LockRecords64(struct RecordLock64 *recArray, ULONG timeout) (D1, D2) +BOOL UnLockRecord64(struct RecordLock64 *rec) (D1) +BOOL UnLockRecords64(struct RecordLock64 *recArray) (D1) +APTR AllocDosObject64(ULONG type, const struct TagItem *tags) (D1, D2) +void FreeDosObject64(ULONG type, APTR ptr) (D1, D2) +LONG IsFileSystem64(BPTR file) (D1) +LONG ExamineName64(CONST_STRPTR name, struct FileInfoBlock *fib, struct TagItem *tags) (D1, D2, D3) +##end functionlist diff --git a/rom/dos64/dos64_init.c b/rom/dos64/dos64_init.c new file mode 100644 index 00000000000..4df44046ebf --- /dev/null +++ b/rom/dos64/dos64_init.c @@ -0,0 +1,32 @@ +/* + Copyright (C) 2026, The AROS Development Team. All rights reserved. + + Desc: dos64.library initialisation. +*/ + +#include +#include + +#include + +#include "dos64_intern.h" + +#include LC_LIBDEFS_FILE + +static int Dos64_Init(struct Dos64Base *DOS64Base) +{ + DOS64Base->d64_DosBase = (struct DosLibrary *)OpenLibrary("dos.library", 50); + + return DOS64Base->d64_DosBase != NULL; +} + +static int Dos64_Expunge(struct Dos64Base *DOS64Base) +{ + if (DOS64Base->d64_DosBase) + CloseLibrary(&DOS64Base->d64_DosBase->dl_lib); + + return TRUE; +} + +ADD2INITLIB(Dos64_Init, 0) +ADD2EXPUNGELIB(Dos64_Expunge, 0) diff --git a/rom/dos64/dos64_intern.h b/rom/dos64/dos64_intern.h new file mode 100644 index 00000000000..88f1fc76fad --- /dev/null +++ b/rom/dos64/dos64_intern.h @@ -0,0 +1,135 @@ +#ifndef DOS64_INTERN_H +#define DOS64_INTERN_H + +/* + Copyright (C) 2026, The AROS Development Team. All rights reserved. + + Desc: Internal definitions for dos64.library +*/ + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +struct Dos64Base +{ + struct Library d64_Lib; + struct DosLibrary *d64_DosBase; +}; + +/* + * Inside the library functions the base parameter is named DOS64Base; + * route the dos.library interface through the base we opened at init. + * (proto/dos.h is included above, so its libbase declaration is not + * affected by this macro.) + */ +#define DOSBase (DOS64Base->d64_DosBase) + +/* Filehandle buffering flags, shared with dos.library */ +#include "dos_fhflags.h" + +/* + * Errors that indicate the filesystem does not understand a packet + * type, meaning we should fall back to the 32-bit operation. + */ +#define dos64_UnsupportedAction(err) \ + ((err) == ERROR_ACTION_NOT_KNOWN || \ + (err) == ERROR_NOT_IMPLEMENTED || \ + (err) == ERROR_BAD_NUMBER) + +/* + * A value-returning packet did not give us an answer, so the caller + * should ask again over the 32-bit path. + * + * Handlers reply to a packet they will not service with either -1 or + * the canonical DOSFALSE, so accept both res1 values - but do not go + * on to insist on a particular error code. Filesystems report refusing + * these packets in whatever terms suit them (pfs3 answers them with + * ERROR_NOT_A_DOS_DISK when it has no valid disk, for instance), and a + * code we failed to anticipate must not be mistaken for a result. + * + * Testing the error rather than the result also keeps the genuine + * answer zero - an empty file, or position zero - distinguishable from + * DOSFALSE: those come back with no error and are returned as-is. + * + * Falling back is always safe here. These packets only ever ask a + * question or reposition a file; reads and writes never travel this + * way, so nothing can be done twice by asking again. + */ +#define dos64_UnsupportedPkt(ret, err) \ + (((ret) == -1 || (ret) == DOSFALSE) && ((err) != 0)) + +/* + * The 64-bit structures must keep their published layout: the MorphOS (tm) + * V51 offsets on 32-bit systems (64-bit integers 2-byte aligned), natural + * alignment on 64-bit systems. Fail the build if a compiler moves a field. + */ +#define DOS64_LAYOUT_CHECK(name, cond) typedef char dos64_layout_##name[(cond) ? 1 : -1] +#if (__WORDSIZE == 64) +DOS64_LAYOUT_CHECK(fib_size, __builtin_offsetof(struct FileInfoBlock, fib_Size) == 128); +DOS64_LAYOUT_CHECK(fib_size64, __builtin_offsetof(struct FileInfoBlock, fib_Size64) == 232); +DOS64_LAYOUT_CHECK(fib_nblk64, __builtin_offsetof(struct FileInfoBlock, fib_NumBlocks64) == 240); +DOS64_LAYOUT_CHECK(fib_actext, __builtin_offsetof(struct FileInfoBlock, fib_ActExtFlags) == 262); +DOS64_LAYOUT_CHECK(fib_total, sizeof(struct FileInfoBlock) == 264); +DOS64_LAYOUT_CHECK(ead_size64, __builtin_offsetof(struct ExAllData, ed_Size64) == 56); +DOS64_LAYOUT_CHECK(rec_offset, __builtin_offsetof(struct RecordLock64, rec_Offset) == 8); +DOS64_LAYOUT_CHECK(rec_total, sizeof(struct RecordLock64) == 32); +DOS64_LAYOUT_CHECK(id_nblk64, __builtin_offsetof(struct InfoData64, id_NumBlocks64) == 48); +#else +DOS64_LAYOUT_CHECK(fib_size, __builtin_offsetof(struct FileInfoBlock, fib_Size) == 124); +DOS64_LAYOUT_CHECK(fib_size64, __builtin_offsetof(struct FileInfoBlock, fib_Size64) == 228); +DOS64_LAYOUT_CHECK(fib_nblk64, __builtin_offsetof(struct FileInfoBlock, fib_NumBlocks64) == 236); +DOS64_LAYOUT_CHECK(fib_actext, __builtin_offsetof(struct FileInfoBlock, fib_ActExtFlags) == 258); +DOS64_LAYOUT_CHECK(fib_total, sizeof(struct FileInfoBlock) == 260); +DOS64_LAYOUT_CHECK(ead_size64, __builtin_offsetof(struct ExAllData, ed_Size64) == 40); +DOS64_LAYOUT_CHECK(rec_offset, __builtin_offsetof(struct RecordLock64, rec_Offset) == 4); +DOS64_LAYOUT_CHECK(rec_length, __builtin_offsetof(struct RecordLock64, rec_Length) == 12); +DOS64_LAYOUT_CHECK(rec_total, sizeof(struct RecordLock64) == 24); +DOS64_LAYOUT_CHECK(id_nblk64, __builtin_offsetof(struct InfoData64, id_NumBlocks64) == 36); +#endif + +/* + * A MorphOS style packet (results stored through pointers, dp_Res1 a + * success flag) succeeded. dp_Res2 is cleared before the packet is sent, + * so a handler that answers an unknown packet with a non-zero dp_Res1 + * still sets an error and is not mistaken for success. + */ +#define dos64_PktOK(ret, err) (((ret) != DOSFALSE) && ((err) == 0)) + +/* Largest chunk handed to the 32-bit ACTION_READ/ACTION_WRITE packets */ +#define DOS64_IOCHUNK 0x40000000 + +/* dos64_packet.c */ +SIPTR dos64_SendPkt(struct Dos64Base *DOS64Base, struct MsgPort *port, LONG action, + SIPTR arg1, SIPTR arg2, SIPTR arg3, SIPTR arg4, SIPTR arg5, + SIPTR *res2); +#if (__WORDSIZE != 64) +QUAD dos64_SendPkt64OS4(struct Dos64Base *DOS64Base, struct MsgPort *port, LONG action, + SIPTR object, QUAD arg64, LONG arg32, SIPTR *res2); +#endif + +/* dos64_support.c */ +QUAD dos64_Seek(struct Dos64Base *DOS64Base, struct FileHandle *fh, + QUAD position, LONG mode); +QUAD dos64_SeekBuffered(struct Dos64Base *DOS64Base, BPTR file, + QUAD position, LONG mode); +QUAD dos64_SetFileSize(struct Dos64Base *DOS64Base, struct FileHandle *fh, + QUAD offset, LONG mode, BOOL wantsize); +QUAD dos64_GetFileSize(struct Dos64Base *DOS64Base, struct FileHandle *fh); +void dos64_FixFIB64(struct FileInfoBlock *fib); +void dos64_PrepFIB64(struct FileInfoBlock *fib); +void dos64_FixSizeFH(struct Dos64Base *DOS64Base, struct FileHandle *fh, + struct FileInfoBlock *fib); +void dos64_SetFIBSize(struct FileInfoBlock *fib, UQUAD size); +LONG dos64_Examine32(struct Dos64Base *DOS64Base, BPTR lock, + struct FileInfoBlock *fib, LONG action); + +#endif /* DOS64_INTERN_H */ diff --git a/rom/dos64/dos64_packet.c b/rom/dos64/dos64_packet.c new file mode 100644 index 00000000000..27396fac1ae --- /dev/null +++ b/rom/dos64/dos64_packet.c @@ -0,0 +1,112 @@ +/* + Copyright (C) 2026, The AROS Development Team. All rights reserved. + + Desc: dos64.library packet transport helpers. +*/ + +#include +#include +#include + +#include "dos64_intern.h" + +/* + * Send a packet to a filesystem handler and wait for the result. + * Values travel in the standard DosPacket argument slots, which are + * SIPTR-sized (i.e. 64-bit on 64-bit systems). Returns dp_Res1; if + * res2 is non-NULL it receives dp_Res2 (the IoErr() value). + */ +SIPTR dos64_SendPkt(struct Dos64Base *DOS64Base, struct MsgPort *port, LONG action, + SIPTR arg1, SIPTR arg2, SIPTR arg3, SIPTR arg4, SIPTR arg5, + SIPTR *res2) +{ + SIPTR res; + + res = DoPkt(port, action, arg1, arg2, arg3, arg4, arg5); + if (res2) + *res2 = IoErr(); + + return res; +} + +#if (__WORDSIZE != 64) +/* + * On 32-bit systems the standard packet arguments cannot carry 64-bit + * values, so the AmigaOS 4 style ACTION_*64 packets use the + * struct DosPacket64 overlay (see ): the object (fh_Arg1) + * goes into the standard dp_Arg1 slot, dp_Res0 is set to DP64_INIT and + * the 64-bit argument travels in the overlay's dp_Arg2. + * + * The overlay is larger than a standard DosPacket, so a private message + * and packet pair is built here instead of using DOS_STDPKT. + */ +QUAD dos64_SendPkt64OS4(struct Dos64Base *DOS64Base, struct MsgPort *port, LONG action, + SIPTR object, QUAD arg64, LONG arg32, SIPTR *res2) +{ + struct Process *me = (struct Process *)FindTask(NULL); + struct + { + struct Message msg; + struct DosPacket64 pkt64; + } *sp; + struct DosPacket *dp; + QUAD res; + + if (me->pr_Task.tc_Node.ln_Type != NT_PROCESS) + { + SetIoErr(ERROR_ACTION_NOT_KNOWN); + if (res2) + *res2 = ERROR_ACTION_NOT_KNOWN; + return -1; + } + + sp = AllocVec(sizeof(*sp), MEMF_PUBLIC | MEMF_CLEAR); + if (sp == NULL) + { + SetIoErr(ERROR_NO_FREE_STORE); + if (res2) + *res2 = ERROR_NO_FREE_STORE; + return -1; + } + + dp = (struct DosPacket *)&sp->pkt64; + sp->msg.mn_Node.ln_Name = (char *)dp; + sp->msg.mn_Length = sizeof(sp->pkt64); + dp->dp_Link = &sp->msg; + dp->dp_Type = action; + dp->dp_Arg1 = object; /* standard slot, as handlers expect */ + sp->pkt64.dp_Res0 = DP64_INIT; /* marks the packet as 64-bit capable */ + sp->pkt64.dp_Arg1 = object; /* the object, where a 64-bit handler looks */ + sp->pkt64.dp_Arg2 = arg64; + sp->pkt64.dp_Arg3 = arg32; + sp->pkt64.dp_Arg5 = 0; /* zero validates dp_Arg4 */ + + SendPkt(dp, port, &me->pr_MsgPort); + if (WaitPkt() != dp) + Alert(AN_AsyncPkt); + + /* + * The overlay's dp_Res0 (holding the DP64_INIT marker) shares its + * offset with the standard packet's dp_Res1. A handler that + * understands the 64-bit packet preserves the marker and answers + * through the overlay fields; a plain 32-bit handler answers + * through the standard fields, overwriting the marker. This is + * what tells the two reply forms apart. + */ + if (sp->pkt64.dp_Res0 == DP64_INIT) + { + res = sp->pkt64.dp_Res1; + if (res2) + *res2 = sp->pkt64.dp_Res2; + } + else + { + res = dp->dp_Res1; + if (res2) + *res2 = dp->dp_Res2; + } + + FreeVec(sp); + return res; +} +#endif diff --git a/rom/dos64/dos64_support.c b/rom/dos64/dos64_support.c new file mode 100644 index 00000000000..0a46450bba4 --- /dev/null +++ b/rom/dos64/dos64_support.c @@ -0,0 +1,340 @@ +/* + Copyright (C) 2026, The AROS Development Team. All rights reserved. + + Desc: dos64.library internal support - 64-bit operations with + 32-bit delegation when the filesystem lacks 64-bit support. +*/ + +#include +#include +#include + +#include "dos64_intern.h" + +/* + * Seek on the underlying filesystem, returning the previous position. + * Tries the 64-bit packets first and falls back to ACTION_SEEK when + * the handler does not understand them. + */ +QUAD dos64_Seek(struct Dos64Base *DOS64Base, struct FileHandle *fh, + QUAD position, LONG mode) +{ + SIPTR err = 0; + QUAD ret, old; + +#if (__WORDSIZE == 64) + /* + * MorphOS style single-packet seek: the new position and the previous + * position travel by pointer, dp_Res1 is a success flag. + */ + { + QUAD pos = position, prev = 0; + + ret = dos64_SendPkt(DOS64Base, fh->fh_Type, ACTION_SEEK64, + fh->fh_Arg1, (SIPTR)&pos, mode, (SIPTR)&prev, 0, &err); + if (dos64_PktOK(ret, err)) + return prev; + } + + /* OS4 style pair: query the old position, then reposition */ + old = dos64_SendPkt(DOS64Base, fh->fh_Type, ACTION_GET_FILE_POSITION64, + fh->fh_Arg1, 0, 0, 0, 0, &err); + if (!dos64_UnsupportedPkt(old, err)) + { + if (old == -1) + return -1; + ret = dos64_SendPkt(DOS64Base, fh->fh_Type, ACTION_CHANGE_FILE_POSITION64, + fh->fh_Arg1, position, mode, 0, 0, &err); + return ret ? old : -1; + } +#else + old = dos64_SendPkt64OS4(DOS64Base, fh->fh_Type, ACTION_GET_FILE_POSITION64, + fh->fh_Arg1, 0, 0, &err); + if (!dos64_UnsupportedPkt(old, err)) + { + if (old == -1) + return -1; + ret = dos64_SendPkt64OS4(DOS64Base, fh->fh_Type, ACTION_CHANGE_FILE_POSITION64, + fh->fh_Arg1, position, mode, &err); + return ret ? old : -1; + } +#endif + + /* 32-bit delegation */ + if (position > 0x7FFFFFFFLL || position < -0x80000000LL) + { + SetIoErr(ERROR_OBJECT_TOO_LARGE); + return -1; + } + return dos64_SendPkt(DOS64Base, fh->fh_Type, ACTION_SEEK, + fh->fh_Arg1, (LONG)position, mode, 0, 0, NULL); +} + +/* + * Seek through a (possibly buffered) filehandle, mirroring the buffer + * handling of dos.library/Seek(). + */ +QUAD dos64_SeekBuffered(struct Dos64Base *DOS64Base, BPTR file, + QUAD position, LONG mode) +{ + struct FileHandle *fh = BADDR(file); + QUAD offset = 0, ret; + + if (fh == NULL) + { + SetIoErr(ERROR_INVALID_LOCK); + return -1; + } + + /* If the file is in append mode, seeking is not allowed. */ + if (fh->fh_Flags & FHF_APPEND) + return dos64_Seek(DOS64Base, fh, 0, OFFSET_CURRENT); + + if (fh->fh_Flags & FHF_WRITE) + { + /* Write mode: flush pending buffered data first. */ + Flush(file); + } + else + { + /* Read mode: adjust the offset for unconsumed buffered data. */ + if (fh->fh_Pos < fh->fh_End && mode == OFFSET_CURRENT) + offset = (QUAD)(fh->fh_Pos - fh->fh_End); + fh->fh_Pos = fh->fh_End = 0; + } + + ret = dos64_Seek(DOS64Base, fh, position + offset, mode); + return (ret == -1) ? -1 : ret + offset; +} + +/* + * Return the size of the file behind fh, using the 64-bit packet when + * available, then ACTION_EXAMINE_FH, then a seek dance as last resort. + */ +QUAD dos64_GetFileSize(struct Dos64Base *DOS64Base, struct FileHandle *fh) +{ + struct FileInfoBlock *fib; + SIPTR err = 0; + QUAD ret, cur; + +#if (__WORDSIZE == 64) + ret = dos64_SendPkt(DOS64Base, fh->fh_Type, ACTION_GET_FILE_SIZE64, + fh->fh_Arg1, 0, 0, 0, 0, &err); + if (!dos64_UnsupportedPkt(ret, err)) + return ret; +#else + ret = dos64_SendPkt64OS4(DOS64Base, fh->fh_Type, ACTION_GET_FILE_SIZE64, + fh->fh_Arg1, 0, 0, &err); + if (!dos64_UnsupportedPkt(ret, err)) + return ret; +#endif + + fib = AllocVec(sizeof(struct FileInfoBlock), MEMF_PUBLIC | MEMF_CLEAR); + if (fib != NULL) + { + ret = dos64_SendPkt(DOS64Base, fh->fh_Type, ACTION_EXAMINE_FH, + fh->fh_Arg1, (SIPTR)MKBADDR(fib), 0, 0, 0, &err); + cur = (QUAD)(ULONG)fib->fib_Size; + FreeVec(fib); + if (ret) + return cur; + if (!dos64_UnsupportedAction(err)) + return -1; + } + + /* + * Seek dance: ACTION_SEEK returns the previous position, so seeking + * to the end yields the old position, and seeking back to it yields + * the file size. + */ + cur = dos64_SendPkt(DOS64Base, fh->fh_Type, ACTION_SEEK, + fh->fh_Arg1, 0, OFFSET_END, 0, 0, &err); + if (cur == -1) + return -1; + return dos64_SendPkt(DOS64Base, fh->fh_Type, ACTION_SEEK, + fh->fh_Arg1, (SIPTR)cur, OFFSET_BEGINNING, 0, 0, NULL); +} + +/* + * Set the size of the file behind fh. Returns the new size (-1 on + * error); when wantsize is FALSE, 0 is returned on success instead of + * querying the resulting size. + */ +QUAD dos64_SetFileSize(struct Dos64Base *DOS64Base, struct FileHandle *fh, + QUAD offset, LONG mode, BOOL wantsize) +{ + SIPTR err = 0; + QUAD ret; + +#if (__WORDSIZE == 64) + /* MorphOS style: offset and resulting size travel by pointer */ + { + QUAD off = offset, newsize = 0; + + ret = dos64_SendPkt(DOS64Base, fh->fh_Type, ACTION_SET_FILE_SIZE64, + fh->fh_Arg1, (SIPTR)&off, mode, (SIPTR)&newsize, 0, &err); + if (dos64_PktOK(ret, err)) + return wantsize ? newsize : 0; + } + + ret = dos64_SendPkt(DOS64Base, fh->fh_Type, ACTION_CHANGE_FILE_SIZE64, + fh->fh_Arg1, offset, mode, 0, 0, &err); +#else + ret = dos64_SendPkt64OS4(DOS64Base, fh->fh_Type, ACTION_CHANGE_FILE_SIZE64, + fh->fh_Arg1, offset, mode, &err); +#endif + if (!dos64_UnsupportedPkt(ret, err)) + { + if (ret == DOSFALSE) + return -1; + return wantsize ? dos64_GetFileSize(DOS64Base, fh) : 0; + } + + /* 32-bit delegation */ + if (offset > 0x7FFFFFFFLL || offset < -0x80000000LL) + { + SetIoErr(ERROR_OBJECT_TOO_LARGE); + return -1; + } + return dos64_SendPkt(DOS64Base, fh->fh_Type, ACTION_SET_FILE_SIZE, + fh->fh_Arg1, (LONG)offset, mode, 0, 0, NULL); +} + +/* Local copy helpers: kickstart modules must not drag in the C library */ +static void dos64_bcopy(const void *src, void *dst, ULONG len) +{ + const UBYTE *s = src; + UBYTE *d = dst; + while (len--) + *d++ = *s++; +} + +static void BSTR2CINLINE(char *s) +{ + UBYTE len = s[0]; + dos64_bcopy(s + 1, s, len); /* forward copy is overlap-safe here */ + s[len] = 0; +} + +/* BSTR -> C string conversion, as dos.library does for FileInfoBlocks */ +void dos64_FixFIB64(struct FileInfoBlock *fib) +{ + BSTR2CINLINE((char *)fib->fib_FileName); + BSTR2CINLINE((char *)fib->fib_Comment); +} + +/* + * Prepare a FileInfoBlock for an ACTION_EXAMINE_*64 packet: the sender + * must clear fib_ActExtFlags, and no extensions are requested. + */ +void dos64_PrepFIB64(struct FileInfoBlock *fib) +{ + fib->fib_ActExtFlags = 0; + fib->fib_ReqExtFlags = 0; +} + +/* + * Store a 64-bit size the way the 64-bit examine packets do: fib_Size64 + * holds it, fib_Size is 0 when it does not fit in 31 bits. + */ +void dos64_SetFIBSize(struct FileInfoBlock *fib, UQUAD size) +{ + fib->fib_Size64 = size; + fib->fib_Size = (size > 0x7FFFFFFFULL) ? 0 : (LONG)size; +} + +/* Replace a clamped 32-bit size by the 64-bit size of the open file */ +void dos64_FixSizeFH(struct Dos64Base *DOS64Base, struct FileHandle *fh, + struct FileInfoBlock *fib) +{ + SIPTR err = 0; +#if (__WORDSIZE == 64) + QUAD size = dos64_SendPkt(DOS64Base, fh->fh_Type, ACTION_GET_FILE_SIZE64, + fh->fh_Arg1, 0, 0, 0, 0, &err); +#else + QUAD size = dos64_SendPkt64OS4(DOS64Base, fh->fh_Type, ACTION_GET_FILE_SIZE64, + fh->fh_Arg1, 0, 0, &err); +#endif + + /* a handler without ACTION_GET_FILE_SIZE64 fails the query: keep the 32-bit size */ + if (size != -1 && err == 0) + dos64_SetFIBSize(fib, (UQUAD)size); + SetIoErr(0); +} + +/* The size of a file entry that may be clamped; a file that cannot be opened keeps it */ +static void dos64_FixSizeEntry(struct Dos64Base *DOS64Base, BPTR obj, + struct FileInfoBlock *fib, LONG action) +{ + struct Process *me = (struct Process *)FindTask(NULL); + BPTR fh; + + if (fib->fib_DirEntryType >= 0 || fib->fib_Size64 < 0x7FFFFFFF || + me->pr_Task.tc_Node.ln_Type != NT_PROCESS) + return; + + if (action == ACTION_EXAMINE_OBJECT) + { + BPTR dup = DupLock(obj); + + if (dup == BNULL) + return; + fh = OpenFromLock(dup); + if (fh == BNULL) + { + UnLock(dup); + return; + } + } + else + { + BPTR old = CurrentDir(obj); + + fh = Open(fib->fib_FileName, MODE_OLDFILE); + CurrentDir(old); + if (fh == BNULL) + return; + } + + dos64_FixSizeFH(DOS64Base, BADDR(fh), fib); + Close(fh); + SetIoErr(0); +} + +/* + * 32-bit delegation for the Examine64 family. The 64-bit fields share + * the FileInfoBlock with the standard ones, so the dos.library call + * fills the caller's block directly; the 64-bit fields are then derived + * from the 32-bit values (which the handler may have clamped). + */ +LONG dos64_Examine32(struct Dos64Base *DOS64Base, BPTR obj, + struct FileInfoBlock *fib, LONG action) +{ + LONG ret = DOSFALSE; + + switch (action) + { + case ACTION_EXAMINE_OBJECT: + ret = Examine(obj, fib); + break; + + case ACTION_EXAMINE_NEXT: + ret = ExNext(obj, fib); + break; + + case ACTION_EXAMINE_FH: + ret = ExamineFH(obj, fib); + break; + } + + if (ret) + { + fib->fib_NumBlocks64 = (UQUAD)(ULONG)fib->fib_NumBlocks; + fib->fib_ActExtFlags = 0; + dos64_SetFIBSize(fib, (UQUAD)(ULONG)fib->fib_Size); + if (action != ACTION_EXAMINE_FH) + dos64_FixSizeEntry(DOS64Base, obj, fib, action); + } + + return ret; +} diff --git a/rom/dos64/examine64.c b/rom/dos64/examine64.c new file mode 100644 index 00000000000..055d37f24c7 --- /dev/null +++ b/rom/dos64/examine64.c @@ -0,0 +1,81 @@ +/* + Copyright (C) 2026, The AROS Development Team. All rights reserved. + + Desc: Examine a directory entry with 64-bit sizes. +*/ + +#include +#include "dos64_intern.h" + +/***************************************************************************** + + NAME */ +#include + + AROS_LH3(LONG, Examine64, + +/* SYNOPSIS */ + AROS_LHA(BPTR, lock, D1), + AROS_LHA(struct FileInfoBlock *, fib, D2), + AROS_LHA(struct TagItem *, tags, D3), + +/* LOCATION */ + struct Dos64Base *, DOS64Base, 13, Dos64) + +/* FUNCTION + Fill a FileInfoBlock with information about the object the + given lock refers to, including the 64-bit fib_Size64 and + fib_NumBlocks64 fields. fib_Size is 0 when the size does not + fit in 31 bits. + + If the filesystem does not support 64-bit examination the + request is delegated to the 32-bit Examine(); the 64-bit fields + then hold what the filesystem reports in 32 bits. + + INPUTS + lock - lock on the object to examine + fib - FileInfoBlock to fill, allocated with + AllocDosObject(DOS_FIB, NULL) or + AllocDosObject64(DOS64_FIB, NULL) + tags - future extensions, pass NULL + + RESULT + Boolean success indicator. On failure IoErr() gives additional + information. + + NOTES + + EXAMPLE + + BUGS + + SEE ALSO + dos.library/Examine(), ExNext64(), ExamineFH64(), + AllocDosObject64() + + INTERNALS + +*****************************************************************************/ +{ + AROS_LIBFUNC_INIT + + struct FileLock *fl = BADDR(lock); + SIPTR err = 0; + LONG ret; + + dos64_PrepFIB64(fib); + ret = dos64_SendPkt(DOS64Base, fl ? fl->fl_Task : GetFileSysTask(), + ACTION_EXAMINE_OBJECT64, (SIPTR)lock, + (SIPTR)MKBADDR(fib), 0, 0, 0, &err); + if (ret) + { + dos64_FixFIB64(fib); + return ret; + } + if (!dos64_UnsupportedAction(err)) + return DOSFALSE; + + return dos64_Examine32(DOS64Base, lock, fib, ACTION_EXAMINE_OBJECT); + + AROS_LIBFUNC_EXIT +} /* Examine64 */ diff --git a/rom/dos64/examinefh64.c b/rom/dos64/examinefh64.c new file mode 100644 index 00000000000..15ff66ed3d6 --- /dev/null +++ b/rom/dos64/examinefh64.c @@ -0,0 +1,89 @@ +/* + Copyright (C) 2026, The AROS Development Team. All rights reserved. + + Desc: Examine an open file with 64-bit sizes. +*/ + +#include +#include "dos64_intern.h" + +/***************************************************************************** + + NAME */ +#include + + AROS_LH3(LONG, ExamineFH64, + +/* SYNOPSIS */ + AROS_LHA(BPTR, fh, D1), + AROS_LHA(struct FileInfoBlock *, fib, D2), + AROS_LHA(struct TagItem *, tags, D3), + +/* LOCATION */ + struct Dos64Base *, DOS64Base, 15, Dos64) + +/* FUNCTION + Fill a FileInfoBlock with information about an open file, + including the 64-bit fib_Size64 and fib_NumBlocks64 fields. + fib_Size is 0 when the size does not fit in 31 bits. + + If the filesystem does not support 64-bit examination the + request is delegated to the 32-bit ExamineFH(). In that case + the file size is additionally corrected through the + filesystem's 64-bit size query, when it provides one. + + INPUTS + fh - filehandle to examine + fib - FileInfoBlock to fill, allocated with + AllocDosObject(DOS_FIB, NULL) or + AllocDosObject64(DOS64_FIB, NULL) + tags - future extensions, pass NULL + + RESULT + Boolean success indicator. On failure IoErr() gives additional + information. + + NOTES + + EXAMPLE + + BUGS + + SEE ALSO + Examine64(), GetFileSize64(), dos.library/ExamineFH() + + INTERNALS + +*****************************************************************************/ +{ + AROS_LIBFUNC_INIT + + struct FileHandle *handle = BADDR(fh); + SIPTR err = 0; + LONG ret; + + if (handle == NULL) + { + SetIoErr(ERROR_INVALID_LOCK); + return DOSFALSE; + } + + dos64_PrepFIB64(fib); + ret = dos64_SendPkt(DOS64Base, handle->fh_Type, ACTION_EXAMINE_FH64, + handle->fh_Arg1, (SIPTR)MKBADDR(fib), 0, 0, 0, &err); + if (ret) + { + dos64_FixFIB64(fib); + return ret; + } + if (!dos64_UnsupportedAction(err)) + return DOSFALSE; + + ret = dos64_Examine32(DOS64Base, fh, fib, ACTION_EXAMINE_FH); + if (ret) + dos64_FixSizeFH(DOS64Base, handle, fib); + + return ret; + + AROS_LIBFUNC_EXIT +} /* ExamineFH64 */ diff --git a/rom/dos64/examinename64.c b/rom/dos64/examinename64.c new file mode 100644 index 00000000000..e1f8b5364c9 --- /dev/null +++ b/rom/dos64/examinename64.c @@ -0,0 +1,141 @@ +/* + Copyright (C) 2026, The AROS Development Team. All rights reserved. + + Desc: Examine an object by name with 64-bit sizes. +*/ + +#include +#include "dos64_intern.h" + +static BOOL dos64_SameName(CONST_STRPTR a, CONST_STRPTR b) +{ + for (;;) + { + UBYTE ca = *a++, cb = *b++; + + if ((ca >= 'a' && ca <= 'z') || (ca >= 0xe0 && ca <= 0xfe && ca != 0xf7)) + ca -= 0x20; + if ((cb >= 'a' && cb <= 'z') || (cb >= 0xe0 && cb <= 0xfe && cb != 0xf7)) + cb -= 0x20; + if (ca != cb) + return FALSE; + if (ca == 0) + return TRUE; + } +} + +/***************************************************************************** + + NAME */ +#include + + AROS_LH3(LONG, ExamineName64, + +/* SYNOPSIS */ + AROS_LHA(CONST_STRPTR, name, D1), + AROS_LHA(struct FileInfoBlock *, fib, D2), + AROS_LHA(struct TagItem *, tags, D3), + +/* LOCATION */ + struct Dos64Base *, DOS64Base, 24, Dos64) + +/* FUNCTION + Fill a 64-bit FileInfoBlock with information about the named + object. + + A file that is open for writing cannot be locked. When the lock + fails with ERROR_OBJECT_IN_USE the entry is read from the + directory that contains it, so the size of a file that is being + written is available too. + + INPUTS + name - path of the object, relative to the current directory + fib - FileInfoBlock to fill, allocated with + AllocDosObject64(DOS64_FIB, NULL) + tags - future extensions, pass NULL + + RESULT + Boolean success indicator. On failure IoErr() gives additional + information. + + NOTES + This is an extension of dos64.library; it needs the version that + has it. + + EXAMPLE + + BUGS + + SEE ALSO + Examine64(), ExNext64() + + INTERNALS + +*****************************************************************************/ +{ + AROS_LIBFUNC_INIT + + BPTR lock; + LONG ret, err; + CONST_STRPTR file; + STRPTR parent; + LONG len; + BOOL found = FALSE; + + lock = Lock(name, SHARED_LOCK); + if (lock != BNULL) + { + ret = Examine64(lock, fib, tags); + err = IoErr(); + UnLock(lock); + if (!ret) + SetIoErr(err); + return ret; + } + + if (IoErr() != ERROR_OBJECT_IN_USE) + return DOSFALSE; + + /* the entry of the directory that holds the object */ + file = FilePart(name); + if (*file == 0) + { + SetIoErr(ERROR_OBJECT_IN_USE); + return DOSFALSE; + } + len = file - name; + if (len > 1 && name[len - 1] == '/' && name[len - 2] != ':' && name[len - 2] != '/') + len--; + + parent = AllocVec(len + 1, MEMF_PUBLIC); + if (parent == NULL) + { + SetIoErr(ERROR_NO_FREE_STORE); + return DOSFALSE; + } + CopyMem(name, parent, len); + parent[len] = 0; + lock = Lock(parent, SHARED_LOCK); + FreeVec(parent); + if (lock == BNULL) + return DOSFALSE; + + if (Examine64(lock, fib, tags)) + { + while (ExNext64(lock, fib, tags)) + { + if (dos64_SameName(fib->fib_FileName, file)) + { + found = TRUE; + break; + } + } + } + UnLock(lock); + + if (!found) + SetIoErr(ERROR_OBJECT_IN_USE); + return found ? DOSTRUE : DOSFALSE; + + AROS_LIBFUNC_EXIT +} /* ExamineName64 */ diff --git a/rom/dos64/exnext64.c b/rom/dos64/exnext64.c new file mode 100644 index 00000000000..ea910d25ad1 --- /dev/null +++ b/rom/dos64/exnext64.c @@ -0,0 +1,79 @@ +/* + Copyright (C) 2026, The AROS Development Team. All rights reserved. + + Desc: Examine the next directory entry with 64-bit sizes. +*/ + +#include +#include "dos64_intern.h" + +/***************************************************************************** + + NAME */ +#include + + AROS_LH3(LONG, ExNext64, + +/* SYNOPSIS */ + AROS_LHA(BPTR, lock, D1), + AROS_LHA(struct FileInfoBlock *, fib, D2), + AROS_LHA(struct TagItem *, tags, D3), + +/* LOCATION */ + struct Dos64Base *, DOS64Base, 14, Dos64) + +/* FUNCTION + Examine the next entry of a directory, continuing an + enumeration started with Examine64() on the same + FileInfoBlock. The 64-bit fields are filled as by Examine64(). + + If the filesystem does not support 64-bit examination the + request is delegated to the 32-bit ExNext(); the 64-bit fields + then hold what the filesystem reports in 32 bits. + + INPUTS + lock - lock on the directory being enumerated + fib - FileInfoBlock as filled by the previous Examine64() + or ExNext64() call + tags - future extensions, pass NULL + + RESULT + Boolean success indicator. On failure IoErr() gives additional + information; ERROR_NO_MORE_ENTRIES means the enumeration is + complete. + + NOTES + + EXAMPLE + + BUGS + + SEE ALSO + Examine64(), dos.library/ExNext() + + INTERNALS + +*****************************************************************************/ +{ + AROS_LIBFUNC_INIT + + struct FileLock *fl = BADDR(lock); + SIPTR err = 0; + LONG ret; + + dos64_PrepFIB64(fib); + ret = dos64_SendPkt(DOS64Base, fl ? fl->fl_Task : GetFileSysTask(), + ACTION_EXAMINE_NEXT64, (SIPTR)lock, + (SIPTR)MKBADDR(fib), 0, 0, 0, &err); + if (ret) + { + dos64_FixFIB64(fib); + return ret; + } + if (!dos64_UnsupportedAction(err)) + return DOSFALSE; + + return dos64_Examine32(DOS64Base, lock, fib, ACTION_EXAMINE_NEXT); + + AROS_LIBFUNC_EXIT +} /* ExNext64 */ diff --git a/rom/dos64/freedosobject64.c b/rom/dos64/freedosobject64.c new file mode 100644 index 00000000000..4071463a5d3 --- /dev/null +++ b/rom/dos64/freedosobject64.c @@ -0,0 +1,61 @@ +/* + Copyright (C) 2026, The AROS Development Team. All rights reserved. + + Desc: Free 64-bit dos objects. +*/ + +#include +#include "dos64_intern.h" + +/***************************************************************************** + + NAME */ +#include + + AROS_LH2(void, FreeDosObject64, + +/* SYNOPSIS */ + AROS_LHA(ULONG, type, D1), + AROS_LHA(APTR, ptr, D2), + +/* LOCATION */ + struct Dos64Base *, DOS64Base, 22, Dos64) + +/* FUNCTION + Frees an object allocated with AllocDosObject64(). + + INPUTS + type - object type the object was allocated with + ptr - pointer to the object; may be NULL + + RESULT + None. + + NOTES + + EXAMPLE + + BUGS + + SEE ALSO + AllocDosObject64() + + INTERNALS + +*****************************************************************************/ +{ + AROS_LIBFUNC_INIT + + switch (type) + { + case DOS64_FIB: + case DOS64_INFODATA: + case DOS64_RECORDLOCK: + FreeVec(ptr); + break; + default: + break; + } + + AROS_LIBFUNC_EXIT +} /* FreeDosObject64 */ diff --git a/rom/dos64/getfileposition64.c b/rom/dos64/getfileposition64.c new file mode 100644 index 00000000000..cb07e26dd74 --- /dev/null +++ b/rom/dos64/getfileposition64.c @@ -0,0 +1,73 @@ +/* + Copyright (C) 2026, The AROS Development Team. All rights reserved. + + Desc: Read the current 64-bit position in a file. +*/ + +#include +#include "dos64_intern.h" + +/***************************************************************************** + + NAME */ +#include + + AROS_LH1(QUAD, GetFilePosition64, + +/* SYNOPSIS */ + AROS_LHA(BPTR, file, D1), + +/* LOCATION */ + struct Dos64Base *, DOS64Base, 7, Dos64) + +/* FUNCTION + Read the current read/write position in a file with full + 64-bit range, without changing it. Buffered data on the + filehandle is taken into account. + + INPUTS + file - filehandle + + RESULT + Current absolute position in bytes, or -1 if an error + happened. IoErr() will give additional information in that + case. + + NOTES + + EXAMPLE + + BUGS + + SEE ALSO + Seek64(), GetFileSize64() + + INTERNALS + +*****************************************************************************/ +{ + AROS_LIBFUNC_INIT + + struct FileHandle *fh = BADDR(file); + QUAD pos; + + if (fh == NULL) + { + SetIoErr(ERROR_INVALID_LOCK); + return -1; + } + + pos = dos64_Seek(DOS64Base, fh, 0, OFFSET_CURRENT); + if (pos == -1) + return -1; + + /* Account for buffered data not yet seen by the filesystem */ + if (fh->fh_Flags & FHF_WRITE) + pos += fh->fh_Pos; + else + pos -= fh->fh_End - fh->fh_Pos; + + return pos; + + AROS_LIBFUNC_EXIT +} /* GetFilePosition64 */ diff --git a/rom/dos64/getfilesize64.c b/rom/dos64/getfilesize64.c new file mode 100644 index 00000000000..acda50ea94e --- /dev/null +++ b/rom/dos64/getfilesize64.c @@ -0,0 +1,66 @@ +/* + Copyright (C) 2026, The AROS Development Team. All rights reserved. + + Desc: Read the 64-bit size of a file. +*/ + +#include +#include "dos64_intern.h" + +/***************************************************************************** + + NAME */ +#include + + AROS_LH1(QUAD, GetFileSize64, + +/* SYNOPSIS */ + AROS_LHA(BPTR, file, D1), + +/* LOCATION */ + struct Dos64Base *, DOS64Base, 8, Dos64) + +/* FUNCTION + Read the size of an open file with full 64-bit range. + + If the filesystem does not support 64-bit operations the size + is obtained via ExamineFH() or, as a last resort, by seeking. + + INPUTS + file - filehandle + + RESULT + Size of the file in bytes, or -1 if an error happened. IoErr() + will give additional information in that case. + + NOTES + Pending buffered writes on the filehandle are flushed first. + + EXAMPLE + + BUGS + + SEE ALSO + SetFileSize64(), GetFilePosition64(), ExamineFH64() + + INTERNALS + +*****************************************************************************/ +{ + AROS_LIBFUNC_INIT + + struct FileHandle *fh = BADDR(file); + + if (fh == NULL) + { + SetIoErr(ERROR_INVALID_LOCK); + return -1; + } + + if (fh->fh_Flags & FHF_WRITE) + Flush(file); + + return dos64_GetFileSize(DOS64Base, fh); + + AROS_LIBFUNC_EXIT +} /* GetFileSize64 */ diff --git a/rom/dos64/info64.c b/rom/dos64/info64.c new file mode 100644 index 00000000000..6cedcc41274 --- /dev/null +++ b/rom/dos64/info64.c @@ -0,0 +1,103 @@ +/* + Copyright (C) 2026, The AROS Development Team. All rights reserved. + + Desc: Get 64-bit information about a volume. +*/ + +#include +#include "dos64_intern.h" + +/***************************************************************************** + + NAME */ +#include + + AROS_LH2(LONG, Info64, + +/* SYNOPSIS */ + AROS_LHA(BPTR, lock, D1), + AROS_LHA(struct InfoData64 *, parameterBlock, D2), + +/* LOCATION */ + struct Dos64Base *, DOS64Base, 16, Dos64) + +/* FUNCTION + Get information about a volume in the system, with 64-bit + block counts. + + The block starts with a standard InfoData; the 64-bit block + counts are in id_NumBlocks64 and id_NumBlocksUsed64. + + If the filesystem does not support the 64-bit query the + request is delegated to the 32-bit Info(), and the 64-bit + counts are taken from ACTION_QUERY_ATTR (FQA_NumBlocks, + FQA_NumBlocksUsed) when the filesystem answers it, otherwise + from the 32-bit counts. + + INPUTS + lock - a lock on any file on the volume for which + information should be supplied, or 0 for the + volume of GetFileSysTask() + parameterBlock - pointer to a longword-aligned InfoData64 + structure + + RESULT + Boolean indicating success or failure. If TRUE (success) the + 'parameterBlock' is filled with information on the volume. + + NOTES + + EXAMPLE + + BUGS + + SEE ALSO + dos.library/Info(), + + INTERNALS + +*****************************************************************************/ +{ + AROS_LIBFUNC_INIT + + struct FileLock *fl = BADDR(lock); + struct MsgPort *port = fl ? fl->fl_Task : GetFileSysTask(); + SIPTR err = 0; + QUAD count; + LONG ret; + +#if (__WORDSIZE == 64) + ret = dos64_SendPkt(DOS64Base, port, ACTION_INFO64, (SIPTR)lock, + (SIPTR)MKBADDR(parameterBlock), 0, 0, 0, &err); + if (ret) + return ret; + if (!dos64_UnsupportedAction(err)) + return DOSFALSE; +#endif + + /* The block starts with a standard InfoData, so Info() can fill it */ + ret = Info(lock, (struct InfoData *)parameterBlock); + if (ret) + { + parameterBlock->id_NumBlocks64 = (UQUAD)(ULONG)parameterBlock->id_NumBlocks; + parameterBlock->id_NumBlocksUsed64 = (UQUAD)(ULONG)parameterBlock->id_NumBlocksUsed; + + /* + * Filesystems that exceed the 32-bit block counts report the full + * counts through the MorphOS style attribute query. + */ + count = 0; + if (dos64_PktOK(dos64_SendPkt(DOS64Base, port, ACTION_QUERY_ATTR, FQA_NumBlocks, + (SIPTR)&count, sizeof(count), 0, 0, &err), err)) + parameterBlock->id_NumBlocks64 = (UQUAD)count; + count = 0; + if (dos64_PktOK(dos64_SendPkt(DOS64Base, port, ACTION_QUERY_ATTR, FQA_NumBlocksUsed, + (SIPTR)&count, sizeof(count), 0, 0, &err), err)) + parameterBlock->id_NumBlocksUsed64 = (UQUAD)count; + SetIoErr(0); + } + + return ret; + + AROS_LIBFUNC_EXIT +} /* Info64 */ diff --git a/rom/dos64/isfilesystem64.c b/rom/dos64/isfilesystem64.c new file mode 100644 index 00000000000..86f93a2aa30 --- /dev/null +++ b/rom/dos64/isfilesystem64.c @@ -0,0 +1,87 @@ +/* + Copyright (C) 2026, The AROS Development Team. All rights reserved. + + Desc: Query whether a filesystem supports 64-bit packets. +*/ + +#include +#include "dos64_intern.h" + +/***************************************************************************** + + NAME */ +#include + + AROS_LH1(LONG, IsFileSystem64, + +/* SYNOPSIS */ + AROS_LHA(BPTR, file, D1), + +/* LOCATION */ + struct Dos64Base *, DOS64Base, 23, Dos64) + +/* FUNCTION + Query whether the filesystem behind an open file understands + 64-bit packets, i.e. whether the 64-bit dos64.library + operations on it are handled natively rather than through + 32-bit delegation. + + Applications may use this to cache the capability per file and + skip 64-bit attempts on filesystems that cannot service them. + + INPUTS + file - filehandle to query + + RESULT + DOSTRUE when the filesystem handles 64-bit packets, DOSFALSE + otherwise. + + NOTES + The query is answered with (position-neutral) probe packets; + no file state is modified. + + EXAMPLE + + BUGS + + SEE ALSO + Seek64(), GetFilePosition64() + + INTERNALS + +*****************************************************************************/ +{ + AROS_LIBFUNC_INIT + + struct FileHandle *fh = BADDR(file); + SIPTR err = 0; + QUAD ret; + + if (fh == NULL || fh->fh_Type == BNULL) + return DOSFALSE; + +#if (__WORDSIZE == 64) + /* MorphOS style: a null seek, positions travel by pointer */ + { + QUAD pos = 0, prev = 0; + + ret = dos64_SendPkt(DOS64Base, fh->fh_Type, ACTION_SEEK64, + fh->fh_Arg1, (SIPTR)&pos, OFFSET_CURRENT, (SIPTR)&prev, 0, &err); + if (dos64_PktOK(ret, err)) + return DOSTRUE; + } + + /* AmigaOS 4 style position query */ + ret = dos64_SendPkt(DOS64Base, fh->fh_Type, ACTION_GET_FILE_POSITION64, + fh->fh_Arg1, 0, 0, 0, 0, &err); +#else + ret = dos64_SendPkt64OS4(DOS64Base, fh->fh_Type, ACTION_GET_FILE_POSITION64, + fh->fh_Arg1, 0, 0, &err); +#endif + if (!dos64_UnsupportedPkt(ret, err)) + return DOSTRUE; + + return DOSFALSE; + + AROS_LIBFUNC_EXIT +} /* IsFileSystem64 */ diff --git a/rom/dos64/lockrecord64.c b/rom/dos64/lockrecord64.c new file mode 100644 index 00000000000..46ce5646b1e --- /dev/null +++ b/rom/dos64/lockrecord64.c @@ -0,0 +1,97 @@ +/* + Copyright (C) 2026, The AROS Development Team. All rights reserved. + + Desc: Lock a portion of a file, 64-bit version. +*/ + +#include +#include "dos64_intern.h" + +/***************************************************************************** + + NAME */ +#include + + AROS_LH2(BOOL, LockRecord64, + +/* SYNOPSIS */ + AROS_LHA(struct RecordLock64 *, rec, D1), + AROS_LHA(ULONG, timeout, D2), + +/* LOCATION */ + struct Dos64Base *, DOS64Base, 17, Dos64) + +/* FUNCTION + Lock a portion of a file for exclusive access, with 64-bit + offsets. The record is described by a RecordLock64 structure + holding the filehandle, offset, length and locking mode. A + timeout may be specified which is the maximum amount of time + to wait for the record to become available. + + If the filesystem does not support 64-bit record locking the + request is delegated to the 32-bit LockRecord(), provided the + record lies within the first 4GB of the file. + + INPUTS + rec - the record to lock (rec_FH, rec_Offset, rec_Length + and rec_Mode must be filled in) + timeout - timeout interval measured in ticks (may be 0) + + RESULT + Success/failure indicator. On failure IoErr() gives additional + information; ERROR_OBJECT_TOO_LARGE indicates the record is + not representable on the filesystem. + + NOTES + Record locks are cooperative, meaning that they only affect + other calls to LockRecord()/LockRecord64(). + + EXAMPLE + + BUGS + + SEE ALSO + LockRecords64(), UnLockRecord64(), dos.library/LockRecord() + + INTERNALS + +*****************************************************************************/ +{ + AROS_LIBFUNC_INIT + + struct FileHandle *fileH; + + if (rec == NULL || (fileH = BADDR(rec->rec_FH)) == NULL) + { + SetIoErr(ERROR_INVALID_LOCK); + return DOSFALSE; + } + +#if (__WORDSIZE == 64) + { + /* MorphOS style: offset and length travel by pointer */ + UQUAD offset = rec->rec_Offset, length = rec->rec_Length; + SIPTR err = 0; + LONG ret; + + ret = dos64_SendPkt(DOS64Base, fileH->fh_Type, ACTION_LOCK_RECORD64, + fileH->fh_Arg1, (SIPTR)&offset, (SIPTR)&length, + rec->rec_Mode, timeout, &err); + if (!(ret == DOSFALSE && dos64_UnsupportedAction(err))) + return ret; + } +#endif + + /* 32-bit delegation */ + if (rec->rec_Offset > 0xFFFFFFFFULL || rec->rec_Length > 0xFFFFFFFFULL + || rec->rec_Offset + rec->rec_Length > 0xFFFFFFFFULL) + { + SetIoErr(ERROR_OBJECT_TOO_LARGE); + return DOSFALSE; + } + + return LockRecord(rec->rec_FH, (ULONG)rec->rec_Offset, + (ULONG)rec->rec_Length, rec->rec_Mode, timeout); + + AROS_LIBFUNC_EXIT +} /* LockRecord64 */ diff --git a/rom/dos64/lockrecords64.c b/rom/dos64/lockrecords64.c new file mode 100644 index 00000000000..ad4da59d11a --- /dev/null +++ b/rom/dos64/lockrecords64.c @@ -0,0 +1,76 @@ +/* + Copyright (C) 2026, The AROS Development Team. All rights reserved. + + Desc: Lock several records of files, 64-bit version. +*/ + +#include +#include "dos64_intern.h" + +/***************************************************************************** + + NAME */ +#include + + AROS_LH2(BOOL, LockRecords64, + +/* SYNOPSIS */ + AROS_LHA(struct RecordLock64 *, recArray, D1), + AROS_LHA(ULONG, timeout, D2), + +/* LOCATION */ + struct Dos64Base *, DOS64Base, 18, Dos64) + +/* FUNCTION + Lock several records of files for exclusive access, with + 64-bit offsets. The array is terminated by an entry with + rec_FH set to NULL. If any lock in the array fails, all + already obtained locks are released again. + + INPUTS + recArray - array of RecordLock64 entries to lock + timeout - timeout interval measured in ticks (may be 0), + applied to each record + + RESULT + Success/failure indicator. On failure IoErr() gives additional + information. + + NOTES + + EXAMPLE + + BUGS + + SEE ALSO + LockRecord64(), UnLockRecords64() + + INTERNALS + +*****************************************************************************/ +{ + AROS_LIBFUNC_INIT + + struct RecordLock64 *rLock = recArray; + + while (BADDR(recArray->rec_FH) != NULL) + { + BPTR temp; + + if (!LockRecord64(recArray, timeout)) + { + temp = recArray->rec_FH; + recArray->rec_FH = BNULL; + UnLockRecords64(rLock); + recArray->rec_FH = temp; + + return DOSFALSE; + } + + recArray++; + } + + return DOSTRUE; + + AROS_LIBFUNC_EXIT +} /* LockRecords64 */ diff --git a/rom/dos64/mmakefile.src b/rom/dos64/mmakefile.src new file mode 100644 index 00000000000..9a51742f41b --- /dev/null +++ b/rom/dos64/mmakefile.src @@ -0,0 +1,31 @@ +# +# Makefile for building dos64.library +# + +include $(SRCDIR)/config/aros.cfg + +#MM- core-linklibs : linklibs-dos64 + +FUNCS := seek64 setfilesize64 getfileposition64 getfilesize64 \ + changefileposition64 changefilesize64 read64 write64 \ + examine64 exnext64 examinefh64 info64 \ + lockrecord64 lockrecords64 unlockrecord64 unlockrecords64 \ + allocdosobject64 freedosobject64 isfilesystem64 examinename64 + +FILES := dos64_packet dos64_support + +USER_INCLUDES := -I$(SRCDIR)/rom/dos +USER_CFLAGS := $(CFLAGS_NO_BUILTIN) +USER_CPPFLAGS := \ + -DNO_INLINE_STDARG \ + -DUSE_EXEC_DEBUG +USER_LDFLAGS := -static + +#MM kernel-dos64 : includes +#MM kernel-dos64-includes : \ +#MM kernel-exec-includes \ +#MM kernel-dos-includes + +%build_module mmake=kernel-dos64 \ + modname=dos64 modtype=library \ + files="dos64_init $(FUNCS) $(FILES)" diff --git a/rom/dos64/read64.c b/rom/dos64/read64.c new file mode 100644 index 00000000000..1f55a025107 --- /dev/null +++ b/rom/dos64/read64.c @@ -0,0 +1,95 @@ +/* + Copyright (C) 2026, The AROS Development Team. All rights reserved. + + Desc: Read up to 64 bits worth of bytes from a file. +*/ + +#include +#include "dos64_intern.h" + +/***************************************************************************** + + NAME */ +#include + + AROS_LH2QUAD1(QUAD, Read64, + +/* SYNOPSIS */ + AROS_LHA(BPTR, file, D1), + AROS_LHA(APTR, buffer, D2), + AROS_LHAQUAD(QUAD, length, D3, D4), + +/* LOCATION */ + struct Dos64Base *, DOS64Base, 11, Dos64) + +/* FUNCTION + Read some data from a given file with a 64-bit length. The + request is passed to the filesystem in chunks the 32-bit + ACTION_READ packet can carry, so it works with every + filesystem - no buffering is involved. + + INPUTS + file - filehandle + buffer - pointer to buffer for the data + length - number of bytes to read. The filesystem is advised + to try to fulfill the request as well as possible. + + RESULT + The number of bytes actually read, 0 if the end of the file + was reached, -1 if an error happened. If an error occurs after + some data has already been transferred, the number of bytes + read so far is returned and IoErr() gives the error. + + NOTES + + EXAMPLE + + BUGS + + SEE ALSO + dos.library/Read(), Write64(), Seek64() + + INTERNALS + +*****************************************************************************/ +{ + AROS_LIBFUNC_INIT + + struct FileHandle *fh = BADDR(file); + QUAD done = 0; + + if (fh == NULL) + { + SetIoErr(ERROR_INVALID_LOCK); + return -1; + } + + if (length < 0) + { + SetIoErr(ERROR_BAD_NUMBER); + return -1; + } + + if (fh->fh_Type == BNULL) + return 0; + + while (done < length) + { + LONG chunk = (length - done > DOS64_IOCHUNK) + ? DOS64_IOCHUNK : (LONG)(length - done); + SIPTR ret; + + ret = dos64_SendPkt(DOS64Base, fh->fh_Type, ACTION_READ, + fh->fh_Arg1, (SIPTR)((UBYTE *)buffer + done), + chunk, 0, 0, NULL); + if (ret < 0) + return done ? done : -1; + done += ret; + if (ret < chunk) + break; + } + + return done; + + AROS_LIBFUNC_EXIT +} /* Read64 */ diff --git a/rom/dos64/seek64.c b/rom/dos64/seek64.c new file mode 100644 index 00000000000..b0e7cc7dfe2 --- /dev/null +++ b/rom/dos64/seek64.c @@ -0,0 +1,64 @@ +/* + Copyright (C) 2026, The AROS Development Team. All rights reserved. + + Desc: Change the current 64-bit read/write position in a file. +*/ + +#include +#include "dos64_intern.h" + +/***************************************************************************** + + NAME */ +#include + + AROS_LH2QUAD1(QUAD, Seek64, + +/* SYNOPSIS */ + AROS_LHA(BPTR, file, D1), + AROS_LHA(LONG, mode, D2), + AROS_LHAQUAD(QUAD, position, D3, D4), + +/* LOCATION */ + struct Dos64Base *, DOS64Base, 5, Dos64) + +/* FUNCTION + Changes the current read/write position in a file with full + 64-bit range, and/or reads the current position, e.g. to get + the current position do a Seek64(file, 0, OFFSET_CURRENT). + + If the filesystem does not support 64-bit operations the + request is delegated to the 32-bit Seek(), provided the + position is representable in 32 bits. + + INPUTS + file - filehandle + mode - Where to count from. Either OFFSET_BEGINNING, + OFFSET_CURRENT or OFFSET_END. + position - relative offset in bytes (positive, negative or 0). + + RESULT + Absolute position in bytes before the Seek64(), -1 if an error + happened. IoErr() will give additional information in that + case. If the position is not representable on the filesystem, + IoErr() returns ERROR_OBJECT_TOO_LARGE. + + NOTES + + EXAMPLE + + BUGS + + SEE ALSO + dos.library/Seek(), SetFileSize64(), GetFilePosition64() + + INTERNALS + +*****************************************************************************/ +{ + AROS_LIBFUNC_INIT + + return dos64_SeekBuffered(DOS64Base, file, position, mode); + + AROS_LIBFUNC_EXIT +} /* Seek64 */ diff --git a/rom/dos64/setfilesize64.c b/rom/dos64/setfilesize64.c new file mode 100644 index 00000000000..627669e8991 --- /dev/null +++ b/rom/dos64/setfilesize64.c @@ -0,0 +1,69 @@ +/* + Copyright (C) 2026, The AROS Development Team. All rights reserved. + + Desc: Change the size of a file, 64-bit version. +*/ + +#include +#include "dos64_intern.h" + +/***************************************************************************** + + NAME */ +#include + + AROS_LH2QUAD1(QUAD, SetFileSize64, + +/* SYNOPSIS */ + AROS_LHA(BPTR, file, D1), + AROS_LHA(LONG, mode, D2), + AROS_LHAQUAD(QUAD, offset, D3, D4), + +/* LOCATION */ + struct Dos64Base *, DOS64Base, 6, Dos64) + +/* FUNCTION + Change the size of a file with full 64-bit range. + + If the filesystem does not support 64-bit operations the + request is delegated to the 32-bit SetFileSize(), provided the + offset is representable in 32 bits. + + INPUTS + file - filehandle + mode - OFFSET_BEGINNING, OFFSET_CURRENT or OFFSET_END + offset - relative size + + RESULT + New size of the file or -1 in case of an error. + IoErr() gives additional information in that case. If the size + is not representable on the filesystem, IoErr() returns + ERROR_OBJECT_TOO_LARGE. + + NOTES + + EXAMPLE + + BUGS + + SEE ALSO + dos.library/SetFileSize(), Seek64(), GetFileSize64() + + INTERNALS + +*****************************************************************************/ +{ + AROS_LIBFUNC_INIT + + struct FileHandle *fh = BADDR(file); + + if (fh == NULL) + { + SetIoErr(ERROR_INVALID_LOCK); + return -1; + } + + return dos64_SetFileSize(DOS64Base, fh, offset, mode, TRUE); + + AROS_LIBFUNC_EXIT +} /* SetFileSize64 */ diff --git a/rom/dos64/unlockrecord64.c b/rom/dos64/unlockrecord64.c new file mode 100644 index 00000000000..d6f2c298eea --- /dev/null +++ b/rom/dos64/unlockrecord64.c @@ -0,0 +1,85 @@ +/* + Copyright (C) 2026, The AROS Development Team. All rights reserved. + + Desc: Unlock a record of a file, 64-bit version. +*/ + +#include +#include "dos64_intern.h" + +/***************************************************************************** + + NAME */ +#include + + AROS_LH1(BOOL, UnLockRecord64, + +/* SYNOPSIS */ + AROS_LHA(struct RecordLock64 *, rec, D1), + +/* LOCATION */ + struct Dos64Base *, DOS64Base, 19, Dos64) + +/* FUNCTION + Release a record lock obtained with LockRecord64(). The + rec_FH, rec_Offset, rec_Length values must match the lock + request exactly. + + INPUTS + rec - the record to unlock + + RESULT + Success/failure indicator. On failure IoErr() gives additional + information. + + NOTES + + EXAMPLE + + BUGS + + SEE ALSO + LockRecord64(), UnLockRecords64(), dos.library/UnLockRecord() + + INTERNALS + +*****************************************************************************/ +{ + AROS_LIBFUNC_INIT + + struct FileHandle *fileH; + + if (rec == NULL || (fileH = BADDR(rec->rec_FH)) == NULL) + { + SetIoErr(ERROR_INVALID_LOCK); + return DOSFALSE; + } + +#if (__WORDSIZE == 64) + { + /* MorphOS style: offset and length travel by pointer */ + UQUAD offset = rec->rec_Offset, length = rec->rec_Length; + SIPTR err = 0; + LONG ret; + + ret = dos64_SendPkt(DOS64Base, fileH->fh_Type, ACTION_FREE_RECORD64, + fileH->fh_Arg1, (SIPTR)&offset, (SIPTR)&length, + 0, 0, &err); + if (!(ret == DOSFALSE && dos64_UnsupportedAction(err))) + return ret; + } +#endif + + /* 32-bit delegation */ + if (rec->rec_Offset > 0xFFFFFFFFULL || rec->rec_Length > 0xFFFFFFFFULL + || rec->rec_Offset + rec->rec_Length > 0xFFFFFFFFULL) + { + SetIoErr(ERROR_OBJECT_TOO_LARGE); + return DOSFALSE; + } + + return UnLockRecord(rec->rec_FH, (ULONG)rec->rec_Offset, + (ULONG)rec->rec_Length); + + AROS_LIBFUNC_EXIT +} /* UnLockRecord64 */ diff --git a/rom/dos64/unlockrecords64.c b/rom/dos64/unlockrecords64.c new file mode 100644 index 00000000000..b1e059b5753 --- /dev/null +++ b/rom/dos64/unlockrecords64.c @@ -0,0 +1,64 @@ +/* + Copyright (C) 2026, The AROS Development Team. All rights reserved. + + Desc: Unlock several records of files, 64-bit version. +*/ + +#include +#include "dos64_intern.h" + +/***************************************************************************** + + NAME */ +#include + + AROS_LH1(BOOL, UnLockRecords64, + +/* SYNOPSIS */ + AROS_LHA(struct RecordLock64 *, recArray, D1), + +/* LOCATION */ + struct Dos64Base *, DOS64Base, 20, Dos64) + +/* FUNCTION + Release the record locks obtained with LockRecords64(). The + array is terminated by an entry with rec_FH set to NULL. + + INPUTS + recArray - array of RecordLock64 entries to unlock, as passed + to LockRecords64() + + RESULT + Success/failure indicator. Unlocking continues over failing + entries; the result of the last failing unlock is returned and + IoErr() gives additional information. + + NOTES + + EXAMPLE + + BUGS + + SEE ALSO + LockRecords64(), UnLockRecord64() + + INTERNALS + +*****************************************************************************/ +{ + AROS_LIBFUNC_INIT + + BOOL ret = DOSTRUE; + + while (BADDR(recArray->rec_FH) != NULL) + { + if (!UnLockRecord64(recArray)) + ret = DOSFALSE; + + recArray++; + } + + return ret; + + AROS_LIBFUNC_EXIT +} /* UnLockRecords64 */ diff --git a/rom/dos64/write64.c b/rom/dos64/write64.c new file mode 100644 index 00000000000..581855af6ca --- /dev/null +++ b/rom/dos64/write64.c @@ -0,0 +1,94 @@ +/* + Copyright (C) 2026, The AROS Development Team. All rights reserved. + + Desc: Write up to 64 bits worth of bytes to a file. +*/ + +#include +#include "dos64_intern.h" + +/***************************************************************************** + + NAME */ +#include + + AROS_LH2QUAD1(QUAD, Write64, + +/* SYNOPSIS */ + AROS_LHA(BPTR, file, D1), + AROS_LHA(CONST_APTR, buffer, D2), + AROS_LHAQUAD(QUAD, length, D3, D4), + +/* LOCATION */ + struct Dos64Base *, DOS64Base, 12, Dos64) + +/* FUNCTION + Write some data to a given file with a 64-bit length. The + request is passed to the filesystem in chunks the 32-bit + ACTION_WRITE packet can carry, so it works with every + filesystem - no buffering is involved. + + INPUTS + file - filehandle + buffer - pointer to the data to write + length - number of bytes to write. + + RESULT + The number of bytes actually written, -1 if an error happened. + If an error occurs after some data has already been + transferred, the number of bytes written so far is returned + and IoErr() gives the error. + + NOTES + + EXAMPLE + + BUGS + + SEE ALSO + dos.library/Write(), Read64(), Seek64() + + INTERNALS + +*****************************************************************************/ +{ + AROS_LIBFUNC_INIT + + struct FileHandle *fh = BADDR(file); + QUAD done = 0; + + if (fh == NULL) + { + SetIoErr(ERROR_INVALID_LOCK); + return -1; + } + + if (length < 0) + { + SetIoErr(ERROR_BAD_NUMBER); + return -1; + } + + if (fh->fh_Type == BNULL) + return length; + + while (done < length) + { + LONG chunk = (length - done > DOS64_IOCHUNK) + ? DOS64_IOCHUNK : (LONG)(length - done); + SIPTR ret; + + ret = dos64_SendPkt(DOS64Base, fh->fh_Type, ACTION_WRITE, + fh->fh_Arg1, (SIPTR)((CONST UBYTE *)buffer + done), + chunk, 0, 0, NULL); + if (ret < 0) + return done ? done : -1; + done += ret; + if (ret < chunk) + break; + } + + return done; + + AROS_LIBFUNC_EXIT +} /* Write64 */ diff --git a/rom/filesys/afs/afs.conf b/rom/filesys/afs/afs.conf index 5dee20a1f8f..0e02d77a074 100644 --- a/rom/filesys/afs/afs.conf +++ b/rom/filesys/afs/afs.conf @@ -1,5 +1,5 @@ ##begin config -version 41.8 +version 41.15 basename afs residentpri -1 handler_func AFS_work diff --git a/rom/filesys/afs/afs_security.c b/rom/filesys/afs/afs_security.c new file mode 100644 index 00000000000..302277415b0 --- /dev/null +++ b/rom/filesys/afs/afs_security.c @@ -0,0 +1,217 @@ +/* + Copyright (C) 2026, The AROS Development Team. All rights reserved. + + Desc: afs multi-user support: ownership and protection enforcement via + security.library, following the muFS filesystem contract + (secGetPktOwner() on packet receipt, secAccess_Control() for + access decisions, creator inheritance for new objects). +*/ + +#if defined(__AROS__) && AFS_SECURITY + +#include +#include + +#include +#include + +#include "os.h" +#include "afshandler.h" +#include "volumes.h" +#include "cache.h" +#include "afsblocks.h" +#include "filehandles1.h" +#include "filehandles2.h" +#include "misc.h" +#include "validator.h" +#include "afs_security.h" + +#define secBase ((struct Library *)afsbase->ab_SecBase) +#include + +/* The root directory has no owner/protection words (they are bitmap + * pointers in the root block): it belongs to the system, everybody may + * read/list it, only root may change it. */ +#define AFS_ROOT_OWNER secOWNER_SYSTEM +#define AFS_ROOT_PROTECTION (FIBF_GRP_READ | FIBF_GRP_EXECUTE | FIBF_OTR_READ | FIBF_OTR_EXECUTE) + +static inline BOOL isSecVolume(struct Volume *volume) +{ + return (volume->dostype == ID_DOS_muFS_DISK); +} + +BOOL afsSecIsActive(struct AFSBase *afsbase) +{ + return afsbase->ab_SecActive; +} + +/* + * Called for every packet before it is dispatched: find out who sent it. + */ +void afsSecBeginPacket(struct AFSBase *afsbase, struct Volume *volume, struct DosPacket *dp) +{ + afsbase->ab_SecActive = FALSE; + afsbase->ab_CurOwner = NULL; + afsbase->ab_CurOwnerId = secOWNER_NOBODY; + afsbase->ab_CurDefProt = 0; + + /* The library is RTF_AFTERDOS: a packet may arrive (boot-time mount) + * before it is initialised, so keep trying while it is resident but + * not yet openable; only give up when it is not resident at all. */ + if (!afsbase->ab_SecBase && !afsbase->ab_SecChecked) + { + if (FindResident(SECURITYNAME)) + afsbase->ab_SecBase = OpenLibrary(SECURITYNAME, 0); + else + afsbase->ab_SecChecked = TRUE; + D(bug("[afs] security.library @ %p\n", afsbase->ab_SecBase)); + } + if (!afsbase->ab_SecBase || !volume || !isSecVolume(volume) || !secIsConfigured()) + return; + + afsbase->ab_SecActive = TRUE; + afsbase->ab_CurPort = &((struct Process *)FindTask(NULL))->pr_MsgPort; + afsbase->ab_CurOwner = secGetPktOwner(dp); + afsbase->ab_CurOwnerId = secExtOwner2ULONG((struct secExtOwner *)afsbase->ab_CurOwner); + afsbase->ab_CurDefProt = secGetPktDefProtection(dp); +} + +void afsSecEndPacket(struct AFSBase *afsbase) +{ + if (afsbase->ab_CurOwner) + { + secFreeExtOwner((struct secExtOwner *)afsbase->ab_CurOwner); + afsbase->ab_CurOwner = NULL; + } + afsbase->ab_SecActive = FALSE; +} + +/* Owner/protection of a header block, with the root directory special-cased */ +static void getBlockOwnerProt(struct Volume *volume, struct BlockCache *bb, ULONG *owner, LONG *prot) +{ + if (OS_BE2LONG(bb->buffer[BLK_SECONDARY_TYPE(volume)]) == ST_ROOT) + { + *owner = AFS_ROOT_OWNER; + *prot = AFS_ROOT_PROTECTION; + } + else + { + *owner = OS_BE2LONG(bb->buffer[BLK_OWNER(volume)]); + *prot = OS_BE2LONG(bb->buffer[BLK_PROTECT(volume)]); + } +} + +/* + * May the sender of the current packet access the object in 'bb'? + * Returns 0 or a DOS error code. + */ +LONG afsSecCheckBlock(struct AFSBase *afsbase, struct Volume *volume, struct BlockCache *bb, LONG access) +{ + ULONG owner; + LONG prot, res; + + if (!afsbase->ab_SecActive) + return 0; + + getBlockOwnerProt(volume, bb, &owner, &prot); + res = secAccess_Control(secAC_FILESYSTEM_CONTEXT, afsbase->ab_CurPort, + (struct secExtOwner *)afsbase->ab_CurOwner, owner, prot, access); + if (res == secAC_PERMISSION_GRANTED) + return 0; + + D(bug("[afs] access %ld to block %u (owner %08lx prot %08lx) denied for %08lx\n", + (long)access, bb->blocknum, (unsigned long)owner, (unsigned long)prot, (unsigned long)afsbase->ab_CurOwnerId)); + + if (access & AFS_ACCESS_DELETE) + return ERROR_DELETE_PROTECTED; + if (access & AFS_ACCESS_WRITE) + return ERROR_WRITE_PROTECTED; + return ERROR_READ_PROTECTED; +} + +/* + * May the sender change the properties (protection, comment, date, owner, + * name) of the object? Root, the owner, or anybody for unowned objects. + */ +LONG afsSecCheckProperty(struct AFSBase *afsbase, struct Volume *volume, struct BlockCache *bb) +{ + ULONG owner; + LONG prot; + + if (!afsbase->ab_SecActive) + return 0; + + getBlockOwnerProt(volume, bb, &owner, &prot); + if (secGetRelationshipA((struct secExtOwner *)afsbase->ab_CurOwner, owner, NULL) & secRelF_PROPERTY_ACCESS) + return 0; + + D(bug("[afs] property access to block %u (owner %08lx) denied for %08lx\n", + bb->blocknum, (unsigned long)owner, (unsigned long)afsbase->ab_CurOwnerId)); + return ERROR_WRITE_PROTECTED; +} + +/* + * Access check on a named object (ERROR_OBJECT_NOT_FOUND if it does not + * exist), on the directory that will hold 'name' (AFS_SECNAMED_PARENT), + * or property check on a named object (AFS_SECNAMED_PROPERTY). + */ +LONG afsSecCheckNamed(struct AFSBase *afsbase, struct AfsHandle *dirah, CONST_STRPTR name, LONG access) +{ + struct BlockCache *bb; + UBYTE fname[34]; + ULONG block; + SIPTR error = 0; + + if (!afsbase->ab_SecActive) + return 0; + if (access & AFS_SECNAMED_PARENT) + bb = getDirBlockBuffer(afsbase, dirah, name, fname, &error); + else + bb = findBlock(afsbase, dirah, name, &block, &error); + if (!bb) + return error ? error : ERROR_OBJECT_NOT_FOUND; + if (access & AFS_SECNAMED_PROPERTY) + return afsSecCheckProperty(afsbase, dirah->volume, bb); + return afsSecCheckBlock(afsbase, dirah->volume, bb, access & ~AFS_SECNAMED_PARENT); +} + +/* Owner word for a newly created object */ +ULONG afsSecNewOwner(struct AFSBase *afsbase) +{ + return afsbase->ab_SecActive ? afsbase->ab_CurOwnerId : 0; +} + +/* Protection bits for a newly created object */ +ULONG afsSecNewProtection(struct AFSBase *afsbase, ULONG def) +{ + return afsbase->ab_SecActive ? (ULONG)afsbase->ab_CurDefProt : def; +} + +/* + * ACTION_SET_OWNER + */ +ULONG afsSecSetOwner(struct AFSBase *afsbase, struct AfsHandle *dirah, CONST_STRPTR name, ULONG owner) +{ + struct BlockCache *bb; + ULONG block; + SIPTR error = 0; + LONG err; + + D(bug("[afs] setOwner(ah,%s,%08lx)\n", name, (unsigned long)owner)); + if (0 == checkValid(afsbase, dirah->volume)) + return ERROR_DISK_WRITE_PROTECTED; + if (!(bb = findBlock(afsbase, dirah, name, &block, &error))) + return error ? error : ERROR_OBJECT_NOT_FOUND; + if (OS_BE2LONG(bb->buffer[BLK_SECONDARY_TYPE(dirah->volume)]) == ST_ROOT) + return ERROR_OBJECT_WRONG_TYPE; + if ((err = afsSecCheckProperty(afsbase, dirah->volume, bb))) + return err; + /* Only root may give objects away */ + if (afsbase->ab_SecActive && + !(secGetRelationshipA((struct secExtOwner *)afsbase->ab_CurOwner, owner, NULL) & (secRelF_ROOT_UID | secRelF_UID_MATCH))) + return ERROR_WRITE_PROTECTED; + bb->buffer[BLK_OWNER(dirah->volume)] = OS_LONG2BE(owner); + return writeHeader(afsbase, dirah->volume, bb); +} + +#endif /* __AROS__ && AFS_SECURITY */ diff --git a/rom/filesys/afs/afs_security.h b/rom/filesys/afs/afs_security.h new file mode 100644 index 00000000000..8344443915b --- /dev/null +++ b/rom/filesys/afs/afs_security.h @@ -0,0 +1,58 @@ +/* + Copyright (C) 2026, The AROS Development Team. All rights reserved. + + Desc: afs multi-user support (security.library). Only active when + security.library is resident, configured, and the volume carries + a muFS dostype (muF\0). Everything is a no-op otherwise. +*/ +#ifndef AFS_SECURITY_H +#define AFS_SECURITY_H + +struct BlockCache; +struct AfsHandle; +struct AFSBase; +struct Volume; +struct DosPacket; + +/* Access types (same values as secAt_#? in ) */ +#define AFS_ACCESS_READ 1 +#define AFS_ACCESS_WRITE 2 +#define AFS_ACCESS_EXECUTE 4 +#define AFS_ACCESS_DELETE 8 + +#if defined(__AROS__) && AFS_SECURITY +#include "os.h" +#include "afshandler.h" +#include "volumes.h" +#include + +void afsSecBeginPacket(struct AFSBase *afsbase, struct Volume *volume, struct DosPacket *dp); +void afsSecEndPacket(struct AFSBase *afsbase); +BOOL afsSecIsActive(struct AFSBase *afsbase); +LONG afsSecCheckBlock(struct AFSBase *afsbase, struct Volume *volume, struct BlockCache *bb, LONG access); +LONG afsSecCheckProperty(struct AFSBase *afsbase, struct Volume *volume, struct BlockCache *bb); +/* what afsSecCheckNamed() looks up and checks, or'ed to the access type */ +#define AFS_SECNAMED_PARENT 0x100 /* the directory that will hold 'name' */ +#define AFS_SECNAMED_PROPERTY 0x200 /* property access instead of an access type */ +LONG afsSecCheckNamed(struct AFSBase *afsbase, struct AfsHandle *dirah, CONST_STRPTR name, LONG access); +#define afsSecCheckName(a,d,n,x) afsSecCheckNamed(a,d,n,x) +#define afsSecCheckParent(a,d,n,x) afsSecCheckNamed(a,d,n,(x) | AFS_SECNAMED_PARENT) +#define afsSecCheckNameProperty(a,d,n) afsSecCheckNamed(a,d,n,AFS_SECNAMED_PROPERTY) +ULONG afsSecNewOwner(struct AFSBase *afsbase); +ULONG afsSecNewProtection(struct AFSBase *afsbase, ULONG def); +ULONG afsSecSetOwner(struct AFSBase *afsbase, struct AfsHandle *dirah, CONST_STRPTR name, ULONG owner); +#else +#define afsSecBeginPacket(a,v,d) do {} while (0) +#define afsSecEndPacket(a) do {} while (0) +#define afsSecIsActive(a) (0) +#define afsSecCheckBlock(a,v,b,x) (0) +#define afsSecCheckProperty(a,v,b) (0) +#define afsSecCheckName(a,d,n,x) (0) +#define afsSecCheckParent(a,d,n,x) (0) +#define afsSecCheckNameProperty(a,d,n) (0) +#define afsSecNewOwner(a) (0) +#define afsSecNewProtection(a,d) (d) +#define afsSecSetOwner(a,d,n,o) (ERROR_ACTION_NOT_KNOWN) +#endif + +#endif /* AFS_SECURITY_H */ diff --git a/rom/filesys/afs/afsblocks.h b/rom/filesys/afs/afsblocks.h index 802fe2e1379..29123828518 100644 --- a/rom/filesys/afs/afsblocks.h +++ b/rom/filesys/afs/afsblocks.h @@ -2,7 +2,7 @@ #define AFSBLOCKS_H /* - Copyright © 1995-2006, The AROS Development Team. All rights reserved. + Copyright © 1995-2026, The AROS Development Team. All rights reserved. $Id$ */ @@ -15,55 +15,97 @@ #define BLOCK_SIZE(volume) (volume->SizeBlock*4) +/* + * Most header fields sit at a fixed distance from the end of the block. + * BLKO_x is that distance in longs (negative), BLK_x(volume) the index from + * the start of the block. BLK_TAILPTR() points just past a block, so + * BLK_TAILPTR(buf, volume)[BLKO_x] is the same long as buf[BLK_x(volume)]; + * functions that touch several of these fields take that pointer once. + */ +#define BLK_TAILPTR(buf, volume) ((ULONG *)(buf) + (volume)->SizeBlock) + //all T_SHORT entries #define BLK_PRIMARY_TYPE 0 #define BLK_CHECKSUM 5 #define BLK_TABLE_START 6 -#define BLK_TABLE_END(volume) (volume->SizeBlock-51) -#define BLK_SECONDARY_TYPE(volume) (volume->SizeBlock-1) +#define BLKO_TABLE_END (-51) +#define BLK_TABLE_END(volume) (volume->SizeBlock+BLKO_TABLE_END) +#define BLKO_SECONDARY_TYPE (-1) +#define BLK_SECONDARY_TYPE(volume) (volume->SizeBlock+BLKO_SECONDARY_TYPE) // rootblock entries #define BLK_TABLE_SIZE 3 -#define BLK_BITMAP_VALID_FLAG(volume) (volume->SizeBlock-50) -#define BLK_BITMAP_POINTERS_START(volume) (volume->SizeBlock-49) -#define BLK_BITMAP_POINTERS_END(volume) (volume->SizeBlock-25) -#define BLK_BITMAP_EXTENSION(volume) (volume->SizeBlock-24) -#define BLK_ROOT_DAYS(volume) (volume->SizeBlock-23) -#define BLK_ROOT_MINS(volume) (volume->SizeBlock-22) -#define BLK_ROOT_TICKS(volume) (volume->SizeBlock-21) -#define BLK_DISKNAME_START(volume) (volume->SizeBlock-20) -#define BLK_DISKNAME_END(volume) (volume->SizeBlock-13) -#define BLK_VOLUME_DAYS(volume) (volume->SizeBlock-10) -#define BLK_VOLUME_MINS(volume) (volume->SizeBlock-9) -#define BLK_VOLUME_TICKS(volume) (volume->SizeBlock-8) -#define BLK_CREATION_DAYS(volume) (volume->SizeBlock-7) -#define BLK_CREATION_MINS(volume) (volume->SizeBlock-6) -#define BLK_CREATION_TICKS(volume) (volume->SizeBlock-5) +#define BLKO_BITMAP_VALID_FLAG (-50) +#define BLK_BITMAP_VALID_FLAG(volume) (volume->SizeBlock+BLKO_BITMAP_VALID_FLAG) +#define BLKO_BITMAP_POINTERS_START (-49) +#define BLK_BITMAP_POINTERS_START(volume) (volume->SizeBlock+BLKO_BITMAP_POINTERS_START) +#define BLKO_BITMAP_POINTERS_END (-25) +#define BLK_BITMAP_POINTERS_END(volume) (volume->SizeBlock+BLKO_BITMAP_POINTERS_END) +#define BLKO_BITMAP_EXTENSION (-24) +#define BLK_BITMAP_EXTENSION(volume) (volume->SizeBlock+BLKO_BITMAP_EXTENSION) +#define BLKO_ROOT_DAYS (-23) +#define BLK_ROOT_DAYS(volume) (volume->SizeBlock+BLKO_ROOT_DAYS) +#define BLKO_ROOT_MINS (-22) +#define BLK_ROOT_MINS(volume) (volume->SizeBlock+BLKO_ROOT_MINS) +#define BLKO_ROOT_TICKS (-21) +#define BLK_ROOT_TICKS(volume) (volume->SizeBlock+BLKO_ROOT_TICKS) +#define BLKO_DISKNAME_START (-20) +#define BLK_DISKNAME_START(volume) (volume->SizeBlock+BLKO_DISKNAME_START) +#define BLKO_DISKNAME_END (-13) +#define BLK_DISKNAME_END(volume) (volume->SizeBlock+BLKO_DISKNAME_END) +#define BLKO_VOLUME_DAYS (-10) +#define BLK_VOLUME_DAYS(volume) (volume->SizeBlock+BLKO_VOLUME_DAYS) +#define BLKO_VOLUME_MINS (-9) +#define BLK_VOLUME_MINS(volume) (volume->SizeBlock+BLKO_VOLUME_MINS) +#define BLKO_VOLUME_TICKS (-8) +#define BLK_VOLUME_TICKS(volume) (volume->SizeBlock+BLKO_VOLUME_TICKS) +#define BLKO_CREATION_DAYS (-7) +#define BLK_CREATION_DAYS(volume) (volume->SizeBlock+BLKO_CREATION_DAYS) +#define BLKO_CREATION_MINS (-6) +#define BLK_CREATION_MINS(volume) (volume->SizeBlock+BLKO_CREATION_MINS) +#define BLKO_CREATION_TICKS (-5) +#define BLK_CREATION_TICKS(volume) (volume->SizeBlock+BLKO_CREATION_TICKS) //file and directory entries #define BLK_OWN_KEY 1 -#define BLK_OWNER(volume) (volume->SizeBlock-49) -#define BLK_PROTECT(volume) (volume->SizeBlock-48) -#define BLK_COMMENT_START(volume) (volume->SizeBlock-46) -#define BLK_COMMENT_END(volume) (volume->SizeBlock-24) -#define BLK_DAYS(volume) (volume->SizeBlock-23) -#define BLK_MINS(volume) (volume->SizeBlock-22) -#define BLK_TICKS(volume) (volume->SizeBlock-21) -#define BLK_LINKCHAIN(volume) (volume->SizeBlock-10) -#define BLK_HASHCHAIN(volume) (volume->SizeBlock-4) -#define BLK_PARENT(volume) (volume->SizeBlock-3) +#define BLKO_OWNER (-49) +#define BLK_OWNER(volume) (volume->SizeBlock+BLKO_OWNER) +#define BLKO_PROTECT (-48) +#define BLK_PROTECT(volume) (volume->SizeBlock+BLKO_PROTECT) +#define BLKO_COMMENT_START (-46) +#define BLK_COMMENT_START(volume) (volume->SizeBlock+BLKO_COMMENT_START) +#define BLKO_COMMENT_END (-24) +#define BLK_COMMENT_END(volume) (volume->SizeBlock+BLKO_COMMENT_END) +#define BLKO_DAYS (-23) +#define BLK_DAYS(volume) (volume->SizeBlock+BLKO_DAYS) +#define BLKO_MINS (-22) +#define BLK_MINS(volume) (volume->SizeBlock+BLKO_MINS) +#define BLKO_TICKS (-21) +#define BLK_TICKS(volume) (volume->SizeBlock+BLKO_TICKS) +#define BLKO_LINKCHAIN (-10) +#define BLK_LINKCHAIN(volume) (volume->SizeBlock+BLKO_LINKCHAIN) +#define BLKO_HASHCHAIN (-4) +#define BLK_HASHCHAIN(volume) (volume->SizeBlock+BLKO_HASHCHAIN) +#define BLKO_PARENT (-3) +#define BLK_PARENT(volume) (volume->SizeBlock+BLKO_PARENT) //directory entries -#define BLK_DIRECTORYNAME_START(volume) (volume->SizeBlock-20) -#define BLK_DIRECTORYNAME_END(volume) (volume->SizeBlock-13) +#define BLKO_DIRECTORYNAME_START (-20) +#define BLK_DIRECTORYNAME_START(volume) (volume->SizeBlock+BLKO_DIRECTORYNAME_START) +#define BLKO_DIRECTORYNAME_END (-13) +#define BLK_DIRECTORYNAME_END(volume) (volume->SizeBlock+BLKO_DIRECTORYNAME_END) //file entries #define BLK_BLOCK_COUNT 2 #define BLK_FIRST_DATA 4 -#define BLK_BYTE_SIZE(volume) (volume->SizeBlock-47) -#define BLK_FILENAME_START(volume) (volume->SizeBlock-20) -#define BLK_FILENAME_END(volume) (volume->SizeBlock-13) -#define BLK_EXTENSION(volume) (volume->SizeBlock-2) +#define BLKO_BYTE_SIZE (-47) +#define BLK_BYTE_SIZE(volume) (volume->SizeBlock+BLKO_BYTE_SIZE) +#define BLKO_FILENAME_START (-20) +#define BLK_FILENAME_START(volume) (volume->SizeBlock+BLKO_FILENAME_START) +#define BLKO_FILENAME_END (-13) +#define BLK_FILENAME_END(volume) (volume->SizeBlock+BLKO_FILENAME_END) +#define BLKO_EXTENSION (-2) +#define BLK_EXTENSION(volume) (volume->SizeBlock+BLKO_EXTENSION) //data blocks OFS #define BLK_HEADER_KEY 1 @@ -73,14 +115,20 @@ #define BLK_DATA_START 6 //hardlinks -#define BLK_HARDLINKNAME_START(volume) (volume->SizeBlock-20) -#define BLK_HARDLINKNAME_END(volume) (volume->SizeBlock-13) -#define BLK_ORIGINAL(volume) (volume->SizeBlock-11) +#define BLKO_HARDLINKNAME_START (-20) +#define BLK_HARDLINKNAME_START(volume) (volume->SizeBlock+BLKO_HARDLINKNAME_START) +#define BLKO_HARDLINKNAME_END (-13) +#define BLK_HARDLINKNAME_END(volume) (volume->SizeBlock+BLKO_HARDLINKNAME_END) +#define BLKO_ORIGINAL (-11) +#define BLK_ORIGINAL(volume) (volume->SizeBlock+BLKO_ORIGINAL) //softlinks #define BLK_SYMBOLICNAME_START 6 -#define BLK_SYMBOLICNAME_END(volume) (volume->SizeBlock-51) -#define BLK_SOFTLINKNAME_START(volume) (volume->SizeBlock-20) -#define BLK_SOFTLINKNAME_END(volume) (volume->SizeBlock-13) +#define BLKO_SYMBOLICNAME_END (-51) +#define BLK_SYMBOLICNAME_END(volume) (volume->SizeBlock+BLKO_SYMBOLICNAME_END) +#define BLKO_SOFTLINKNAME_START (-20) +#define BLK_SOFTLINKNAME_START(volume) (volume->SizeBlock+BLKO_SOFTLINKNAME_START) +#define BLKO_SOFTLINKNAME_END (-13) +#define BLK_SOFTLINKNAME_END(volume) (volume->SizeBlock+BLKO_SOFTLINKNAME_END) #endif diff --git a/rom/filesys/afs/afshandler.h b/rom/filesys/afs/afshandler.h index 18abc040954..1553d8beac0 100644 --- a/rom/filesys/afs/afshandler.h +++ b/rom/filesys/afs/afshandler.h @@ -2,13 +2,23 @@ #define AFS_HANDLER_H /* - Copyright © 1995-2020, The AROS Development Team. All rights reserved. + Copyright © 1995-2026, The AROS Development Team. All rights reserved. $Id$ */ #include #include +struct DosList; + +/* A volume node kept alive by open locks after its medium went away */ +struct OfflineNode +{ + struct MinNode node; + struct DosList *dl; + BOOL added; /* node is published in the system DosList */ +}; + struct AFSBase { struct Library ab_Lib; @@ -19,8 +29,19 @@ struct AFSBase struct MsgPort *timer_mp; struct MsgPort port; /* sigtask and sigbit for changeint */ struct List device_list; /* list of mounted devices (struct Volume) */ + struct MinList offlinevols; /* offline volume nodes (struct OfflineNode) */ + ULONG parkedvols; /* volume nodes parked with locks, also without an OfflineNode */ struct timerequest *timer_request; ULONG timer_flags; + + /* multi-user support (afs_security.c) */ + struct Library *ab_SecBase; /* security.library, if resident */ + BOOL ab_SecChecked; /* tried to open it */ + BOOL ab_SecActive; /* enforcing for the packet being processed */ + APTR ab_CurOwner; /* struct secExtOwner * of the packet's sender */ + ULONG ab_CurOwnerId; /* uid<<16 | gid of the sender */ + LONG ab_CurDefProt; /* default protection bits of the sender */ + struct MsgPort *ab_CurPort; /* our port (filesystem context) */ }; #define TIMER_ACTIVE 0x00000001 diff --git a/rom/filesys/afs/bitmap.c b/rom/filesys/afs/bitmap.c index 7338b5ed13a..e01066c2a7b 100644 --- a/rom/filesys/afs/bitmap.c +++ b/rom/filesys/afs/bitmap.c @@ -1,7 +1,11 @@ /* - Copyright � 1995-2005, The AROS Development Team. All rights reserved. - $Id$ + Copyright (C) 1995-2026, The AROS Development Team. All rights reserved. */ + +#ifndef DEBUG +#define DEBUG 0 +#endif + #include "os.h" #include "bitmap.h" #include "cache.h" @@ -10,6 +14,66 @@ #include "afsblocks.h" #include "baseredef.h" +/* like countUsedBlocksInBitmap, but counting in an already-read block image */ +static ULONG countUsedBlocksInData + ( + struct AFSBase *afsbase, + struct Volume *volume, + ULONG block, + ULONG *data, + ULONG maxcount + ) +{ +UWORD i=1; +ULONG count=0,lg,bits; + + if (!calcChkSum(volume->SizeBlock, data)) + { + while (maxcount>=32) + { + lg=OS_BE2LONG(data[i]); + if (!lg) + { + count += 32; + } + else if (lg!=0xFFFFFFFF) + { + bits=1; + do + { + if (!(bits & lg)) + count++; + bits=bits<<1; + } while (bits); + } + maxcount -=32; + i++; + } + /* are there some bits left ? */ + if (maxcount) + { + lg=OS_BE2LONG(data[i]); + if (!lg) + { + count += maxcount; + } + else if (lg!=0xFFFFFFFF) + { + bits=1; + for (;maxcount;maxcount--) + { + if (!(bits & lg)) + count++; + bits=bits<<1; + } + } + } + } + else + showError(afsbase, ERR_CHECKSUM, block); + return count; +} + /********************************************** Name : countUsedBlocksInBitmap Descr.: count used blocks in a bitmap block @@ -19,72 +83,66 @@ Output: nr of used blocks ***********************************************/ ULONG countUsedBlocksInBitmap - ( - struct AFSBase *afsbase, - struct Volume *volume, - ULONG block, - ULONG maxcount - ) + ( + struct AFSBase *afsbase, + struct Volume *volume, + ULONG block, + ULONG maxcount + ) { -UWORD i=1; -ULONG count=0,lg,bits; struct BlockCache *blockbuffer; - if ((blockbuffer=getBlock(afsbase, volume,block))==0) - { - showText(afsbase, "Couldn't read bitmap block %lu\nCount used blocks failed!",block); - return count; - } - if (!calcChkSum(volume->SizeBlock, blockbuffer->buffer)) - { - while (maxcount>=32) - { - lg=OS_BE2LONG(blockbuffer->buffer[i]); - if (!lg) - { - count += 32; - } - else if (lg!=0xFFFFFFFF) - { - bits=1; - do - { - if (!(bits & lg)) - count++; - bits=bits<<1; - } while (bits); - } - maxcount -=32; - i++; - } - /* are there some bits left ? */ - if (maxcount) - { - lg=OS_BE2LONG(blockbuffer->buffer[i]); - if (!lg) - { - count += maxcount; - } - else if (lg!=0xFFFFFFFF) - { - bits=1; - for (;maxcount;maxcount--) - { - if (!(bits & lg)) - count++; - bits=bits<<1; - } - } - } - } - else - showError(afsbase, ERR_CHECKSUM,block); - return count; + if ((blockbuffer=getBlock(afsbase, volume,block))==0) + { + showText(afsbase, "Couldn't read bitmap block %lu\nCount used blocks failed!",block); + return 0; + } + return countUsedBlocksInData(afsbase, volume, block, blockbuffer->buffer, maxcount); +} + +struct bmWindow +{ + ULONG start; + ULONG avail; + UBYTE *buf; + ULONG bufblocks; +}; + +/* sliding read-ahead window over the (usually contiguous) bitmap area; + serves bitmap and extension blocks alike from one sequential sweep */ +static ULONG *bmFetchBlock + ( + struct AFSBase *afsbase, + struct Volume *volume, + struct bmWindow *win, + ULONG blk + ) +{ + if ((blk < win->start) || (blk >= win->start + win->avail)) + { + ULONG chunk = win->bufblocks; + + if (blk >= volume->countblocks) + return NULL; + if (chunk > volume->countblocks - blk) + chunk = volume->countblocks - blk; + if (readDisk(afsbase, volume, blk, chunk, win->buf) != 0) + return NULL; + win->start = blk; + win->avail = chunk; + } + return (ULONG *)(win->buf + (blk - win->start) * BLOCK_SIZE(volume)); } +#define BM_COUNTBATCHBYTES 65536 + /************************************** Name : countUsedBlocks - Descr.: count used blocks of a volume + Descr.: count used blocks of a volume; the bitmap area (bitmap and + extension blocks alike) is swept through a sliding read-ahead + window instead of one IO per block. Without a window buffer + (single bitmap block, or no memory) the blocks are read one by + one through the block cache. Input : volume - Output: nr of used blocks of the volume ***************************************/ @@ -94,189 +152,262 @@ ULONG blocks; ULONG maxinbitmap; ULONG curblock; ULONG count=0; +ULONG span; +ULONG bmblk; +ULONG tablesize; +ULONG *data; +ULONG *table; +ULONG *extcopy; struct BlockCache *blockbuffer; +struct bmWindow win = {0, 0, NULL, 0}; + + blocks=volume->countblocks-volume->bootblocks; /* blocks to count */ + maxinbitmap = (volume->SizeBlock-1)*32; /* max blocks marked in a bitmapblock */ - blocks=volume->countblocks-volume->bootblocks; /* blocks to count */ - maxinbitmap = (volume->SizeBlock-1)*32; /* max blocks marked in a bitmapblock */ - /* check bitmap blocks stored in rootblock */ - for (i=0;i<=24;i++) - { - if (maxinbitmap>blocks) - maxinbitmap = blocks; - if (volume->bitmapblockpointers[i]) - { - count += - countUsedBlocksInBitmap - (afsbase, volume, volume->bitmapblockpointers[i], maxinbitmap); - blocks -= maxinbitmap; - } - if (blocks == 0) - break; - } - /* check extension blocks if neccessary */ - if (blocks != 0) - { - curblock = volume->bitmapextensionblock; - while (curblock != 0) - { - - blockbuffer = getBlock(afsbase, volume, curblock); - if (blockbuffer == NULL) - { - showText - ( - afsbase, - "Couldn't read bitmap extension block %lu\nCount used blocks failed!", - curblock - ); - return count; - } - blockbuffer->flags |= BCF_USED; - for (i=0;iSizeBlock-1;i++) - { - if (maxinbitmap > blocks) - maxinbitmap = blocks; - if (blockbuffer->buffer[i] != 0) - { - count += - countUsedBlocksInBitmap - ( - afsbase, - volume, - OS_BE2LONG(blockbuffer->buffer[i]), - maxinbitmap - ); - blocks -= maxinbitmap; - } - if (blocks == 0) - break; - } - blockbuffer->flags &= ~BCF_USED; - if (blocks == 0) - break; - curblock = OS_BE2LONG(blockbuffer->buffer[volume->SizeBlock-1]); - } - if (blocks != 0) - showError(afsbase, ERR_MISSING_BITMAP_BLOCKS); - } - return count; + win.bufblocks = BM_COUNTBATCHBYTES / BLOCK_SIZE(volume); + /* + * Never read ahead more blocks than the volume's bitmap has. The window + * pays off on hard disks with many bitmap blocks; on a floppy the bitmap + * is a single block, and a 64 KB read from there costs several extra + * cylinders (seconds) on every mount. + */ + { + ULONG bmblocks = (blocks + maxinbitmap - 1) / maxinbitmap; + + if (bmblocks > 25) + bmblocks += (bmblocks - 25 + volume->SizeBlock - 2) / (volume->SizeBlock - 1); + if (win.bufblocks > bmblocks) + win.bufblocks = bmblocks; + } + if (win.bufblocks > 1) + win.buf = AllocVec((win.bufblocks + 1) * BLOCK_SIZE(volume), MEMF_PUBLIC); + /* first the bitmap blocks stored in rootblock, then the extension blocks */ + table = volume->bitmapblockpointers; + tablesize = 25; + curblock = volume->bitmapextensionblock; + blockbuffer = NULL; + for (;;) + { + for (i=0;ibitmapblockpointers) + ? OS_BE2LONG(table[i]) : table[i]; + span = (maxinbitmap > blocks) ? blocks : maxinbitmap; + if (win.buf == NULL) + count += countUsedBlocksInBitmap(afsbase, volume, bmblk, span); + else + { + data = bmFetchBlock(afsbase, volume, &win, bmblk); + if (data == NULL) + goto readfail; + count += countUsedBlocksInData(afsbase, volume, bmblk, data, span); + } + blocks -= span; + } + if (blocks == 0) + break; + } + if (blockbuffer != NULL) + blockbuffer->flags &= ~BCF_USED; + if (blocks == 0) + break; + if (table != volume->bitmapblockpointers) + curblock = OS_BE2LONG(table[volume->SizeBlock-1]); + if (curblock == 0) + { + showError(afsbase, ERR_MISSING_BITMAP_BLOCKS); + break; + } + if (win.buf == NULL) + { + blockbuffer = getBlock(afsbase, volume, curblock); + if (blockbuffer == NULL) + { + showText + ( + afsbase, + "Couldn't read bitmap extension block %lu\nCount used blocks failed!", + curblock + ); + return count; + } + blockbuffer->flags |= BCF_USED; + table = blockbuffer->buffer; + } + else + { + data = bmFetchBlock(afsbase, volume, &win, curblock); + if (data == NULL) + goto readfail; + /* extension block content must survive window refills */ + extcopy = (ULONG *)(win.buf + win.bufblocks * BLOCK_SIZE(volume)); + CopyMem(data, extcopy, BLOCK_SIZE(volume)); + table = extcopy; + } + tablesize = volume->SizeBlock-1; + } + FreeVec(win.buf); + return count; + +readfail: + showText(afsbase, "Couldn't read bitmap block\nCount used blocks failed!"); + FreeVec(win.buf); + return count; } ULONG createNewBitmapBlocks(struct AFSBase *afsbase, struct Volume *volume) { struct BlockCache *bitmapblock,*extensionblock; ULONG i, blocks, maxinbitmap; - /* initialize a block as a bitmap block */ - extensionblock = getFreeCacheBlock(afsbase, volume, -1); - extensionblock->flags |= BCF_USED; - bitmapblock = getFreeCacheBlock(afsbase, volume, volume->rootblock+1); - /* all blocks are free */ - for (i=1;iSizeBlock;i++) - bitmapblock->buffer[i] = 0xFFFFFFFF; - bitmapblock->buffer[0] = 0; - bitmapblock->buffer[0] = OS_LONG2BE(0-calcChkSum(volume->SizeBlock,bitmapblock->buffer)); - /* get nr of blocks to mark in bitmap blocks */ - blocks = volume->countblocks - volume->bootblocks; - /* calc max blocks that can be marked in a single bitmap block */ - maxinbitmap = (volume->SizeBlock-1)*32; - /* first create bitmapblocks stored in rootblock */ - for (i=0;i<=24;i++) - { - if (maxinbitmap > blocks) - maxinbitmap = blocks; - volume->bitmapblockpointers[i] = bitmapblock->blocknum; - writeBlock(afsbase, volume, bitmapblock, -1); - bitmapblock->blocknum += 1; - blocks = blocks - maxinbitmap; - if (blocks == 0) - { - i++; - while (i<=24) - volume->bitmapblockpointers[i++] = 0; - } - } - /* check extension blocks if necessary */ - if (blocks != 0) - { - volume->bitmapextensionblock=bitmapblock->blocknum; - do - { - /* initialize extensionblock with zeros */ - extensionblock->blocknum = bitmapblock->blocknum; - for (i=0;iSizeBlock;i++) - extensionblock->buffer[i] = 0; - /* fill extensionblock and write bitmapblocks */ - for (i=0;iSizeBlock-1;i++) - { - if (maxinbitmap > blocks) - maxinbitmap = blocks; - bitmapblock->blocknum += 1; - extensionblock->buffer[i] = OS_LONG2BE(bitmapblock->blocknum); - writeBlock(afsbase, volume, bitmapblock, -1); - blocks = blocks-maxinbitmap; - if (blocks == 0) - break; - } - if (blocks != 0) /*write another extensionblock ? */ - { - /* fill next extension */ - extensionblock->buffer[volume->SizeBlock-1]=OS_LONG2BE(bitmapblock->blocknum+1); - } - writeBlock(afsbase, volume, extensionblock, -1); - bitmapblock->blocknum += 1; - } while (blocks != 0); - } - else - volume->bitmapextensionblock = 0; - extensionblock->flags &= ~BCF_USED; - return DOSTRUE; + /* initialize a block as a bitmap block */ + extensionblock = getFreeCacheBlock(afsbase, volume, -1); + if (extensionblock == NULL) + return DOSFALSE; + extensionblock->flags |= BCF_USED; + bitmapblock = getFreeCacheBlock(afsbase, volume, volume->rootblock+1); + if (bitmapblock == NULL) + { + extensionblock->flags &= ~BCF_USED; + return DOSFALSE; + } + /* all blocks are free */ + for (i=1;iSizeBlock;i++) + bitmapblock->buffer[i] = 0xFFFFFFFF; + bitmapblock->buffer[0] = 0; + bitmapblock->buffer[0] = OS_LONG2BE(0-calcChkSum(volume->SizeBlock,bitmapblock->buffer)); + /* get nr of blocks to mark in bitmap blocks */ + blocks = volume->countblocks - volume->bootblocks; + /* calc max blocks that can be marked in a single bitmap block */ + maxinbitmap = (volume->SizeBlock-1)*32; + /* first create bitmapblocks stored in rootblock */ + for (i=0;i<=24;i++) + { + if (maxinbitmap > blocks) + maxinbitmap = blocks; + volume->bitmapblockpointers[i] = bitmapblock->blocknum; + if (!writeBlock(afsbase, volume, bitmapblock, -1)) + { + extensionblock->flags &= ~BCF_USED; + return DOSFALSE; + } + bitmapblock->blocknum += 1; + blocks = blocks - maxinbitmap; + if (blocks == 0) + { + i++; + while (i<=24) + volume->bitmapblockpointers[i++] = 0; + } + } + /* check extension blocks if necessary */ + if (blocks != 0) + { + volume->bitmapextensionblock=bitmapblock->blocknum; + do + { + /* initialize extensionblock with zeros */ + extensionblock->blocknum = bitmapblock->blocknum; + for (i=0;iSizeBlock;i++) + extensionblock->buffer[i] = 0; + /* fill extensionblock and write bitmapblocks */ + for (i=0;iSizeBlock-1;i++) + { + if (maxinbitmap > blocks) + maxinbitmap = blocks; + bitmapblock->blocknum += 1; + extensionblock->buffer[i] = OS_LONG2BE(bitmapblock->blocknum); + if (!writeBlock(afsbase, volume, bitmapblock, -1)) + { + extensionblock->flags &= ~BCF_USED; + return DOSFALSE; + } + blocks = blocks-maxinbitmap; + if (blocks == 0) + break; + } + if (blocks != 0) /*write another extensionblock ? */ + { + /* fill next extension */ + extensionblock->buffer[volume->SizeBlock-1]=OS_LONG2BE(bitmapblock->blocknum+1); + } + if (!writeBlock(afsbase, volume, extensionblock, -1)) + { + extensionblock->flags &= ~BCF_USED; + return DOSFALSE; + } + bitmapblock->blocknum += 1; + } while (blocks != 0); + } + else + volume->bitmapextensionblock = 0; + extensionblock->flags &= ~BCF_USED; + return DOSTRUE; } LONG setBitmapFlag(struct AFSBase *afsbase, struct Volume *volume, LONG flag) { struct BlockCache *blockbuffer; - D(bug("[AFS] setBitmapFlag()\n")); - blockbuffer = getBlock(afsbase, volume, volume->rootblock); - if (blockbuffer == NULL) - return DOSFALSE; - blockbuffer->buffer[BLK_BITMAP_VALID_FLAG(volume)] = flag; - if ((blockbuffer->flags & BCF_WRITE) == 0) - { - writeBlock(afsbase, volume, blockbuffer, BLK_CHECKSUM); - blockbuffer->flags |= BCF_WRITE; - } - else - writeBlockDeferred(afsbase, volume, blockbuffer, BLK_CHECKSUM); - return DOSTRUE; + D(bug("[afs] setBitmapFlag()\n")); + blockbuffer = getBlock(afsbase, volume, volume->rootblock); + if (blockbuffer == NULL) + return DOSFALSE; + blockbuffer->buffer[BLK_BITMAP_VALID_FLAG(volume)] = flag; + if (flag == 0 && !volume->bitmapinvalid && !volume->writefailed) + { + if (!writeBlock(afsbase, volume, blockbuffer, BLK_CHECKSUM)) + return DOSFALSE; + blockbuffer->flags |= BCF_WRITE; + } + else + writeBlockDeferred(afsbase, volume, blockbuffer, BLK_CHECKSUM); + return DOSTRUE; } LONG invalidBitmap(struct AFSBase *afsbase, struct Volume *volume) { - volume->lastextensionblock = 0; - volume->lastposition = 0; - volume->bstartblock = volume->bootblocks; /* reserved */ - volume->bitmapblock = getBlock(afsbase, volume, volume->bitmapblockpointers[volume->lastposition]); - if (volume->bitmapblock != NULL) - { - volume->bitmapblock->flags |= BCF_USED; - if (setBitmapFlag(afsbase, volume, 0)) - { - return DOSTRUE; - } - volume->bitmapblock->flags &= ~BCF_USED; - } - return DOSFALSE; + if (volume->writefailed || volume->cachepending) + return DOSFALSE; + volume->lastextensionblock = 0; + volume->lastposition = 0; + volume->bstartblock = 0; /* relative, see volumes.h */ + volume->bitmapblock = getBlock(afsbase, volume, volume->bitmapblockpointers[volume->lastposition]); + if (volume->bitmapblock != NULL) + { + volume->bitmapblock->flags |= BCF_USED; + if (setBitmapFlag(afsbase, volume, 0)) + { + return DOSTRUE; + } + volume->bitmapblock->flags &= ~BCF_USED; + } + return DOSFALSE; +} + +void releaseBitmap(struct Volume *volume) +{ + if (volume->bitmapblock != NULL) + volume->bitmapblock->flags &= ~BCF_USED; } LONG validBitmap(struct AFSBase *afsbase, struct Volume *volume) { - if (volume->bitmapblock->flags & BCF_WRITE) - { - writeBlockDeferred(afsbase, volume, volume->bitmapblock, 0); - } - volume->bitmapblock->flags &= ~BCF_USED; - setBitmapFlag(afsbase, volume, -1); - return DOSTRUE; + if (volume->bitmapblock == NULL) + { + volume->writefailed = TRUE; + volume->state = ID_VALIDATING; + setBitmapFlag(afsbase, volume, 0); + return DOSFALSE; + } + if (volume->bitmapblock->flags & BCF_WRITE) + { + writeBlockDeferred(afsbase, volume, volume->bitmapblock, 0); + } + volume->bitmapblock->flags &= ~BCF_USED; + return setBitmapFlag(afsbase, volume, volume->writefailed ? 0 : -1) + && !volume->writefailed; } /************************************************* @@ -289,264 +420,275 @@ LONG validBitmap(struct AFSBase *afsbase, struct Volume *volume) { Note : bitmapblock is changed (should be initialized first!) **************************************************/ LONG gotoBitmapBlock - ( - struct AFSBase *afsbase, - struct Volume *volume, - ULONG block, - ULONG *longnr, - ULONG *bitnr - ) + ( + struct AFSBase *afsbase, + struct Volume *volume, + ULONG block, + ULONG *longnr, + ULONG *bitnr + ) { struct BlockCache *extensionblock; ULONG bblock,togo,maxinbitmap; - block -= volume->bootblocks; /* reserved blocks are not marked */ - maxinbitmap = (volume->SizeBlock-1)*32; /* max blocks marked in a bitmapblock */ - *bitnr = block % maxinbitmap; /* in the bblock-th block we have to mark the bit-th bit */ - *longnr = *bitnr/32+1; /* int the longnr-th LONG is "block" marked (+1 because [0]=BLK_CHECKSUM) */ - *bitnr = *bitnr % 32; /* in the bit-th bit of LONG "longnr" "block" is marked */ - /* load new block ? */ - if ( - (blockbstartblock) || - (block>=(volume->bstartblock+maxinbitmap)) - ) - { - bblock = block/maxinbitmap; /* in the bblock-th bitmap block is "block" marked */ - if (volume->bitmapblock->flags & BCF_WRITE) - { - writeBlockDeferred(afsbase, volume, volume->bitmapblock, 0); - } - volume->bitmapblock->flags &= ~BCF_USED; - /* load new block */ - if (bblock<=24) - { - volume->bitmapblock = getBlock(afsbase, volume, volume->bitmapblockpointers[bblock]); - } - else - { - volume->lastextensionblock = volume->bitmapextensionblock; + block -= volume->bootblocks; /* reserved blocks are not marked */ + maxinbitmap = (volume->SizeBlock-1)*32; /* max blocks marked in a bitmapblock */ + *bitnr = block % maxinbitmap; /* in the bblock-th block we have to mark the bit-th bit */ + *longnr = *bitnr/32+1; /* int the longnr-th LONG is "block" marked (+1 because [0]=BLK_CHECKSUM) */ + *bitnr = *bitnr % 32; /* in the bit-th bit of LONG "longnr" "block" is marked */ + /* load new block ? */ + if ( + (volume->bitmapblock == NULL) || + (blockbstartblock) || + (block>=(volume->bstartblock+maxinbitmap)) + ) + { + bblock = block/maxinbitmap; /* in the bblock-th bitmap block is "block" marked */ + if (volume->bitmapblock != NULL && (volume->bitmapblock->flags & BCF_WRITE)) + { + writeBlockDeferred(afsbase, volume, volume->bitmapblock, 0); + } + releaseBitmap(volume); + volume->bitmapblock = NULL; + /* load new block */ + if (bblock<=24) + { + volume->bitmapblock = getBlock(afsbase, volume, volume->bitmapblockpointers[bblock]); + } + else + { + volume->lastextensionblock = volume->bitmapextensionblock; //kprintf("get block from extension %lu\n", volume->lastextensionblock); - /* 25 entries in rootblock already processed */ - volume->lastposition = bblock-25; - /* do we have to go to another extensionblock ? */ - togo = volume->lastposition / (volume->SizeBlock-1); + /* 25 entries in rootblock already processed */ + volume->lastposition = bblock-25; + /* do we have to go to another extensionblock ? */ + togo = volume->lastposition / (volume->SizeBlock-1); //kprintf("togo=%lu\n", togo); - volume->lastposition %= volume->SizeBlock-1; + volume->lastposition %= volume->SizeBlock-1; //kprintf("lp=%lu\n", volume->lastposition); - extensionblock=getBlock(afsbase, volume, volume->lastextensionblock); - if (extensionblock == NULL) - { - showText(afsbase, "Could not read bitmap extionsion block %lu!", volume->lastextensionblock); - return FALSE; - } + extensionblock=getBlock(afsbase, volume, volume->lastextensionblock); + if (extensionblock == NULL) + { + showText(afsbase, "Could not read bitmap extionsion block %lu!", volume->lastextensionblock); + return FALSE; + } //if (volume->lastposition == 5) //{ -// kprintf("00: %08lx %08lx %08lx %08lx\n", extensionblock->buffer[0], extensionblock->buffer[1], extensionblock->buffer[2], extensionblock->buffer[3]); -// kprintf("10: %08lx %08lx %08lx %08lx\n", extensionblock->buffer[4], extensionblock->buffer[5], extensionblock->buffer[6], extensionblock->buffer[7]); +// kprintf("00: %08lx %08lx %08lx %08lx\n", extensionblock->buffer[0], extensionblock->buffer[1], extensionblock->buffer[2], extensionblock->buffer[3]); +// kprintf("10: %08lx %08lx %08lx %08lx\n", extensionblock->buffer[4], extensionblock->buffer[5], extensionblock->buffer[6], extensionblock->buffer[7]); //} - while (togo != 0) - { - extensionblock = - getBlock - ( - afsbase, - volume, - OS_BE2LONG(extensionblock->buffer[volume->SizeBlock-1]) - ); - if (extensionblock == NULL) - { - showText(afsbase, "Could not read bitmap extension block %lu!", OS_BE2LONG(extensionblock->buffer[volume->SizeBlock-1])); - return FALSE; - } - volume->lastextensionblock = extensionblock->blocknum; - togo--; - } - volume->bitmapblock = - getBlock - ( - afsbase, - volume, - OS_BE2LONG(extensionblock->buffer[volume->lastposition]) - ); - } - volume->bstartblock = bblock*maxinbitmap; - if (volume->bitmapblock == NULL) - { - showText(afsbase, "Could not read bitmap block!"); - return FALSE; - } - volume->bitmapblock->flags |= BCF_USED; - } - return TRUE; + while (togo != 0) + { + extensionblock = + getBlock + ( + afsbase, + volume, + OS_BE2LONG(extensionblock->buffer[volume->SizeBlock-1]) + ); + if (extensionblock == NULL) + { + showText(afsbase, "Could not read bitmap extension block after %lu!", volume->lastextensionblock); + return FALSE; + } + volume->lastextensionblock = extensionblock->blocknum; + togo--; + } + volume->bitmapblock = + getBlock + ( + afsbase, + volume, + OS_BE2LONG(extensionblock->buffer[volume->lastposition]) + ); + } + volume->bstartblock = bblock*maxinbitmap; + if (volume->bitmapblock == NULL) + { + showText(afsbase, "Could not read bitmap block!"); + return FALSE; + } + volume->bitmapblock->flags |= BCF_USED; + } + return TRUE; } LONG markBlock(struct AFSBase *afsbase, struct Volume *volume, ULONG block, ULONG mode) { -ULONG bitnr, longnr,null=0; - - //D(bug("[AFS] markBlock: block=%lu mode=%lu\n",block,mode)); - if (block>=volume->countblocks) - null = null/null; - if (!gotoBitmapBlock(afsbase, volume, block, &longnr, &bitnr)) - return 0; - if (mode) - { - /* free a block */ - volume->bitmapblock->buffer[longnr] = - OS_LONG2BE(OS_BE2LONG(volume->bitmapblock->buffer[longnr]) | (1 << bitnr)); - volume->usedblockscount -= 1; - if ( - ( - (volume->lastaccessrootblock) && (block>=volume->rootblock) - ) || // 1. case - ( - ( - ((volume->lastaccess>=volume->rootblock) && (block>=volume->rootblock)) || // 2.case and ... - ((volume->lastaccessrootblock) && (blockrootblock)) // 3.case with ... - ) && - (blocklastaccess) - ) - ) - { - volume->lastaccess = block; - } - } - else - { - volume->bitmapblock->buffer[longnr] = - OS_LONG2BE(OS_BE2LONG(volume->bitmapblock->buffer[longnr]) & ~(1 << bitnr)); - volume->usedblockscount += 1; - volume->lastaccess = block; /* all blocks before "block" are used! */ - } - volume->bitmapblock->flags |= BCF_WRITE; - return DOSTRUE; +ULONG bitnr, longnr; + + if (volume->cachepending || volume->writefailed) + return DOSFALSE; + D(bug("[afs] markBlock: block=%u mode=%u\n",block,mode)); + if (block>=volume->countblocks) + { + showText(afsbase, "Illegal Block - %lu >= %lu", block, volume->countblocks); + return 0; + } + if (!gotoBitmapBlock(afsbase, volume, block, &longnr, &bitnr)) + { + volume->writefailed = TRUE; + volume->state = ID_VALIDATING; + return 0; + } + if (mode) + { + /* free a block */ + volume->bitmapblock->buffer[longnr] = + OS_LONG2BE(OS_BE2LONG(volume->bitmapblock->buffer[longnr]) | (1 << bitnr)); + volume->usedblockscount -= 1; + if ( + ( + (volume->lastaccessrootblock) && (block>=volume->rootblock) + ) || // 1. case + ( + ( + ((volume->lastaccess>=volume->rootblock) && (block>=volume->rootblock)) || // 2.case and ... + ((volume->lastaccessrootblock) && (blockrootblock)) // 3.case with ... + ) && + (blocklastaccess) + ) + ) + { + volume->lastaccess = block; + } + } + else + { + volume->bitmapblock->buffer[longnr] = + OS_LONG2BE(OS_BE2LONG(volume->bitmapblock->buffer[longnr]) & ~(1 << bitnr)); + volume->usedblockscount += 1; + volume->lastaccess = block; /* all blocks before "block" are used! */ + } + volume->bitmapblock->flags |= BCF_WRITE; + return DOSTRUE; } ULONG findFreeBlock - ( - struct AFSBase *afsbase, - struct Volume *volume, - ULONG togo, - ULONG longnr, - ULONG block - ) + ( + struct AFSBase *afsbase, + struct Volume *volume, + ULONG togo, + ULONG longnr, + ULONG block + ) { ULONG maxinbitmap,maxblocks; ULONG bits,trash,lg; - maxinbitmap = (volume->SizeBlock-1)*32; /* max blocks marked in a bitmapblock */ - maxblocks = maxinbitmap-((longnr-1)*32); /* blocks left to check */ - if (maxblocks > togo) - maxblocks = togo; - for (;;) - { - togo -= maxblocks; - while (maxblocks>=32) - { - /* do we have a free block ? - if yes search within this long which block */ - lg = OS_BE2LONG(volume->bitmapblock->buffer[longnr]); - if (lg != 0) - { - bits = 1; - do - { - if (bits & lg) - return block; - bits = bits<<1; - block++; - } while (bits != 0); - } - else - block += 32; - longnr++; - maxblocks -= 32; - } - if (maxblocks != 0) - { - lg = OS_BE2LONG(volume->bitmapblock->buffer[longnr]); - bits = 1; - for (;maxblocks;maxblocks--) - { - if (bits & lg) - return block; - bits = bits<<1; - block++; - } - } - if (togo == 0) - break; - if (!gotoBitmapBlock(afsbase, volume,block,&longnr,&trash)) - return 0; - if ((longnr!=1) || (trash!=0)) - showText(afsbase, "Wrong bitmapblockjump!"); - maxblocks = togoSizeBlock-1)*32; /* max blocks marked in a bitmapblock */ + maxblocks = maxinbitmap-((longnr-1)*32); /* blocks left to check */ + if (maxblocks > togo) + maxblocks = togo; + for (;;) + { + togo -= maxblocks; + while (maxblocks>=32) + { + /* do we have a free block ? + if yes search within this long which block */ + lg = OS_BE2LONG(volume->bitmapblock->buffer[longnr]); + if (lg != 0) + { + bits = 1; + do + { + if (bits & lg) + return block; + bits = bits<<1; + block++; + } while (bits != 0); + } + else + block += 32; + longnr++; + maxblocks -= 32; + } + if (maxblocks != 0) + { + lg = OS_BE2LONG(volume->bitmapblock->buffer[longnr]); + bits = 1; + for (;maxblocks;maxblocks--) + { + if (bits & lg) + return block; + bits = bits<<1; + block++; + } + } + if (togo == 0) + break; + if (!gotoBitmapBlock(afsbase, volume,block,&longnr,&trash)) + return 0; + if ((longnr!=1) || (trash!=0)) + showText(afsbase, "Wrong bitmapblockjump!"); + maxblocks = togolastaccess; - /* - got exact position of last accessed block - this will update volume->bitmapblock and return - the long number and bit number that block is - */ - if (!gotoBitmapBlock(afsbase, volume, block, &longnr, &bitnr)) - return 0; - if (bitnr != 0) - { - maxbitcount = volume->countblocks-block; - if (maxbitcount != 0) - { - maxbitcount = ((32-bitnr)bitmapblock->buffer[longnr]); - for (;bitnr=volume->countblocks) - block = volume->bootblocks; - } - if (block>=volume->rootblock) - { - block = - findFreeBlock - ( - afsbase, - volume, - volume->countblocks-block-1, - longnr, - block - ); - if (block != 0) - return block; - block = volume->bootblocks; - } - if (!gotoBitmapBlock(afsbase, volume, block, &longnr, &bitnr)) - return 0; - block = findFreeBlock(afsbase, volume, volume->rootblock-block,longnr, block); - return block; + D(bug("[afshandler] %s: enter\n", __FUNCTION__)); + /* check all blocks after rootblock */ + block = volume->lastaccess; + /* + got exact position of last accessed block + this will update volume->bitmapblock and return + the long number and bit number that block is + */ + if (!gotoBitmapBlock(afsbase, volume, block, &longnr, &bitnr)) + return 0; + if (bitnr != 0) + { + maxbitcount = volume->countblocks-block; + if (maxbitcount != 0) + { + maxbitcount = ((32-bitnr)bitmapblock->buffer[longnr]); + for (;bitnr=volume->countblocks) + block = volume->bootblocks; + } + if (block>=volume->rootblock) + { + block = + findFreeBlock + ( + afsbase, + volume, + volume->countblocks-block-1, + longnr, + block + ); + if (block != 0) + return block; + block = volume->bootblocks; + } + if (!gotoBitmapBlock(afsbase, volume, block, &longnr, &bitnr)) + return 0; + block = findFreeBlock(afsbase, volume, volume->rootblock-block,longnr, block); + return block; } ULONG allocBlock(struct AFSBase *afsbase, struct Volume *volume) { ULONG block; - block = getFreeBlock(afsbase, volume); - if (block != 0) - { - D(bug("[AFS] allocBlock: found a free block on %lu\n", block)); - if (!markBlock(afsbase, volume,block,0)) - block = 0; - } - return block; + block = getFreeBlock(afsbase, volume); + if (block != 0) + { + D(bug("[afs] allocBlock: found a free block on %u\n", block)); + if (!markBlock(afsbase, volume,block,0)) + block = 0; + } + return block; } diff --git a/rom/filesys/afs/bitmap.h b/rom/filesys/afs/bitmap.h index ac43f1111ec..22512c94ee9 100644 --- a/rom/filesys/afs/bitmap.h +++ b/rom/filesys/afs/bitmap.h @@ -14,6 +14,7 @@ ULONG createNewBitmapBlocks(struct AFSBase *, struct Volume *); LONG setBitmapFlag(struct AFSBase *, struct Volume *, LONG); LONG invalidBitmap(struct AFSBase *, struct Volume *); LONG validBitmap(struct AFSBase *, struct Volume *); +void releaseBitmap(struct Volume *); LONG markBlock(struct AFSBase *, struct Volume *, ULONG, ULONG); ULONG allocBlock(struct AFSBase *, struct Volume *); diff --git a/rom/filesys/afs/cache.c b/rom/filesys/afs/cache.c index e816b5c133f..4640c9fac51 100644 --- a/rom/filesys/afs/cache.c +++ b/rom/filesys/afs/cache.c @@ -1,8 +1,13 @@ /* - Copyright � 1995-2013, The AROS Development Team. All rights reserved. - $Id$ + Copyright (C) 1995-2026, The AROS Development Team. All rights reserved. */ +#undef DEBUG +#define DEBUG 0 +#if defined(__AROS__) +#include +#endif + #include "os.h" #include "cache.h" #include "checksums.h" @@ -10,6 +15,8 @@ #include "afsblocks.h" #include "baseredef.h" +#define BULK_MAX_BYTES 65536 + /******************************************************** Name : initCache Descr.: initializes block cache for a volume @@ -18,149 +25,245 @@ Output: first buffer (main cache pointer) *********************************************************/ struct BlockCache *initCache - ( - struct AFSBase *afsbase, - struct Volume *volume, - ULONG numBuffers - ) + ( + struct AFSBase *afsbase, + struct Volume *volume, + ULONG numBuffers + ) { struct BlockCache *head; struct BlockCache *cache; ULONG i; - head = AllocVec - ( - numBuffers*(sizeof(struct BlockCache)+BLOCK_SIZE(volume)), - MEMF_PUBLIC | MEMF_CLEAR - ); - if (head != NULL) - { - cache = head; - for (i=0; i<(numBuffers-1); i++) - { - cache->buffer = (ULONG *)((char *)cache+sizeof(struct BlockCache)); - cache->next = - (struct BlockCache *)((char *)cache->buffer+BLOCK_SIZE(volume)); - cache = cache->next; - } - cache->buffer = (ULONG *)((char *)cache+sizeof(struct BlockCache)); - cache->next = NULL; - } - D(bug("[AFS] InitCache: my Mem is 0x%p size 0x%lx\n", head, numBuffers*(sizeof(struct BlockCache)+BLOCK_SIZE(volume)))); - return head; + if (numBuffers == 0) + return NULL; + + head = AllocVec + ( + numBuffers*(sizeof(struct BlockCache)+BLOCK_SIZE(volume)), + MEMF_PUBLIC | MEMF_CLEAR + ); + if (head != NULL) + { + cache = head; + for (i=0; i<(numBuffers-1); i++) + { + cache->buffer = (ULONG *)((char *)cache+sizeof(struct BlockCache)); + cache->next = + (struct BlockCache *)((char *)cache->buffer+BLOCK_SIZE(volume)); + cache = cache->next; + } + cache->buffer = (ULONG *)((char *)cache+sizeof(struct BlockCache)); + cache->next = NULL; + } + D(bug + ( + "initCache: my Mem is 0x%p size 0x%lx\n", + head, + numBuffers*(sizeof(struct BlockCache)+BLOCK_SIZE(volume)) + )); + return head; } void freeCache(struct AFSBase *afsbase, struct BlockCache *cache) { - FreeVec(cache); + FreeVec(cache); } -void clearCache(struct AFSBase *afsbase, struct BlockCache *cache) { - - while (cache != NULL) - { - if ((cache->flags & BCF_WRITE) == 0) - { - cache->blocknum = 0; - cache->newness = 0; - cache->flags = 0; - } - else - showText(afsbase, "You MUST re-insert ejected volume"); - cache = cache->next; - } +void discardCache(struct Volume *volume) +{ + struct BlockCache *block; + for (block = volume->blockcache; block != NULL; block = block->next) + { + block->blocknum = 0; + block->newness = 0; + block->flags = 0; + } + volume->cachepending = FALSE; + volume->bitmapinvalid = FALSE; + volume->writefailed = FALSE; +} + +void clearCleanCache(struct Volume *volume) +{ + struct BlockCache *block; + for (block = volume->blockcache; block != NULL; block = block->next) + { + /* A packet cannot still own a cache block during a media change. */ + block->flags &= ~BCF_USED; + if (!(block->flags & BCF_WRITE)) + { + block->blocknum = 0; + block->newness = 0; + } + } +} + +BOOL cacheDirty(struct Volume *volume) +{ + struct BlockCache *block; + for (block = volume->blockcache; block != NULL; block = block->next) + if (block->flags & BCF_WRITE) + return TRUE; + return FALSE; } -VOID flushCache - (struct AFSBase *afsbase, struct Volume *volume) +BOOL flushCache + (struct AFSBase *afsbase, struct Volume *volume) { struct BlockCache *block; +BOOL success = DOSTRUE; - for (block = volume->blockcache; block != NULL; block = block->next) - { - if ((block->flags & (BCF_WRITE | BCF_USED)) == BCF_WRITE) - { - writeDisk(afsbase, volume, block->blocknum, 1, block->buffer); - block->flags &= ~BCF_WRITE; - } - } + if (volume->cachepending) + return DOSFALSE; + for (block = volume->blockcache; block != NULL; block = block->next) + { + /* The root must be written last, including when it is not pinned. */ + if (block->blocknum == volume->rootblock || !(block->flags & BCF_WRITE)) + continue; + if (block->flags & BCF_USED) + success = DOSFALSE; + else if (writeDisk(afsbase, volume, block->blocknum, 1, block->buffer) != 0) + { + volume->writefailed = TRUE; + volume->state = ID_VALIDATING; + success = DOSFALSE; + break; /* Cancel ends this attempt, including its requesters. */ + } + else + block->flags &= ~BCF_WRITE; + } + return success; +} + +/* A full flush writes the root last; eviction only uses flushCache. */ +BOOL flushBlocks(struct AFSBase *afsbase, struct Volume *volume) +{ + struct BlockCache *root; + BOOL previousFailure = volume->writefailed; + + /* Only a full, explicit flush retries a cancelled write. */ + volume->writefailed = FALSE; + if (!flushCache(afsbase, volume)) + { + volume->writefailed |= previousFailure; + return DOSFALSE; + } + for (root = volume->blockcache; root != NULL; root = root->next) + if (root->blocknum == volume->rootblock && (root->flags & BCF_WRITE) + && !writeBlock(afsbase, volume, root, -1)) + return DOSFALSE; + return DOSTRUE; +} + +/* Discard is allowed only by a positive confirmation, including without a GUI. */ +BOOL flushForRelease(struct AFSBase *afsbase, struct Volume *volume) +{ + if (flush(afsbase, volume)) + return DOSTRUE; +#ifdef __AROS__ + if (showPtrArgsText(afsbase, + "Pending changes could not be saved. Continue to discard them and release the volume, or Cancel to keep them", + Req_ContinueCancel, NULL) == 1) + { + discardCache(volume); + volume->state = ID_VALIDATING; + return DOSTRUE; + } +#endif + return DOSFALSE; +} + +/* Mark a buffer as the most recently used */ +static void markRecent(struct Volume *volume, struct BlockCache *bc) +{ +struct BlockCache *cache; + bc->newness = ++volume->cachecounter; + /* Reset cache history if counter has overflowed */ + if (volume->cachecounter == 0) + { + for (cache = volume->blockcache; cache != NULL; cache = cache->next) + cache->newness = 0; + } } struct BlockCache *getCacheBlock - (struct AFSBase *afsbase, struct Volume *volume, ULONG blocknum) + (struct AFSBase *afsbase, struct Volume *volume, ULONG blocknum) { struct BlockCache *cache; struct BlockCache *bestcache=NULL; BOOL found = FALSE; +BOOL retried = FALSE; + +retry: + + /* Check if block is already cached, or else reuse least-recently-used buffer */ + D(bug("[afs] getCacheBlock: getting cacheblock %u\n",blocknum)); + cache = volume->blockcache; + while ((cache != NULL) && !found) + { + if (cache->blocknum == blocknum) + { + if (!(cache->flags & BCF_USED)) + { + D(bug("[afs] getCacheBlock: already cached (counter=%u)\n", + cache->newness)); + bestcache = cache; + found = TRUE; + } + else + { + if (blocknum != volume->rootblock) + { + /* should only occur while using setBitmap() + ->that's ok (see setBitmap()) */ + D(bug("Concurrent access on block %u!\n",blocknum)); + } + else + { + bestcache = cache; + found = TRUE; + } + } + } + else if ((cache->flags & (BCF_USED | BCF_WRITE)) == 0) + { + if (bestcache != NULL) + { + if (bestcache->newness > cache->newness) + bestcache = cache; + } + else + { + bestcache = cache; + } + } + cache = cache->next; + } - /* Check if block is already cached, or else reuse least-recently-used buffer */ - //D(bug("[AFS] GetCacheBlock: getting cacheblock %lu\n",blocknum)); - cache = volume->blockcache; - while ((cache != NULL) && !found) - { - if (cache->blocknum == blocknum) - { - if (!(cache->flags & BCF_USED)) - { - //D(bug("[AFS] GetCacheBlock: already cached (counter=%lu)\n", cache->newness)); - bestcache = cache; - found = TRUE; - } - else - { - if (blocknum != volume->rootblock) - { - /* should only occur while using setBitmap() - ->that's ok (see setBitmap()) */ - //D(bug("[AFS] Concurrent access on block %lu!\n",blocknum)); - } - else - { - bestcache = cache; - found = TRUE; - } - } - } - else if ((cache->flags & (BCF_USED | BCF_WRITE)) == 0) - { - if (bestcache != NULL) - { - if (bestcache->newness > cache->newness) - bestcache = cache; - } - else - { - bestcache = cache; - } - } - cache = cache->next; - } - - if (bestcache != NULL) - { - if (!found) - bestcache->blocknum = 0; - - /* Mark buffer as the most recently used */ - bestcache->newness = ++volume->cachecounter; - - /* Reset cache history if counter has overflowed */ - if (volume->cachecounter == 0) - { - for (cache = volume->blockcache; cache != NULL; cache = cache->next) - cache->newness = 0; - } - } - else - { - /* We should only run out of cache blocks if blocks need to be - written, so write them and try again */ - flushCache(afsbase, volume); - bestcache = getCacheBlock(afsbase, volume, blocknum); - if (bestcache == NULL) - showText(afsbase, "Oh, ohhhhh, where is all the cache gone? BUG!!!"); - } - - return bestcache; + if (bestcache != NULL) + { + if (!found) + bestcache->blocknum = 0; + + markRecent(volume, bestcache); + } + else + { + /* We should only run out of cache blocks if blocks need to be + written, so write them and try again */ + if (!retried) + { + /* A pinned bitmap can prevent a durable flush even when + * other buffers were cleaned and can now be reused. */ + if (volume->writefailed) + return NULL; + flushCache(afsbase, volume); + retried = TRUE; + goto retry; + } + } + + return bestcache; } /*************************************************************************** @@ -174,108 +277,206 @@ BOOL found = FALSE; Output: an unfilled cache block for the specified block. ***************************************************************************/ struct BlockCache *getFreeCacheBlock - (struct AFSBase *afsbase, struct Volume *volume, ULONG blocknum) + (struct AFSBase *afsbase, struct Volume *volume, ULONG blocknum) { struct BlockCache *cache; - cache = getCacheBlock(afsbase, volume, blocknum); - cache->blocknum = blocknum; - cache->newness = 0; - return cache; + if (volume->cachepending) + return NULL; + cache = getCacheBlock(afsbase, volume, blocknum); + if (cache != NULL) + { + cache->blocknum = blocknum; + cache->newness = 0; + } + return cache; } -void checkCache(struct AFSBase *afsbase, struct Volume *volume) { +/* A buffer that speculative read-ahead may fill, or NULL. + * + * Read-ahead is speculative: nobody asked for the sibling blocks, so it must + * never reassign a buffer that some caller is still holding. AFS callers walk + * hash chains and directory trees holding a plain BlockCache pointer across + * getBlock() calls WITHOUT setting BCF_USED, relying on the historical cache + * contract that a populated buffer is only ever recycled to satisfy a real + * getBlock() miss (one per call), never proactively. So read-ahead only ever + * fills a genuinely FREE buffer (blocknum == 0); it must not evict a populated + * clean buffer, or a directory block a caller is mid-walk on gets silently + * repurposed to file data (corrupt hash pointer -> getBlock() out of range). + * When no buffer is free, read-ahead simply does nothing this time. */ +static struct BlockCache *readAheadSlot(struct Volume *volume, ULONG blocknum) +{ +struct BlockCache *cache; +struct BlockCache *best = NULL; + for (cache = volume->blockcache; cache != NULL; cache = cache->next) + { + if (cache->blocknum == blocknum) + return NULL; + if (cache->blocknum == 0 + && (cache->flags & (BCF_USED | BCF_WRITE)) == 0 + && (best == NULL || cache->newness < best->newness)) + best = cache; + } + return best; +} + +/* + * Fill the missed block and, from the same request, the blocks following it + * into free buffers. Returns TRUE if the block was filled. + */ +static BOOL readAhead(struct AFSBase *afsbase, struct Volume *volume, struct BlockCache *first) +{ struct BlockCache *bc; +ULONG count, i; +char *src; + if (first->blocknum >= volume->countblocks) + return FALSE; + count = (ULONG)volume->numbuffers / 4; + if (count > volume->bulkblocks) + count = volume->bulkblocks; + if (first->blocknum + count > volume->countblocks) + count = volume->countblocks - first->blocknum; + if (count < 2) + return FALSE; + if (readDisk(afsbase, volume, first->blocknum, count, volume->bulkbuffer) != 0) + return FALSE; + src = (char *)volume->bulkbuffer; + CopyMem(src, first->buffer, BLOCK_SIZE(volume)); + first->flags |= BCF_USED; + for (i = 1; i < count; i++) + { + src += BLOCK_SIZE(volume); + bc = readAheadSlot(volume, first->blocknum + i); + if (bc == NULL) + continue; + bc->blocknum = first->blocknum + i; + CopyMem(src, bc->buffer, BLOCK_SIZE(volume)); + markRecent(volume, bc); + } + first->flags &= ~BCF_USED; + markRecent(volume, first); + return TRUE; +} - bc = volume->blockcache; - while (bc != NULL) - { - if (((bc->flags & BCF_USED) != 0) && (bc->blocknum != volume->rootblock)) - { - showText(afsbase, "Unreleased block: %lu!", bc->blocknum); - } - bc = bc->next; - } +/* Shorten a run of blocks so that it stops before any block with unwritten changes */ +ULONG cleanRun(struct Volume *volume, ULONG start, ULONG count) +{ +struct BlockCache *cache; + for (cache = volume->blockcache; cache != NULL; cache = cache->next) + { + if ((cache->flags & BCF_WRITE) != 0 + && cache->blocknum >= start && cache->blocknum - start < count) + count = cache->blocknum - start; + } + return count; } -#ifdef DEBUG -void umpBlock(struct AFSBase *afsbase, struct BlockCache *block) { -UWORD i,j; +BOOL initBulkBuffer(struct AFSBase *afsbase, struct Volume *volume) +{ +ULONG blocks = BULK_MAX_BYTES / BLOCK_SIZE(volume); + if (blocks > (ULONG)volume->numbuffers) + blocks = volume->numbuffers; + if (blocks < 2) + blocks = 2; + volume->bulkbuffer = AllocVec((IPTR)blocks * BLOCK_SIZE(volume), MEMF_PUBLIC); + volume->bulkblocks = volume->bulkbuffer != NULL ? blocks : 0; + return volume->bulkbuffer != NULL; +} - for (i=0; i<=31; i++) { - D(bug("0x%x: ",i*16)); - for (j=0; j<=3; j++) - D(bug(" %x", OS_BE2LONG(block->buffer[i*4+j]))); - D(bug("\n")); - } +void freeBulkBuffer(struct AFSBase *afsbase, struct Volume *volume) +{ + FreeVec(volume->bulkbuffer); + volume->bulkbuffer = NULL; + volume->bulkblocks = 0; } -#endif struct BlockCache *getBlock - (struct AFSBase *afsbase, struct Volume *volume, ULONG blocknum) + (struct AFSBase *afsbase, struct Volume *volume, ULONG blocknum) { struct BlockCache *blockbuffer; - blockbuffer = getCacheBlock(afsbase, volume, blocknum); - if (blockbuffer != NULL) - { - if (blockbuffer->blocknum == 0) - { - blockbuffer->blocknum = blocknum; - if (readDisk(afsbase, volume, blocknum, 1, blockbuffer->buffer) != 0) - { - blockbuffer = NULL; - } - } - } - //D(bug("[AFS] GetBlock: using cache block with address 0x%p\n", blockbuffer)); - return blockbuffer; + blockbuffer = getCacheBlock(afsbase, volume, blocknum); + if (blockbuffer != NULL) + { + if (blockbuffer->blocknum == 0) + { + blockbuffer->blocknum = blocknum; + if (!readAhead(afsbase, volume, blockbuffer) + && readDisk(afsbase, volume, blocknum, 1, blockbuffer->buffer) != 0) + { + /* don't leave an unreadable block looking cached */ + blockbuffer->blocknum = 0; + blockbuffer = NULL; + } + } + } + D(bug("[afs] getBlock: using cache block with address 0x%p\n", blockbuffer)); + return blockbuffer; } LONG writeBlock - ( - struct AFSBase *afsbase, - struct Volume *volume, - struct BlockCache *blockbuffer, - LONG checksumoffset - ) + ( + struct AFSBase *afsbase, + struct Volume *volume, + struct BlockCache *blockbuffer, + LONG checksumoffset + ) { - /* Update checksum if requested by caller */ - if(checksumoffset != -1) - { - blockbuffer->buffer[checksumoffset] = 0; - blockbuffer->buffer[checksumoffset] = - OS_LONG2BE(0 - calcChkSum(volume->SizeBlock,blockbuffer->buffer)); - } - - /* Ensure bitmap isn't marked valid while there are dirty blocks in the cache */ - if (blockbuffer->blocknum == volume->rootblock) - flushCache(afsbase, volume); - - /* Write block to disk */ - writeDisk(afsbase, volume, blockbuffer->blocknum, 1, blockbuffer->buffer); - blockbuffer->flags &= ~BCF_WRITE; - return DOSTRUE; + if (volume->cachepending) + return DOSFALSE; + /* Update checksum if requested by caller */ + if(checksumoffset != -1) + { + blockbuffer->buffer[checksumoffset] = 0; + blockbuffer->buffer[checksumoffset] = + OS_LONG2BE(0 - calcChkSum(volume->SizeBlock,blockbuffer->buffer)); + } + + /* Retain the block for retry if either prerequisite or write fails. */ + blockbuffer->flags |= BCF_WRITE; + if (volume->writefailed) + return DOSFALSE; + /* Ensure bitmap isn't marked valid while there are dirty blocks in the cache */ + if (blockbuffer->blocknum == volume->rootblock + && blockbuffer->buffer[BLK_BITMAP_VALID_FLAG(volume)] != 0 + && !flushCache(afsbase, volume)) + return DOSFALSE; + + /* A failed/partial root write makes the on-disk flag uncertain. */ + if (blockbuffer->blocknum == volume->rootblock) + volume->bitmapinvalid = FALSE; + if (writeDisk(afsbase, volume, blockbuffer->blocknum, 1, blockbuffer->buffer) != 0) + { + volume->writefailed = TRUE; + volume->state = ID_VALIDATING; + return DOSFALSE; + } + if (blockbuffer->blocknum == volume->rootblock) + volume->bitmapinvalid = blockbuffer->buffer[BLK_BITMAP_VALID_FLAG(volume)] == 0; + blockbuffer->flags &= ~BCF_WRITE; + return DOSTRUE; } VOID writeBlockDeferred - ( - struct AFSBase *afsbase, - struct Volume *volume, - struct BlockCache *blockbuffer, - LONG checksumoffset - ) + ( + struct AFSBase *afsbase, + struct Volume *volume, + struct BlockCache *blockbuffer, + LONG checksumoffset + ) { - /* Update checksum if requested by caller */ - if(checksumoffset != -1) - { - blockbuffer->buffer[checksumoffset] = 0; - blockbuffer->buffer[checksumoffset] = - OS_LONG2BE(0 - calcChkSum(volume->SizeBlock,blockbuffer->buffer)); - } - - /* Mark block as needing to be written when the time comes */ - blockbuffer->flags |= BCF_WRITE; - return; + /* Update checksum if requested by caller */ + if(checksumoffset != -1) + { + blockbuffer->buffer[checksumoffset] = 0; + blockbuffer->buffer[checksumoffset] = + OS_LONG2BE(0 - calcChkSum(volume->SizeBlock,blockbuffer->buffer)); + } + + if (volume->cachepending) + return; + /* Mark block as needing to be written when the time comes */ + blockbuffer->flags |= BCF_WRITE; + return; } diff --git a/rom/filesys/afs/cache.h b/rom/filesys/afs/cache.h index 808564d279e..19cee616686 100644 --- a/rom/filesys/afs/cache.h +++ b/rom/filesys/afs/cache.h @@ -2,7 +2,7 @@ #define BLOCKACCESS_H /* - Copyright © 1995-2005, The AROS Development Team. All rights reserved. + Copyright © 1995-2026, The AROS Development Team. All rights reserved. $Id$ */ @@ -24,10 +24,16 @@ struct BlockCache *initCache(struct AFSBase *, struct Volume *volume, ULONG); void freeCache(struct AFSBase *, struct BlockCache *); struct BlockCache *getFreeCacheBlock(struct AFSBase *, struct Volume *, ULONG); struct BlockCache *getBlock(struct AFSBase *, struct Volume *, ULONG); +ULONG cleanRun(struct Volume *, ULONG, ULONG); +BOOL initBulkBuffer(struct AFSBase *, struct Volume *); +void freeBulkBuffer(struct AFSBase *, struct Volume *); LONG writeBlock(struct AFSBase *, struct Volume *, struct BlockCache *, LONG); VOID writeBlockDeferred(struct AFSBase *, struct Volume *, struct BlockCache *, LONG); -void clearCache(struct AFSBase *, struct BlockCache *); -VOID flushCache(struct AFSBase *, struct Volume *); -void checkCache(struct AFSBase *, struct Volume *); +void discardCache(struct Volume *); +void clearCleanCache(struct Volume *); +BOOL cacheDirty(struct Volume *); +BOOL flushCache(struct AFSBase *, struct Volume *); +BOOL flushBlocks(struct AFSBase *, struct Volume *); +BOOL flushForRelease(struct AFSBase *, struct Volume *); #endif diff --git a/rom/filesys/afs/checksums.c b/rom/filesys/afs/checksums.c index 60a2c831b2c..c5220fb548f 100644 --- a/rom/filesys/afs/checksums.c +++ b/rom/filesys/afs/checksums.c @@ -1,6 +1,5 @@ /* - Copyright © 1995-2005, The AROS Development Team. All rights reserved. - $Id$ + Copyright (C) 1995-2005, The AROS Development Team. All rights reserved. */ #include "os.h" @@ -10,13 +9,13 @@ ULONG calcChkSum(ULONG SizeBlock, ULONG *buffer) { ULONG sum=0, value; ULONG *p, *end; - p = buffer; - end = buffer + SizeBlock; - while (p < end) - { - value = *p++; - sum += OS_BE2LONG(value); - } - return sum; + p = buffer; + end = buffer + SizeBlock; + while (p < end) + { + value = *p++; + sum += OS_BE2LONG(value); + } + return sum; } diff --git a/rom/filesys/afs/error.c b/rom/filesys/afs/error.c index ed970669fc6..f5e84e7a7a2 100644 --- a/rom/filesys/afs/error.c +++ b/rom/filesys/afs/error.c @@ -1,6 +1,5 @@ /* - Copyright © 1995-2015, The AROS Development Team. All rights reserved. - $Id$ + Copyright (C) 1995-2026, The AROS Development Team. All rights reserved. */ /* @@ -23,40 +22,39 @@ /* * displays requester on screen or puts text to the debug buffer */ -LONG showPtrArgsText(struct AFSBase *afsbase, const char *string, enum showReqType type, RAWARG args) +LONG showPtrArgsText(struct AFSBase *afsbase, const char *string, enum showReqType type, RAWARG args) { - LONG answer = 0; - char* options[] = - { - "Cancel", - "Retry|Cancel", - "Check disk|Cancel", - "Continue|Cancel", - "Continue", - NULL - }; - struct EasyStruct es={sizeof (struct EasyStruct),0,"AFFS",0,options[type]}; - struct IntuitionBase *IntuitionBase; + LONG answer = 0; + static const char * const options[] = + { + "Cancel", + "Retry|Cancel", + "Check disk|Cancel", + "Continue|Cancel", + "Continue" + }; + struct EasyStruct es={sizeof (struct EasyStruct),0,"AFFS",0,options[type]}; + struct IntuitionBase *IntuitionBase; - IntuitionBase = (APTR)TaggedOpenLibrary(TAGGEDOPEN_INTUITION); - if (IntuitionBase != NULL) - { - es.es_TextFormat=string; + IntuitionBase = (APTR)TaggedOpenLibrary(TAGGEDOPEN_INTUITION); + if (IntuitionBase != NULL) + { + es.es_TextFormat=string; - if (IntuitionBase->FirstScreen != NULL) - { - answer = EasyRequestArgs(NULL,&es,NULL,args); - } - CloseLibrary((struct Library *)IntuitionBase); - } - else - { - /* We use serial for error printing when gfx.hidd is not initialized */ - RawDoFmt(string, args, RAWFMTFUNC_SERIAL, NULL); - RawPutChar('\n'); - } + if (IntuitionBase->FirstScreen != NULL) + { + answer = EasyRequestArgs(NULL,&es,NULL,args); + } + CloseLibrary((struct Library *)IntuitionBase); + } + else + { + /* We use serial for error printing when gfx.hidd is not initialized */ + RawDoFmt(string, args, RAWFMTFUNC_SERIAL, NULL); + RawPutChar('\n'); + } - return answer; + return answer; } LONG showError(struct AFSBase *afsbase, ULONG error, ...) diff --git a/rom/filesys/afs/errstrings.h b/rom/filesys/afs/errstrings.h index 9843b8851bc..9e4b534f3a4 100644 --- a/rom/filesys/afs/errstrings.h +++ b/rom/filesys/afs/errstrings.h @@ -20,7 +20,7 @@ const struct showReqStruct { const char* text; - enum showReqType type; + UBYTE type; /* enum showReqType */ } texts[] = { {NULL, Req_Cancel }, diff --git a/rom/filesys/afs/extstrings.c b/rom/filesys/afs/extstrings.c index 34e791bffc4..c9f1c547aec 100644 --- a/rom/filesys/afs/extstrings.c +++ b/rom/filesys/afs/extstrings.c @@ -1,6 +1,5 @@ /* - Copyright © 1995-2020, The AROS Development Team. All rights reserved. - $Id$ + Copyright (C) 1995-2026, The AROS Development Team. All rights reserved. */ #include "extstrings.h" @@ -8,10 +7,10 @@ UBYTE capitalch(UBYTE ch, UBYTE flags) { if ((flags==0) || (flags==1)) - return (UBYTE)((ch>='a') && (ch<='z') ? ch-('a'-'A') : ch); - else // DOS\(>=2) - return (UBYTE)(((ch>=224) && (ch<=254) && (ch!=247)) || - ((ch>='a') && (ch<='z')) ? ch-('a'-'A') : ch); + return (UBYTE)((ch>='a') && (ch<='z') ? ch-('a'-'A') : ch); + else // DOS\(>=2) + return (UBYTE)(((ch>=224) && (ch<=254) && (ch!=247)) || + ((ch>='a') && (ch<='z')) ? ch-('a'-'A') : ch); } /* @@ -26,31 +25,22 @@ UBYTE length, i=0; /* str2 is a BSTR */ length=str2++[0]; do { - if (((*str1==0) || (length==maxlen)) && (i==length)) - return 1; - i++; + if (((*str1==0) || (length==maxlen)) && (i==length)) + return 1; + i++; } while (capitalch(*str1++,flags)==capitalch(*str2++,flags)); return 0; } -LONG StrCmp(CONST_STRPTR str1, CONST_STRPTR str2) { - do - { - if ((*str1==0) && (*str2==0)) - return 1; - } while ((*str1++==*str2++)); - return 0; -} - void StrCpyToBstr(const char *src, FSBSTR dst, int maxlen) { UWORD len=0; while (*src && (len < maxlen)) { - dst[1 + len++]=*src++; + dst[1 + len++]=*src++; } if ((dst[0] = len) < maxlen - 1) - dst[1 + len] = 0; + dst[1 + len] = 0; } void StrCpyFromBstr(CONST_FSBSTR src, char *dst, int maxlen) { @@ -58,13 +48,13 @@ UWORD len=0; if (*src != 0) { - if (maxlen > *src) - maxlen = *src; - - src++; - while (len < maxlen) - { - dst[len++]=*src++; - } + if (maxlen > *src) + maxlen = *src; + + src++; + while (len < maxlen) + { + dst[len++]=*src++; + } } } diff --git a/rom/filesys/afs/extstrings.h b/rom/filesys/afs/extstrings.h index 343b9e9fd8e..1200c544162 100644 --- a/rom/filesys/afs/extstrings.h +++ b/rom/filesys/afs/extstrings.h @@ -2,7 +2,7 @@ #define EXTSTRINGS_H /* - Copyright © 1995-2020, The AROS Development Team. All rights reserved. + Copyright © 1995-2026, The AROS Development Team. All rights reserved. $Id$ */ @@ -15,7 +15,6 @@ typedef const char * CONST_FSBSTR; UBYTE capitalch(UBYTE, UBYTE); LONG noCaseStrCmp(const char *, CONST_FSBSTR, UBYTE, int); -LONG StrCmp(CONST_STRPTR, CONST_STRPTR); ULONG StrLen(CONST_STRPTR); void StrCpyToBstr(const char *, FSBSTR, int); void StrCpyFromBstr(CONST_FSBSTR, char *, int); diff --git a/rom/filesys/afs/filehandles1.c b/rom/filesys/afs/filehandles1.c index 577efb9691e..80eac21febe 100644 --- a/rom/filesys/afs/filehandles1.c +++ b/rom/filesys/afs/filehandles1.c @@ -1,8 +1,12 @@ /* - Copyright � 1995-2020, The AROS Development Team. All rights reserved. - $Id$ + Copyright (C) 1995-2026, The AROS Development Team. All rights reserved. */ +#ifdef DEBUG +#undef DEBUG +#endif +#define DEBUG 0 + #include "os.h" #include "filehandles1.h" #include "filehandles2.h" @@ -15,6 +19,45 @@ #include "baseredef.h" #include "validator.h" +/* + * Get a block that must be a checksummed T_SHORT header. A bad block is + * reported (and validation offered) exactly once here. + * The caller does not keep the previous buffer, so it need not be preserved. + */ +AFS_SHARED struct BlockCache *getShortBlock + ( + struct AFSBase *afsbase, + struct Volume *volume, + ULONG blocknum, + SIPTR *error + ) +{ +struct BlockCache *blockbuffer; +ULONG errtext; + + blockbuffer = getBlock(afsbase, volume, blocknum); + if (blockbuffer == NULL) + { + *error = ERROR_UNKNOWN; + return NULL; + } + if (calcChkSum(volume->SizeBlock, blockbuffer->buffer) != 0) + { + errtext = ERR_CHECKSUM; + *error = ERROR_UNKNOWN; + } + else if (OS_BE2LONG(blockbuffer->buffer[BLK_PRIMARY_TYPE]) != T_SHORT) + { + errtext = ERR_BLOCKTYPE; + *error = ERROR_OBJECT_WRONG_TYPE; + } + else + return blockbuffer; + if (showError(afsbase, errtext, blocknum)) + launchValidator(afsbase, volume); + return NULL; +} + /*********************************************** Name : getHeaderBlock Descr.: search through blocks until header block found @@ -26,109 +69,37 @@ See : locateObject, setDate, setComment, deleteObject ************************************************/ struct BlockCache *getHeaderBlock - ( - struct AFSBase *afsbase, - struct Volume *volume, - CONST_STRPTR name, - struct BlockCache *blockbuffer, - ULONG *block, - SIPTR *error - ) + ( + struct AFSBase *afsbase, + struct Volume *volume, + CONST_STRPTR name, + struct BlockCache *blockbuffer, + ULONG *block, + SIPTR *error + ) { ULONG key; - D(bug("[AFS] getHeaderBlock: searching for block of '%s'\n",name)); - key = getHashKey(name,volume->SizeBlock-56,volume->dosflags)+BLK_TABLE_START; - *block = blockbuffer->blocknum; - if (blockbuffer->buffer[key] == 0) - { - *error = ERROR_OBJECT_NOT_FOUND; - return NULL; - } - blockbuffer=getBlock(afsbase, volume,OS_BE2LONG(blockbuffer->buffer[key])); - if (blockbuffer == NULL) - { - *error = ERROR_UNKNOWN; - return NULL; - } -D -( - { - char *name; - name = (char *)blockbuffer->buffer+(BLK_DIRECTORYNAME_START(volume)*4); - kprintf("[AFS] %.*s\n", name[0], name+1); - } -); - if (calcChkSum(volume->SizeBlock, blockbuffer->buffer) != 0) - { - /* - * since we will not work on blockbuffer here any more, - * we don't have to preserve it. - */ - if (showError(afsbase, ERR_CHECKSUM, blockbuffer->blocknum)) - launchValidator(afsbase, volume); - - *error = ERROR_UNKNOWN; - return NULL; - } - if (OS_BE2LONG(blockbuffer->buffer[BLK_PRIMARY_TYPE]) != T_SHORT) - { - /* - * again, we don't work on blockbuffer any more - * no need to preserve BlockCache structure. - */ - if (showError(afsbase, ERR_BLOCKTYPE, blockbuffer->blocknum)) - launchValidator(afsbase, volume); - - *error = ERROR_OBJECT_WRONG_TYPE; - return NULL; - } - - while (!noCaseStrCmp(name, (char *)blockbuffer->buffer + (BLK_DIRECTORYNAME_START(volume)*4), - volume->dosflags, MAX_NAME_LENGTH)) - { - *block = blockbuffer->blocknum; - if (blockbuffer->buffer[BLK_HASHCHAIN(volume)] == 0) - { - *error=ERROR_OBJECT_NOT_FOUND; - return NULL; - } - blockbuffer=getBlock - ( - afsbase, - volume, - OS_BE2LONG(blockbuffer->buffer[BLK_HASHCHAIN(volume)]) - ); - if (blockbuffer == NULL) - { - *error = ERROR_UNKNOWN; - return NULL; - } - if (calcChkSum(volume->SizeBlock, blockbuffer->buffer) != 0) - { - /* - * we won't work on blockbuffer any more - * don't preserve the buffer. - */ - if (showError(afsbase, ERR_CHECKSUM,blockbuffer->blocknum)) - launchValidator(afsbase, volume); - - *error=ERROR_UNKNOWN; - return NULL; - } - if (OS_BE2LONG(blockbuffer->buffer[BLK_PRIMARY_TYPE]) != T_SHORT) - { - /* - * not working with blockbuffer :) - */ - if (showError(afsbase, ERR_BLOCKTYPE, blockbuffer->blocknum)) - launchValidator(afsbase, volume); - - *error = ERROR_OBJECT_WRONG_TYPE; - return NULL; - } - } - return blockbuffer; + D(bug("[afs] getHeaderBlock: searching for block of '%s'\n",name)); + /* first the hash table slot, then along the hash chain */ + key = getHashKey(name,volume->SizeBlock-56,volume->dosflags)+BLK_TABLE_START; + for (;;) + { + *block = blockbuffer->blocknum; + if (blockbuffer->buffer[key] == 0) + { + *error = ERROR_OBJECT_NOT_FOUND; + return NULL; + } + blockbuffer = getShortBlock + (afsbase, volume, OS_BE2LONG(blockbuffer->buffer[key]), error); + if (blockbuffer == NULL) + return NULL; + if (noCaseStrCmp(name, (char *)blockbuffer->buffer + (BLK_DIRECTORYNAME_START(volume)*4), + volume->dosflags, MAX_NAME_LENGTH)) + return blockbuffer; + key = BLK_HASHCHAIN(volume); + } } /******************************************* @@ -144,189 +115,162 @@ D blockcache structure of found block otherwise ********************************************/ struct BlockCache *findBlock - ( - struct AFSBase *afsbase, - struct AfsHandle *dirah, - CONST_STRPTR name, - ULONG *block, - SIPTR *error - ) + ( + struct AFSBase *afsbase, + struct AfsHandle *dirah, + CONST_STRPTR name, + ULONG *block, + SIPTR *error + ) { +struct Volume *volume = dirah->volume; STRPTR pos; struct BlockCache *blockbuffer; UBYTE buffer[32]; - if ((dirah->volume->dostype != ID_DOS_DISK) && (dirah->volume->dostype != ID_DOS_muFS_DISK)) - { - D(bug("[AFS] Unknown dostype 0x%08x\n", dirah->volume->dostype)); - *error = ERROR_NOT_A_DOS_DISK; - return 0; - } - *block = dirah->header_block; - - D(bug("[AFS] findBlock: startblock=%ld\n",*block)); - /* get first entry (root or filelock refers to) */ - blockbuffer = getBlock(afsbase, dirah->volume, *block); - if (blockbuffer == NULL) - { - *error = ERROR_UNKNOWN; - D(bug("[AFS] error blockbuffer\n")); - return NULL; - } - if (calcChkSum(dirah->volume->SizeBlock, blockbuffer->buffer) != 0) - { - /* - * not working with blockbuffer any more. - * otherwise we would need to preserve it (BCF_USED or one more time getBlock) - */ - if (showError(afsbase, ERR_CHECKSUM, *block)) - launchValidator(afsbase, dirah->volume); - - *error = ERROR_UNKNOWN; - D(bug("[AFS] error checksum\n")); - return NULL; - } - if (OS_BE2LONG(blockbuffer->buffer[BLK_PRIMARY_TYPE]) != T_SHORT) - { - /* - * read above comment - */ - if (showError(afsbase, ERR_BLOCKTYPE, *block)) - launchValidator(afsbase, dirah->volume); - - *error = ERROR_OBJECT_WRONG_TYPE; - D(bug("[AFS] error wrong type\n")); - return NULL; - } - while (*name) - { - if (*name == '/') /* get parent entry ? */ - { - if (blockbuffer->buffer[BLK_PARENT(dirah->volume)] == 0) - { - *error = ERROR_OBJECT_NOT_FOUND; - D(bug("[AFS] object not found\n")); - return NULL; - } - D(bug("[AFS] findBlock: getting parent\n")); - blockbuffer = getBlock - ( - afsbase, - dirah->volume, - OS_BE2LONG(blockbuffer->buffer[BLK_PARENT(dirah->volume)]) - ); - if (blockbuffer == NULL) - { - *error = ERROR_UNKNOWN; - D(bug("[AFS] error no blockbuffer\n")); - return NULL; - } - name++; - } - else - { - if ( - (OS_BE2LONG - ( - blockbuffer->buffer[BLK_SECONDARY_TYPE(dirah->volume)] - ) != ST_ROOT) && - (OS_BE2LONG - ( - blockbuffer->buffer[BLK_SECONDARY_TYPE(dirah->volume)] - ) != ST_USERDIR) && - (OS_BE2LONG - ( - blockbuffer->buffer[BLK_SECONDARY_TYPE(dirah->volume)] - ) != ST_LINKDIR)) - { - *error = ERROR_OBJECT_WRONG_TYPE; - D(bug("[AFS] error wrong type\n")); - return NULL; - } - pos = buffer; - while ((*name != 0) && (*name != '/')) - { - *pos++ = *name++; - } - if (*name == '/') - name++; - *pos=0; - D(bug - ( - "[AFS] findBlock: searching for header block of %s\n", - buffer - )); - blockbuffer = - getHeaderBlock(afsbase, dirah->volume, buffer, blockbuffer, block, error); - if (blockbuffer == NULL) - break; /* object not found or other error */ - } - } - D( - if (blockbuffer != NULL) - bug("[AFS] findBlock: block=%ld\n",blockbuffer->blocknum); - else - bug("[AFS] findBlock: error\n"); - ); - return blockbuffer; + if ((volume->dostype != ID_DOS_DISK) && (volume->dostype != ID_DOS_muFS_DISK)) + { + D(bug("[afs] Unknown dostype 0x%08x\n", volume->dostype)); + *error = ERROR_NOT_A_DOS_DISK; + return 0; + } + *block = dirah->header_block; + + D(bug("[afs] findBlock: startblock=%d\n",*block)); + /* get first entry (root or filelock refers to) */ + blockbuffer = getShortBlock(afsbase, volume, *block, error); + if (blockbuffer == NULL) + return NULL; + while (*name) + { + if (*name == '/') /* get parent entry ? */ + { + if (blockbuffer->buffer[BLK_PARENT(volume)] == 0) + { + *error = ERROR_OBJECT_NOT_FOUND; + D(bug("[afs] object not found\n")); + return NULL; + } + D(bug("[afs] findBlock: getting parent\n")); + blockbuffer = getBlock + ( + afsbase, + volume, + OS_BE2LONG(blockbuffer->buffer[BLK_PARENT(volume)]) + ); + if (blockbuffer == NULL) + { + *error = ERROR_UNKNOWN; + D(bug("[afs] error no blockbuffer\n")); + return NULL; + } + name++; + } + else + { + if ( + (OS_BE2LONG + ( + blockbuffer->buffer[BLK_SECONDARY_TYPE(volume)] + ) != ST_ROOT) && + (OS_BE2LONG + ( + blockbuffer->buffer[BLK_SECONDARY_TYPE(volume)] + ) != ST_USERDIR) && + (OS_BE2LONG + ( + blockbuffer->buffer[BLK_SECONDARY_TYPE(volume)] + ) != ST_LINKDIR)) + { + *error = ERROR_OBJECT_WRONG_TYPE; + D(bug("[afs] error wrong type\n")); + return NULL; + } + pos = buffer; + while ((*name != 0) && (*name != '/') && ((UBYTE *)pos < buffer + sizeof(buffer) - 1)) + { + *pos++ = *name++; + } + if (*name == '/') + name++; + *pos=0; + D(bug + ( + "[afs] findBlock: searching for header block of %s\n", + buffer + )); + blockbuffer = + getHeaderBlock(afsbase, volume, buffer, blockbuffer, block, error); + if (blockbuffer == NULL) + break; /* object not found or other error */ + } + } + D( + if (blockbuffer != NULL) + bug("[afs] findBlock: block=%d\n",blockbuffer->blocknum); + else + bug("[afs] findBlock: error\n"); + ); + return blockbuffer; } /* add handle to locklist */ void addHandle(struct AfsHandle *ah) { - ah->next=ah->volume->locklist; - ah->volume->locklist=ah; + ah->next=ah->volume->locklist; + ah->volume->locklist=ah; } /* remove handle from locklist */ void remHandle(struct AFSBase *afsbase, struct AfsHandle *ah) { struct AfsHandle *old = NULL; - D(bug("[afs 0x%08lX] Removing handle 0x%08lX\n", ah->volume, ah)); - if (ah->volume->volumenode == ah->volumenode) { - D(bug("[afs 0x%08lX] Lock's volume is online\n", ah->volume)); - if (ah->volume->locklist==ah) - ah->volume->locklist=ah->next; - else - old=ah->volume->locklist; - } + D(bug("[afs 0x%p] Removing handle 0x%p\n", ah->volume, ah)); + if (ah->volumenode == NULL || ah->volume->volumenode == ah->volumenode) { + D(bug("[afs 0x%p] Lock's volume is online\n", ah->volume)); + if (ah->volume->locklist==ah) + ah->volume->locklist=ah->next; + else + old=ah->volume->locklist; + } #ifdef __AROS__ - else { - D(bug("[afs 0x%08lX] Lock's volume is offline\n", ah->volume)); - if (BADDR(ah->volumenode->dol_misc.dol_volume.dol_LockList) == ah) - if (ah->next) - ah->volumenode->dol_misc.dol_volume.dol_LockList = MKBADDR(ah->next); - else { - D(bug("[afs 0x%08lX] Last lock removed, removing VolumeNode\n", ah->volume)); - remDosNode(afsbase, ah->volumenode); - } - else - old = BADDR(ah->volumenode->dol_misc.dol_volume.dol_LockList); - } + else { + D(bug("[afs 0x%08lX] Lock's volume is offline\n", ah->volume)); + if (BADDR(ah->volumenode->dol_misc.dol_volume.dol_LockList) == ah) + if (ah->next) + ah->volumenode->dol_misc.dol_volume.dol_LockList = MKBADDR(ah->next); + else { + D(bug("[afs 0x%08lX] Last lock removed, removing VolumeNode\n", ah->volume)); + afsbase->parkedvols--; + remDosNode(afsbase, ah->volumenode); + } + else + old = BADDR(ah->volumenode->dol_misc.dol_volume.dol_LockList); + } #endif - while (old) - { - if (old->next==ah) - { - old->next=ah->next; - return; - } - old=old->next; - } + while (old) + { + if (old->next==ah) + { + old->next=ah->next; + return; + } + old=old->next; + } } /* find handle in locklist */ struct AfsHandle *findHandle(struct Volume *volume, ULONG block) { struct AfsHandle *ah; - ah=volume->locklist; - while (ah) - { - if (ah->header_block==block) - return ah; - ah=ah->next; - } - return NULL; + ah=volume->locklist; + while (ah) + { + if (ah->header_block==block) + return ah; + ah=ah->next; + } + return NULL; } /**************************************** @@ -339,36 +283,36 @@ struct AfsHandle *ah; Output: AfsHandle for success; NULL otherwise ****************************************/ struct AfsHandle *allocHandle - ( - struct AFSBase *afsbase, - struct Volume *volume, - struct BlockCache *fileblock, - ULONG mode, - ULONG *hashtable, - SIPTR *error - ) + ( + struct AFSBase *afsbase, + struct Volume *volume, + struct BlockCache *fileblock, + ULONG mode, + ULONG *hashtable, + SIPTR *error + ) { struct AfsHandle *ah; - ah=(struct AfsHandle *)AllocMem - (sizeof(struct AfsHandle), MEMF_PUBLIC | MEMF_CLEAR); - if (ah != NULL) - { - ah->header_block = fileblock->blocknum; - ah->dirpos = fileblock->blocknum; - ah->mode = mode; - ah->current.block = fileblock->blocknum; - ah->current.filekey = BLK_TABLE_END(volume); - ah->current.byte = 0; - ah->current.offset = 0; - ah->filesize = OS_BE2LONG(fileblock->buffer[BLK_BYTE_SIZE(volume)]); - ah->volume = volume; - ah->volumenode = volume->volumenode; - addHandle(ah); - } - else - *error = ERROR_NO_FREE_STORE; - return ah; + ah=(struct AfsHandle *)AllocMem + (sizeof(struct AfsHandle), MEMF_PUBLIC | MEMF_CLEAR); + if (ah != NULL) + { + ah->header_block = fileblock->blocknum; + ah->dirpos = fileblock->blocknum; + ah->mode = mode; + ah->current.block = fileblock->blocknum; + ah->current.filekey = BLK_TABLE_END(volume); + ah->current.byte = 0; + ah->current.offset = 0; + ah->filesize = OS_BE2LONG(fileblock->buffer[BLK_BYTE_SIZE(volume)]); + ah->volume = volume; + ah->volumenode = volume->volumenode; + addHandle(ah); + } + else + *error = ERROR_NO_FREE_STORE; + return ah; } /**************************************** @@ -382,49 +326,49 @@ struct AfsHandle *ah; Output: AfsHandle for success; NULL otherwise ****************************************/ struct AfsHandle *getHandle - ( - struct AFSBase *afsbase, - struct Volume *volume, - struct BlockCache *fileblock, - ULONG mode, - SIPTR *error - ) + ( + struct AFSBase *afsbase, + struct Volume *volume, + struct BlockCache *fileblock, + ULONG mode, + SIPTR *error + ) { struct AfsHandle *ah; - D(bug - ( - "[AFS] getHandle: trying to get handle for block %lu\n", - fileblock->blocknum) - ); - - *error = 0; - - ah = findHandle(volume, fileblock->blocknum); - if (ah != NULL) - { - if (ah->mode == MODE_READWRITE || - ah->mode == MODE_NEWFILE) - { - *error = ERROR_OBJECT_IN_USE; - ah = NULL; - } - } - - if (*error == 0) - { - ah = allocHandle - ( - afsbase, - volume, - fileblock, - mode, - (ULONG *)((char *)fileblock->buffer+(BLK_TABLE_START*4)), - error - ); - } - - return ah; + D(bug + ( + "[afs] getHandle: trying to get handle for block %u\n", + fileblock->blocknum) + ); + + *error = 0; + + ah = findHandle(volume, fileblock->blocknum); + if (ah != NULL) + { + if (ah->mode == MODE_READWRITE || + ah->mode == MODE_NEWFILE) + { + *error = ERROR_OBJECT_IN_USE; + ah = NULL; + } + } + + if (*error == 0) + { + ah = allocHandle + ( + afsbase, + volume, + fileblock, + mode, + (ULONG *)((char *)fileblock->buffer+(BLK_TABLE_START*4)), + error + ); + } + + return ah; } /***************************************** @@ -437,23 +381,23 @@ struct AfsHandle *ah; Output: AfsHandle for success; NULL otherwise ******************************************/ struct AfsHandle *openf - ( - struct AFSBase *afsbase, - struct AfsHandle *dirah, - CONST_STRPTR filename, - ULONG mode, - SIPTR *error - ) + ( + struct AFSBase *afsbase, + struct AfsHandle *dirah, + CONST_STRPTR filename, + ULONG mode, + SIPTR *error + ) { struct AfsHandle *ah = NULL; struct BlockCache *fileblock; ULONG block; - D(bug("[AFS] openf(%ld,%s,0x%8lx)\n",dirah->header_block,filename,mode)); - fileblock = findBlock(afsbase, dirah, filename, &block, error); - if (fileblock != NULL) - ah = getHandle(afsbase, dirah->volume, fileblock, mode, error); - return ah; + D(bug("[afs] openf(%d,%s,0x%8x)\n",dirah->header_block,filename,mode)); + fileblock = findBlock(afsbase, dirah, filename, &block, error); + if (fileblock != NULL) + ah = getHandle(afsbase, dirah->volume, fileblock, mode, error); + return ah; } /***************************************** @@ -467,118 +411,138 @@ ULONG block; Output: AfsHandle for success; NULL otherwise ******************************************/ struct AfsHandle *openfile - ( - struct AFSBase *afsbase, - struct AfsHandle *dirah, - CONST_STRPTR name, - ULONG mode, - ULONG protection, - SIPTR *error - ) + ( + struct AFSBase *afsbase, + struct AfsHandle *dirah, + CONST_STRPTR name, + ULONG mode, + ULONG protection, + SIPTR *error + ) { +struct Volume *volume = dirah->volume; struct AfsHandle *ah = NULL; struct BlockCache *fileblock, *dirblock; UBYTE filename[34]; ULONG block; ULONG fileblocknum = -1; - - /* - * nicely say what's going on - */ - D(bug("[AFS] openfile(%lu,%s,0x%lx,%lu)\n", dirah->header_block,name,mode,protection)); - *error = 0; - - /* - * if user wants to delete or create a new file - make sure we can do that. - */ - if ((mode != MODE_OLDFILE) && (0 == checkValid(afsbase, dirah->volume))) - *error = ERROR_DISK_WRITE_PROTECTED; - - /* - * get the directory the last component of "name" is in - */ - dirblock = getDirBlockBuffer(afsbase, dirah, name, filename, error); - - /* - * if no error so far and directory block is found, move on. - */ - if (*error == 0 && dirblock != NULL) - { - /* - * only if the directory is of DIR or ROOT type - */ - if ((OS_BE2LONG(dirblock->buffer[BLK_SECONDARY_TYPE(dirah->volume)]) == ST_USERDIR) || - (OS_BE2LONG(dirblock->buffer[BLK_SECONDARY_TYPE(dirah->volume)]) == ST_ROOT)) - { - D(bug("[AFS] parent of %s is on block %lu\n", name, dirblock->blocknum)); - - /* - * get the header block of the file to open - */ - fileblock = getHeaderBlock(afsbase, dirah->volume, filename, dirblock, &block, error); - - /* - * check if 'file' is really a FILE - */ - if ((fileblock != NULL) && (OS_BE2LONG(fileblock->buffer[BLK_SECONDARY_TYPE(dirah->volume)])!=ST_FILE)) - { - *error = ERROR_OBJECT_WRONG_TYPE; - } - else - { - /* - * get file block, if there was (is) a file - */ - if (fileblock != NULL) - fileblocknum = fileblock->blocknum; - - /* - * remove existing file if we are asked to clear its contents - */ - if (mode == MODE_NEWFILE) - *error = deleteObject(afsbase, dirah, name); - - /* - * if we cleared the file or there was no file at all, move on - */ - if ((*error == 0) || (*error == ERROR_OBJECT_NOT_FOUND)) - { - /* - * in case we could not find existing file, or if we deleted this file previously, - * create a new one. - */ - if (mode == MODE_NEWFILE) - { - /* - * please note that dirblock may become invalid here - */ - fileblock = createNewEntry(afsbase, dirah->volume, ST_FILE, filename, dirblock, protection, error); - } - else - { - /* - * we should already have fileblock here - * again, dirblock may become invalid here - */ - if (fileblock != NULL) - fileblock = getBlock(afsbase, dirah->volume, fileblocknum); - } - - /* - * create a handle for the file - */ - if (fileblock != NULL) - { - *error = 0; - ah = getHandle(afsbase, dirah->volume, fileblock, mode, error); - } - } - } - } - else - *error = ERROR_OBJECT_WRONG_TYPE; - } - return ah; +ULONG dirblocknum = 0; + + /* + * nicely say what's going on + */ + D(bug("[afs] openfile(%u,%s,0x%x,%u)\n", dirah->header_block,name,mode,protection)); + *error = 0; + + /* + * if user wants to delete or create a new file - make sure we can do that. + */ + if ((mode != MODE_OLDFILE) && (0 == checkValid(afsbase, volume))) + *error = ERROR_DISK_WRITE_PROTECTED; + + /* + * get the directory the last component of "name" is in + */ + dirblock = getDirBlockBuffer(afsbase, dirah, name, filename, error); + + /* + * if no error so far and directory block is found, move on. + */ + if (*error == 0 && dirblock != NULL) + { + /* + * only if the directory is of DIR or ROOT type + */ + if ((OS_BE2LONG(dirblock->buffer[BLK_SECONDARY_TYPE(volume)]) == ST_USERDIR) || + (OS_BE2LONG(dirblock->buffer[BLK_SECONDARY_TYPE(volume)]) == ST_ROOT)) + { + D(bug("[afs] parent of %s is on block %u\n", name, dirblock->blocknum)); + + /* + * get the header block of the file to open + */ + fileblock = getHeaderBlock(afsbase, volume, filename, dirblock, &block, error); + + /* + * check if 'file' is really a FILE + */ + if ((fileblock != NULL) && (OS_BE2LONG(fileblock->buffer[BLK_SECONDARY_TYPE(volume)])!=ST_FILE)) + { + *error = ERROR_OBJECT_WRONG_TYPE; + } + else + { + /* + * get file block, if there was (is) a file + */ + if (fileblock != NULL) + fileblocknum = fileblock->blocknum; + + /* + * remove existing file if we are asked to clear its contents + */ + if (mode == MODE_NEWFILE) + { + /* + * deleteObject() walks the directory again and frees every + * block of the old file through the bitmap; each of those + * getBlock() calls may recycle the cache entry dirblock points + * at. Re-fetch the directory by block number afterwards - using + * the stale pointer made createNewEntry() treat whatever block + * now occupied the entry (typically the deleted file's own + * header) as the directory and link the new file into it. + */ + dirblocknum = dirblock->blocknum; + *error = deleteObject(afsbase, dirah, name); + if ((*error == 0) || (*error == ERROR_OBJECT_NOT_FOUND)) + { + dirblock = getBlock(afsbase, volume, dirblocknum); + if (dirblock == NULL) + *error = ERROR_UNKNOWN; + } + } + + /* + * if we cleared the file or there was no file at all, move on + */ + if ((*error == 0) || (*error == ERROR_OBJECT_NOT_FOUND)) + { + /* + * in case we could not find existing file, or if we deleted this file previously, + * create a new one. + */ + if (mode == MODE_NEWFILE) + { + /* + * please note that dirblock may become invalid here + */ + fileblock = createNewEntry(afsbase, volume, ST_FILE, filename, dirblock, protection, error); + } + else + { + /* + * we should already have fileblock here + * again, dirblock may become invalid here + */ + if (fileblock != NULL) + fileblock = getBlock(afsbase, volume, fileblocknum); + } + + /* + * create a handle for the file + */ + if (fileblock != NULL) + { + *error = 0; + ah = getHandle(afsbase, volume, fileblock, mode, error); + } + } + } + } + else + *error = ERROR_OBJECT_WRONG_TYPE; + } + return ah; } /*********************************** @@ -589,9 +553,9 @@ ULONG fileblocknum = -1; ************************************/ void closef(struct AFSBase *afsbase, struct AfsHandle *ah) { - D(bug("[AFS] closef(%lu)\n",ah->header_block)); - remHandle(afsbase, ah); - FreeMem(ah,sizeof(struct AfsHandle)); + D(bug("[afs] closef(%u)\n",ah->header_block)); + remHandle(afsbase, ah); + FreeMem(ah,sizeof(struct AfsHandle)); } /****************************************** @@ -602,446 +566,549 @@ void closef(struct AFSBase *afsbase, struct AfsHandle *ah) { length - size of data to read Output: read bytes *******************************************/ +/* + * Read consecutive whole data blocks, starting at the current one, in one + * request. Returns the number of blocks read, 0 if none qualified, -1 on error. + */ +static ULONG bulkRead + ( + struct AFSBase *afsbase, + struct AfsHandle *ah, + struct BlockCache *extensionbuffer, + char *dest, + ULONG maxblocks + ) +{ +struct Volume *volume = ah->volume; +ULONG key = ah->current.filekey; +ULONG start = OS_BE2LONG(extensionbuffer->buffer[key]); +ULONG count = 1; + if (maxblocks > volume->bulkblocks) + maxblocks = volume->bulkblocks; + while (count < maxblocks && key >= BLK_TABLE_START + count + && OS_BE2LONG(extensionbuffer->buffer[key - count]) == start + count) + count++; + count = cleanRun(volume, start, count); + if (count == 0) + return 0; + if (readDisk(afsbase, volume, start, count, volume->bulkbuffer) != 0) + return (ULONG)-1; + CopyMem(volume->bulkbuffer, dest, count * BLOCK_SIZE(volume)); + return count; +} + LONG readData - ( - struct AFSBase *afsbase, - struct AfsHandle *ah, - void *buffer, - ULONG length, - SIPTR *error - ) + ( + struct AFSBase *afsbase, + struct AfsHandle *ah, + void *buffer, + ULONG length, + SIPTR *error + ) { +struct Volume *volume = ah->volume; struct BlockCache *extensionbuffer; struct BlockCache *databuffer; -UWORD size; +ULONG size; LONG readbytes=0; char *source; - if (ah->current.block == 0) - return 0; /* we can't read beyond EOF so return EOF */ - if (length > (ah->filesize-ah->current.offset)) - { - length = ah->filesize-ah->current.offset; /* we can't read more bytes than left in file! */ - } - D(bug("[AFS] readData: offset=%ld\n", ah->current.offset)); - extensionbuffer = getBlock(afsbase, ah->volume, ah->current.block); - if (extensionbuffer == NULL) - { - *error = ERROR_UNKNOWN; - return ENDSTREAMCH; - } - extensionbuffer->flags |= BCF_USED; /* don't overwrite that cache block! */ - while (length != 0) - { - D(bug("[AFS] readData: bytes left=%ld\n",length)); - /* - block, filekey always point to the next block - so update them if we have read a whole block - */ - /* do we have to read next extension block? */ - if (ah->current.filekeycurrent.block= - OS_BE2LONG(extensionbuffer->buffer[BLK_EXTENSION(ah->volume)]); - ah->current.filekey = BLK_TABLE_END(ah->volume); - extensionbuffer->flags &= ~BCF_USED; //we can now overwrite that cache block - D(bug("[AFS] readData: reading extensionblock=%ld\n",ah->current.block)); - if (ah->current.block != 0) - { - extensionbuffer = getBlock(afsbase, ah->volume,ah->current.block); - if (extensionbuffer == 0) - { - *error = ERROR_UNKNOWN; - return ENDSTREAMCH; //was readbytes; - } - extensionbuffer->flags |= BCF_USED; //don't overwrite this cache block - } + if (ah->current.block == 0) + return 0; /* we can't read beyond EOF so return EOF */ + if (length > (ah->filesize-ah->current.offset)) + { + length = ah->filesize-ah->current.offset; /* we can't read more bytes than left in file! */ + } + D(bug("[afs] readData: offset=%d\n", ah->current.offset)); + extensionbuffer = getBlock(afsbase, volume, ah->current.block); + if (extensionbuffer == NULL) + { + *error = ERROR_UNKNOWN; + return ENDSTREAMCH; + } + extensionbuffer->flags |= BCF_USED; /* don't overwrite that cache block! */ + while (length != 0) + { + D(bug("[afs] readData: bytes left=%d\n",length)); + /* + block, filekey always point to the next block + so update them if we have read a whole block + */ + /* do we have to read next extension block? */ + if (ah->current.filekeycurrent.block= + OS_BE2LONG(extensionbuffer->buffer[BLK_EXTENSION(volume)]); + ah->current.filekey = BLK_TABLE_END(volume); + extensionbuffer->flags &= ~BCF_USED; //we can now overwrite that cache block + D(bug("[afs] readData: reading extensionblock=%d\n",ah->current.block)); + if (ah->current.block != 0) + { + extensionbuffer = getBlock(afsbase, volume,ah->current.block); + if (extensionbuffer == 0) + { + *error = ERROR_UNKNOWN; + return ENDSTREAMCH; //was readbytes; + } + extensionbuffer->flags |= BCF_USED; //don't overwrite this cache block + } D( - else - if (length) - bug - ( - "Shit, out of extensionblocks!\n" - "Bytes left: %ld\n" - "Last extensionblock: %ld\n", - length,extensionbuffer->blocknum - ); + else + if (length) + bug + ( + "Shit, out of extensionblocks!\n" + "Bytes left: %d\n" + "Last extensionblock: %d\n", + length,extensionbuffer->blocknum + ); ); - } - D(bug - ( - "[AFS] readData: reading datablock %ld\n", - OS_BE2LONG(extensionbuffer->buffer[ah->current.filekey])) - ); - databuffer = getBlock - ( - afsbase, - ah->volume, - OS_BE2LONG(extensionbuffer->buffer[ah->current.filekey]) - ); - if (databuffer == 0) - { - extensionbuffer->flags &= ~BCF_USED; //free that block - *error = ERROR_UNKNOWN; - return ENDSTREAMCH; //was readbytes; - } - source = (char *)databuffer->buffer+ah->current.byte; - if (ah->volume->dosflags == 0) - { - size = OS_BE2LONG(databuffer->buffer[BLK_DATA_SIZE]); - source += (BLK_DATA_START*4); - } - else - { - size = BLOCK_SIZE(ah->volume); - } - size -= ah->current.byte; - if (size > length) - { - size = length; - ah->current.byte += size; - } - else - { - ah->current.byte = 0; - ah->current.filekey--; - } - CopyMem((APTR)source, (APTR)((char *)buffer+readbytes),size); - length -= size; - readbytes += size; - } - extensionbuffer->flags &= ~BCF_USED; - return readbytes; + } + D(bug + ( + "[afs] readData: reading datablock %d\n", + OS_BE2LONG(extensionbuffer->buffer[ah->current.filekey])) + ); + if (volume->dosflags != 0 && ah->current.byte == 0 + && length >= BLOCK_SIZE(volume) && volume->bulkblocks != 0) + { + ULONG count = bulkRead(afsbase, ah, extensionbuffer, + (char *)buffer + readbytes, length / BLOCK_SIZE(volume)); + if (count == (ULONG)-1) + { + extensionbuffer->flags &= ~BCF_USED; + *error = ERROR_UNKNOWN; + return ENDSTREAMCH; + } + if (count != 0) + { + ah->current.filekey -= count; + count *= BLOCK_SIZE(volume); + length -= count; + readbytes += count; + continue; + } + } + databuffer = getBlock + ( + afsbase, + volume, + OS_BE2LONG(extensionbuffer->buffer[ah->current.filekey]) + ); + if (databuffer == 0) + { + extensionbuffer->flags &= ~BCF_USED; //free that block + *error = ERROR_UNKNOWN; + return ENDSTREAMCH; //was readbytes; + } + source = (char *)databuffer->buffer+ah->current.byte; + if (volume->dosflags == 0) + { + size = OS_BE2LONG(databuffer->buffer[BLK_DATA_SIZE]); + if (size > BLOCK_SIZE(volume) - BLK_DATA_START * 4 + || size <= ah->current.byte) + { + extensionbuffer->flags &= ~BCF_USED; + *error = ERROR_DISK_NOT_VALIDATED; + return ENDSTREAMCH; + } + source += (BLK_DATA_START*4); + } + else + { + size = BLOCK_SIZE(volume); + } + size -= ah->current.byte; + if (size > length) + { + size = length; + ah->current.byte += size; + } + else + { + ah->current.byte = 0; + ah->current.filekey--; + } + CopyMem((APTR)source, (APTR)((char *)buffer+readbytes),size); + length -= size; + readbytes += size; + } + extensionbuffer->flags &= ~BCF_USED; + return readbytes; } LONG readf - (struct AFSBase *afsbase, struct AfsHandle *ah, void *buffer, ULONG length, SIPTR *error) + (struct AFSBase *afsbase, struct AfsHandle *ah, void *buffer, ULONG length, SIPTR *error) { LONG readbytes; - D(bug("[AFS] read(%ld,buffer,%ld)\n", ah->header_block, length)); - readbytes = readData(afsbase, ah,buffer,length, error); - if (readbytes != ENDSTREAMCH) - ah->current.offset = ah->current.offset+readbytes; - return readbytes; + D(bug("[afs] read(%d,buffer,%d)\n", ah->header_block, length)); + readbytes = readData(afsbase, ah,buffer,length, error); + if (readbytes != ENDSTREAMCH) + ah->current.offset = ah->current.offset+readbytes; + return readbytes; } void newFileExtensionBlock - ( - struct Volume *volume, - struct BlockCache *extension, - ULONG parent) + ( + struct Volume *volume, + struct BlockCache *extension, + ULONG parent) { UWORD i; - extension->buffer[BLK_PRIMARY_TYPE] = OS_LONG2BE(T_LIST); - extension->buffer[BLK_OWN_KEY ] = OS_LONG2BE(extension->blocknum); - for (i=2; ibuffer[i] = 0; - extension->buffer[BLK_PARENT(volume)] = OS_LONG2BE(parent); - extension->buffer[BLK_EXTENSION(volume)] = 0; - extension->buffer[BLK_SECONDARY_TYPE(volume)] = OS_LONG2BE(ST_FILE); + extension->buffer[BLK_PRIMARY_TYPE] = OS_LONG2BE(T_LIST); + extension->buffer[BLK_OWN_KEY ] = OS_LONG2BE(extension->blocknum); + for (i=2; ibuffer[i] = 0; + extension->buffer[BLK_PARENT(volume)] = OS_LONG2BE(parent); + extension->buffer[BLK_EXTENSION(volume)] = 0; + extension->buffer[BLK_SECONDARY_TYPE(volume)] = OS_LONG2BE(ST_FILE); } void writeExtensionBlock - ( - struct AFSBase *afsbase, - struct Volume *volume, - struct BlockCache *extension, - ULONG filekey, - ULONG next - ) + ( + struct AFSBase *afsbase, + struct Volume *volume, + struct BlockCache *extension, + ULONG filekey, + ULONG next + ) { ULONG newcount = BLK_TABLE_END(volume)-(filekey-1); - if (OS_BE2LONG(extension->buffer[BLK_BLOCK_COUNT]) < newcount) - extension->buffer[BLK_BLOCK_COUNT] = OS_LONG2BE(newcount); - if (next != 0) - extension->buffer[BLK_EXTENSION(volume)] = OS_LONG2BE(next); - writeBlockDeferred(afsbase, volume, extension, BLK_CHECKSUM); + if (OS_BE2LONG(extension->buffer[BLK_BLOCK_COUNT]) < newcount) + extension->buffer[BLK_BLOCK_COUNT] = OS_LONG2BE(newcount); + if (next != 0) + extension->buffer[BLK_EXTENSION(volume)] = OS_LONG2BE(next); + writeBlockDeferred(afsbase, volume, extension, BLK_CHECKSUM); } LONG writeData - ( - struct AFSBase *afsbase, - struct AfsHandle *ah, - void *buffer, - ULONG length, - SIPTR *error - ) + ( + struct AFSBase *afsbase, + struct AfsHandle *ah, + void *buffer, + ULONG length, + SIPTR *error + ) { +struct Volume *volume = ah->volume; ULONG block = 0; -ULONG lastblock = 0; /* 0 means: don't update BLK_NEXT_DATA */ +ULONG savedBitmap = 0; +ULONG lastblock = 0; /* 0 means: don't update BLK_NEXT_DATA */ struct BlockCache *extensionbuffer = NULL; struct BlockCache *databuffer = NULL; +struct BlockCache *previous = NULL; UWORD size, blockCapacity; LONG writtenbytes = 0, sumoffset; char *destination; BOOL extensionModified = FALSE; - D(bug("[AFS] writeData: offset=%ld\n", ah->current.offset)); - extensionbuffer = getBlock(afsbase, ah->volume, ah->current.block); - if (extensionbuffer == NULL) - { - *error = ERROR_UNKNOWN; - return ENDSTREAMCH; - } - extensionbuffer->flags |=BCF_USED; /* don't overwrite that cache block! */ - while (length != 0) - { - /* save last data block for OFS data */ - if ( - (ah->current.byte==0) && /* last block fully written */ - (ah->current.filekey!=BLK_TABLE_END(ah->volume)) /* this is not the first block of the file */ - ) - { - lastblock = OS_BE2LONG(extensionbuffer->buffer[ah->current.filekey+1]); - D(bug - ("[AFS] writeData: for OFS last datablock was %lu\n", lastblock)); - } - /* - block, filekey always point to the last block - so update them if we have read a whole block - */ - /* read next extension block? */ - if (ah->current.filekey < BLK_TABLE_START) - { - extensionModified = FALSE; - if (extensionbuffer->buffer[BLK_EXTENSION(ah->volume)] != 0) - { - block = OS_BE2LONG(extensionbuffer->buffer[BLK_EXTENSION(ah->volume)]); - extensionbuffer->flags &= ~BCF_USED; - extensionbuffer = getBlock(afsbase, ah->volume, block); - if (extensionbuffer == NULL) - { - *error = ERROR_UNKNOWN; - return ENDSTREAMCH; // was writtenbytes; - } - } - else - { - D(bug("[AFS] writeData: need new extensionblock\n")); - block = allocBlock(afsbase, ah->volume); - writeExtensionBlock - ( - afsbase, - ah->volume, - extensionbuffer, - ah->current.filekey+1, - block - ); - extensionbuffer->flags &= ~BCF_USED; - if (block == 0) - { - *error = ERROR_NO_FREE_STORE; - return ENDSTREAMCH; /* was writtenbytes; */ - } - extensionbuffer = getFreeCacheBlock(afsbase, ah->volume,block); - if (extensionbuffer == NULL) - { - *error = ERROR_UNKNOWN; - return ENDSTREAMCH; /* was writtenbytes; */ - } - newFileExtensionBlock(ah->volume,extensionbuffer, ah->header_block); - } - ah->current.filekey = BLK_TABLE_END(ah->volume); - extensionbuffer->flags |= BCF_USED; /* don't overwrite this cache block */ - ah->current.block = block; - } - /* find a block to write data into */ - if (extensionbuffer->buffer[ah->current.filekey] != 0) /* do we already have that block? */ - { - D(bug - ( - "[AFS] writeData: using old datablock %lu\n", - OS_BE2LONG(extensionbuffer->buffer[ah->current.filekey])) - ); - /* Only get the block's old contents if some of it won't be overwritten - (except for OFS or a final, partially-used block) */ - block = OS_BE2LONG(extensionbuffer->buffer[ah->current.filekey]); - if ((ah->current.byte == 0) && (length >= BLOCK_SIZE(ah->volume)) - && (ah->volume->dosflags != 0)) - databuffer = getFreeCacheBlock(afsbase, ah->volume, block); - else - databuffer = getBlock(afsbase, ah->volume, block); - if (databuffer == NULL) - { - writeExtensionBlock - ( - afsbase, - ah->volume, - extensionbuffer, - ah->current.filekey, - 0 - ); - extensionbuffer->flags &= ~BCF_USED; //free that block - *error = ERROR_UNKNOWN; - return ENDSTREAMCH; //was writtenbytes; - } - } - else - { - extensionModified = TRUE; - D(bug("[AFS] writeData: need a new datablock\n")); - block=allocBlock(afsbase, ah->volume); - if (block == 0) - { - writeExtensionBlock - ( - afsbase, - ah->volume, - extensionbuffer, - ah->current.filekey, - 0 - ); - extensionbuffer->flags &= ~BCF_USED; - *error = ERROR_NO_FREE_STORE; - return ENDSTREAMCH; //was writtenbytes; - } - extensionbuffer->buffer[ah->current.filekey] = OS_LONG2BE(block); - if ((ah->volume->dosflags==0) && (lastblock != 0)) - { - D(bug("[AFS] writeData: OFS->fill in %ld BLK_NEXT_DATA\n",lastblock)); - /* - we allocated a new block - so there MUST be an initialized lastblock - */ - databuffer = getBlock(afsbase, ah->volume,lastblock); - if (databuffer == NULL) - { - writeExtensionBlock - ( - afsbase, - ah->volume, - extensionbuffer, - ah->current.filekey, - 0 - ); - extensionbuffer->flags &= ~BCF_USED; //free that block - *error = ERROR_UNKNOWN; - return ENDSTREAMCH; //was writtenbytes; - } - databuffer->buffer[BLK_NEXT_DATA] = OS_LONG2BE(block); - writeBlock(afsbase, ah->volume,databuffer, BLK_CHECKSUM); - } - databuffer = getFreeCacheBlock(afsbase, ah->volume,block); - if (databuffer == NULL) - { - writeExtensionBlock - (afsbase, ah->volume, extensionbuffer, ah->current.filekey, 0); - extensionbuffer->flags &= ~BCF_USED; //free that block - *error = ERROR_UNKNOWN; - return ENDSTREAMCH; //was writtenbytes; - } - if (ah->volume->dosflags == 0) - { - databuffer->buffer[BLK_PRIMARY_TYPE] = OS_LONG2BE(T_DATA); - databuffer->buffer[BLK_HEADER_KEY] = OS_LONG2BE(ah->header_block); - blockCapacity = (ah->volume->SizeBlock-BLK_DATA_START)*sizeof(ULONG); - databuffer->buffer[BLK_SEQUENCE_NUMBER] = - OS_LONG2BE - (((ah->current.offset+writtenbytes)/blockCapacity)+1); - databuffer->buffer[BLK_DATA_SIZE] = 0; - databuffer->buffer[BLK_NEXT_DATA] = 0; - } - } - destination = (char *)databuffer->buffer+ah->current.byte; - size = BLOCK_SIZE(ah->volume); - if (ah->volume->dosflags == 0) - { - size -= (6*4); - destination += (BLK_DATA_START*4); - } - size -= ah->current.byte; - if (size > length) - { - size = length; - ah->current.byte += size; - } - else - { - ah->current.byte = 0; - ah->current.filekey--; - } - if (buffer != NULL) - CopyMem((APTR)((char *)buffer+writtenbytes),(APTR)destination,size); - if (ah->volume->dosflags == 0) - { - if (ah->current.byte == 0) - { - databuffer->buffer[BLK_DATA_SIZE] = - OS_LONG2BE(BLOCK_SIZE(ah->volume)-(6*4)); - } - else if (OS_BE2LONG(databuffer->buffer[BLK_DATA_SIZE]) < ah->current.byte) - { - databuffer->buffer[BLK_DATA_SIZE] = OS_LONG2BE(ah->current.byte); - } - sumoffset = BLK_CHECKSUM; - } - else - sumoffset = -1; - if (buffer != NULL || ah->volume->dosflags == 0) - writeBlock(afsbase, ah->volume, databuffer, sumoffset); - length -= size; - writtenbytes += size; - } - if (extensionModified) - { - writeExtensionBlock - ( - afsbase, - ah->volume, - extensionbuffer, - ah->current.byte==0 ? ah->current.filekey+1 : ah->current.filekey, - 0 - ); - } - extensionbuffer->flags &= ~BCF_USED; - D(bug("[AFS] writeData=%ld\n", writtenbytes)); - return writtenbytes; + D(bug("[afs] writeData: offset=%d\n", ah->current.offset)); + extensionbuffer = getBlock(afsbase, volume, ah->current.block); + if (extensionbuffer == NULL) + { + *error = ERROR_UNKNOWN; + return writtenbytes != 0 ? writtenbytes : ENDSTREAMCH; + } + extensionbuffer->flags |=BCF_USED; /* don't overwrite that cache block! */ + while (length != 0) + { + savedBitmap = 0; + /* save last data block for OFS data */ + if ( + (ah->current.byte==0) && /* last block fully written */ + (ah->current.filekey!=BLK_TABLE_END(volume)) /* this is not the first block of the file */ + ) + { + lastblock = OS_BE2LONG(extensionbuffer->buffer[ah->current.filekey+1]); + D(bug + ("[afs] writeData: for OFS last datablock was %u\n", lastblock)); + } + /* + block, filekey always point to the last block + so update them if we have read a whole block + */ + /* read next extension block? */ + if (ah->current.filekey < BLK_TABLE_START) + { + extensionModified = FALSE; + if (extensionbuffer->buffer[BLK_EXTENSION(volume)] != 0) + { + block = OS_BE2LONG(extensionbuffer->buffer[BLK_EXTENSION(volume)]); + extensionbuffer->flags &= ~BCF_USED; + extensionbuffer = getBlock(afsbase, volume, block); + if (extensionbuffer == NULL) + { + *error = ERROR_UNKNOWN; + return writtenbytes != 0 ? writtenbytes : ENDSTREAMCH; // was writtenbytes; + } + } + else + { + D(bug("[afs] writeData: need new extensionblock\n")); + block = allocBlock(afsbase, volume); + writeExtensionBlock + ( + afsbase, + volume, + extensionbuffer, + ah->current.filekey+1, + block + ); + extensionbuffer->flags &= ~BCF_USED; + if (block == 0) + { + *error = ERROR_NO_FREE_STORE; + return writtenbytes != 0 ? writtenbytes : ENDSTREAMCH; /* was writtenbytes; */ + } + extensionbuffer = getFreeCacheBlock(afsbase, volume,block); + if (extensionbuffer == NULL) + { + *error = ERROR_UNKNOWN; + return writtenbytes != 0 ? writtenbytes : ENDSTREAMCH; /* was writtenbytes; */ + } + newFileExtensionBlock(volume,extensionbuffer, ah->header_block); + } + ah->current.filekey = BLK_TABLE_END(volume); + extensionbuffer->flags |= BCF_USED; /* don't overwrite this cache block */ + ah->current.block = block; + } + /* find a block to write data into */ + if (extensionbuffer->buffer[ah->current.filekey] != 0) /* do we already have that block? */ + { + D(bug + ( + "[afs] writeData: using old datablock %u\n", + OS_BE2LONG(extensionbuffer->buffer[ah->current.filekey])) + ); + /* Only get the block's old contents if some of it won't be overwritten + (except for OFS or a final, partially-used block) */ + block = OS_BE2LONG(extensionbuffer->buffer[ah->current.filekey]); + if ((ah->current.byte == 0) && (length >= BLOCK_SIZE(volume)) + && (volume->dosflags != 0)) + databuffer = getFreeCacheBlock(afsbase, volume, block); + else + databuffer = getBlock(afsbase, volume, block); + if (databuffer == NULL) + { + writeExtensionBlock + ( + afsbase, + volume, + extensionbuffer, + ah->current.filekey, + 0 + ); + extensionbuffer->flags &= ~BCF_USED; //free that block + *error = ERROR_UNKNOWN; + return writtenbytes != 0 ? writtenbytes : ENDSTREAMCH; //was writtenbytes; + } + } + else + { + extensionModified = TRUE; + D(bug("[afs] writeData: need a new datablock\n")); + block=allocBlock(afsbase, volume); + if (block == 0) + { + writeExtensionBlock + ( + afsbase, + volume, + extensionbuffer, + ah->current.filekey, + 0 + ); + extensionbuffer->flags &= ~BCF_USED; + *error = ERROR_NO_FREE_STORE; + return writtenbytes != 0 ? writtenbytes : ENDSTREAMCH; //was writtenbytes; + } + previous = NULL; + if (volume->dosflags == 0 && lastblock != 0) + { + /* Keep the previous block resident while allocating its successor. */ + previous = getBlock(afsbase, volume, lastblock); + if (previous == NULL) + { + writeExtensionBlock(afsbase, volume, extensionbuffer, + ah->current.filekey + 1, 0); + extensionbuffer->flags &= ~BCF_USED; + *error = ERROR_UNKNOWN; + return writtenbytes != 0 ? writtenbytes : ENDSTREAMCH; + } + previous->flags |= BCF_USED; + } + databuffer = getFreeCacheBlock(afsbase, volume,block); + if (databuffer == NULL && previous != NULL + && !volume->writefailed && volume->bitmapblock != NULL) + { + /* Four-buffer OFS caches have no fifth slot. The root is + * already invalid: checksum and release the bitmap so + * eviction can persist it and make room for the new data. */ + savedBitmap = volume->bitmapblock->blocknum; + writeBlockDeferred(afsbase, volume, volume->bitmapblock, 0); + releaseBitmap(volume); + volume->bitmapblock = NULL; + databuffer = getFreeCacheBlock(afsbase, volume, block); + } + if (databuffer == NULL) + { + if (previous != NULL) + previous->flags &= ~BCF_USED; + writeExtensionBlock + (afsbase, volume, extensionbuffer, ah->current.filekey + 1, 0); + extensionbuffer->flags &= ~BCF_USED; //free that block + *error = ERROR_UNKNOWN; + return writtenbytes != 0 ? writtenbytes : ENDSTREAMCH; //was writtenbytes; + } + if (volume->dosflags == 0) + { + databuffer->buffer[BLK_PRIMARY_TYPE] = OS_LONG2BE(T_DATA); + databuffer->buffer[BLK_HEADER_KEY] = OS_LONG2BE(ah->header_block); + blockCapacity = (volume->SizeBlock-BLK_DATA_START)*sizeof(ULONG); + databuffer->buffer[BLK_SEQUENCE_NUMBER] = + OS_LONG2BE + (((ah->current.offset+writtenbytes)/blockCapacity)+1); + databuffer->buffer[BLK_DATA_SIZE] = 0; + databuffer->buffer[BLK_NEXT_DATA] = 0; + } + extensionbuffer->buffer[ah->current.filekey] = OS_LONG2BE(block); + if (previous != NULL) + { + previous->buffer[BLK_NEXT_DATA] = OS_LONG2BE(block); + writeBlock(afsbase, volume,previous, BLK_CHECKSUM); + previous->flags &= ~BCF_USED; + } + } + destination = (char *)databuffer->buffer+ah->current.byte; + size = BLOCK_SIZE(volume); + if (volume->dosflags == 0) + { + size -= (6*4); + destination += (BLK_DATA_START*4); + } + size -= ah->current.byte; + if (size > length) + { + size = length; + ah->current.byte += size; + } + else + { + ah->current.byte = 0; + ah->current.filekey--; + } + if (buffer != NULL) + CopyMem((APTR)((char *)buffer+writtenbytes),(APTR)destination,size); + if (volume->dosflags == 0) + { + if (ah->current.byte == 0) + { + databuffer->buffer[BLK_DATA_SIZE] = + OS_LONG2BE(BLOCK_SIZE(volume)-(6*4)); + } + else if (OS_BE2LONG(databuffer->buffer[BLK_DATA_SIZE]) < ah->current.byte) + { + databuffer->buffer[BLK_DATA_SIZE] = OS_LONG2BE(ah->current.byte); + } + sumoffset = BLK_CHECKSUM; + } + else + sumoffset = -1; + if (buffer != NULL || volume->dosflags == 0) + writeBlock(afsbase, volume, databuffer, sumoffset); + length -= size; + writtenbytes += size; + if (savedBitmap != 0 && !volume->writefailed) + { + volume->bitmapblock = getBlock(afsbase, volume, savedBitmap); + if (volume->bitmapblock != NULL) + volume->bitmapblock->flags |= BCF_USED; + else + { + volume->writefailed = TRUE; + volume->state = ID_VALIDATING; + } + } + /* A failed buffer remains queued. Finish its metadata/accounting, + * then stop before allocating or advancing to another block. */ + if (volume->writefailed) + break; + } + if (extensionModified) + { + writeExtensionBlock + ( + afsbase, + volume, + extensionbuffer, + ah->current.byte==0 ? ah->current.filekey+1 : ah->current.filekey, + 0 + ); + } + extensionbuffer->flags &= ~BCF_USED; + D(bug("[afs] writeData=%d\n", writtenbytes)); + return writtenbytes; } LONG writef - (struct AFSBase *afsbase, struct AfsHandle *ah, void *buffer, ULONG length, SIPTR *error) + (struct AFSBase *afsbase, struct AfsHandle *ah, void *buffer, ULONG length, SIPTR *error) { +struct Volume *volume = ah->volume; struct BlockCache *headerblock; LONG writtenbytes; struct DateStamp ds; - D(bug("[AFS] write(ah,buffer,%ld)\n", length)); - if (0 == checkValid(afsbase, ah->volume)) - { - *error = ERROR_DISK_WRITE_PROTECTED; - return 0; - } - - invalidBitmap(afsbase, ah->volume); - writtenbytes = writeData(afsbase, ah, buffer, length, error); - if (writtenbytes != ENDSTREAMCH) - { - ah->current.offset += writtenbytes; - headerblock = getBlock(afsbase, ah->volume,ah->header_block); - if (headerblock != NULL) - { - headerblock->buffer[BLK_FIRST_DATA] = - headerblock->buffer[BLK_TABLE_END(ah->volume)]; - if (ah->current.offset > ah->filesize) - { - ah->filesize = ah->current.offset; - headerblock->buffer[BLK_BYTE_SIZE(ah->volume)] = - OS_LONG2BE(ah->filesize); - } - DateStamp(&ds); - setHeaderDate(afsbase, ah->volume, headerblock, &ds); - } - } - validBitmap(afsbase, ah->volume); - return writtenbytes; + D(bug("[afs] write(ah,buffer,%d)\n", length)); + if (0 == checkValid(afsbase, volume)) + { + *error = ERROR_DISK_WRITE_PROTECTED; + return 0; + } + + if (!invalidBitmap(afsbase, volume)) + { + *error = ERROR_UNKNOWN; + return 0; + } + writtenbytes = writeData(afsbase, ah, buffer, length, error); + if (writtenbytes != ENDSTREAMCH) + { + ah->current.offset += writtenbytes; + headerblock = getBlock(afsbase, volume,ah->header_block); + if (headerblock != NULL) + { + headerblock->buffer[BLK_FIRST_DATA] = + headerblock->buffer[BLK_TABLE_END(volume)]; + if (ah->current.offset > ah->filesize) + { + ah->filesize = ah->current.offset; + headerblock->buffer[BLK_BYTE_SIZE(volume)] = + OS_LONG2BE(ah->filesize); + } + DateStamp(&ds); + setHeaderDate(afsbase, volume, headerblock, &ds); + } + else + { + *error = ERROR_UNKNOWN; + writtenbytes = ENDSTREAMCH; + } + } + if (!validBitmap(afsbase, volume)) + { + *error = ERROR_UNKNOWN; + return ENDSTREAMCH; + } + return writtenbytes; } LONG seek - (struct AFSBase* afsbase, struct AfsHandle *ah, LONG offset, LONG mode, SIPTR *error) + (struct AFSBase* afsbase, struct AfsHandle *ah, LONG offset, LONG mode, SIPTR *error) { +struct Volume *volume = ah->volume; LONG old = -1; UWORD filekey, byte; ULONG block, extblockindex, newextblockindex; @@ -1049,166 +1116,179 @@ UWORD blocksize, tablesize; ULONG newoffset; struct BlockCache *blockbuffer; - D(bug("[AFS] seek(%ld,%ld,%ld)\n", ah->header_block, offset, mode)); - *error = ERROR_SEEK_ERROR; - if (mode == OFFSET_BEGINNING) - { - newoffset = (ULONG)offset; - } - else if (mode == OFFSET_CURRENT) - { - if (offset == 0) - { - *error = 0; - return ah->current.offset; - } - newoffset = ah->current.offset+offset; - } - else if (mode == OFFSET_END) - { - newoffset = ah->filesize+offset; - } - else - return -1; - if ((LONG)newoffset >= 0) - { - blocksize = BLOCK_SIZE(ah->volume); - if (ah->volume->dosflags == 0) - blocksize -= (BLK_DATA_START*4); - newextblockindex = newoffset / blocksize; - tablesize = BLK_TABLE_END(ah->volume)-BLK_TABLE_START+1; - filekey = BLK_TABLE_END(ah->volume)-(newextblockindex % tablesize); - newextblockindex /= tablesize; /* # of extensionblock we need */ - byte = newoffset % blocksize; - if (newoffset != 0 && byte == 0 && filekey == BLK_TABLE_END(ah->volume)) - { - newextblockindex--; - filekey = BLK_TABLE_START - 1; - } - - /* Get index of current extension block */ - extblockindex = (ah->current.offset / blocksize) / tablesize; - if (ah->current.filekey= extblockindex) - block = ah->current.block; - else - { - block = ah->header_block; - extblockindex = 0; - } - - while ((extblockindex != newextblockindex) && (block != 0)) - { - blockbuffer = getBlock(afsbase, ah->volume, block); - if (blockbuffer == NULL) - return -1; - block = OS_BE2LONG(blockbuffer->buffer[BLK_EXTENSION(ah->volume)]); - extblockindex++; - } - if (block != 0) - { - *error = 0; - old = ah->current.offset; - ah->current.block = block; - ah->current.filekey = filekey; - ah->current.byte = byte; - ah->current.offset = newoffset; - } - } - return old; + D(bug("[afs] seek(%d,%d,%d)\n", ah->header_block, offset, mode)); + *error = ERROR_SEEK_ERROR; + if (mode == OFFSET_BEGINNING) + { + newoffset = (ULONG)offset; + } + else if (mode == OFFSET_CURRENT) + { + if (offset == 0) + { + *error = 0; + return ah->current.offset; + } + newoffset = ah->current.offset+offset; + } + else if (mode == OFFSET_END) + { + newoffset = ah->filesize+offset; + } + else + return -1; + if ((LONG)newoffset >= 0) + { + blocksize = BLOCK_SIZE(volume); + if (volume->dosflags == 0) + blocksize -= (BLK_DATA_START*4); + newextblockindex = newoffset / blocksize; + tablesize = BLK_TABLE_END(volume)-BLK_TABLE_START+1; + filekey = BLK_TABLE_END(volume)-(newextblockindex % tablesize); + newextblockindex /= tablesize; /* # of extensionblock we need */ + byte = newoffset % blocksize; + if (newoffset != 0 && byte == 0 && filekey == BLK_TABLE_END(volume)) + { + newextblockindex--; + filekey = BLK_TABLE_START - 1; + } + + /* Get index of current extension block */ + extblockindex = (ah->current.offset / blocksize) / tablesize; + if (ah->current.filekey= extblockindex) + block = ah->current.block; + else + { + block = ah->header_block; + extblockindex = 0; + } + + while ((extblockindex != newextblockindex) && (block != 0)) + { + blockbuffer = getBlock(afsbase, volume, block); + if (blockbuffer == NULL) + return -1; + block = OS_BE2LONG(blockbuffer->buffer[BLK_EXTENSION(volume)]); + extblockindex++; + } + if (block != 0) + { + *error = 0; + old = ah->current.offset; + ah->current.block = block; + ah->current.filekey = filekey; + ah->current.byte = byte; + ah->current.offset = newoffset; + } + } + return old; } LONG setFileSize - (struct AFSBase* afsbase, struct AfsHandle *ah, LONG size, LONG mode, SIPTR *error) + (struct AFSBase* afsbase, struct AfsHandle *ah, LONG size, LONG mode, SIPTR *error) { +struct Volume *volume = ah->volume; LONG pos = -1, extra, savederror, newsize; struct BlockCache *headerblock; struct DateStamp ds; struct AfsHandle *ah2; - if (0 == checkValid(afsbase, ah->volume)) - { - *error = ERROR_DISK_WRITE_PROTECTED; - return -1; - } - - /* Get absolute new length */ - D(bug("[AFS] setfilesize(%ld,%ld,%ld)\n", ah->header_block, size, mode)); - *error = ERROR_SEEK_ERROR; - if (mode == OFFSET_BEGINNING) - { - newsize = 0; - } - else if (mode == OFFSET_CURRENT) - { - newsize = ah->current.offset; - } - else if (mode == OFFSET_END) - { - newsize = ah->filesize; - } - else - return -1; - - /* Ensure new length isn't negative */ - if (-size > newsize) - { - return -1; - } - newsize += size; - - /* Ensure there aren't any other filehandles positioned after the new - length */ - for (ah2 = ah->volume->locklist; ah2 != NULL; ah2 = ah2->next) - { - if (ah2 != ah && ah2->header_block == ah->header_block - && ah2->current.offset > newsize) - return -1; - } - - /* Lengthen or shorten file */ - pos = ah->current.offset; - if (newsize > ah->filesize) - { - seek(afsbase, ah, 0, OFFSET_END, error); - invalidBitmap(afsbase, ah->volume); - extra = writeData(afsbase, ah, NULL, newsize - ah->filesize, error); - validBitmap(afsbase, ah->volume); - - /* Revert to original size if we couldn't fully lengthen the file */ - if (extra < newsize - ah->filesize) - { - savederror = *error; - setFileSize(afsbase, ah, ah->filesize, OFFSET_BEGINNING, error); - *error = savederror; - return -1; - } - } - else - { - seek(afsbase, ah, newsize, OFFSET_BEGINNING, error); - deleteFileRemainder(afsbase, ah); - if (pos < newsize) - pos = newsize; - } - *error = 0; - - /* Update metadata */ - headerblock = getBlock(afsbase, ah->volume, ah->header_block); - if (headerblock != NULL) - { - ah->filesize = newsize; - headerblock->buffer[BLK_BYTE_SIZE(ah->volume)] = - OS_LONG2BE(ah->filesize); - DateStamp(&ds); - setHeaderDate(afsbase, ah->volume, headerblock, &ds); - } - seek(afsbase, ah, pos, OFFSET_BEGINNING, error); - - return newsize; + if (0 == checkValid(afsbase, volume)) + { + *error = ERROR_DISK_WRITE_PROTECTED; + return -1; + } + + /* Get absolute new length */ + D(bug("[afs] setfilesize(%d,%d,%d)\n", ah->header_block, size, mode)); + *error = ERROR_SEEK_ERROR; + if (mode == OFFSET_BEGINNING) + { + newsize = 0; + } + else if (mode == OFFSET_CURRENT) + { + newsize = ah->current.offset; + } + else if (mode == OFFSET_END) + { + newsize = ah->filesize; + } + else + return -1; + + /* Ensure new length isn't negative */ + if (-size > newsize) + { + return -1; + } + newsize += size; + + /* Ensure there aren't any other filehandles positioned after the new + length */ + for (ah2 = volume->locklist; ah2 != NULL; ah2 = ah2->next) + { + if (ah2 != ah && ah2->header_block == ah->header_block + && ah2->current.offset > newsize) + return -1; + } + + /* Lengthen or shorten file */ + pos = ah->current.offset; + if (newsize > ah->filesize) + { + seek(afsbase, ah, 0, OFFSET_END, error); + if (!invalidBitmap(afsbase, volume)) + { + *error = ERROR_UNKNOWN; + return -1; + } + extra = writeData(afsbase, ah, NULL, newsize - ah->filesize, error); + if (!validBitmap(afsbase, volume)) + { + *error = ERROR_UNKNOWN; + return -1; + } + + /* Revert to original size if we couldn't fully lengthen the file */ + if (extra < newsize - ah->filesize) + { + savederror = *error; + setFileSize(afsbase, ah, ah->filesize, OFFSET_BEGINNING, error); + *error = savederror; + return -1; + } + } + else + { + seek(afsbase, ah, newsize, OFFSET_BEGINNING, error); + if (deleteFileRemainder(afsbase, ah) != 0) + { + *error = ERROR_UNKNOWN; + return -1; + } + if (pos < newsize) + pos = newsize; + } + *error = 0; + + /* Update metadata */ + headerblock = getBlock(afsbase, volume, ah->header_block); + if (headerblock != NULL) + { + ah->filesize = newsize; + headerblock->buffer[BLK_BYTE_SIZE(volume)] = + OS_LONG2BE(ah->filesize); + DateStamp(&ds); + setHeaderDate(afsbase, volume, headerblock, &ds); + } + seek(afsbase, ah, pos, OFFSET_BEGINNING, error); + + return newsize; } diff --git a/rom/filesys/afs/filehandles2.c b/rom/filesys/afs/filehandles2.c index c352f4d7e24..1b929f72d61 100644 --- a/rom/filesys/afs/filehandles2.c +++ b/rom/filesys/afs/filehandles2.c @@ -1,6 +1,5 @@ /* - Copyright � 1995-2020, The AROS Development Team. All rights reserved. - $Id$ + Copyright (C) 1995-2026, The AROS Development Team. All rights reserved. */ /* * -date------ -name------------------- -description----------------------------- @@ -8,6 +7,10 @@ * 04-jan-2008 [Tomasz Wiszkowski] corrected tabulation */ +#ifdef DEBUG +#undef DEBUG +#endif +#define DEBUG 0 #include "os.h" #include "filehandles2.h" @@ -19,40 +22,41 @@ #include "filehandles1.h" #include "hashing.h" #include "misc.h" +#include "afs_security.h" #include "baseredef.h" #include "validator.h" /******************************************** Name : setHeaderDate Descr.: set actual date for an object - Input : volume - + Input : volume - blockbuffer - header block of object ds - datestamp to set Output: 0 for success; error code otherwise *********************************************/ ULONG setHeaderDate - ( - struct AFSBase *afsbase, - struct Volume *volume, - struct BlockCache *blockbuffer, - struct DateStamp *ds - ) + ( + struct AFSBase *afsbase, + struct Volume *volume, + struct BlockCache *blockbuffer, + struct DateStamp *ds + ) { - - D(bug - ( - "[AFS] setHeaderDate: for headerblock %lu\n", - blockbuffer->blocknum) - ); - blockbuffer->buffer[BLK_DAYS(volume)] = OS_LONG2BE(ds->ds_Days); - blockbuffer->buffer[BLK_MINS(volume)] = OS_LONG2BE(ds->ds_Minute); - blockbuffer->buffer[BLK_TICKS(volume)] = OS_LONG2BE(ds->ds_Tick); - writeBlockDeferred(afsbase, volume, blockbuffer, BLK_CHECKSUM); - blockbuffer = getBlock - (afsbase, volume, OS_BE2LONG(blockbuffer->buffer[BLK_PARENT(volume)])); - if (blockbuffer == NULL) - return ERROR_UNKNOWN; - return writeHeader(afsbase, volume, blockbuffer); +ULONG *tail; + + D(bug + ( + "[afs] setHeaderDate: for headerblock %u\n", + blockbuffer->blocknum) + ); + tail = BLK_TAILPTR(blockbuffer->buffer, volume); + putStamp(&tail[BLKO_DAYS], ds); + writeBlockDeferred(afsbase, volume, blockbuffer, BLK_CHECKSUM); + blockbuffer = getBlock + (afsbase, volume, OS_BE2LONG(tail[BLKO_PARENT])); + if (blockbuffer == NULL) + return ERROR_UNKNOWN; + return writeHeader(afsbase, volume, blockbuffer); } @@ -60,30 +64,30 @@ ULONG setHeaderDate Name : setDate Descr.: set actual date for an object Input : ah - filehandle name is relative to - name - name of object + name - name of object ds - datestamp to set Output: 0 for success; error code otherwise *********************************************/ ULONG setDate - ( - struct AFSBase *afsbase, - struct AfsHandle *ah, - CONST_STRPTR name, - struct DateStamp *ds - ) + ( + struct AFSBase *afsbase, + struct AfsHandle *ah, + CONST_STRPTR name, + struct DateStamp *ds + ) { ULONG block; struct BlockCache *blockbuffer; SIPTR error; - D(bug("[AFS] setData()\n")); - if (0 == checkValid(afsbase, ah->volume)) - return ERROR_DISK_WRITE_PROTECTED; + D(bug("[afs] setData()\n")); + if (0 == checkValid(afsbase, ah->volume)) + return ERROR_DISK_WRITE_PROTECTED; - blockbuffer = findBlock(afsbase, ah, name, &block, &error); - if (blockbuffer == NULL) - return error; - return setHeaderDate(afsbase, ah->volume, blockbuffer, ds); + blockbuffer = findBlock(afsbase, ah, name, &block, &error); + if (blockbuffer == NULL) + return error; + return setHeaderDate(afsbase, ah->volume, blockbuffer, ds); } /******************************************** @@ -95,25 +99,26 @@ SIPTR error; Output: 0 for success; error code otherwise *********************************************/ ULONG setProtect - ( - struct AFSBase *afsbase, - struct AfsHandle *ah, - CONST_STRPTR name, - ULONG mask - ) + ( + struct AFSBase *afsbase, + struct AfsHandle *ah, + CONST_STRPTR name, + ULONG mask + ) { +struct Volume *volume = ah->volume; ULONG block; struct BlockCache *blockbuffer; SIPTR error; - D(bug("[AFS] setProtect(ah,%s,%ld)\n", name, mask)); - if (0 == checkValid(afsbase, ah->volume)) - return ERROR_DISK_WRITE_PROTECTED; - blockbuffer = findBlock(afsbase, ah, name, &block, &error); - if (blockbuffer == NULL) - return error; - blockbuffer->buffer[BLK_PROTECT(ah->volume)] = OS_LONG2BE(mask); - return writeHeader(afsbase, ah->volume, blockbuffer); + D(bug("[afs] setProtect(ah,%s,%d)\n", name, mask)); + if (0 == checkValid(afsbase, volume)) + return ERROR_DISK_WRITE_PROTECTED; + blockbuffer = findBlock(afsbase, ah, name, &block, &error); + if (blockbuffer == NULL) + return error; + blockbuffer->buffer[BLK_PROTECT(volume)] = OS_LONG2BE(mask); + return writeHeader(afsbase, volume, blockbuffer); } /******************************************** @@ -125,28 +130,29 @@ SIPTR error; Output: 0 for success; error code otherwise *********************************************/ ULONG setComment - (struct AFSBase *afsbase, struct AfsHandle *ah, CONST_STRPTR name, - CONST_STRPTR comment) + (struct AFSBase *afsbase, struct AfsHandle *ah, CONST_STRPTR name, + CONST_STRPTR comment) { +struct Volume *volume = ah->volume; ULONG block; struct BlockCache *blockbuffer; SIPTR error; - D(bug("[AFS] setComment(ah,%s,%s)\n", name, comment)); - if (0 == checkValid(afsbase, ah->volume)) - return ERROR_DISK_WRITE_PROTECTED; - if (strlen(comment) >= MAXCOMMENTLENGTH) - return ERROR_COMMENT_TOO_BIG; - blockbuffer = findBlock(afsbase, ah, name, &block, &error); - if (blockbuffer == NULL) - return error; - StrCpyToBstr - ( - comment, - (APTR)((char *)blockbuffer->buffer+(BLK_COMMENT_START(ah->volume)*4)), - MAX_COMMENT_LENGTH - ); - return writeHeader(afsbase, ah->volume, blockbuffer); + D(bug("[afs] setComment(ah,%s,%s)\n", name, comment)); + if (0 == checkValid(afsbase, volume)) + return ERROR_DISK_WRITE_PROTECTED; + if (strlen(comment) >= MAXCOMMENTLENGTH) + return ERROR_COMMENT_TOO_BIG; + blockbuffer = findBlock(afsbase, ah, name, &block, &error); + if (blockbuffer == NULL) + return error; + StrCpyToBstr + ( + comment, + (APTR)((char *)blockbuffer->buffer+(BLK_COMMENT_START(volume)*4)), + MAX_COMMENT_LENGTH + ); + return writeHeader(afsbase, volume, blockbuffer); } /************************************************ @@ -156,37 +162,100 @@ SIPTR error; (directory itself (head) or last block which HASHCHAIN points to the entry to unlink entry - entry to unlink - Output: - + Output: - Note : unlink is only done in buffers nothing is written to disk! ************************************************/ void unLinkBlock - ( - struct AFSBase *afsbase, - struct Volume *volume, - struct BlockCache *lastentry, - struct BlockCache *entry - ) + ( + struct AFSBase *afsbase, + struct Volume *volume, + struct BlockCache *lastentry, + struct BlockCache *entry + ) { ULONG key; - D(bug("[AFS] unlinkBlock: unlinking %lu\n", entry->blocknum)); - /* find the "member" where entry is linked - ->linked into hashchain or hashtable */ - key = BLK_HASHCHAIN(volume); - if (OS_BE2LONG(lastentry->buffer[key])!=entry->blocknum) - { - for (key = BLK_TABLE_START; key<=BLK_TABLE_END(volume); key++) - { - if (OS_BE2LONG(lastentry->buffer[key]) == entry->blocknum) - break; - } - } - /* unlink block */ - lastentry->buffer[key] = entry->buffer[BLK_HASHCHAIN(volume)]; - lastentry->buffer[BLK_CHECKSUM] = 0; - lastentry->buffer[BLK_CHECKSUM] = - OS_LONG2BE(0-calcChkSum(volume->SizeBlock, lastentry->buffer)); + D(bug("[afs] unlinkBlock: unlinking %u\n", entry->blocknum)); + /* find the "member" where entry is linked + ->linked into hashchain or hashtable */ + key = BLK_HASHCHAIN(volume); + if (OS_BE2LONG(lastentry->buffer[key])!=entry->blocknum) + { + for (key = BLK_TABLE_START; key<=BLK_TABLE_END(volume); key++) + { + if (OS_BE2LONG(lastentry->buffer[key]) == entry->blocknum) + break; + } + } + /* unlink block */ + lastentry->buffer[key] = entry->buffer[BLK_HASHCHAIN(volume)]; + lastentry->buffer[BLK_CHECKSUM] = 0; + lastentry->buffer[BLK_CHECKSUM] = + OS_LONG2BE(0-calcChkSum(volume->SizeBlock, lastentry->buffer)); +} + +/* + * Free the data blocks listed in a header/extension block from "key" + * downwards, then every following extension block and its data blocks. + * *block is the pinned block to start with and, on success, the pinned + * last block of the chain. On failure everything is released (including + * "prior", if given, and the bitmap) and ERROR_UNKNOWN is returned. + */ +static ULONG freeFileBlocks + ( + struct AFSBase *afsbase, + struct Volume *volume, + struct BlockCache **block, + ULONG key, + struct BlockCache *prior + ) +{ +struct BlockCache *blockbuffer = *block; + + for (;;) + { + D(bug("[afs] extensionblock=%u\n", blockbuffer->blocknum)); + while (key >= BLK_TABLE_START && blockbuffer->buffer[key] != 0) + { + if (!markBlock(afsbase, volume, + OS_BE2LONG(blockbuffer->buffer[key]), -1)) + goto mark_error; + key--; + } + if (blockbuffer->buffer[BLK_EXTENSION(volume)] == 0) + break; + /* get next extensionblock */ + blockbuffer->flags &= ~BCF_USED; + blockbuffer = getBlock + ( + afsbase, + volume, + OS_BE2LONG(blockbuffer->buffer[BLK_EXTENSION(volume)]) + ); + if (blockbuffer == NULL || calcChkSum(volume->SizeBlock, blockbuffer->buffer)) + { + if (prior != NULL) + prior->flags &= ~BCF_USED; + releaseBitmap(volume); + if (blockbuffer != NULL && showError(afsbase, ERR_CHECKSUM)) + launchValidator(afsbase, volume); + return ERROR_UNKNOWN; + } + blockbuffer->flags |= BCF_USED; + if (!markBlock(afsbase, volume, blockbuffer->blocknum, -1)) + goto mark_error; + key = BLK_TABLE_END(volume); + } + *block = blockbuffer; + return 0; + +mark_error: + releaseBitmap(volume); + blockbuffer->flags &= ~BCF_USED; + if (prior != NULL) + prior->flags &= ~BCF_USED; + return ERROR_UNKNOWN; } /******************************************** @@ -197,106 +266,91 @@ ULONG key; Output: 0 for success; error code otherwise *********************************************/ ULONG deleteObject(struct AFSBase *afsbase, struct AfsHandle *ah, - CONST_STRPTR name) + CONST_STRPTR name) { +struct Volume *volume = ah->volume; ULONG lastblock,key; struct BlockCache *blockbuffer, *priorbuffer; SIPTR error; - D(bug("[AFS] delete(ah,%s)\n", name)); - /* - * check disk validity *first* - * it may turn out, that during validation, invalid entry gets deleted either way. - */ - if (0 == checkValid(afsbase, ah->volume)) - return ERROR_DISK_WRITE_PROTECTED; - blockbuffer = findBlock(afsbase, ah, name, &lastblock, &error); - if (blockbuffer == NULL) - return error; - blockbuffer = findBlock(afsbase, ah, name, &lastblock, &error); - if (findHandle(ah->volume, blockbuffer->blocknum) != NULL) - return ERROR_OBJECT_IN_USE; - if (OS_BE2LONG(blockbuffer->buffer[BLK_PROTECT(ah->volume)]) & FIBF_DELETE) - return ERROR_DELETE_PROTECTED; - /* if we try to delete a directory, check if it is empty */ - if ( - OS_BE2LONG - (blockbuffer->buffer[BLK_SECONDARY_TYPE(ah->volume)]) == ST_USERDIR - ) - { - for (key=BLK_TABLE_START; key<=BLK_TABLE_END(ah->volume); key++) - { - if (blockbuffer->buffer[key] != 0) - return ERROR_DIRECTORY_NOT_EMPTY; - } - } - blockbuffer->flags |= BCF_USED; - priorbuffer = getBlock(afsbase, ah->volume, lastblock); - if (priorbuffer == NULL) - { - blockbuffer->flags &= ~BCF_USED; - return ERROR_UNKNOWN; - } - if (calcChkSum(ah->volume->SizeBlock, priorbuffer->buffer) != 0) - { - blockbuffer->flags &= ~BCF_USED; - if (showError(afsbase, ERR_CHECKSUM, priorbuffer->blocknum)) - launchValidator(afsbase, ah->volume); - return ERROR_UNKNOWN; - } - priorbuffer->flags |= BCF_USED; - unLinkBlock(afsbase, ah->volume, priorbuffer, blockbuffer); - invalidBitmap(afsbase, ah->volume); - writeBlock(afsbase, ah->volume, priorbuffer, -1); - markBlock(afsbase, ah->volume, blockbuffer->blocknum, -1); - if ( - OS_BE2LONG - (blockbuffer->buffer[BLK_SECONDARY_TYPE(ah->volume)]) == ST_FILE - ) - { - for (;;) - { - D(bug("[AFS] extensionblock=%lu\n", blockbuffer->blocknum)); - for - ( - key = BLK_TABLE_END(ah->volume); - (key >= BLK_TABLE_START) && (blockbuffer->buffer[key]!=0); - key-- - ) - { - markBlock - (afsbase, ah->volume, OS_BE2LONG(blockbuffer->buffer[key]), -1); - } - if (blockbuffer->buffer[BLK_EXTENSION(ah->volume)] == 0) - break; - /* get next extensionblock */ - blockbuffer->flags &= ~BCF_USED; - blockbuffer = getBlock - ( - afsbase, - ah->volume, - OS_BE2LONG(blockbuffer->buffer[BLK_EXTENSION(ah->volume)]) - ); - if (blockbuffer == NULL) - { - priorbuffer->flags &= ~BCF_USED; - return ERROR_UNKNOWN; - } - if (calcChkSum(ah->volume->SizeBlock, blockbuffer->buffer)) - { - priorbuffer->flags &= ~BCF_USED; - if (showError(afsbase, ERR_CHECKSUM)) - launchValidator(afsbase, ah->volume); - return ERROR_UNKNOWN; - } - blockbuffer->flags |= BCF_USED; - markBlock(afsbase, ah->volume, blockbuffer->blocknum, -1); - } - } - validBitmap(afsbase, ah->volume); - blockbuffer->flags &= ~BCF_USED; - priorbuffer->flags &= ~BCF_USED; - return 0; + D(bug("[afs] delete(ah,%s)\n", name)); + /* + * check disk validity *first* + * it may turn out, that during validation, invalid entry gets deleted either way. + */ + if (0 == checkValid(afsbase, volume)) + return ERROR_DISK_WRITE_PROTECTED; + blockbuffer = findBlock(afsbase, ah, name, &lastblock, &error); + if (blockbuffer == NULL) + return error; + if (findHandle(volume, blockbuffer->blocknum) != NULL) + return ERROR_OBJECT_IN_USE; + if (OS_BE2LONG(blockbuffer->buffer[BLK_PROTECT(volume)]) & FIBF_DELETE) + return ERROR_DELETE_PROTECTED; + /* if we try to delete a directory, check if it is empty */ + if ( + OS_BE2LONG + (blockbuffer->buffer[BLK_SECONDARY_TYPE(volume)]) == ST_USERDIR + ) + { + for (key=BLK_TABLE_START; key<=BLK_TABLE_END(volume); key++) + { + if (blockbuffer->buffer[key] != 0) + return ERROR_DIRECTORY_NOT_EMPTY; + } + } + blockbuffer->flags |= BCF_USED; + priorbuffer = getBlock(afsbase, volume, lastblock); + if (priorbuffer == NULL) + { + blockbuffer->flags &= ~BCF_USED; + return ERROR_UNKNOWN; + } + if (calcChkSum(volume->SizeBlock, priorbuffer->buffer) != 0) + { + blockbuffer->flags &= ~BCF_USED; + if (showError(afsbase, ERR_CHECKSUM, priorbuffer->blocknum)) + launchValidator(afsbase, volume); + return ERROR_UNKNOWN; + } + priorbuffer->flags |= BCF_USED; + if (!invalidBitmap(afsbase, volume)) + { + priorbuffer->flags &= ~BCF_USED; + blockbuffer->flags &= ~BCF_USED; + return ERROR_UNKNOWN; + } + unLinkBlock(afsbase, volume, priorbuffer, blockbuffer); + if (!writeBlock(afsbase, volume, priorbuffer, -1)) + { + releaseBitmap(volume); + priorbuffer->flags &= ~BCF_USED; + blockbuffer->flags &= ~BCF_USED; + return ERROR_UNKNOWN; + } + if (!markBlock(afsbase, volume, blockbuffer->blocknum, -1)) + goto delete_error; + if ( + OS_BE2LONG + (blockbuffer->buffer[BLK_SECONDARY_TYPE(volume)]) == ST_FILE + && freeFileBlocks(afsbase, volume, &blockbuffer, + BLK_TABLE_END(volume), priorbuffer) != 0 + ) + return ERROR_UNKNOWN; + if (!validBitmap(afsbase, volume)) + { + blockbuffer->flags &= ~BCF_USED; + priorbuffer->flags &= ~BCF_USED; + return ERROR_UNKNOWN; + } + blockbuffer->flags &= ~BCF_USED; + priorbuffer->flags &= ~BCF_USED; + return 0; +delete_error: + releaseBitmap(volume); + blockbuffer->flags &= ~BCF_USED; + priorbuffer->flags &= ~BCF_USED; + return ERROR_UNKNOWN; } /******************************************** @@ -307,56 +361,36 @@ SIPTR error; *********************************************/ ULONG deleteFileRemainder(struct AFSBase *afsbase, struct AfsHandle *ah) { +struct Volume *volume = ah->volume; ULONG key; struct BlockCache *blockbuffer; - invalidBitmap(afsbase, ah->volume); - - blockbuffer = getBlock(afsbase, ah->volume, ah->current.block); - blockbuffer->flags |= BCF_USED; - - /* Start with the first block that will be wholly unused afterwards */ - key = ah->current.filekey; - if (ah->current.byte != 0) - key--; - - while (TRUE) - { - D(bug("[AFS] extensionblock=%lu\n", blockbuffer->blocknum)); - while (key >= BLK_TABLE_START && blockbuffer->buffer[key] != 0) - { - markBlock(afsbase, ah->volume, - OS_BE2LONG(blockbuffer->buffer[key]), -1); - key--; - } - if (blockbuffer->buffer[BLK_EXTENSION(ah->volume)] == 0) - break; - /* get next extensionblock */ - blockbuffer->flags &= ~BCF_USED; - blockbuffer = getBlock - ( - afsbase, - ah->volume, - OS_BE2LONG(blockbuffer->buffer[BLK_EXTENSION(ah->volume)]) - ); - if (blockbuffer == NULL) - { - return ERROR_UNKNOWN; - } - if (calcChkSum(ah->volume->SizeBlock, blockbuffer->buffer)) - { - if (showError(afsbase, ERR_CHECKSUM)) - launchValidator(afsbase, ah->volume); - return ERROR_UNKNOWN; - } - blockbuffer->flags |= BCF_USED; - markBlock(afsbase, ah->volume, blockbuffer->blocknum, -1); - key = BLK_TABLE_END(ah->volume); - } - - validBitmap(afsbase, ah->volume); - blockbuffer->flags &= ~BCF_USED; - return 0; + if (!invalidBitmap(afsbase, volume)) + return ERROR_UNKNOWN; + + blockbuffer = getBlock(afsbase, volume, ah->current.block); + if (blockbuffer == NULL) + { + releaseBitmap(volume); + return ERROR_UNKNOWN; + } + blockbuffer->flags |= BCF_USED; + + /* Start with the first block that will be wholly unused afterwards */ + key = ah->current.filekey; + if (ah->current.byte != 0) + key--; + + if (freeFileBlocks(afsbase, volume, &blockbuffer, key, NULL) != 0) + return ERROR_UNKNOWN; + + if (!validBitmap(afsbase, volume)) + { + blockbuffer->flags &= ~BCF_USED; + return ERROR_UNKNOWN; + } + blockbuffer->flags &= ~BCF_USED; + return 0; } /******************************************** @@ -372,53 +406,55 @@ struct BlockCache *blockbuffer; NULL if error *********************************************/ struct BlockCache *linkNewBlock - ( - struct AFSBase *afsbase, - struct Volume *volume, - struct BlockCache *dir, - struct BlockCache *file - ) + ( + struct AFSBase *afsbase, + struct Volume *volume, + struct BlockCache *dir, + struct BlockCache *file + ) { ULONG key; /* parent; */ UBYTE buffer[volume->FNameMax + 1]; CONST_FSBSTR name; - - SetMem(buffer, 0, volume->FNameMax + 1); - file->buffer[BLK_PARENT(volume)] = OS_LONG2BE(dir->blocknum); - D(bug("[AFS] linkNewBlock: linking block %ld\n", file->blocknum)); - name = (CONST_FSBSTR)((char *)file->buffer+(BLK_FILENAME_START(volume)*4)); - StrCpyFromBstr(name, buffer, sizeof(buffer) - 1); - - key = getHashKey - (buffer, volume->SizeBlock-56, volume->dosflags)+BLK_TABLE_START; - /* sort in ascending order */ - if ( - (dir->buffer[key] != 0) && - (OS_BE2LONG(dir->buffer[key]) < file->blocknum)) - { - dir = getBlock(afsbase, volume, OS_BE2LONG(dir->buffer[key])); - if (dir == NULL) - return NULL; - key = BLK_HASHCHAIN(volume); - while ( - (dir->buffer[key] != 0) && - (OS_BE2LONG(dir->buffer[key]) < file->blocknum) - ) - { - dir = getBlock(afsbase, volume, OS_BE2LONG(dir->buffer[key])); - if (dir == NULL) - return NULL; - } - } - file->buffer[BLK_HASHCHAIN(volume)] = dir->buffer[key]; - dir->buffer[key] = OS_LONG2BE(file->blocknum); - file->buffer[BLK_CHECKSUM] = 0; - file->buffer[BLK_CHECKSUM] = - OS_LONG2BE(0-calcChkSum(volume->SizeBlock,file->buffer)); - dir->buffer[BLK_CHECKSUM] = 0; - dir->buffer[BLK_CHECKSUM] = - OS_LONG2BE(0-calcChkSum(volume->SizeBlock,dir->buffer)); - return dir; +ULONG *filetail; + + SetMem(buffer, 0, volume->FNameMax + 1); + filetail = BLK_TAILPTR(file->buffer, volume); + filetail[BLKO_PARENT] = OS_LONG2BE(dir->blocknum); + D(bug("[afs] linkNewBlock: linking block %d\n", file->blocknum)); + name = (CONST_FSBSTR)&filetail[BLKO_FILENAME_START]; + StrCpyFromBstr(name, buffer, sizeof(buffer) - 1); + + key = getHashKey + (buffer, volume->SizeBlock-56, volume->dosflags)+BLK_TABLE_START; + /* sort in ascending order */ + if ( + (dir->buffer[key] != 0) && + (OS_BE2LONG(dir->buffer[key]) < file->blocknum)) + { + dir = getBlock(afsbase, volume, OS_BE2LONG(dir->buffer[key])); + if (dir == NULL) + return NULL; + key = BLK_HASHCHAIN(volume); + while ( + (dir->buffer[key] != 0) && + (OS_BE2LONG(dir->buffer[key]) < file->blocknum) + ) + { + dir = getBlock(afsbase, volume, OS_BE2LONG(dir->buffer[key])); + if (dir == NULL) + return NULL; + } + } + filetail[BLKO_HASHCHAIN] = dir->buffer[key]; + dir->buffer[key] = OS_LONG2BE(file->blocknum); + file->buffer[BLK_CHECKSUM] = 0; + file->buffer[BLK_CHECKSUM] = + OS_LONG2BE(0-calcChkSum(volume->SizeBlock,file->buffer)); + dir->buffer[BLK_CHECKSUM] = 0; + dir->buffer[BLK_CHECKSUM] = + OS_LONG2BE(0-calcChkSum(volume->SizeBlock,dir->buffer)); + return dir; } /******************************************** @@ -436,27 +472,37 @@ CONST_FSBSTR name; pointer to a struct BlockCache otherwise *********************************************/ struct BlockCache *getDirBlockBuffer - ( - struct AFSBase *afsbase, - struct AfsHandle *ah, - CONST_STRPTR name, - STRPTR entryname, - SIPTR *error - ) + ( + struct AFSBase *afsbase, + struct AfsHandle *ah, + CONST_STRPTR name, + STRPTR entryname, + SIPTR *error + ) { ULONG block,len; CONST_STRPTR end; UBYTE buffer[256]; - end = PathPart(name); - if (end[0] == '/') - end++; - CopyMem(name, buffer, end-name); - buffer[end-name] = 0; - len = strlen(name)+name-end; - CopyMem(end, entryname, len); /* skip slash or colon */ - entryname[len] = 0; - return findBlock(afsbase, ah, buffer, &block, error); + end = PathPart(name); + if (end[0] == '/') + end++; + len = strlen(name)+name-end; + /* + * Every caller passes a 34-byte entryname, and FFS names are at most + * MAX_NAME_LENGTH - 1 characters: a longer component, or a path + * longer than buffer, used to overrun the handler's stack. + */ + if ((ULONG)(end-name) >= sizeof(buffer) || len >= MAX_NAME_LENGTH) + { + *error = ERROR_INVALID_COMPONENT_NAME; + return NULL; + } + CopyMem(name, buffer, end-name); + buffer[end-name] = 0; + CopyMem(end, entryname, len); /* skip slash or colon */ + entryname[len] = 0; + return findBlock(afsbase, ah, buffer, &block, error); } /******************************************** @@ -468,153 +514,159 @@ UBYTE buffer[256]; Output: 0 for success; error code otherwise *********************************************/ ULONG renameObject - ( - struct AFSBase *afsbase, - struct AfsHandle *dirah, - CONST_STRPTR oname, - CONST_STRPTR newname - ) + ( + struct AFSBase *afsbase, + struct AfsHandle *dirah, + CONST_STRPTR oname, + CONST_STRPTR newname + ) { -struct BlockCache *lastlink,*oldfile,*existingfile,*dirblock; +struct Volume *volume = dirah->volume; +struct BlockCache *lastlink = NULL,*oldfile,*existingfile,*dirblock; ULONG block,dirblocknum,lastblock; UBYTE newentryname[34]; SIPTR error; - D(bug("[AFS] rename(%ld,%s,%s)\n", dirah->header_block, oname, newname)); - if (0 == checkValid(afsbase, dirah->volume)) - return ERROR_DISK_WRITE_PROTECTED; - dirblock = getDirBlockBuffer(afsbase, dirah, newname, newentryname, &error); - if (dirblock == NULL) - return error; - dirblocknum = dirblock->blocknum; - D(bug("[AFS] dir is on block %ld\n", dirblocknum)); - oldfile = findBlock(afsbase, dirah, oname, &lastblock, &error); - if (oldfile == NULL) - return error; - oldfile->flags |= BCF_USED; - existingfile = getHeaderBlock(afsbase, dirah->volume, newentryname, - dirblock, &block, &error); - if (existingfile != NULL && existingfile->blocknum != oldfile->blocknum) - { - dirblock->flags &= ~BCF_USED; - return ERROR_OBJECT_EXISTS; - } - /* do we move a directory? */ - if (OS_BE2LONG(oldfile->buffer[BLK_SECONDARY_TYPE(dirah->volume)])==ST_USERDIR) - { - /* is newdirblock child of olock/oname */ - dirblock = getBlock(afsbase, dirah->volume, dirblocknum); - if (dirblock == NULL) - { - oldfile->flags &= ~BCF_USED; - return ERROR_UNKNOWN; - } - while ((block = OS_BE2LONG(dirblock->buffer[BLK_PARENT(dirah->volume)]))) - { - if (block == oldfile->blocknum) - { - oldfile->flags &= ~BCF_USED; - return ERROR_OBJECT_IN_USE; - } - dirblock = getBlock(afsbase, dirah->volume, block); - if (dirblock == NULL) - { - oldfile->flags &= ~BCF_USED; - return ERROR_UNKNOWN; - } - } - } - lastlink = getBlock(afsbase, dirah->volume, lastblock); - if (lastlink == NULL) - { - oldfile->flags &= ~BCF_USED; - return ERROR_UNKNOWN; - } - lastlink->flags |= BCF_USED; - unLinkBlock(afsbase, dirah->volume, lastlink, oldfile); - /* rename in same dir ? */ - if (lastlink->blocknum == dirblocknum) - { - /* use same buffers! */ - dirblock = lastlink; - } - /* otherwise we use different blocks */ - else - { - dirblock = getBlock(afsbase, dirah->volume, dirblocknum); - if (dirblock == NULL) - { - oldfile->flags &= ~BCF_USED; - lastlink->flags &= ~BCF_USED; - return ERROR_UNKNOWN; - } - } - if ( - ( - OS_BE2LONG - ( - dirblock->buffer[BLK_SECONDARY_TYPE(dirah->volume)] - ) != ST_USERDIR - ) && - ( - OS_BE2LONG - ( - dirblock->buffer[BLK_SECONDARY_TYPE(dirah->volume)] - ) != ST_ROOT - ) - ) - { - oldfile->flags &= ~BCF_USED; - lastlink->flags &= ~BCF_USED; - return ERROR_OBJECT_WRONG_TYPE; - } - StrCpyToBstr - ( - newentryname, - (APTR)((char *)oldfile->buffer+(BLK_FILENAME_START(dirah->volume)*4)), - MAX_NAME_LENGTH - ); - dirblock = linkNewBlock(afsbase, dirah->volume, dirblock, oldfile); - if (dirblock == NULL) - { - oldfile->flags &= ~BCF_USED; - lastlink->flags &= ~BCF_USED; - return ERROR_UNKNOWN; - } - /* concurrent access if newdir=rootblock! */ - dirblock->flags |= BCF_USED; - /* - mark it as used, so that this buffer isn't - used in invalidating volume! - */ - if (!setBitmapFlag(afsbase, dirah->volume, 0)) - { - oldfile->flags &= ~BCF_USED; - lastlink->flags &= ~BCF_USED; - dirblock->flags &= ~BCF_USED; - return ERROR_UNKNOWN; - } - /* now we can release that buffer */ - dirblock->flags &= ~BCF_USED; - /* - syscrash after this: 2 dirs pointing to the same - dir and one wrong linked entry->recoverable - */ - writeBlock(afsbase, dirah->volume, dirblock, -1); - /* - syscrash after this: directory pointing is now - correct but one wrong linked entry->recoverable - */ - writeBlock(afsbase, dirah->volume, lastlink, -1); - writeBlock(afsbase, dirah->volume, oldfile, -1); - oldfile->flags &= ~BCF_USED; - lastlink->flags &= ~BCF_USED; - /* - if newdir=rootblock we now write the correct - (changed) buffer back - */ - setBitmapFlag(afsbase, dirah->volume, -1); - return 0; + D(bug("[afs] rename(%d,%s,%s)\n", dirah->header_block, oname, newname)); + if (0 == checkValid(afsbase, volume)) + return ERROR_DISK_WRITE_PROTECTED; + dirblock = getDirBlockBuffer(afsbase, dirah, newname, newentryname, &error); + if (dirblock == NULL) + return error; + dirblocknum = dirblock->blocknum; + D(bug("[afs] dir is on block %d\n", dirblocknum)); + oldfile = findBlock(afsbase, dirah, oname, &lastblock, &error); + if (oldfile == NULL) + return error; + oldfile->flags |= BCF_USED; + existingfile = getHeaderBlock(afsbase, volume, newentryname, + dirblock, &block, &error); + if (existingfile == NULL && error != ERROR_OBJECT_NOT_FOUND) + goto rename_exit; + if (existingfile != NULL && existingfile->blocknum != oldfile->blocknum) + { + /* Release the source header too, as every other exit does. */ + dirblock->flags &= ~BCF_USED; + error = ERROR_OBJECT_EXISTS; + goto rename_exit; + } + /* every failure from here on is ERROR_UNKNOWN unless said otherwise */ + error = ERROR_UNKNOWN; + /* do we move a directory? */ + if (OS_BE2LONG(oldfile->buffer[BLK_SECONDARY_TYPE(volume)])==ST_USERDIR) + { + /* is newdirblock olock/oname itself, or a child of it */ + if (dirblocknum == oldfile->blocknum) + { + error = ERROR_OBJECT_IN_USE; + goto rename_exit; + } + dirblock = getBlock(afsbase, volume, dirblocknum); + if (dirblock == NULL) + goto rename_exit; + while ((block = OS_BE2LONG(dirblock->buffer[BLK_PARENT(volume)]))) + { + if (block == oldfile->blocknum) + { + error = ERROR_OBJECT_IN_USE; + goto rename_exit; + } + dirblock = getBlock(afsbase, volume, block); + if (dirblock == NULL) + goto rename_exit; + } + } + lastlink = getBlock(afsbase, volume, lastblock); + if (lastlink == NULL) + goto rename_exit; + lastlink->flags |= BCF_USED; + unLinkBlock(afsbase, volume, lastlink, oldfile); + /* rename in same dir ? */ + if (lastlink->blocknum == dirblocknum) + { + /* use same buffers! */ + dirblock = lastlink; + } + /* otherwise we use different blocks */ + else + { + dirblock = getBlock(afsbase, volume, dirblocknum); + if (dirblock == NULL) + goto rename_exit; + } + if ( + ( + OS_BE2LONG + ( + dirblock->buffer[BLK_SECONDARY_TYPE(volume)] + ) != ST_USERDIR + ) && + ( + OS_BE2LONG + ( + dirblock->buffer[BLK_SECONDARY_TYPE(volume)] + ) != ST_ROOT + ) + ) + { + error = ERROR_OBJECT_WRONG_TYPE; + goto rename_exit; + } + StrCpyToBstr + ( + newentryname, + (APTR)((char *)oldfile->buffer+(BLK_FILENAME_START(volume)*4)), + MAX_NAME_LENGTH + ); + dirblock = linkNewBlock(afsbase, volume, dirblock, oldfile); + if (dirblock == NULL) + goto rename_exit; + /* concurrent access if newdir=rootblock! */ + dirblock->flags |= BCF_USED; + /* + mark it as used, so that this buffer isn't + used in invalidating volume! + */ + if (!setBitmapFlag(afsbase, volume, 0)) + { + dirblock->flags &= ~BCF_USED; + goto rename_exit; + } + /* now we can release that buffer */ + dirblock->flags &= ~BCF_USED; + /* + syscrash after this: 2 dirs pointing to the same + dir and one wrong linked entry->recoverable + */ + if (!writeBlock(afsbase, volume, dirblock, -1)) + goto rename_error; + /* + syscrash after this: directory pointing is now + correct but one wrong linked entry->recoverable + */ + if (!writeBlock(afsbase, volume, lastlink, -1) + || !writeBlock(afsbase, volume, oldfile, -1)) + goto rename_error; + oldfile->flags &= ~BCF_USED; + lastlink->flags &= ~BCF_USED; + /* + if newdir=rootblock we now write the correct + (changed) buffer back + */ + if (!setBitmapFlag(afsbase, volume, -1)) + return ERROR_UNKNOWN; + return 0; + +rename_error: + /* Preserve all modified headers for an explicit retry. */ + writeBlockDeferred(afsbase, volume, dirblock, BLK_CHECKSUM); + writeBlockDeferred(afsbase, volume, lastlink, BLK_CHECKSUM); + writeBlockDeferred(afsbase, volume, oldfile, BLK_CHECKSUM); +rename_exit: + oldfile->flags &= ~BCF_USED; + if (lastlink != NULL) + lastlink->flags &= ~BCF_USED; + return error; } /******************************************** @@ -632,91 +684,111 @@ SIPTR error; created object otherwise *********************************************/ struct BlockCache *createNewEntry - ( - struct AFSBase *afsbase, - struct Volume *volume, - ULONG entrytype, - CONST_STRPTR entryname, - struct BlockCache *dirblock, - ULONG protection, - SIPTR *error - ) + ( + struct AFSBase *afsbase, + struct Volume *volume, + ULONG entrytype, + CONST_STRPTR entryname, + struct BlockCache *dirblock, + ULONG protection, + SIPTR *error + ) { struct BlockCache *newblock; struct DateStamp ds; +ULONG *tail; ULONG i; - - D(bug("[AFS] createNewEntry(%ld, %s)\n", dirblock->blocknum, entryname)); - dirblock->flags |= BCF_USED; - if (getHeaderBlock(afsbase, volume, entryname, dirblock, &i, error) != NULL) - { - dirblock->flags &= ~BCF_USED; - *error = ERROR_OBJECT_EXISTS; - return NULL; - } - *error = 0; - if (!invalidBitmap(afsbase, volume)) - { - dirblock->flags &= ~BCF_USED; - return NULL; - } - i = allocBlock(afsbase, volume); - if (i == 0) - { - dirblock->flags &= ~BCF_USED; - validBitmap(afsbase, volume); - *error = ERROR_DISK_FULL; - return NULL; - } - newblock = getFreeCacheBlock(afsbase, volume, i); - if (newblock == NULL) - { - dirblock->flags &= ~BCF_USED; - validBitmap(afsbase, volume); - *error = ERROR_UNKNOWN; - return NULL; - } - newblock->flags |= BCF_USED; - newblock->buffer[BLK_PRIMARY_TYPE] = OS_LONG2BE(T_SHORT); - for (i=BLK_BLOCK_COUNT; i<=BLK_COMMENT_END(volume); i++) - newblock->buffer[i] = 0; - newblock->buffer[BLK_PROTECT(volume)] = OS_LONG2BE(protection); - DateStamp(&ds); - newblock->buffer[BLK_DAYS(volume)] = OS_LONG2BE(ds.ds_Days); - newblock->buffer[BLK_MINS(volume)] = OS_LONG2BE(ds.ds_Minute); - newblock->buffer[BLK_TICKS(volume)] = OS_LONG2BE(ds.ds_Tick); - StrCpyToBstr - ( - entryname, - (APTR)((char *)newblock->buffer+(BLK_FILENAME_START(volume)*4)), - MAX_NAME_LENGTH - ); - for (i=BLK_FILENAME_END(volume)+1; ibuffer[i] = 0; - newblock->buffer[BLK_PARENT(volume)] = OS_LONG2BE(dirblock->blocknum); - newblock->buffer[BLK_EXTENSION(volume)] = 0; - newblock->buffer[BLK_SECONDARY_TYPE(volume)] = OS_LONG2BE(entrytype); - newblock->buffer[BLK_OWN_KEY] = OS_LONG2BE(newblock->blocknum); - dirblock->flags &= ~BCF_USED; - dirblock = linkNewBlock(afsbase, volume, dirblock, newblock); - if (dirblock == NULL) - { - markBlock(afsbase, volume, newblock->blocknum, -1); - newblock->flags &= ~BCF_USED; - newblock->newness = 0; - validBitmap(afsbase, volume); - return NULL; - } - /* - if crash after this block not yet linked->block - not written to disk, bitmap corrected - */ - writeBlock(afsbase, volume, newblock, -1); - /* consistent after this */ - writeBlock(afsbase, volume, dirblock, -1); - validBitmap(afsbase, volume); - newblock->flags &= ~BCF_USED; - return newblock; +LONG j; + + D(bug("[afs] createNewEntry(%d, %s)\n", dirblock->blocknum, entryname)); + dirblock->flags |= BCF_USED; + if (getHeaderBlock(afsbase, volume, entryname, dirblock, &i, error) != NULL) + { + dirblock->flags &= ~BCF_USED; + *error = ERROR_OBJECT_EXISTS; + return NULL; + } + if (*error != ERROR_OBJECT_NOT_FOUND) + { + dirblock->flags &= ~BCF_USED; + return NULL; + } + *error = 0; + if (!invalidBitmap(afsbase, volume)) + { + dirblock->flags &= ~BCF_USED; + *error = ERROR_UNKNOWN; + return NULL; + } + i = allocBlock(afsbase, volume); + if (i == 0) + { + dirblock->flags &= ~BCF_USED; + validBitmap(afsbase, volume); + *error = ERROR_DISK_FULL; + return NULL; + } + newblock = getFreeCacheBlock(afsbase, volume, i); + if (newblock == NULL) + { + dirblock->flags &= ~BCF_USED; + validBitmap(afsbase, volume); + *error = ERROR_UNKNOWN; + return NULL; + } + newblock->flags |= BCF_USED; + tail = BLK_TAILPTR(newblock->buffer, volume); + newblock->buffer[BLK_PRIMARY_TYPE] = OS_LONG2BE(T_SHORT); + for (i=BLK_BLOCK_COUNT; i<=BLK_COMMENT_END(volume); i++) + newblock->buffer[i] = 0; + tail[BLKO_PROTECT] = OS_LONG2BE(protection); + /* multi-user: new objects belong to the creator */ + tail[BLKO_OWNER] = OS_LONG2BE(afsSecNewOwner(afsbase)); + DateStamp(&ds); + putStamp(&tail[BLKO_DAYS], &ds); + StrCpyToBstr + ( + entryname, + (APTR)&tail[BLKO_FILENAME_START], + MAX_NAME_LENGTH + ); + for (j=BLKO_FILENAME_END+1; jblocknum); + tail[BLKO_EXTENSION] = 0; + tail[BLKO_SECONDARY_TYPE] = OS_LONG2BE(entrytype); + newblock->buffer[BLK_OWN_KEY] = OS_LONG2BE(newblock->blocknum); + dirblock->flags &= ~BCF_USED; + dirblock = linkNewBlock(afsbase, volume, dirblock, newblock); + if (dirblock == NULL) + { + markBlock(afsbase, volume, newblock->blocknum, -1); + newblock->flags &= ~BCF_USED; + newblock->newness = 0; + validBitmap(afsbase, volume); + return NULL; + } + /* + if crash after this block not yet linked->block + not written to disk, bitmap corrected + */ + if (!writeBlock(afsbase, volume, newblock, -1) + || !writeBlock(afsbase, volume, dirblock, -1)) + { + writeBlockDeferred(afsbase, volume, dirblock, BLK_CHECKSUM); + newblock->flags &= ~BCF_USED; + validBitmap(afsbase, volume); /* Release bitmap while retaining invalid flag. */ + *error = ERROR_UNKNOWN; + return NULL; + } + if (!validBitmap(afsbase, volume)) + { + newblock->flags &= ~BCF_USED; + *error = ERROR_UNKNOWN; + return NULL; + } + newblock->flags &= ~BCF_USED; + return newblock; } @@ -730,33 +802,33 @@ ULONG i; NULL otherwise (global error set) *********************************************/ struct AfsHandle *createDir - ( - struct AFSBase *afsbase, - struct AfsHandle *dirah, - CONST_STRPTR filename, - ULONG protection, - SIPTR *error - ) + ( + struct AFSBase *afsbase, + struct AfsHandle *dirah, + CONST_STRPTR filename, + ULONG protection, + SIPTR *error + ) { struct AfsHandle *ah = NULL; struct BlockCache *dirblock; char dirname[34]; - D(bug("[AFS] createDir(ah,%s,%ld)\n", filename, protection)); - if (0 == checkValid(afsbase, dirah->volume)) - { - *error = ERROR_DISK_WRITE_PROTECTED; - return NULL; - } - dirblock = getDirBlockBuffer(afsbase, dirah, filename, dirname, error); - if (dirblock != NULL) - { - D(bug("[AFS] dir is on block %ld\n", dirblock->blocknum)); - dirblock = createNewEntry - (afsbase, dirah->volume, ST_USERDIR, dirname, dirblock, protection, error); - if (dirblock != NULL) - ah = getHandle(afsbase, dirah->volume, dirblock, MODE_OLDFILE, error); - } - return ah; + D(bug("[afs] createDir(ah,%s,%d)\n", filename, protection)); + if (0 == checkValid(afsbase, dirah->volume)) + { + *error = ERROR_DISK_WRITE_PROTECTED; + return NULL; + } + dirblock = getDirBlockBuffer(afsbase, dirah, filename, dirname, error); + if (dirblock != NULL) + { + D(bug("[afs] dir is on block %d\n", dirblock->blocknum)); + dirblock = createNewEntry + (afsbase, dirah->volume, ST_USERDIR, dirname, dirblock, protection, error); + if (dirblock != NULL) + ah = getHandle(afsbase, dirah->volume, dirblock, MODE_OLDFILE, error); + } + return ah; } diff --git a/rom/filesys/afs/filehandles3.c b/rom/filesys/afs/filehandles3.c index dbe589462bd..fdfe8a8a312 100644 --- a/rom/filesys/afs/filehandles3.c +++ b/rom/filesys/afs/filehandles3.c @@ -1,8 +1,11 @@ /* - Copyright � 1995-2015, The AROS Development Team. All rights reserved. - $Id$ + Copyright (C) 1995-2026, The AROS Development Team. All rights reserved. */ +#ifndef DEBUG +#define DEBUG 0 +#endif + #include #include "os.h" #include "filehandles3.h" @@ -13,7 +16,7 @@ LONG sameLock(struct AfsHandle *ah1, struct AfsHandle *ah2) { - return (ah1->header_block == ah2->header_block) ? LOCK_SAME : LOCK_DIFFERENT; + return (ah1->header_block == ah2->header_block) ? LOCK_SAME : LOCK_DIFFERENT; } static const ULONG sizes[]= @@ -25,277 +28,217 @@ static const ULONG sizes[]= offsetof(struct ExAllData,ed_Days), offsetof(struct ExAllData,ed_Comment), offsetof(struct ExAllData,ed_OwnerUID), - sizeof(struct ExAllData) + offsetof(struct ExAllData,ed_Size64) /* ED_OWNER: up to ed_OwnerGID */ }; ULONG examineEAD - ( - struct AFSBase *afsbase, - struct Volume *volume, - struct ExAllData *ead, - struct BlockCache *entryblock, - ULONG size, - ULONG mode - ) + ( + struct AFSBase *afsbase, + struct Volume *volume, + struct ExAllData *ead, + struct BlockCache *entryblock, + ULONG size, + ULONG mode + ) { -STRPTR next,end,name; +STRPTR next,end; +UBYTE *name; ULONG owner; - - next = (STRPTR)ead+sizes[mode]; - end = (STRPTR)ead+size; - - if (next > end) /* > is correct. Not >= */ - return ERROR_BUFFER_OVERFLOW; - - switch (mode) - { - case ED_OWNER : - owner = OS_BE2LONG(entryblock->buffer[BLK_OWNER(volume)]); - ead->ed_OwnerUID = owner>>16; - ead->ed_OwnerGID = owner & 0xFFFF; - case ED_COMMENT : - if (OS_BE2LONG(entryblock->buffer[BLK_SECONDARY_TYPE(volume)]) != ST_ROOT) - { - name = (STRPTR)((char *)entryblock->buffer+(BLK_COMMENT_START(volume)*4)); - if ((next+name[0]+1) > end) - return ERROR_BUFFER_OVERFLOW; - ead->ed_Comment = next; - CopyMem(name+1, ead->ed_Comment, name[0]); - ead->ed_Comment[(ULONG)name[0]] = 0; - next += name[0]+1; /* NULL-Byte */ - } - else - ead->ed_Comment = 0; - case ED_DATE : - ead->ed_Days = OS_BE2LONG(entryblock->buffer[BLK_DAYS(volume)]); - ead->ed_Mins = OS_BE2LONG(entryblock->buffer[BLK_MINS(volume)]); - ead->ed_Ticks = OS_BE2LONG(entryblock->buffer[BLK_TICKS(volume)]); - case ED_PROTECTION : - ead->ed_Prot = OS_BE2LONG(entryblock->buffer[BLK_PROTECT(volume)]); - case ED_SIZE : - ead->ed_Size = OS_BE2LONG(entryblock->buffer[BLK_BYTE_SIZE(volume)]); - case ED_TYPE : - ead->ed_Type = OS_BE2LONG(entryblock->buffer[BLK_SECONDARY_TYPE(volume)]); - case ED_NAME : - name = (STRPTR)((char *)entryblock->buffer+(BLK_FILENAME_START(volume)*4)); - if ((next+name[0]+1) > end) - return ERROR_BUFFER_OVERFLOW; - ead->ed_Name = next; - CopyMem(name+1, ead->ed_Name, name[0]); - ead->ed_Name[(ULONG)name[0]] = 0; - next += name[0]+1; /* NULL-Byte */ - case 0 : - ead->ed_Next = (struct ExAllData *)(((IPTR)next + OS_PTRALIGN - 1) & ~(OS_PTRALIGN - 1)); - } - return 0; +ULONG *tail; + + next = (STRPTR)ead+sizes[mode]; + end = (STRPTR)ead+size; + + if (next > end) /* > is correct. Not >= */ + return ERROR_BUFFER_OVERFLOW; + + tail = BLK_TAILPTR(entryblock->buffer, volume); + switch (mode) + { + case ED_OWNER : + owner = OS_BE2LONG(tail[BLKO_OWNER]); + ead->ed_OwnerUID = owner>>16; + ead->ed_OwnerGID = owner & 0xFFFF; + case ED_COMMENT : + if (OS_BE2LONG(tail[BLKO_SECONDARY_TYPE]) != ST_ROOT) + { + name = (UBYTE *)&tail[BLKO_COMMENT_START]; + if (name[0] > MAX_COMMENT_LENGTH) + return ERROR_DISK_NOT_VALIDATED; + if ((next+name[0]+1) > end) + return ERROR_BUFFER_OVERFLOW; + ead->ed_Comment = next; + CopyMem(name+1, ead->ed_Comment, name[0]); + ead->ed_Comment[(ULONG)name[0]] = 0; + next += name[0]+1; /* NULL-Byte */ + } + else + ead->ed_Comment = 0; + case ED_DATE : + ead->ed_Days = OS_BE2LONG(tail[BLKO_DAYS]); + ead->ed_Mins = OS_BE2LONG(tail[BLKO_MINS]); + ead->ed_Ticks = OS_BE2LONG(tail[BLKO_TICKS]); + case ED_PROTECTION : + ead->ed_Prot = OS_BE2LONG(tail[BLKO_PROTECT]); + case ED_SIZE : + ead->ed_Size = OS_BE2LONG(tail[BLKO_BYTE_SIZE]); + case ED_TYPE : + ead->ed_Type = OS_BE2LONG(tail[BLKO_SECONDARY_TYPE]); + case ED_NAME : + name = (UBYTE *)&tail[BLKO_FILENAME_START]; + if (name[0] > MAX_NAME_LENGTH) + return ERROR_DISK_NOT_VALIDATED; + if ((next+name[0]+1) > end) + return ERROR_BUFFER_OVERFLOW; + ead->ed_Name = next; + CopyMem(name+1, ead->ed_Name, name[0]); + ead->ed_Name[(ULONG)name[0]] = 0; + next += name[0]+1; /* NULL-Byte */ + case 0 : + ead->ed_Next = (struct ExAllData *)(((IPTR)next + OS_PTRALIGN - 1) & ~(OS_PTRALIGN - 1)); + } + return 0; } ULONG examine - ( - struct AFSBase *afsbase, - struct AfsHandle *ah, - struct ExAllData *ead, - ULONG size, - ULONG mode, - IPTR *dirpos - ) + ( + struct AFSBase *afsbase, + struct AfsHandle *ah, + struct ExAllData *ead, + ULONG size, + ULONG mode, + IPTR *dirpos + ) { struct BlockCache *entryblock; - D(bug("[AFS] examine(%ld,ead,%ld,%ld)\n",ah->header_block,size,mode)); - if (mode > ED_OWNER) - return ERROR_BAD_NUMBER; - entryblock = getBlock(afsbase, ah->volume, ah->header_block); - if (entryblock == NULL) - return ERROR_UNKNOWN; - examineEAD(afsbase, ah->volume, ead, entryblock, size, mode); - *dirpos = ah->header_block; - return 0; + D(bug("[afs] examine(%d,ead,%d,%d)\n",ah->header_block,size,mode)); + if (mode > ED_OWNER) + return ERROR_BAD_NUMBER; + entryblock = getBlock(afsbase, ah->volume, ah->header_block); + if (entryblock == NULL) + return ERROR_UNKNOWN; + { + ULONG error = examineEAD(afsbase, ah->volume, ead, entryblock, size, mode); + if (error != 0) + return error; + } + *dirpos = ah->header_block; + return 0; } ULONG getNextExamineBlock - (struct AFSBase *afsbase, struct AfsHandle *ah, ULONG *key, ULONG *pos) + (struct AFSBase *afsbase, struct AfsHandle *ah, ULONG *key, ULONG *pos) { +struct Volume *volume = ah->volume; struct BlockCache *entryblock; UBYTE cstr[34]; -STRPTR string; - - entryblock = getBlock(afsbase, ah->volume, *key); - if (entryblock == NULL) - return ERROR_UNKNOWN; - if (*key == ah->header_block) /* start examining entries in ah */ - { - *pos = BLK_TABLE_START; - } - else - { - if (entryblock->buffer[BLK_HASHCHAIN(ah->volume)] != 0) - { - /* chained entry */ - *pos = BLK_HASHCHAIN(ah->volume); - } - else - { - string = (char *)entryblock->buffer+(BLK_FILENAME_START(ah->volume)*4); - CopyMem(string+1, cstr, string[0]); - cstr[(ULONG)string[0]] = 0; - *pos = BLK_TABLE_START+getHashKey(cstr, ah->volume->SizeBlock-56, ah->volume->dosflags)+1; - if (*pos > BLK_TABLE_END(ah->volume)) - return ERROR_NO_MORE_ENTRIES; - entryblock = getBlock(afsbase, ah->volume, ah->header_block); - if (entryblock == NULL) - return ERROR_UNKNOWN; - } - } - /* in one case entryblock->buffer[i] points to a block - which should be examined next - in the other cases it may point to NULL */ - while (entryblock->buffer[*pos] == 0) - { - if (*pos == BLK_TABLE_END(ah->volume)) - return ERROR_NO_MORE_ENTRIES; - *pos += 1; - } - /* now i is on a valid position */ - *key = OS_BE2LONG(entryblock->buffer[*pos]); - return 0; +UBYTE *string; + + entryblock = getBlock(afsbase, volume, *key); + if (entryblock == NULL) + return ERROR_UNKNOWN; + if (*key == ah->header_block) /* start examining entries in ah */ + { + *pos = BLK_TABLE_START; + } + else + { + if (entryblock->buffer[BLK_HASHCHAIN(volume)] != 0) + { + /* chained entry */ + *pos = BLK_HASHCHAIN(volume); + } + else + { + string = (UBYTE *)entryblock->buffer+(BLK_FILENAME_START(volume)*4); + if (string[0] > MAX_NAME_LENGTH || string[0] >= sizeof(cstr)) + return ERROR_DISK_NOT_VALIDATED; + CopyMem(string+1, cstr, string[0]); + cstr[(ULONG)string[0]] = 0; + *pos = BLK_TABLE_START+getHashKey(cstr, volume->SizeBlock-56, volume->dosflags)+1; + if (*pos > BLK_TABLE_END(volume)) + return ERROR_NO_MORE_ENTRIES; + entryblock = getBlock(afsbase, volume, ah->header_block); + if (entryblock == NULL) + return ERROR_UNKNOWN; + } + } + /* in one case entryblock->buffer[i] points to a block + which should be examined next + in the other cases it may point to NULL */ + while (entryblock->buffer[*pos] == 0) + { + if (*pos == BLK_TABLE_END(volume)) + return ERROR_NO_MORE_ENTRIES; + *pos += 1; + } + /* now i is on a valid position */ + *key = OS_BE2LONG(entryblock->buffer[*pos]); + return 0; } -ULONG examineAll - ( - struct AFSBase *afsbase, - struct AfsHandle *ah, - struct ExAllData *ead, - struct ExAllControl *eac, - ULONG size, - ULONG mode - ) -{ -struct BlockCache *headerblock; -struct BlockCache *entryblock; -struct ExAllData *last; -ULONG error,i,block; - - D(bug("[AFS] examineAll(%ld,ead,%ld,%ld)\n",ah->header_block,size,mode)); - eac->eac_Entries = 0; - if (mode > ED_OWNER) - return ERROR_BAD_NUMBER; - headerblock = getBlock(afsbase, ah->volume, ah->header_block); - if (headerblock == NULL) - return ERROR_UNKNOWN; - /* is it a file? */ - if ((LONG)(OS_BE2LONG(headerblock->buffer[BLK_SECONDARY_TYPE(ah->volume)])) < 0) - { - error = examineEAD(afsbase, ah->volume, ead, headerblock, size, mode); - if (error == 0) - eac->eac_Entries = 1; - return error; - } - error = getNextExamineBlock(afsbase, ah, &ah->dirpos, &i); - /* FIXME: if ah->dirpos is an entry stored in a hashchain we return entries twice */ - if (error != 0) - return error; - last = ead; - /* - the contents of headerblock may have changed - by getNextExamineBlock - */ - if (headerblock->blocknum != ah->header_block) - { - headerblock = getBlock(afsbase, ah->volume, ah->header_block); - if (headerblock == NULL) - return ERROR_UNKNOWN; - } - headerblock->flags |= BCF_USED; - for (; i<=BLK_TABLE_END(ah->volume); i++) - { - if (headerblock->buffer[i] != 0) - { - block = OS_BE2LONG(headerblock->buffer[i]); - do - { - entryblock = getBlock(afsbase, ah->volume, block); - if (entryblock == NULL) - { - headerblock->flags &= ~BCF_USED; - return ERROR_UNKNOWN; - } - error = examineEAD(afsbase, ah->volume, ead, entryblock, size, mode); - if (error != 0) - { - /* stegerg: CHECK CHECK CHECK CHECK CHECK */ - if (error == ERROR_BUFFER_OVERFLOW) - { - ah->dirpos = OS_BE2LONG(headerblock->buffer[i]); - error = 0; - } - /* stegerg: END CHECK CHECK CHECK CHECK CHECK */ - - ead->ed_Next = NULL; - headerblock->flags &= ~BCF_USED; - return error; - } - size -= (ULONG)((char *)ead->ed_Next-(char *)ead); - last = ead; - ead = ead->ed_Next; - ah->dirpos = OS_BE2LONG(headerblock->buffer[i]); - block = OS_BE2LONG(entryblock->buffer[BLK_HASHCHAIN(ah->volume)]); - eac->eac_Entries++; - } while (block != 0); - } - } - last->ed_Next = NULL; - headerblock->flags &= ~BCF_USED; - return ERROR_NO_MORE_ENTRIES; -} - ULONG examineNext - (struct AFSBase *afsbase, struct AfsHandle *ah, struct FileInfoBlock *fib) + (struct AFSBase *afsbase, struct AfsHandle *ah, struct FileInfoBlock *fib) { - struct BlockCache *entryblock; - STRPTR string; - ULONG filelistentries,datablocksize,datablocks; - ULONG owner; - ULONG error,filekey; - ULONG dirkey = fib->fib_DiskKey; /* fib_DiskKey is an IPTR, so we need this conversion */ - - D(bug("[AFS] examineNext(%ld,fib)\n", ah->header_block)); - D(bug("[AFS] examineNext: diskey=%ld\n", dirkey)); - - error = getNextExamineBlock(afsbase, ah, &dirkey, &filekey); - fib->fib_DiskKey = dirkey; - if (error != 0) - return error; - /* examine the block */ - entryblock = getBlock(afsbase, ah->volume, dirkey); - if (entryblock == NULL) - return ERROR_UNKNOWN; - fib->fib_DirEntryType = - OS_BE2LONG(entryblock->buffer[BLK_SECONDARY_TYPE(ah->volume)]); - string = (char *)entryblock->buffer+(BLK_FILENAME_START(ah->volume)*4); - CopyMem(string, fib->fib_FileName, string[0]+1); - fib->fib_Protection = OS_BE2LONG(entryblock->buffer[BLK_PROTECT(ah->volume)]); - fib->fib_EntryType = fib->fib_DirEntryType; - fib->fib_Size = OS_BE2LONG(entryblock->buffer[BLK_BYTE_SIZE(ah->volume)]); - filelistentries = ah->volume->SizeBlock-56; - datablocksize = BLOCK_SIZE(ah->volume); - if (ah->volume->dosflags == 0) - datablocksize = datablocksize-24; - datablocks = ((fib->fib_Size+datablocksize-1)/datablocksize); - fib->fib_NumBlocks = - datablocks+((datablocks+filelistentries-1)/filelistentries); - fib->fib_Date.ds_Days = OS_BE2LONG(entryblock->buffer[BLK_DAYS(ah->volume)]); - fib->fib_Date.ds_Minute = OS_BE2LONG(entryblock->buffer[BLK_MINS(ah->volume)]); - fib->fib_Date.ds_Tick = OS_BE2LONG(entryblock->buffer[BLK_TICKS(ah->volume)]); - if (fib->fib_DirEntryType != ST_ROOT) - { - string = (char *)entryblock->buffer+(BLK_COMMENT_START(ah->volume)*4); - CopyMem(string, fib->fib_Comment, string[0] + 1); - } - owner = OS_BE2LONG(entryblock->buffer[BLK_OWNER(ah->volume)]); - fib->fib_OwnerUID = owner>>16; - fib->fib_OwnerGID = owner & 0xFFFF; - return 0; + struct Volume *volume = ah->volume; + struct BlockCache *entryblock; + UBYTE *string; + ULONG *tail; + ULONG filelistentries,datablocksize,datablocks; + ULONG owner, commentlength; + ULONG error,filekey; + ULONG dirkey = fib->fib_DiskKey; /* fib_DiskKey is an IPTR, so we need this conversion */ + + D(bug("[afs] examineNext(%d,fib)\n", ah->header_block)); + D(bug("[afs] examineNext: diskey=%d\n", dirkey)); + + error = getNextExamineBlock(afsbase, ah, &dirkey, &filekey); + fib->fib_DiskKey = dirkey; + if (error != 0) + return error; + /* examine the block */ + entryblock = getBlock(afsbase, volume, dirkey); + if (entryblock == NULL) + return ERROR_UNKNOWN; + tail = BLK_TAILPTR(entryblock->buffer, volume); + string = (UBYTE *)&tail[BLKO_FILENAME_START]; + if (string[0] > MAX_NAME_LENGTH) + return ERROR_DISK_NOT_VALIDATED; + string = (UBYTE *)&tail[BLKO_COMMENT_START]; + if (OS_BE2LONG(tail[BLKO_SECONDARY_TYPE]) != ST_ROOT + && string[0] > MAX_COMMENT_LENGTH) + return ERROR_DISK_NOT_VALIDATED; + fib->fib_DirEntryType = + OS_BE2LONG(tail[BLKO_SECONDARY_TYPE]); + string = (UBYTE *)&tail[BLKO_FILENAME_START]; + CopyMem(string, fib->fib_FileName, string[0]+1); + fib->fib_Protection = OS_BE2LONG(tail[BLKO_PROTECT]); + fib->fib_EntryType = fib->fib_DirEntryType; + fib->fib_Size = OS_BE2LONG(tail[BLKO_BYTE_SIZE]); + filelistentries = volume->SizeBlock-56; + datablocksize = BLOCK_SIZE(volume); + if (volume->dosflags == 0) + datablocksize = datablocksize-24; + datablocks = ((fib->fib_Size+datablocksize-1)/datablocksize); + fib->fib_NumBlocks = + datablocks+((datablocks+filelistentries-1)/filelistentries); + fib->fib_Date.ds_Days = OS_BE2LONG(tail[BLKO_DAYS]); + fib->fib_Date.ds_Minute = OS_BE2LONG(tail[BLKO_MINS]); + fib->fib_Date.ds_Tick = OS_BE2LONG(tail[BLKO_TICKS]); + if (fib->fib_DirEntryType != ST_ROOT) + { + string = (UBYTE *)&tail[BLKO_COMMENT_START]; + commentlength = string[0]; + if (commentlength >= sizeof(fib->fib_Comment)) + commentlength = sizeof(fib->fib_Comment) - 1; + fib->fib_Comment[0] = commentlength; + CopyMem(string + 1, fib->fib_Comment + 1, commentlength); + } + owner = OS_BE2LONG(tail[BLKO_OWNER]); + fib->fib_OwnerUID = owner>>16; + fib->fib_OwnerGID = owner & 0xFFFF; + return 0; } diff --git a/rom/filesys/afs/filehandles3.h b/rom/filesys/afs/filehandles3.h index 503ebcc1aff..0d09422fb21 100644 --- a/rom/filesys/afs/filehandles3.h +++ b/rom/filesys/afs/filehandles3.h @@ -2,7 +2,7 @@ #define FILEHANDLES3_H /* - Copyright © 1995-2011, The AROS Development Team. All rights reserved. + Copyright © 1995-2026, The AROS Development Team. All rights reserved. $Id$ */ @@ -11,7 +11,6 @@ LONG sameLock(struct AfsHandle *, struct AfsHandle *); ULONG examine(struct AFSBase *, struct AfsHandle *, struct ExAllData *, ULONG, ULONG, IPTR *); -ULONG examineAll(struct AFSBase *, struct AfsHandle *, struct ExAllData *, struct ExAllControl *, ULONG, ULONG); ULONG examineNext(struct AFSBase *, struct AfsHandle *, struct FileInfoBlock *); #endif diff --git a/rom/filesys/afs/hashing.c b/rom/filesys/afs/hashing.c index 62c3f77a4d1..f40420971c5 100644 --- a/rom/filesys/afs/hashing.c +++ b/rom/filesys/afs/hashing.c @@ -1,6 +1,5 @@ /* - Copyright © 1995-2008, The AROS Development Team. All rights reserved. - $Id$ + Copyright (C) 1995-2008, The AROS Development Team. All rights reserved. */ #include @@ -12,11 +11,11 @@ ULONG getHashKey(CONST_STRPTR name, ULONG tablesize, UBYTE flags) { ULONG result; UWORD length, i; - length=strlen(name); - if (length>MAX_NAME_LENGTH) - length=MAX_NAME_LENGTH; - result=length; - for (i=0; iMAX_NAME_LENGTH) + length=MAX_NAME_LENGTH; + result=length; + for (i=0; i #include #include #include +#include + #include "afshandler.h" #include "cache.h" #include "error.h" @@ -16,27 +21,28 @@ #include "filehandles2.h" #include "filehandles3.h" #include "misc.h" +#include "afs_security.h" #include "volumes.h" #include "baseredef.h" static void replypkt(struct DosPacket *dp, SIPTR res1) { - struct MsgPort *mp; - struct Message *mn; - - mp = dp->dp_Port; - mn = dp->dp_Link; - mn->mn_Node.ln_Name = (char*)dp; - dp->dp_Port = &((struct Process*)FindTask(NULL))->pr_MsgPort; - dp->dp_Res1 = res1; - PutMsg(mp, mn); + struct MsgPort *mp; + struct Message *mn; + + mp = dp->dp_Port; + mn = dp->dp_Link; + mn->mn_Node.ln_Name = (char*)dp; + dp->dp_Port = &((struct Process*)FindTask(NULL))->pr_MsgPort; + dp->dp_Res1 = res1; + PutMsg(mp, mn); } static void replypkt2(struct DosPacket *dp, SIPTR res1, SIPTR res2) { - dp->dp_Res2 = res2; - replypkt(dp, res1); + dp->dp_Res2 = res2; + replypkt(dp, res1); } static struct AFSBase *AFS_alloc(void) @@ -45,44 +51,47 @@ static struct AFSBase *AFS_alloc(void) handler = AllocMem(sizeof(*handler), MEMF_ANY | MEMF_CLEAR); if (handler == NULL) - return NULL; + return NULL; handler->utilitybase = TaggedOpenLibrary(TAGGEDOPEN_UTILITY); if (handler->utilitybase != NULL) { - handler->dosbase = (struct DosLibrary *)TaggedOpenLibrary(TAGGEDOPEN_DOS); - if (handler->dosbase != NULL) { - - /* changeint task and sigbit */ - handler->port.mp_SigTask = FindTask(0); - handler->port.mp_SigBit = SIGBREAKB_CTRL_F; - - /* Port for device commands */ - handler->timer_mp = CreateMsgPort(); - /* Open timer */ - handler->timer_request = (struct timerequest *) - CreateIORequest(handler->timer_mp, sizeof(struct timerequest)); - if (handler->timer_request != NULL) { - if (OpenDevice("timer.device", UNIT_VBLANK, - (APTR)handler->timer_request, 0) == 0) { - return handler; - } - DeleteIORequest((struct IORequest *)handler->timer_request); - } - CloseLibrary((struct Library *)handler->dosbase); - } - CloseLibrary((struct Library *)handler->utilitybase); + handler->dosbase = (struct DosLibrary *)TaggedOpenLibrary(TAGGEDOPEN_DOS); + if (handler->dosbase != NULL) { + + /* changeint task and sigbit */ + handler->port.mp_SigTask = FindTask(0); + handler->port.mp_SigBit = SIGBREAKB_CTRL_F; + + /* Port for device commands */ + handler->timer_mp = CreateMsgPort(); + /* Open timer */ + handler->timer_request = (struct timerequest *) + CreateIORequest(handler->timer_mp, sizeof(struct timerequest)); + if (handler->timer_request != NULL) { + if (OpenDevice("timer.device", UNIT_VBLANK, + (APTR)handler->timer_request, 0) == 0) { + return handler; + } + DeleteIORequest((struct IORequest *)handler->timer_request); + } + DeleteMsgPort(handler->timer_mp); + CloseLibrary((struct Library *)handler->dosbase); + } + CloseLibrary((struct Library *)handler->utilitybase); } + FreeMem(handler, sizeof(*handler)); return NULL; } static void AFS_free(struct AFSBase *handler) { if (handler->timer_flags & TIMER_ACTIVE) { - AbortIO((struct IORequest *)handler->timer_request); - WaitIO((struct IORequest *)handler->timer_request); + AbortIO((struct IORequest *)handler->timer_request); + WaitIO((struct IORequest *)handler->timer_request); } CloseDevice((struct IORequest *)handler->timer_request); DeleteIORequest((struct IORequest *)handler->timer_request); + DeleteMsgPort(handler->timer_mp); CloseLibrary((struct Library *)handler->dosbase); CloseLibrary((struct Library *)handler->utilitybase); FreeMem(handler, sizeof(*handler)); @@ -92,30 +101,43 @@ static struct Volume *AFS_open_volume(struct AFSBase *handler, struct DosPacket { struct FileSysStartupMsg *fssm = BADDR(dp->dp_Arg2); - D(bug("[AFS] Volume on Device=%b | Unit=%ld | Flags %ld | Environ %p\n", fssm->fssm_Device, fssm->fssm_Unit)); - - struct DosEnvec *de = BADDR(fssm->fssm_Environ); - - D(bug("\t[%s] de_SizeBlock = %10ld\n", __FUNCTION__ , de->de_SizeBlock)); - D(bug("\t[%s] de_Surfaces = %10ld\n", __FUNCTION__ , de->de_Surfaces)); - D(bug("\t[%s] de_BlocksPerTrack = %10ld\n", __FUNCTION__ , de->de_BlocksPerTrack)); - D(bug("\t[%s] de_LowCyl = %10ld\n", __FUNCTION__ , de->de_LowCyl)); - D(bug("\t[%s] de_HighCyl = %10ld\n", __FUNCTION__ , de->de_HighCyl)); - - return initVolume(handler, NULL, AROS_BSTR_ADDR(fssm->fssm_Device), fssm->fssm_Unit, fssm->fssm_Flags, BADDR(fssm->fssm_Environ), error); + D(bug("AFS: Volume on Device %b, Unit %ld, Flags %ld, Environ %p\n", + fssm->fssm_Device, fssm->fssm_Unit, + fssm->fssm_Flags, BADDR(fssm->fssm_Environ))); + return initVolume(handler, + NULL, AROS_BSTR_ADDR(fssm->fssm_Device), + fssm->fssm_Unit, + fssm->fssm_Flags, + BADDR(fssm->fssm_Environ), + error); } static BOOL AFS_close_volume(struct AFSBase *handler, struct Volume *volume, SIPTR *io_DosError) { - if (!volume->locklist) { - uninitVolume(handler, volume); - return TRUE; + /* Locks parked with an offline volume still name this handler */ + if (!volume->locklist && handler->parkedvols == 0) { + if (!flushForRelease(handler, volume)) { + *io_DosError = ERROR_UNKNOWN; + return FALSE; + } + uninitVolume(handler, volume); + return TRUE; } *io_DosError = ERROR_OBJECT_IN_USE; return FALSE; } +/* Called before any client knows pr_MsgPort, where UnLock() waits for its reply */ +static void AFS_drop_proc_locks(struct AFSBase *afsbase) +{ + struct Process *me = (struct Process *)FindTask(NULL); + + if (me->pr_Flags & PRF_FREECURRDIR) + UnLock(CurrentDir(BNULL)); + UnLock(SetProgramDir(BNULL)); +} + static BOOL AFS_protect_volume(struct AFSBase *handler, struct Volume *volume, BOOL on, ULONG key, SIPTR *io_DosError) { if (!volume->locklist) @@ -139,58 +161,123 @@ static VOID startFlushTimer(struct AFSBase *handler) /* Set up delay for next flush */ if (handler->timer_flags & TIMER_ACTIVE) { - handler->timer_flags |= TIMER_RESTART; + handler->timer_flags |= TIMER_RESTART; } else { - /* D(bug("[AFS] Starting timer\n")); */ - request = handler->timer_request; - request->tr_node.io_Command = TR_ADDREQUEST; - request->tr_time.tv_secs = 1; - request->tr_time.tv_micro = 0; - SendIO((struct IORequest *)handler->timer_request); - handler->timer_flags = TIMER_ACTIVE; + /* D(bug("[afs] Starting timer\n")); */ + request = handler->timer_request; + request->tr_node.io_Command = TR_ADDREQUEST; + request->tr_time.tv_secs = 1; + request->tr_time.tv_micro = 0; + SendIO((struct IORequest *)handler->timer_request); + handler->timer_flags = TIMER_ACTIVE; + } +} + +static VOID stopFlushMotor(struct AFSBase *handler, struct Volume *volume) +{ + if (volume->ioh.flags & IOHF_MOTOR_OFF) { + motorOff(handler, &volume->ioh); + volume->ioh.flags &= ~IOHF_MOTOR_OFF; } } static VOID onFlushTimer(struct AFSBase *handler, struct Volume *volume) { + /* The reply has to leave the port before the request is sent again */ + if (GetMsg(handler->timer_mp) == NULL) + return; handler->timer_flags &= ~TIMER_ACTIVE; + if (volume->writefailed || volume->cachepending) + { + handler->timer_flags &= ~TIMER_RESTART; + stopFlushMotor(handler, volume); + return; /* Retry/Cancel already ran; only an explicit flush retries now. */ + } if (handler->timer_flags & TIMER_RESTART) { - startFlushTimer(handler); + startFlushTimer(handler); } else { - struct BlockCache *blockbuffer; - - /* D(bug("[AFS] Alarm rang.\n")); */ - if (((volume->dostype == ID_DOS_DISK) || (volume->dostype == ID_DOS_muFS_DISK)) && mediumPresent(&volume->ioh)) - { - /* Check if adding volume node needs to be retried */ - if (volume->volumenode == NULL) - attemptAddDosVolume(handler, volume); - - flushCache(handler, volume); - blockbuffer = getBlock(handler, volume, volume->rootblock); - if ((blockbuffer->flags & BCF_WRITE) != 0) - { - writeBlock(handler, volume, blockbuffer, -1); - blockbuffer->flags &= ~BCF_WRITE; - } - if (volume->ioh.flags & IOHF_MOTOR_OFF) { - D(bug("[afs 0x%08lX] turning off motor\n", volume)); - motorOff(handler, &volume->ioh); - volume->ioh.flags &= ~IOHF_MOTOR_OFF; - } - } + struct BlockCache *blockbuffer; + + /* D(bug("[afs] Alarm rang.\n")); */ + if (((volume->dostype == ID_DOS_DISK) || (volume->dostype == ID_DOS_muFS_DISK)) && mediumPresent(&volume->ioh)) + { + /* Check if publishing the volume node needs to be retried */ + if ((volume->volumenode != NULL) && !volume->volumenodeadded) + addDosVolume(handler, volume); + + if (!flushCache(handler, volume)) + { + if (!volume->writefailed) + startFlushTimer(handler); + else + stopFlushMotor(handler, volume); + return; + } + blockbuffer = getBlock(handler, volume, volume->rootblock); + if (blockbuffer == NULL) + { + volume->writefailed = TRUE; + volume->state = ID_VALIDATING; + } + if (blockbuffer == NULL || ((blockbuffer->flags & BCF_WRITE) != 0 + && !writeBlock(handler, volume, blockbuffer, -1))) + { + if (!volume->writefailed) + startFlushTimer(handler); + else + stopFlushMotor(handler, volume); + return; + } + if (volume->ioh.flags & IOHF_MOTOR_OFF) { + D(bug("[afs 0x%08lX] turning off motor\n", volume)); + motorOff(handler, &volume->ioh); + volume->ioh.flags &= ~IOHF_MOTOR_OFF; + } + } } } -static BOOL mediacheck(struct Volume *volume, SIPTR *ok, SIPTR *res2) +/* + * ACTION_FLUSH: write every dirty block and the root, then ask the device + * to commit its own cache, without detaching the volume. A failed device + * commit is reported: a caller asking for a barrier must not be told the + * data is durable when it is not. + */ +static LONG flushVolumeNow(struct AFSBase *handler, struct Volume *volume) +{ + return flush(handler, volume) ? 0 : ERROR_UNKNOWN; +} + +/* The handle a lock argument refers to; a zero lock is the root. */ +AFS_SHARED struct AfsHandle *lockhandle(struct Volume *volume, SIPTR lock) { - if (!mediumPresent(&volume->ioh)) { - *ok = DOSFALSE; - *res2 = ERROR_NO_DISK; - return FALSE; + struct FileLock *fl = BADDR(lock); + + return fl ? (struct AfsHandle *)fl->fl_Key : &volume->ah; +} + +/* Wrap a freshly opened handle into a FileLock; closes it again on failure. */ +static SIPTR makelock(struct AFSBase *handler, struct Volume *volume, + struct MsgPort *mp, struct AfsHandle *ah, LONG access, SIPTR *res2) +{ + struct FileLock *fl; + + if (ah == NULL) + return DOSFALSE; + fl = AllocMem(sizeof(*fl), MEMF_CLEAR); + if (fl == NULL) { + closef(handler, ah); + *res2 = ERROR_NO_FREE_STORE; + return DOSFALSE; } - return TRUE; + fl->fl_Link = BNULL; + fl->fl_Key = (SIPTR)ah; + fl->fl_Access = access; + fl->fl_Task = mp; + fl->fl_Volume = MKBADDR(&volume->devicelist); + *res2 = 0; + return (SIPTR)MKBADDR(fl); } static LONG gethandletype(struct AFSBase *handler, struct AfsHandle *h) @@ -204,7 +291,7 @@ static LONG gethandletype(struct AFSBase *handler, struct AfsHandle *h) res2 = examine(handler, h, ead, size, mode, &dirpos); if (res2 == 0) - return ead->ed_Type; + return ead->ed_Type; return 0; } @@ -213,12 +300,12 @@ static CONST_STRPTR skipdevname(CONST_STRPTR fn) CONST_STRPTR cp; /* Skip past device names */ for (cp = fn; *cp; cp++) { - if (*cp == '/') - break; - if (*cp == ':') { - fn = cp+1; - break; - } + if (*cp == '/') + break; + if (*cp == ':') { + fn = cp+1; + break; + } } return fn; } @@ -236,595 +323,528 @@ LONG AFS_work(struct ExecBase *SysBase) struct Message *mn; struct AFSBase *handler; struct Volume *volume; + struct DeviceNode *dn; LONG retval; BOOL dead = FALSE; + BOOL nodisk; - D(bug("\n[AFS] Started\n")); - + D(bug("[AFS] started\n")); mp = &((struct Process *)FindTask(NULL))->pr_MsgPort; WaitPort(mp); dp = (struct DosPacket *)GetMsg(mp)->mn_Node.ln_Name; - D(bug("[AFS] Start message received: Port=%p | Path=%b\n", mp, dp->dp_Arg1)); + D(bug("[AFS] start message recevied. port=%p, path='%b'\n", mp, dp->dp_Arg1)); handler = AFS_alloc(); if (handler == NULL) { - D(bug("[AFS] Can't allocate an instance of the handler for this volume\n")); - replypkt(dp, DOSFALSE); - return RETURN_FAIL; + D(bug("[AFS] Can't allocate an instance of the handler for this volume\n")); + replypkt(dp, DOSFALSE); + return RETURN_FAIL; } + AFS_drop_proc_locks(handler); + + NEWLIST(&handler->offlinevols); volume = AFS_open_volume(handler, dp, &retval); if (volume == NULL) { - D(bug("[AFS] Can't open volume\n")); - replypkt2(dp, DOSFALSE, retval); - AFS_free(handler); - return RETURN_FAIL; - } else { - D(bug("[AFS] SUCCES opening volume: 0x%8lx\n", volume)); - } + D(bug("[AFS] Can't open volume\n")); + replypkt2(dp, DOSFALSE, retval); + AFS_free(handler); + return RETURN_FAIL; + } /* make non-packet functions to see our volume */ NEWLIST(&handler->device_list); AddHead(&handler->device_list, &volume->ln); /* Say that we are going to persist */ - ((struct DeviceNode *)BADDR(dp->dp_Arg3))->dn_Task = mp; + dn = (struct DeviceNode *)BADDR(dp->dp_Arg3); + dn->dn_Task = mp; replypkt(dp, DOSTRUE); while (!dead) { - ULONG packetmask = 1L << mp->mp_SigBit; - ULONG timermask = 1L << handler->timer_mp->mp_SigBit; - ULONG changemask = 1L << SIGBREAKB_CTRL_F; - ULONG sigs; - - sigs = Wait(packetmask | timermask | changemask); - - if (sigs & timermask) - onFlushTimer(handler, volume); - if (sigs & changemask) { - checkDeviceFlags(handler); - } - - if (!(sigs & packetmask)) - continue; - - /* DOS Packet processing */ - - while ((mn = GetMsg(mp)) != NULL) { - SIPTR res2 = 0; - SIPTR ok = DOSFALSE; - - dp = (struct DosPacket *)mn->mn_Node.ln_Name; - - //D(bug("[AFS] packet %p:%d\n", dp, dp->dp_Type)); - startFlushTimer(handler); - - switch (dp->dp_Type) { - case ACTION_DIE: - if (!AFS_close_volume(handler, volume, &res2)) { - ok = FALSE; - break; - } - dead = DOSTRUE; - ok = TRUE; - break; - case ACTION_IS_FILESYSTEM: - ok = TRUE; - break; - case ACTION_INHIBIT: - res2 = inhibit(handler, volume, dp->dp_Arg1); - ok = res2 ? DOSFALSE : DOSTRUE; - break; - case ACTION_END: - closef(handler, (struct AfsHandle *)dp->dp_Arg1); - ok = DOSTRUE; - break; - case ACTION_MORE_CACHE: - { - LONG numbuff = dp->dp_Arg1; - - if (numbuff) { - volume->numbuffers += numbuff; - - if (volume->numbuffers < 1) - volume->numbuffers = 1; - - flushCache(handler, volume); - Forbid(); - freeCache(handler, volume->blockcache); - for (;;) { - volume->blockcache = initCache(handler, volume, volume->numbuffers); - if (volume->blockcache) - break; - volume->numbuffers /= 2; - if (volume->numbuffers < 1) - volume->numbuffers = 1; - } - } - ok = DOSTRUE; - res2 = volume->numbuffers; - } - break; - case ACTION_DISK_INFO: - ok = getDiskInfo(volume, BADDR(dp->dp_Arg1)) ? DOSFALSE : DOSTRUE; - break; - case ACTION_SAME_LOCK: - { - struct FileLock *f1 = BADDR(dp->dp_Arg1); - struct FileLock *f2 = BADDR(dp->dp_Arg2); - ok = (sameLock((struct AfsHandle*)f1->fl_Key, (struct AfsHandle*)f2->fl_Key) == LOCK_SAME) ? DOSTRUE : DOSFALSE; - break; - } - - default: - - switch (dp->dp_Type) { - case ACTION_FINDINPUT: - case ACTION_FINDOUTPUT: - case ACTION_FINDUPDATE: - { - struct FileHandle *fh = BADDR(dp->dp_Arg1); - struct FileLock *dl = BADDR(dp->dp_Arg2); - CONST_STRPTR fn = AROS_BSTR_ADDR(dp->dp_Arg3); - struct AfsHandle *dh; - struct AfsHandle *ah; - ULONG mode = 0; - - if (!mediacheck(volume, &ok, &res2)) - break; - - if (dl == NULL) - dh = &volume->ah; - else - dh = (APTR)(dl->fl_Key); - - /* MODE_* directly matches its - * corresponding ACTION_* counterpart. - */ - mode = dp->dp_Type; - - fn = skipdevname(fn); - - if (dp->dp_Type == ACTION_FINDOUTPUT) { - ah = openfile(handler, dh, fn, mode, 0, &res2); - } else { - ah = openf(handler, dh, fn, mode, &res2); - } - ok = (ah != NULL) ? DOSTRUE : DOSFALSE; - if (ok) { - if (dp->dp_Type != ACTION_FINDOUTPUT) { - LONG type = gethandletype(handler, ah); - if (type >= 0) { - /* was directory */ - res2 = ERROR_OBJECT_WRONG_TYPE; - ok = DOSFALSE; - closef(handler, ah); - break; - } - } - fh->fh_Arg1 = (SIPTR)ah; - } - break; - } - case ACTION_LOCATE_OBJECT: - { - struct FileLock *dl = BADDR(dp->dp_Arg1); - struct FileLock *fl; - CONST_STRPTR fn = AROS_BSTR_ADDR(dp->dp_Arg2); - struct AfsHandle *dh; - struct AfsHandle *ah; - ULONG mode = 0; - - if (!mediacheck(volume, &ok, &res2)) - break; - - if (dl == NULL) - dh = &volume->ah; - else - dh = (APTR)(dl->fl_Key); - - if (dp->dp_Arg3 == ACCESS_READ) - mode = MODE_OLDFILE; - else if (dp->dp_Arg3 == ACCESS_WRITE) - mode = MODE_NEWFILE; - - fn = skipdevname(fn); - - ah = openf(handler, dh, fn, mode, &res2); - if (ah == NULL) { - ok = DOSFALSE; - break; - } - fl = AllocMem(sizeof(*fl), MEMF_CLEAR); - if (fl != NULL) { - fl->fl_Link = BNULL; - fl->fl_Key = (SIPTR)ah; - fl->fl_Access = dp->dp_Arg3; - fl->fl_Task = mp; - fl->fl_Volume = MKBADDR(&volume->devicelist); - ok = (SIPTR)MKBADDR(fl); - res2 = 0; - } else { - closef(handler, ah); - ok = DOSFALSE; - res2 = ERROR_NO_FREE_STORE; - } - break; - } - case ACTION_COPY_DIR: /* Aka DupLock() */ - case ACTION_COPY_DIR_FH: - { - struct FileLock *ol = BADDR(dp->dp_Arg1); - struct FileLock *fl; - struct AfsHandle *oh; - struct AfsHandle *ah; - - if (!mediacheck(volume, &ok, &res2)) - break; - - if (dp->dp_Type == ACTION_COPY_DIR) { - oh = ol ? (APTR)ol->fl_Key : &volume->ah; - } else { - oh = (APTR)dp->dp_Arg1; - } - - ah = openf(handler, oh, "", MODE_OLDFILE, &res2); - if (ah == NULL) { - ok = DOSFALSE; - break; - } - fl = AllocMem(sizeof(*fl), MEMF_CLEAR); - if (fl != NULL) { - fl->fl_Link = BNULL; - fl->fl_Key = (SIPTR)ah; - fl->fl_Access = ACCESS_READ; - fl->fl_Task = mp; - fl->fl_Volume = MKBADDR(&volume->devicelist); - ok = (SIPTR)MKBADDR(fl); - res2 = 0; - } else { - closef(handler, ah); - ok = DOSFALSE; - res2 = ERROR_NO_FREE_STORE; - } - break; - } - case ACTION_FREE_LOCK: - { - struct FileLock *fl; - struct AfsHandle *ah; - - if (!mediacheck(volume, &ok, &res2)) - break; - - fl = BADDR(dp->dp_Arg1); - if (fl == NULL) { - ok = DOSTRUE; - break; - } - ah = (APTR)(fl->fl_Key); - closef(handler, ah); - FreeMem(fl, sizeof(*fl)); - ok = DOSTRUE; - break; - } - case ACTION_READ: - if (!mediacheck(volume, &ok, &res2)) - break; - ok = readf(handler, (struct AfsHandle *)(dp->dp_Arg1), (APTR)dp->dp_Arg2, (LONG)dp->dp_Arg3, &res2); - break; - case ACTION_WRITE: - if (!mediacheck(volume, &ok, &res2)) - break; - ok = writef(handler, (struct AfsHandle *)(dp->dp_Arg1), (APTR)dp->dp_Arg2, (LONG)dp->dp_Arg3, &res2); - break; - case ACTION_SEEK: - if (!mediacheck(volume, &ok, &res2)) - break; - ok = seek(handler, (struct AfsHandle *)(dp->dp_Arg1), (LONG)dp->dp_Arg2, (LONG)dp->dp_Arg3, &res2); - break; - case ACTION_SET_FILE_SIZE: - if (!mediacheck(volume, &ok, &res2)) - break; - ok = setFileSize(handler, (struct AfsHandle *)(dp->dp_Arg1),(LONG)dp->dp_Arg2, (LONG)dp->dp_Arg3, &res2); - break; - case ACTION_FH_FROM_LOCK: - { - struct FileHandle *fh = BADDR(dp->dp_Arg1); - struct FileLock *fl = BADDR(dp->dp_Arg2); - fh->fh_Arg1 = (SIPTR)fl->fl_Key; - FreeMem(fl, sizeof(*fl)); - break; - } - case ACTION_EXAMINE_OBJECT: - case ACTION_EXAMINE_FH: - { - struct FileLock *fl = BADDR(dp->dp_Arg1); - struct AfsHandle *ah; - struct FileInfoBlock *fib = BADDR(dp->dp_Arg2); - UBYTE buffer[sizeof(struct ExAllData) + MAXFILENAMELENGTH + MAXCOMMENTLENGTH]; - struct ExAllData *ead = (APTR)&buffer[0]; - ULONG size = sizeof(buffer); - ULONG mode = ED_OWNER; - SIPTR dirpos; - - if (!mediacheck(volume, &ok, &res2)) - break; - - if (dp->dp_Type == ACTION_EXAMINE_OBJECT) - ah = fl ? (APTR)fl->fl_Key : &volume->ah; - else - ah = (APTR)dp->dp_Arg1; - - if (fib == NULL) { - ok = DOSTRUE; - break; - } - - res2 = examine(handler, ah, ead, size, mode, &dirpos); - if (res2 != 0) { - ok = DOSFALSE; - break; - } - - if (ah == &volume->ah) { - fib->fib_DirEntryType = ST_ROOT; - } else { - fib->fib_DirEntryType = ead->ed_Type; - } - - fib->fib_DiskKey = ah->header_block; - strncpy(&fib->fib_FileName[1], ead->ed_Name, sizeof(fib->fib_FileName)-1); - fib->fib_FileName[0] = strlen(&fib->fib_FileName[1]); - fib->fib_Protection = ead->ed_Prot; - fib->fib_EntryType = fib->fib_DirEntryType; - fib->fib_Size = ead->ed_Size; - fib->fib_NumBlocks = (ead->ed_Size + ah->volume->sectorsize - 1) / ah->volume->sectorsize; - fib->fib_Date.ds_Days = ead->ed_Days; - fib->fib_Date.ds_Minute = ead->ed_Mins; - fib->fib_Date.ds_Tick = ead->ed_Ticks; - if (ead->ed_Comment) { - strncpy(&fib->fib_Comment[1], ead->ed_Comment, sizeof(fib->fib_Comment)-1); - fib->fib_Comment[0] = strlen(&fib->fib_Comment[1]); - } else { - fib->fib_Comment[0] = 0; - } - fib->fib_OwnerUID = ead->ed_OwnerUID; - fib->fib_OwnerGID = ead->ed_OwnerGID; - ok = DOSTRUE; - break; - } - case ACTION_EXAMINE_NEXT: - { - struct FileLock *fl = BADDR(dp->dp_Arg1); - struct AfsHandle *ah; - struct FileInfoBlock *fib = BADDR(dp->dp_Arg2); - - if (!mediacheck(volume, &ok, &res2)) - break; - - if (fib == NULL) { - ok = DOSTRUE; - break; - } - - if (fl == NULL) - ah = &volume->ah; - else - ah = (APTR)fl->fl_Key; - - res2 = examineNext(handler, ah, fib); - if (res2 != 0) { - ok = DOSFALSE; - break; - } - - if (ah == &volume->ah) { - fib->fib_DirEntryType = ST_ROOT; - } - ok = DOSTRUE; - break; - } - case ACTION_PARENT: - case ACTION_PARENT_FH: - { - struct FileLock *opl = BADDR(dp->dp_Arg1); - struct FileLock *fl; - struct AfsHandle *oh; - struct AfsHandle *ah; - - if (!mediacheck(volume, &ok, &res2)) - break; - - if (dp->dp_Type == ACTION_PARENT) - oh = (APTR)opl->fl_Key; - else - oh = (APTR)dp->dp_Arg1; - ah = openf(handler, oh, "/", MODE_OLDFILE, &res2); - if (ah == NULL) { - ok = DOSFALSE; - if (res2 == ERROR_OBJECT_NOT_FOUND && gethandletype(handler, oh) == ST_ROOT) - res2 = 0; /* need to return res2 = 0 (not 205) if oh == ST_ROOT */ - break; - } - fl = AllocMem(sizeof(*fl), MEMF_CLEAR); - if (fl != NULL) { - fl->fl_Link = BNULL; - fl->fl_Key = (SIPTR)ah; - fl->fl_Access = ACCESS_READ; - fl->fl_Task = mp; - fl->fl_Volume = MKBADDR(&volume->devicelist); - ok = (SIPTR)MKBADDR(fl); - res2 = 0; - } else { - closef(handler, ah); - ok = DOSFALSE; - res2 = ERROR_NO_FREE_STORE; - } - break; - } - case ACTION_INFO: - { - struct FileLock *opl = BADDR(dp->dp_Arg1); - struct AfsHandle *oh; - if (opl == NULL) - oh = &volume->ah; - else - oh = (APTR)opl->fl_Key; - if (gethandletype(handler, oh) == 0 || !mediacheck(volume, &ok, &res2)) { - res2 = ERROR_OBJECT_NOT_FOUND; - ok = DOSFALSE; - } - res2 = getDiskInfo(volume, BADDR(dp->dp_Arg2)); - ok = res2 ? DOSFALSE : DOSTRUE; - break; - } - break; - case ACTION_RENAME_OBJECT: - { - struct FileLock *opl = BADDR(dp->dp_Arg1); - //unused//struct FileLock *npl = BADDR(dp->dp_Arg3); - CONST_STRPTR on = AROS_BSTR_ADDR(dp->dp_Arg2); - CONST_STRPTR nn = AROS_BSTR_ADDR(dp->dp_Arg4); - struct AfsHandle *oh; - - if (opl == NULL) - oh = &volume->ah; - else - oh = (APTR)opl->fl_Key; - on = skipdevname(on); - nn = skipdevname(nn); - res2 = renameObject(handler, oh, on, nn); - ok = res2 ? DOSFALSE : DOSTRUE; - break; - } - case ACTION_RENAME_DISK: - { - CONST_STRPTR n = AROS_BSTR_ADDR(dp->dp_Arg1); - ok = relabel(handler, volume, n, &res2); - break; - } - case ACTION_CREATE_DIR: - { - struct FileLock *fl = BADDR(dp->dp_Arg1), *flnew; - struct AfsHandle *h, *ah; - CONST_STRPTR n = AROS_BSTR_ADDR(dp->dp_Arg2); - if (fl == NULL) - h = &volume->ah; - else - h = (APTR)fl->fl_Key; - n = skipdevname(n); - flnew = AllocMem(sizeof(*flnew), MEMF_CLEAR); - if (flnew != NULL) { - ah = createDir(handler, h, n, 0, &res2); - ok = res2 ? DOSFALSE : DOSTRUE; - if (ok) { - flnew->fl_Link = BNULL; - flnew->fl_Key = (SIPTR)ah; - flnew->fl_Access = ACCESS_READ; - flnew->fl_Task = mp; - flnew->fl_Volume = MKBADDR(&volume->devicelist); - ok = (SIPTR)MKBADDR(flnew); - } - } else { - ok = DOSFALSE; - res2 = ERROR_NO_FREE_STORE; - } - break; - } - case ACTION_DELETE_OBJECT: - { - struct FileLock *fl = BADDR(dp->dp_Arg1); - struct AfsHandle *h; - CONST_STRPTR n = AROS_BSTR_ADDR(dp->dp_Arg2); - if (fl == NULL) - h = &volume->ah; - else - h = (APTR)fl->fl_Key; - n = skipdevname(n); - res2 = deleteObject(handler, h, n); - ok = res2 ? DOSFALSE : DOSTRUE; - break; - } - case ACTION_SET_COMMENT: - { - struct FileLock *fl = BADDR(dp->dp_Arg2); - struct AfsHandle *h; - CONST_STRPTR n = AROS_BSTR_ADDR(dp->dp_Arg3); - CONST_STRPTR c = AROS_BSTR_ADDR(dp->dp_Arg4); - if (fl == NULL) - h = &volume->ah; - else - h = (APTR)fl->fl_Key; - n = skipdevname(n); - res2 = setComment(handler, h, n, c); - ok = res2 ? DOSFALSE : DOSTRUE; - break; - } - case ACTION_SET_PROTECT: - { - struct FileLock *fl = BADDR(dp->dp_Arg2); - struct AfsHandle *h; - CONST_STRPTR n = AROS_BSTR_ADDR(dp->dp_Arg3); - ULONG p = dp->dp_Arg4; - if (fl == NULL) - h = &volume->ah; - else - h = (APTR)fl->fl_Key; - n = skipdevname(n); - res2 = setProtect(handler, h, n, p); - ok = res2 ? DOSFALSE : DOSTRUE; - break; - } - case ACTION_SET_DATE: - { - struct FileLock *fl = BADDR(dp->dp_Arg2); - struct AfsHandle *h; - CONST_STRPTR n = AROS_BSTR_ADDR(dp->dp_Arg3); - struct DateStamp *ds = (struct DateStamp*)dp->dp_Arg4; - if (fl == NULL) - h = &volume->ah; - else - h = (APTR)fl->fl_Key; - n = skipdevname(n); - res2 = setDate(handler, h, n, ds); - ok = res2 ? DOSFALSE : DOSTRUE; - break; - } - case ACTION_INHIBIT: - res2 = inhibit(handler, volume, dp->dp_Arg1); - ok = res2 ? DOSFALSE : DOSTRUE; - break; - case ACTION_FORMAT: - { - CONST_STRPTR n = AROS_BSTR_ADDR(dp->dp_Arg1); - res2 = format(handler, volume, n, dp->dp_Arg2); - ok = res2 ? DOSFALSE : DOSTRUE; - break; - } - case ACTION_SERIALIZE_DISK: - ok = relabel(handler, volume, NULL, &res2); - break; - case ACTION_WRITE_PROTECT: - ok = AFS_protect_volume(handler, volume, dp->dp_Arg1, dp->dp_Arg2, &res2) ? DOSFALSE : DOSTRUE; - break; - default: - ok = DOSFALSE; - res2 = ERROR_ACTION_NOT_KNOWN; - D(bug("[AFS] %d not implemented\n", dp->dp_Type)); - break; - } - break; - } - - replypkt2(dp, ok, res2); - } + ULONG packetmask = 1L << mp->mp_SigBit; + ULONG timermask = 1L << handler->timer_mp->mp_SigBit; + ULONG changemask = 1L << SIGBREAKB_CTRL_F; + ULONG sigs; + + sigs = Wait(packetmask | timermask | changemask); + + /* Process a media-change interrupt before touching cached disk data, + * even when it woke the packet port rather than SIGBREAKB_CTRL_F. */ + checkDeviceFlags(handler); + if (sigs & timermask) + onFlushTimer(handler, volume); + + if (!(sigs & packetmask)) + continue; + + /* DOS Packet processing */ + + while ((mn = GetMsg(mp)) != NULL) { + SIPTR res2 = 0; + SIPTR ok = DOSFALSE; + + dp = (struct DosPacket *)mn->mn_Node.ln_Name; + + D(bug("[AFS] packet %p:%d\n", dp, dp->dp_Type)); + if (volume->cachepending && dp->dp_Type != ACTION_END + && dp->dp_Type != ACTION_FREE_LOCK + && dp->dp_Type != ACTION_IS_FILESYSTEM +#if AFS_SECURITY + && dp->dp_Type != ACTION_IS_SECFS + && dp->dp_Type != ACTION_GET_SECFS_VERSION +#endif + && dp->dp_Type != ACTION_DISK_INFO) { + replypkt2(dp, DOSFALSE, ERROR_NO_DISK); + continue; + } + if (!volume->cachepending) + startFlushTimer(handler); + afsSecBeginPacket(handler, volume, dp); + + nodisk = !mediumPresent(&volume->ioh); + + switch (dp->dp_Type) { + case ACTION_DIE: + if (!AFS_close_volume(handler, volume, &res2)) { + ok = FALSE; + break; + } + /* No new packets for a handler that is leaving */ + dn->dn_Task = NULL; + dead = DOSTRUE; + ok = TRUE; + break; + case ACTION_IS_FILESYSTEM: + ok = TRUE; + break; +#if AFS_SECURITY + case ACTION_IS_SECFS: + ok = afsSecIsActive(handler) ? DOSTRUE : DOSFALSE; + break; + case ACTION_GET_SECFS_VERSION: + ok = secFS_API_VERSION; + break; +#endif + case ACTION_INHIBIT: + res2 = inhibit(handler, volume, dp->dp_Arg1); + goto res2_reply; + case ACTION_END: + closef(handler, (struct AfsHandle *)dp->dp_Arg1); + ok = DOSTRUE; + break; + case ACTION_MORE_CACHE: + { + LONG numbuff = dp->dp_Arg1; + + if (numbuff) { + if (!flush(handler, volume)) { + res2 = ERROR_UNKNOWN; + break; + } + volume->numbuffers += numbuff; + + if (volume->numbuffers < 1) + volume->numbuffers = 1; + + Forbid(); + freeCache(handler, volume->blockcache); + for (;;) { + volume->blockcache = initCache(handler, volume, volume->numbuffers); + if (volume->blockcache) + break; + volume->numbuffers /= 2; + if (volume->numbuffers < 1) + volume->numbuffers = 1; + } + } + ok = DOSTRUE; + res2 = volume->numbuffers; + } + break; + case ACTION_DISK_INFO: + ok = getDiskInfo(volume, BADDR(dp->dp_Arg1)) ? DOSFALSE : DOSTRUE; + break; + case ACTION_SAME_LOCK: + { + struct FileLock *f1 = BADDR(dp->dp_Arg1); + struct FileLock *f2 = BADDR(dp->dp_Arg2); + ok = (sameLock((struct AfsHandle*)f1->fl_Key, (struct AfsHandle*)f2->fl_Key) == LOCK_SAME) ? DOSTRUE : DOSFALSE; + break; + } + case ACTION_FINDINPUT: + case ACTION_FINDOUTPUT: + case ACTION_FINDUPDATE: + { + struct FileHandle *fh = BADDR(dp->dp_Arg1); + CONST_STRPTR fn; + struct AfsHandle *dh; + struct AfsHandle *ah; + + if (nodisk) + goto nodisk_reply; + + dh = lockhandle(volume, dp->dp_Arg2); + fn = skipdevname(AROS_BSTR_ADDR(dp->dp_Arg3)); + + /* multi-user: check access before touching anything */ + if (afsSecIsActive(handler)) { + LONG err; + + if (dp->dp_Type == ACTION_FINDINPUT) { + err = afsSecCheckName(handler, dh, fn, AFS_ACCESS_READ); + } else if (dp->dp_Type == ACTION_FINDUPDATE) { + err = afsSecCheckName(handler, dh, fn, AFS_ACCESS_WRITE); + if (err == ERROR_OBJECT_NOT_FOUND) + err = afsSecCheckParent(handler, dh, fn, AFS_ACCESS_WRITE); + } else { + err = afsSecCheckName(handler, dh, fn, AFS_ACCESS_WRITE | AFS_ACCESS_DELETE); + if (err == ERROR_OBJECT_NOT_FOUND) + err = 0; + if (err == 0) + err = afsSecCheckParent(handler, dh, fn, AFS_ACCESS_WRITE); + } + if (err) { + res2 = err; + break; + } + } + + /* MODE_* directly matches its corresponding ACTION_* counterpart. */ + if (dp->dp_Type == ACTION_FINDOUTPUT) { + ah = openfile(handler, dh, fn, dp->dp_Type, afsSecNewProtection(handler, 0), &res2); + } else { + ah = openf(handler, dh, fn, dp->dp_Type, &res2); + } + if (ah != NULL) { + if (dp->dp_Type != ACTION_FINDOUTPUT) { + LONG type = gethandletype(handler, ah); + if (type >= 0) { + /* was directory */ + res2 = ERROR_OBJECT_WRONG_TYPE; + closef(handler, ah); + break; + } + } + fh->fh_Arg1 = (SIPTR)ah; + ok = DOSTRUE; + } + break; + } + case ACTION_LOCATE_OBJECT: + { + CONST_STRPTR fn; + struct AfsHandle *dh; + ULONG mode = 0; + + if (nodisk) + goto nodisk_reply; + + dh = lockhandle(volume, dp->dp_Arg1); + + if (dp->dp_Arg3 == ACCESS_READ) + mode = MODE_OLDFILE; + else if (dp->dp_Arg3 == ACCESS_WRITE) + mode = MODE_NEWFILE; + + fn = skipdevname(AROS_BSTR_ADDR(dp->dp_Arg2)); + + /* multi-user: locking needs read access to the object */ + if (afsSecIsActive(handler)) { + LONG err = afsSecCheckName(handler, dh, fn, AFS_ACCESS_READ); + if (err && err != ERROR_OBJECT_NOT_FOUND) { + res2 = err; + break; + } + } + + ok = makelock(handler, volume, mp, + openf(handler, dh, fn, mode, &res2), dp->dp_Arg3, &res2); + break; + } + case ACTION_COPY_DIR: /* Aka DupLock() */ + case ACTION_COPY_DIR_FH: + { + struct AfsHandle *oh; + + if (nodisk) + goto nodisk_reply; + + if (dp->dp_Type == ACTION_COPY_DIR) + oh = lockhandle(volume, dp->dp_Arg1); + else + oh = (APTR)dp->dp_Arg1; + + ok = makelock(handler, volume, mp, + openf(handler, oh, "", MODE_OLDFILE, &res2), ACCESS_READ, &res2); + break; + } + case ACTION_FREE_LOCK: + { + struct FileLock *fl; + + if (!volume->cachepending && nodisk) + goto nodisk_reply; + + fl = BADDR(dp->dp_Arg1); + if (fl != NULL) { + closef(handler, (APTR)(fl->fl_Key)); + FreeMem(fl, sizeof(*fl)); + } + ok = DOSTRUE; + break; + } + case ACTION_READ: + if (nodisk) + goto nodisk_reply; + ok = readf(handler, (struct AfsHandle *)(dp->dp_Arg1), (APTR)dp->dp_Arg2, (LONG)dp->dp_Arg3, &res2); + break; + case ACTION_WRITE: + if (nodisk) + goto nodisk_reply; + ok = writef(handler, (struct AfsHandle *)(dp->dp_Arg1), (APTR)dp->dp_Arg2, (LONG)dp->dp_Arg3, &res2); + break; + case ACTION_SEEK: + if (nodisk) + goto nodisk_reply; + ok = seek(handler, (struct AfsHandle *)(dp->dp_Arg1), (LONG)dp->dp_Arg2, (LONG)dp->dp_Arg3, &res2); + break; + case ACTION_SET_FILE_SIZE: + if (nodisk) + goto nodisk_reply; + ok = setFileSize(handler, (struct AfsHandle *)(dp->dp_Arg1),(LONG)dp->dp_Arg2, (LONG)dp->dp_Arg3, &res2); + break; + case ACTION_FH_FROM_LOCK: + { + struct FileHandle *fh = BADDR(dp->dp_Arg1); + struct FileLock *fl = BADDR(dp->dp_Arg2); + fh->fh_Arg1 = (SIPTR)fl->fl_Key; + FreeMem(fl, sizeof(*fl)); + ok = DOSTRUE; + break; + } + case ACTION_EXAMINE_OBJECT: + case ACTION_EXAMINE_FH: + { + struct AfsHandle *ah; + struct FileInfoBlock *fib = BADDR(dp->dp_Arg2); + UBYTE buffer[sizeof(struct ExAllData) + MAXFILENAMELENGTH + MAXCOMMENTLENGTH]; + struct ExAllData *ead = (APTR)&buffer[0]; + SIPTR dirpos; + + if (nodisk) + goto nodisk_reply; + + if (dp->dp_Type == ACTION_EXAMINE_OBJECT) + ah = lockhandle(volume, dp->dp_Arg1); + else + ah = (APTR)dp->dp_Arg1; + + if (fib == NULL) { + ok = DOSTRUE; + break; + } + + res2 = examine(handler, ah, ead, sizeof(buffer), ED_OWNER, &dirpos); + if (res2 != 0) + break; + + if (ah == &volume->ah) { + fib->fib_DirEntryType = ST_ROOT; + } else { + fib->fib_DirEntryType = ead->ed_Type; + } + + fib->fib_DiskKey = ah->header_block; + strncpy(&fib->fib_FileName[1], ead->ed_Name, sizeof(fib->fib_FileName)-1); + fib->fib_FileName[0] = strlen(&fib->fib_FileName[1]); + fib->fib_Protection = ead->ed_Prot; + fib->fib_EntryType = fib->fib_DirEntryType; + fib->fib_Size = ead->ed_Size; + fib->fib_NumBlocks = (ead->ed_Size + ah->volume->sectorsize - 1) / ah->volume->sectorsize; + fib->fib_Date.ds_Days = ead->ed_Days; + fib->fib_Date.ds_Minute = ead->ed_Mins; + fib->fib_Date.ds_Tick = ead->ed_Ticks; + if (ead->ed_Comment) { + strncpy(&fib->fib_Comment[1], ead->ed_Comment, sizeof(fib->fib_Comment)-1); + fib->fib_Comment[0] = strlen(&fib->fib_Comment[1]); + } else { + fib->fib_Comment[0] = 0; + } + fib->fib_OwnerUID = ead->ed_OwnerUID; + fib->fib_OwnerGID = ead->ed_OwnerGID; + ok = DOSTRUE; + break; + } + case ACTION_EXAMINE_NEXT: + { + struct AfsHandle *ah; + struct FileInfoBlock *fib = BADDR(dp->dp_Arg2); + + if (nodisk) + goto nodisk_reply; + + if (fib == NULL) { + ok = DOSTRUE; + break; + } + + ah = lockhandle(volume, dp->dp_Arg1); + + res2 = examineNext(handler, ah, fib); + if (res2 != 0) + break; + + if (ah == &volume->ah) { + fib->fib_DirEntryType = ST_ROOT; + } + ok = DOSTRUE; + break; + } + case ACTION_PARENT: + case ACTION_PARENT_FH: + { + struct AfsHandle *oh; + struct AfsHandle *ah; + + if (nodisk) + goto nodisk_reply; + + if (dp->dp_Type == ACTION_PARENT) + oh = (APTR)((struct FileLock *)BADDR(dp->dp_Arg1))->fl_Key; + else + oh = (APTR)dp->dp_Arg1; + ah = openf(handler, oh, "/", MODE_OLDFILE, &res2); + if (ah == NULL) { + if (res2 == ERROR_OBJECT_NOT_FOUND && gethandletype(handler, oh) == ST_ROOT) + res2 = 0; /* need to return res2 = 0 (not 205) if oh == ST_ROOT */ + break; + } + ok = makelock(handler, volume, mp, ah, ACCESS_READ, &res2); + break; + } + case ACTION_INFO: + /* reads the header as before; its result never mattered */ + gethandletype(handler, lockhandle(volume, dp->dp_Arg1)); + res2 = getDiskInfo(volume, BADDR(dp->dp_Arg2)); + goto res2_reply; + case ACTION_RENAME_OBJECT: + { + struct AfsHandle *oh = lockhandle(volume, dp->dp_Arg1); + CONST_STRPTR on = skipdevname(AROS_BSTR_ADDR(dp->dp_Arg2)); + CONST_STRPTR nn = skipdevname(AROS_BSTR_ADDR(dp->dp_Arg4)); + + /* multi-user: property access to the object, write access to both directories */ + if ((res2 = afsSecCheckNameProperty(handler, oh, on)) == 0 && + (res2 = afsSecCheckParent(handler, oh, on, AFS_ACCESS_WRITE)) == 0 && + (res2 = afsSecCheckParent(handler, oh, nn, AFS_ACCESS_WRITE)) == 0) + res2 = renameObject(handler, oh, on, nn); + goto res2_reply; + } + case ACTION_RENAME_DISK: + ok = relabel(handler, volume, AROS_BSTR_ADDR(dp->dp_Arg1), &res2); + break; + case ACTION_CREATE_DIR: + { + struct FileLock *flnew; + struct AfsHandle *h = lockhandle(volume, dp->dp_Arg1), *ah; + CONST_STRPTR n = skipdevname(AROS_BSTR_ADDR(dp->dp_Arg2)); + + /* multi-user: write access to the parent directory */ + if ((res2 = afsSecCheckParent(handler, h, n, AFS_ACCESS_WRITE))) + break; + flnew = AllocMem(sizeof(*flnew), MEMF_CLEAR); + if (flnew != NULL) { + ah = createDir(handler, h, n, afsSecNewProtection(handler, 0), &res2); + if (res2 == 0) { + flnew->fl_Link = BNULL; + flnew->fl_Key = (SIPTR)ah; + flnew->fl_Access = ACCESS_READ; + flnew->fl_Task = mp; + flnew->fl_Volume = MKBADDR(&volume->devicelist); + ok = (SIPTR)MKBADDR(flnew); + } + } else { + res2 = ERROR_NO_FREE_STORE; + } + break; + } + case ACTION_DELETE_OBJECT: + { + struct AfsHandle *h = lockhandle(volume, dp->dp_Arg1); + CONST_STRPTR n = skipdevname(AROS_BSTR_ADDR(dp->dp_Arg2)); + + /* multi-user: delete access to the object, write access to its directory */ + if ((res2 = afsSecCheckName(handler, h, n, AFS_ACCESS_DELETE)) == 0 && + (res2 = afsSecCheckParent(handler, h, n, AFS_ACCESS_WRITE)) == 0) + res2 = deleteObject(handler, h, n); + goto res2_reply; + } + case ACTION_SET_COMMENT: + case ACTION_SET_PROTECT: + case ACTION_SET_DATE: + { + struct AfsHandle *h = lockhandle(volume, dp->dp_Arg2); + CONST_STRPTR n = skipdevname(AROS_BSTR_ADDR(dp->dp_Arg3)); + + if ((res2 = afsSecCheckNameProperty(handler, h, n)) == 0) { + if (dp->dp_Type == ACTION_SET_COMMENT) + res2 = setComment(handler, h, n, AROS_BSTR_ADDR(dp->dp_Arg4)); + else if (dp->dp_Type == ACTION_SET_PROTECT) + res2 = setProtect(handler, h, n, dp->dp_Arg4); + else + res2 = setDate(handler, h, n, (struct DateStamp *)dp->dp_Arg4); + } + goto res2_reply; + } + case ACTION_SET_OWNER: + if (nodisk) + goto nodisk_reply; + res2 = afsSecSetOwner(handler, lockhandle(volume, dp->dp_Arg2), + skipdevname(AROS_BSTR_ADDR(dp->dp_Arg3)), (ULONG)dp->dp_Arg4); + goto res2_reply; + case ACTION_FLUSH: + if (volume->inhibitcounter != 0 || nodisk) + goto nodisk_reply; + res2 = flushVolumeNow(handler, volume); + goto res2_reply; + case ACTION_FORMAT: + res2 = format(handler, volume, AROS_BSTR_ADDR(dp->dp_Arg1), dp->dp_Arg2); + goto res2_reply; + case ACTION_SERIALIZE_DISK: + ok = relabel(handler, volume, NULL, &res2); + break; + case ACTION_WRITE_PROTECT: + ok = AFS_protect_volume(handler, volume, dp->dp_Arg1, dp->dp_Arg2, &res2) ? DOSFALSE : DOSTRUE; + break; + default: + res2 = ERROR_ACTION_NOT_KNOWN; + D(bug("[AFS] %d not implemented\n", dp->dp_Type)); + break; + } + goto reply; + +nodisk_reply: + res2 = ERROR_NO_DISK; + goto reply; +res2_reply: + ok = res2 ? DOSFALSE : DOSTRUE; +reply: + afsSecEndPacket(handler); + replypkt2(dp, ok, res2); + if (dead) + break; + } } AFS_free(handler); - replypkt(dp, DOSTRUE); + + /* Packets sent before dn_Task was cleared; exit before any can follow */ + Forbid(); + while ((mn = GetMsg(mp)) != NULL) + replypkt2((struct DosPacket *)mn->mn_Node.ln_Name, DOSFALSE, ERROR_DEVICE_NOT_MOUNTED); return RETURN_OK; } diff --git a/rom/filesys/afs/misc.c b/rom/filesys/afs/misc.c index a6d994abc5f..e6bfd447eb4 100644 --- a/rom/filesys/afs/misc.c +++ b/rom/filesys/afs/misc.c @@ -1,6 +1,5 @@ /* - Copyright � 1995-2008, The AROS Development Team. All rights reserved. - $Id$ + Copyright (C) 1995-2026, The AROS Development Team. All rights reserved. */ /* * -date------ -name------------------- -description----------------------------- @@ -9,6 +8,10 @@ */ +#ifndef DEBUG +#define DEBUG 0 +#endif + #include "os.h" #include "misc.h" #include "afsblocks.h" @@ -19,6 +22,14 @@ #include "baseredef.h" #include "validator.h" +/* store a DateStamp into three consecutive (days, mins, ticks) block longs */ +void putStamp(ULONG *dest, const struct DateStamp *ds) +{ + dest[0] = OS_LONG2BE(ds->ds_Days); + dest[1] = OS_LONG2BE(ds->ds_Minute); + dest[2] = OS_LONG2BE(ds->ds_Tick); +} + /********************************************** Name : writeHeader Descr.: update header information (time) @@ -28,36 +39,34 @@ Output: 0 for success; error code otherwise ***********************************************/ ULONG writeHeader - ( - struct AFSBase *afsbase, - struct Volume *volume, - struct BlockCache *blockbuffer - ) + ( + struct AFSBase *afsbase, + struct Volume *volume, + struct BlockCache *blockbuffer + ) { struct DateStamp ds; +ULONG *tail; - /* store current time as modification date for this object and all its ancestors */ - DateStamp(&ds); - for (;;) - { - blockbuffer->buffer[BLK_DAYS(volume)] = OS_LONG2BE(ds.ds_Days); - blockbuffer->buffer[BLK_MINS(volume)] = OS_LONG2BE(ds.ds_Minute); - blockbuffer->buffer[BLK_TICKS(volume)] = OS_LONG2BE(ds.ds_Tick); - if (blockbuffer->buffer[BLK_PARENT(volume)] == 0) - break; - writeBlockDeferred(afsbase, volume, blockbuffer, BLK_CHECKSUM); - blockbuffer = getBlock - (afsbase, volume, OS_BE2LONG(blockbuffer->buffer[BLK_PARENT(volume)])); - if (blockbuffer == NULL) - return ERROR_UNKNOWN; - } - /* last block is not written yet - it's the rootblock */ - /* we have to change BLK_VOLUME_xxx */ - blockbuffer->buffer[BLK_VOLUME_DAYS(volume)] = OS_LONG2BE(ds.ds_Days); - blockbuffer->buffer[BLK_VOLUME_MINS(volume)] = OS_LONG2BE(ds.ds_Minute); - blockbuffer->buffer[BLK_VOLUME_TICKS(volume)] = OS_LONG2BE(ds.ds_Tick); - writeBlockDeferred(afsbase, volume, blockbuffer, BLK_CHECKSUM); - return 0; + /* store current time as modification date for this object and all its ancestors */ + DateStamp(&ds); + for (;;) + { + tail = BLK_TAILPTR(blockbuffer->buffer, volume); + putStamp(&tail[BLKO_DAYS], &ds); + if (tail[BLKO_PARENT] == 0) + break; + writeBlockDeferred(afsbase, volume, blockbuffer, BLK_CHECKSUM); + blockbuffer = getBlock + (afsbase, volume, OS_BE2LONG(tail[BLKO_PARENT])); + if (blockbuffer == NULL) + return ERROR_UNKNOWN; + } + /* last block is not written yet - it's the rootblock */ + /* we have to change BLK_VOLUME_xxx */ + putStamp(&tail[BLKO_VOLUME_DAYS], &ds); + writeBlockDeferred(afsbase, volume, blockbuffer, BLK_CHECKSUM); + return 0; } /******************************************* @@ -70,16 +79,16 @@ struct DateStamp ds; ********************************************/ LONG getDiskInfo(struct Volume *volume, struct InfoData *id) { - id->id_NumSoftErrors = 0; - id->id_UnitNumber = volume->unit; - id->id_DiskState = volume->state; - id->id_NumBlocks = volume->countblocks-volume->bootblocks; - id->id_NumBlocksUsed = volume->usedblockscount; - id->id_BytesPerBlock = volume->dosflags==0 ? BLOCK_SIZE(volume)-24 : BLOCK_SIZE(volume); - id->id_DiskType = mediumPresent(&volume->ioh) ? (volume->dostype | volume->dosflags) : ID_NO_DISK_PRESENT; - id->id_VolumeNode = MKBADDR(volume->volumenode); - id->id_InUse = (LONG)TRUE; /* if we are here the device should be in use! */ - return 0; + id->id_NumSoftErrors = 0; + id->id_UnitNumber = volume->unit; + id->id_DiskState = volume->state; + id->id_NumBlocks = volume->countblocks-volume->bootblocks; + id->id_NumBlocksUsed = volume->usedblockscount; + id->id_BytesPerBlock = volume->dosflags==0 ? BLOCK_SIZE(volume)-24 : BLOCK_SIZE(volume); + id->id_DiskType = mediumPresent(&volume->ioh) ? (volume->dostype | volume->dosflags) : ID_NO_DISK_PRESENT; + id->id_VolumeNode = MKBADDR(volume->volumenode); + id->id_InUse = (LONG)TRUE; /* if we are here the device should be in use! */ + return 0; } /******************************************* @@ -91,36 +100,51 @@ LONG getDiskInfo(struct Volume *volume, struct InfoData *id) { Output: 0 = no error ********************************************/ LONG inhibit(struct AFSBase *afsbase, struct Volume *volume, ULONG forbid) { - D(bug("[afs 0x%08lX] inhibit(%ld)\n", volume, forbid)); - if (forbid) - { - if (volume->inhibitcounter++ == 0) - { - D(bug("[afs 0x%08lX] inhibiting\n", volume)); -/* if (exclusiveLocks(&volume->locklist)) return DOSFALSE; */ - if (mediumPresent(&volume->ioh)) - { - flush(afsbase, volume); - osMediumFree(afsbase, volume, FALSE); - } - } - } - else if (volume->inhibitcounter) - { - if (--volume->inhibitcounter == 0) - { - D(bug("[afs 0x%08lX] uninhibiting\n", volume)); - if (diskPresent(afsbase, &volume->ioh)) - { - D(bug("[afs 0x%08lX] media inserted\n", volume)); - newMedium(afsbase, volume); - volume->ioh.ioflags |= IOHF_DISK_IN; - } - else - volume->ioh.ioflags &= ~IOHF_DISK_IN; - } - } - return 0; + D(bug("[afs 0x%p] inhibit(%d)\n", volume, forbid)); + if (forbid) + { + if (volume->inhibitcounter++ == 0) + { + D(bug("[afs 0x%p] inhibiting\n", volume)); +/* if (exclusiveLocks(&volume->locklist)) return DOSFALSE; */ + if (mediumPresent(&volume->ioh)) + { + if (!flushForRelease(afsbase, volume)) + { + volume->inhibitcounter--; + return ERROR_UNKNOWN; + } + osMediumFree(afsbase, volume, FALSE); + clearCleanCache(volume); + } + } + } + else if (volume->inhibitcounter) + { + if (--volume->inhibitcounter == 0) + { + D(bug("[afs 0x%p] uninhibiting\n", volume)); + if (diskPresent(afsbase, &volume->ioh)) + { + D(bug("[afs 0x%p] media inserted\n", volume)); + volume->ioh.ioflags |= IOHF_DISK_IN; + { + LONG error = newMedium(afsbase, volume); + /* NDOS and unreadable media are still present. + * Only pending writes prevent us from accepting + * this medium after a failed remount. */ + if (error != 0 && volume->cachepending) + { + volume->ioh.ioflags &= ~IOHF_DISK_IN; + return error; + } + } + } + else + volume->ioh.ioflags &= ~IOHF_DISK_IN; + } + } + return 0; } /******************************************* @@ -130,29 +154,36 @@ LONG inhibit(struct AFSBase *afsbase, struct Volume *volume, ULONG forbid) { Input : volume - the volume Output: - ********************************************/ -void markBitmaps(struct AFSBase *afsbase, struct Volume *volume) { +BOOL markBitmaps(struct AFSBase *afsbase, struct Volume *volume) { struct BlockCache *blockbuffer; ULONG i,curblock; - for (i=0; (i<=24) && (volume->bitmapblockpointers[i] != 0); i++) - markBlock(afsbase, volume, volume->bitmapblockpointers[i], 0); - curblock = volume->bitmapextensionblock; - while (curblock != 0) - { - blockbuffer = getBlock(afsbase, volume, curblock); - if (blockbuffer == NULL) - return; - blockbuffer->flags |= BCF_USED; - markBlock(afsbase, volume, curblock, 0); - for (i=0; iSizeBlock-1; i++) - { - if (blockbuffer->buffer[i] == 0) - break; - markBlock(afsbase, volume, OS_BE2LONG(blockbuffer->buffer[i]), 0); - } - curblock = OS_BE2LONG(blockbuffer->buffer[volume->SizeBlock-1]); - blockbuffer->flags &= ~BCF_USED; - } + for (i=0; (i<=24) && (volume->bitmapblockpointers[i] != 0); i++) + if (!markBlock(afsbase, volume, volume->bitmapblockpointers[i], 0)) + return DOSFALSE; + curblock = volume->bitmapextensionblock; + while (curblock != 0) + { + blockbuffer = getBlock(afsbase, volume, curblock); + if (blockbuffer == NULL) + return DOSFALSE; + blockbuffer->flags |= BCF_USED; + if (!markBlock(afsbase, volume, curblock, 0)) + goto failed; + for (i=0; iSizeBlock-1; i++) + { + if (blockbuffer->buffer[i] == 0) + break; + if (!markBlock(afsbase, volume, OS_BE2LONG(blockbuffer->buffer[i]), 0)) + goto failed; + } + curblock = OS_BE2LONG(blockbuffer->buffer[volume->SizeBlock-1]); + blockbuffer->flags &= ~BCF_USED; + } + return DOSTRUE; +failed: + blockbuffer->flags &= ~BCF_USED; + return DOSFALSE; } /******************************************* @@ -164,77 +195,89 @@ ULONG i,curblock; Output: 0 for success; error code otherwise ********************************************/ LONG format - (struct AFSBase *afsbase, struct Volume *volume, CONST_STRPTR name, - ULONG dostype) + (struct AFSBase *afsbase, struct Volume *volume, CONST_STRPTR name, + ULONG dostype) { struct BlockCache *blockbuffer; struct DateStamp ds; +ULONG *root, *tail; UWORD i; - blockbuffer = getFreeCacheBlock(afsbase, volume, 0); - if (blockbuffer != NULL) - { - blockbuffer->buffer[0] = OS_LONG2BE(dostype); - blockbuffer->buffer[2] = OS_LONG2BE(volume->rootblock); - writeBlock(afsbase, volume, blockbuffer, -1); - blockbuffer = getFreeCacheBlock(afsbase, volume, volume->rootblock); - if (blockbuffer != NULL) - { - blockbuffer->flags |= BCF_USED; - DateStamp(&ds); - blockbuffer->buffer[BLK_PRIMARY_TYPE] = OS_LONG2BE(T_SHORT); - blockbuffer->buffer[1] = 0; - blockbuffer->buffer[2] = 0; - blockbuffer->buffer[BLK_TABLE_SIZE] = OS_LONG2BE(volume->SizeBlock-56); - blockbuffer->buffer[4] = 0; - for (i=BLK_TABLE_START; i<=BLK_TABLE_END(volume); i++) - blockbuffer->buffer[i] = 0; - blockbuffer->buffer[BLK_BITMAP_VALID_FLAG(volume)] = -1; - createNewBitmapBlocks(afsbase, volume); - for ( - i=BLK_BITMAP_POINTERS_START(volume); - i<=BLK_BITMAP_POINTERS_END(volume); - i++ - ) - { - blockbuffer->buffer[i] = OS_LONG2BE - ( - volume->bitmapblockpointers[i-BLK_BITMAP_POINTERS_START(volume)] - ); - } - blockbuffer->buffer[BLK_BITMAP_EXTENSION(volume)] = - OS_LONG2BE(volume->bitmapextensionblock); - blockbuffer->buffer[BLK_ROOT_DAYS(volume)] = OS_LONG2BE(ds.ds_Days); - blockbuffer->buffer[BLK_ROOT_MINS(volume)] = OS_LONG2BE(ds.ds_Minute); - blockbuffer->buffer[BLK_ROOT_TICKS(volume)] = OS_LONG2BE(ds.ds_Tick); - StrCpyToBstr - ( - name, - (APTR)((char *)blockbuffer->buffer+(BLK_DISKNAME_START(volume)*4)), - MAX_NAME_LENGTH - ); - blockbuffer->buffer[volume->SizeBlock-12] = 0; - blockbuffer->buffer[volume->SizeBlock-11] = 0; - blockbuffer->buffer[BLK_VOLUME_DAYS(volume)] = OS_LONG2BE(ds.ds_Days); - blockbuffer->buffer[BLK_VOLUME_MINS(volume)] = OS_LONG2BE(ds.ds_Minute); - blockbuffer->buffer[BLK_VOLUME_TICKS(volume)] = OS_LONG2BE(ds.ds_Tick); - blockbuffer->buffer[BLK_CREATION_DAYS(volume)] = OS_LONG2BE(ds.ds_Days); - blockbuffer->buffer[BLK_CREATION_MINS(volume)] = OS_LONG2BE(ds.ds_Minute); - blockbuffer->buffer[BLK_CREATION_TICKS(volume)] = OS_LONG2BE(ds.ds_Tick); - blockbuffer->buffer[volume->SizeBlock-4] = 0; - blockbuffer->buffer[volume->SizeBlock-3] = 0; - blockbuffer->buffer[volume->SizeBlock-2] = 0; - blockbuffer->buffer[BLK_SECONDARY_TYPE(volume)] = OS_LONG2BE(ST_ROOT); - writeBlock(afsbase, volume, blockbuffer, BLK_CHECKSUM); - blockbuffer->flags &= ~BCF_USED; - invalidBitmap(afsbase, volume); - markBlock(afsbase, volume, volume->rootblock, 0); - markBitmaps(afsbase, volume); - validBitmap(afsbase, volume); - return 0; - } - } - return ERROR_UNKNOWN; + blockbuffer = getFreeCacheBlock(afsbase, volume, 0); + if (blockbuffer != NULL) + { + blockbuffer->buffer[0] = OS_LONG2BE(dostype); + blockbuffer->buffer[2] = OS_LONG2BE(volume->rootblock); + if (!writeBlock(afsbase, volume, blockbuffer, -1)) + return ERROR_UNKNOWN; + blockbuffer = getFreeCacheBlock(afsbase, volume, volume->rootblock); + if (blockbuffer != NULL) + { + blockbuffer->flags |= BCF_USED; + DateStamp(&ds); + root = blockbuffer->buffer; + tail = BLK_TAILPTR(root, volume); + root[BLK_PRIMARY_TYPE] = OS_LONG2BE(T_SHORT); + root[1] = 0; + root[2] = 0; + root[BLK_TABLE_SIZE] = OS_LONG2BE(volume->SizeBlock-56); + root[4] = 0; + for (i=BLK_TABLE_START; i<=BLK_TABLE_END(volume); i++) + root[i] = 0; + tail[BLKO_BITMAP_VALID_FLAG] = -1; + if (!createNewBitmapBlocks(afsbase, volume)) + { + blockbuffer->flags &= ~BCF_USED; + return ERROR_UNKNOWN; + } + for (i=0; i<=BLKO_BITMAP_POINTERS_END-BLKO_BITMAP_POINTERS_START; i++) + { + tail[BLKO_BITMAP_POINTERS_START+i] = OS_LONG2BE + ( + volume->bitmapblockpointers[i] + ); + } + tail[BLKO_BITMAP_EXTENSION] = + OS_LONG2BE(volume->bitmapextensionblock); + putStamp(&tail[BLKO_ROOT_DAYS], &ds); + StrCpyToBstr + ( + name, + (APTR)&tail[BLKO_DISKNAME_START], + MAX_NAME_LENGTH + ); + tail[-12] = 0; + tail[-11] = 0; + putStamp(&tail[BLKO_VOLUME_DAYS], &ds); + putStamp(&tail[BLKO_CREATION_DAYS], &ds); + tail[-4] = 0; + tail[-3] = 0; + tail[-2] = 0; + tail[BLKO_SECONDARY_TYPE] = OS_LONG2BE(ST_ROOT); + if (!writeBlock(afsbase, volume, blockbuffer, BLK_CHECKSUM)) + { + blockbuffer->flags &= ~BCF_USED; + return ERROR_UNKNOWN; + } + blockbuffer->flags &= ~BCF_USED; + if (!invalidBitmap(afsbase, volume)) + return ERROR_UNKNOWN; + if (!markBlock(afsbase, volume, volume->rootblock, 0) + || !markBitmaps(afsbase, volume)) + { + if (volume->bitmapblock != NULL) + volume->bitmapblock->flags &= ~BCF_USED; + volume->writefailed = TRUE; + volume->state = ID_VALIDATING; + setBitmapFlag(afsbase, volume, 0); + return ERROR_UNKNOWN; + } + if (!validBitmap(afsbase, volume)) + return ERROR_UNKNOWN; + return 0; + } + } + return ERROR_UNKNOWN; } /******************************************* @@ -245,40 +288,42 @@ UWORD i; Output: DOSTRUE for success; DOSFALSE otherwise ********************************************/ LONG relabel(struct AFSBase *afsbase, struct Volume *volume, - CONST_STRPTR name, SIPTR *error) { + CONST_STRPTR name, SIPTR *error) { struct BlockCache *blockbuffer; struct DateStamp ds; +ULONG *tail; - if (0 == checkValid(afsbase, volume)) - { - *error = ERROR_DISK_WRITE_PROTECTED; - return DOSFALSE; - } - osMediumFree(afsbase, volume, FALSE); - blockbuffer=getBlock(afsbase, volume,volume->rootblock); - if (blockbuffer == NULL) - return DOSFALSE; + if (0 == checkValid(afsbase, volume)) + { + *error = ERROR_DISK_WRITE_PROTECTED; + return DOSFALSE; + } + osMediumFree(afsbase, volume, FALSE); + blockbuffer=getBlock(afsbase, volume,volume->rootblock); + if (blockbuffer == NULL) + return DOSFALSE; if (strlen(name) > MAX_NAME_LENGTH) { *error = ERROR_LINE_TOO_LONG; return DOSFALSE; } - StrCpyToBstr - ( - name, - (APTR)((char *)blockbuffer->buffer+(BLK_DISKNAME_START(volume)*4)), - MAX_NAME_LENGTH - ); - DateStamp(&ds); - blockbuffer->buffer[BLK_ROOT_DAYS(volume)] = OS_LONG2BE(ds.ds_Days); - blockbuffer->buffer[BLK_ROOT_MINS(volume)] = OS_LONG2BE(ds.ds_Minute); - blockbuffer->buffer[BLK_ROOT_TICKS(volume)] = OS_LONG2BE(ds.ds_Tick); - blockbuffer->buffer[BLK_VOLUME_DAYS(volume)] = OS_LONG2BE(ds.ds_Days); - blockbuffer->buffer[BLK_VOLUME_MINS(volume)] = OS_LONG2BE(ds.ds_Minute); - blockbuffer->buffer[BLK_VOLUME_TICKS(volume)] = OS_LONG2BE(ds.ds_Tick); - writeBlock(afsbase, volume, blockbuffer, BLK_CHECKSUM); - /* update os specific information of the medium */ - osMediumInit(afsbase, volume, blockbuffer); - return DOSTRUE; + tail = BLK_TAILPTR(blockbuffer->buffer, volume); + StrCpyToBstr + ( + name, + (APTR)&tail[BLKO_DISKNAME_START], + MAX_NAME_LENGTH + ); + DateStamp(&ds); + putStamp(&tail[BLKO_ROOT_DAYS], &ds); + putStamp(&tail[BLKO_VOLUME_DAYS], &ds); + if (!writeBlock(afsbase, volume, blockbuffer, BLK_CHECKSUM)) + { + *error = ERROR_UNKNOWN; + return DOSFALSE; + } + /* update os specific information of the medium */ + osMediumInit(afsbase, volume, blockbuffer); + return DOSTRUE; } diff --git a/rom/filesys/afs/misc.h b/rom/filesys/afs/misc.h index 9bab4ddd5fd..26922548d4a 100644 --- a/rom/filesys/afs/misc.h +++ b/rom/filesys/afs/misc.h @@ -2,7 +2,7 @@ #define MISC_H /* - Copyright © 1995-2008, The AROS Development Team. All rights reserved. + Copyright © 1995-2026, The AROS Development Team. All rights reserved. $Id$ */ @@ -10,6 +10,7 @@ #include "volumes.h" ULONG writeHeader(struct AFSBase *, struct Volume *, struct BlockCache *); +void putStamp(ULONG *dest, const struct DateStamp *ds); LONG getDiskInfo(struct Volume *, struct InfoData *); LONG inhibit(struct AFSBase *, struct Volume *, ULONG forbid); LONG format(struct AFSBase *, struct Volume *, CONST_STRPTR, ULONG); diff --git a/rom/filesys/afs/mmakefile.src b/rom/filesys/afs/mmakefile.src index 7965403714d..46e0c9ee627 100644 --- a/rom/filesys/afs/mmakefile.src +++ b/rom/filesys/afs/mmakefile.src @@ -1,7 +1,12 @@ -# $Id$ +# Copyright (C) 2026, The AROS Development Team. All rights reserved. include $(SRCDIR)/config/aros.cfg +AFS_INLINE_REQUESTERS ?= 1 +# muFS permissions need security.library, which ApolloOS does not have +AFS_SECURITY ?= 0 +-include $(SRCDIR)/arch/$(CPU)-$(ARCH)/filesys/afs/make.opts + FILES := main \ bitmap \ cache \ @@ -11,20 +16,31 @@ FILES := main \ filehandles1 \ filehandles2 \ filehandles3 \ + afs_security \ hashing \ misc \ os_aros_support \ volumes \ validator -#MM- kernel-fs-afs : includes linklibs +ifeq ($(AFS_INLINE_REQUESTERS),0) +FILES += os_aros_requesters +endif + +#MM- kernel-fs-afs : includes linklibs kernel-security-includes kernel-task-includes USER_CPPFLAGS := \ -DUSE_EXEC_DEBUG \ + -DAFS_INLINE_REQUESTERS=$(AFS_INLINE_REQUESTERS) \ + -DAFS_SECURITY=$(AFS_SECURITY) \ -D__INTUITION_NOLIBBASE__ \ -DADATE="\"$(shell date '+%d.%m.%Y')\"" USER_LDFLAGS := -static +ifneq ($(ROM_OPTIMIZATION_CFLAGS),) +OPTIMIZATION_CFLAGS := $(ROM_OPTIMIZATION_CFLAGS) +endif + %build_module mmake=kernel-fs-afs \ modname=afs modtype=handler \ files="$(FILES)" diff --git a/rom/filesys/afs/os.h b/rom/filesys/afs/os.h index a57637686d7..1a9bf247993 100644 --- a/rom/filesys/afs/os.h +++ b/rom/filesys/afs/os.h @@ -2,7 +2,7 @@ #define OS_SUPPORT_H /* - Copyright © 1995-2010, The AROS Development Team. All rights reserved. + Copyright © 1995-2026, The AROS Development Team. All rights reserved. $Id$ */ @@ -12,6 +12,17 @@ #include "os_unix_support.h" #endif +/* + * Storage class for static helpers shared by several code paths. On m68k + * the handler lives in the Kickstart ROM, so keep one out of line copy; + * elsewhere inline them into every caller as the open coded original was. + */ +#if defined(__mc68000__) +#define AFS_SHARED static __attribute__((noinline)) +#else +#define AFS_SHARED static inline __attribute__((always_inline)) +#endif + struct BlockCache; struct Volume; @@ -22,11 +33,13 @@ LONG readDisk(struct AFSBase *, struct Volume *, ULONG, ULONG, APTR); LONG writeDisk(struct AFSBase *, struct Volume *, ULONG, ULONG, APTR); UBYTE diskPresent(struct AFSBase *, struct IOHandle *); BOOL diskWritable(struct AFSBase *, struct IOHandle *); -ULONG sectorSize(struct AFSBase *, struct IOHandle *); BOOL flush(struct AFSBase *, struct Volume *); +#ifdef __AROS__ +LONG prepareMediumCache(struct AFSBase *, struct Volume *); +#endif struct IOHandle *openBlockDevice(struct AFSBase *, struct IOHandle *); void closeBlockDevice(struct AFSBase *, struct IOHandle *); void check64BitSupport(struct AFSBase *, struct Volume *); -LONG attemptAddDosVolume(struct AFSBase *afsbase, struct Volume *volume); +LONG addDosVolume(struct AFSBase *afsbase, struct Volume *volume); #endif diff --git a/rom/filesys/afs/os_aros_requesters.c b/rom/filesys/afs/os_aros_requesters.c new file mode 100644 index 00000000000..92ceb7c6e7b --- /dev/null +++ b/rom/filesys/afs/os_aros_requesters.c @@ -0,0 +1,11 @@ +/* + Copyright (C) 2026, The AROS Development Team. All rights reserved. +*/ + +#include "os_aros_support.h" + +#if !AFS_INLINE_REQUESTERS +#define AFS_REQUESTER_LINKAGE +#include "os_aros_requesters.h" +#undef AFS_REQUESTER_LINKAGE +#endif diff --git a/rom/filesys/afs/os_aros_requesters.h b/rom/filesys/afs/os_aros_requesters.h new file mode 100644 index 00000000000..767e825ba87 --- /dev/null +++ b/rom/filesys/afs/os_aros_requesters.h @@ -0,0 +1,28 @@ +/* + Copyright (C) 2026, The AROS Development Team. All rights reserved. + + Shared implementation for the inline and external requester wrappers. + Include after os_aros_support.h with AFS_REQUESTER_LINKAGE selected. +*/ + +AFS_REQUESTER_LINKAGE LONG showText(struct AFSBase *afsbase, const char *format, ...) +{ + LONG ret; + + AROS_SLOWSTACKFORMAT_PRE(format); + ret = showPtrArgsText(afsbase, format, Req_Cancel, AROS_SLOWSTACKFORMAT_ARG(format)); + AROS_SLOWSTACKFORMAT_POST(format); + + return ret; +} + +AFS_REQUESTER_LINKAGE LONG showRetriableError(struct AFSBase *afsbase, const char *format, ...) +{ + LONG ret; + + AROS_SLOWSTACKFORMAT_PRE(format); + ret = showPtrArgsText(afsbase, format, Req_RetryCancel, AROS_SLOWSTACKFORMAT_ARG(format)); + AROS_SLOWSTACKFORMAT_POST(format); + + return ret; +} diff --git a/rom/filesys/afs/os_aros_support.c b/rom/filesys/afs/os_aros_support.c index eb1fdd72727..873d0306bb9 100644 --- a/rom/filesys/afs/os_aros_support.c +++ b/rom/filesys/afs/os_aros_support.c @@ -1,8 +1,11 @@ /* - Copyright � 1995-2013, The AROS Development Team. All rights reserved. - $Id$ + Copyright (C) 1995-2026, The AROS Development Team. All rights reserved. */ +#ifndef DEBUG +#define DEBUG 0 +#endif + #include #include #include @@ -18,6 +21,8 @@ #include "error.h" #include "extstrings.h" #include "volumes.h" +#include "cache.h" +#include "checksums.h" #include "baseredef.h" /* @@ -66,507 +71,692 @@ static void SendEvent(struct AFSBase *afsbase, LONG event) { Output: DOSTRUE for success; DOSFALSE otherwise ********************************************/ LONG initDeviceList - ( - struct AFSBase *afsbase, - struct Volume *volume, - struct BlockCache *rootblock - ) + ( + struct AFSBase *afsbase, + struct Volume *volume, + struct BlockCache *rootblock + ) { STRPTR name; BSTR newname; -UBYTE i; +UBYTE i, length; + + name=(char *)rootblock->buffer+(BLK_DISKNAME_START(volume)*4); + length = (UBYTE)name[0]; + if (length > MAX_NAME_LENGTH) + return DOSFALSE; + volume->devicelist.dl_Next = 0; + volume->devicelist.dl_Type = DLT_VOLUME; + volume->devicelist.dl_Lock = 0; + volume->devicelist.dl_VolumeDate.ds_Days = + AROS_BE2LONG(rootblock->buffer[BLK_CREATION_DAYS(volume)]); + volume->devicelist.dl_VolumeDate.ds_Minute = + AROS_BE2LONG(rootblock->buffer[BLK_CREATION_MINS(volume)]); + volume->devicelist.dl_VolumeDate.ds_Tick = + AROS_BE2LONG(rootblock->buffer[BLK_CREATION_TICKS(volume)]); + volume->devicelist.dl_LockList = 0; + volume->devicelist.dl_DiskType = volume->dostype; + if (volume->devicelist.dl_Name != BNULL) + { + newname = volume->devicelist.dl_Name; + } + else + { + newname = MKBADDR(AllocVec(32,MEMF_CLEAR | MEMF_PUBLIC)); + if (newname == BNULL) + return DOSFALSE; + } + for (i=0; idevicelist.dl_Name = newname; + return DOSTRUE; +} - name=(char *)rootblock->buffer+(BLK_DISKNAME_START(volume)*4); - volume->devicelist.dl_Next = 0; - volume->devicelist.dl_Type = DLT_VOLUME; - volume->devicelist.dl_Lock = 0; - volume->devicelist.dl_VolumeDate.ds_Days = - AROS_BE2LONG(rootblock->buffer[BLK_ROOT_DAYS(volume)]); - volume->devicelist.dl_VolumeDate.ds_Minute = - AROS_BE2LONG(rootblock->buffer[BLK_ROOT_MINS(volume)]); - volume->devicelist.dl_VolumeDate.ds_Tick = - AROS_BE2LONG(rootblock->buffer[BLK_ROOT_TICKS(volume)]); - volume->devicelist.dl_LockList = 0; - volume->devicelist.dl_DiskType = volume->dostype; - if (volume->devicelist.dl_Name != BNULL) - { - newname = volume->devicelist.dl_Name; - } - else - { - newname = MKBADDR(AllocVec(32,MEMF_CLEAR | MEMF_PUBLIC)); - if (newname == BNULL) - return DOSFALSE; - } - for (i=0; idevicelist.dl_Name = newname; - return DOSTRUE; +/******************************************* + Name : findOfflineNode + Descr.: find a parked offline volume node for this medium, + matched by name and volume creation date + Input : volume - the mounted medium + name - its volume name as a C string + Output: the parked node, or NULL +********************************************/ +static struct OfflineNode *findOfflineNode + (struct AFSBase *afsbase, struct Volume *volume, CONST_STRPTR name) +{ +struct OfflineNode *on; + + for (on = (struct OfflineNode *)afsbase->offlinevols.mlh_Head; + on->node.mln_Succ != NULL; + on = (struct OfflineNode *)on->node.mln_Succ) + { + struct DosList *dl = on->dl; + BSTR bname = dl->dol_Name; + UBYTE len = AROS_BSTR_strlen(bname); + UBYTE i; + + if (dl->dol_misc.dol_volume.dol_VolumeDate.ds_Days != + volume->devicelist.dl_VolumeDate.ds_Days || + dl->dol_misc.dol_volume.dol_VolumeDate.ds_Minute != + volume->devicelist.dl_VolumeDate.ds_Minute || + dl->dol_misc.dol_volume.dol_VolumeDate.ds_Tick != + volume->devicelist.dl_VolumeDate.ds_Tick) + continue; + for (i=0; ivolumenode) { - D(bug("[AFS] VolumeNode 0x%08lX is already present!\n", volume)); - return DOSTRUE; - } - bname = volume->devicelist.dl_Name; - for (i=0; idol_Task = &((struct Process *)FindTask(NULL))->pr_MsgPort; - doslist->dol_misc.dol_volume.dol_VolumeDate.ds_Days = - volume->devicelist.dl_VolumeDate.ds_Days; - doslist->dol_misc.dol_volume.dol_VolumeDate.ds_Minute = - volume->devicelist.dl_VolumeDate.ds_Minute; - doslist->dol_misc.dol_volume.dol_VolumeDate.ds_Tick = - volume->devicelist.dl_VolumeDate.ds_Tick; - AddDosEntry(doslist); - /* if we re-use "volume" clear locklist */ - volume->locklist = NULL; - dl = doslist; - } - volume->volumenode = dl; - SendEvent(afsbase, IECLASS_DISKINSERTED); - return DOSTRUE; + if (volume->volumenode) { + D(bug("[afs 0x%08lX] VolumeNode is already present!\n", volume)); + return DOSTRUE; + } + bname = volume->devicelist.dl_Name; + if (AROS_BSTR_strlen(bname) >= sizeof(string)) + return DOSFALSE; + for (i=0; idl; + volume->volumenodeadded = on->added; + Remove((struct Node *)&on->node); + FreeMem(on, sizeof(struct OfflineNode)); + afsbase->parkedvols--; + /* take back the locks that kept the node alive */ + volume->locklist = BADDR(dl->dol_misc.dol_volume.dol_LockList); + dl->dol_misc.dol_volume.dol_LockList = BNULL; + Forbid(); + dl->dol_Task = &((struct Process *)FindTask(NULL))->pr_MsgPort; + Permit(); + } + else + { + D(bug("[afs 0x%08lX] Creating new VolumeNode\n", volume)); + dl = MakeDosEntry(string,DLT_VOLUME); + if (dl == NULL) + return DOSFALSE; + dl->dol_Task = &((struct Process *)FindTask(NULL))->pr_MsgPort; + dl->dol_misc.dol_volume.dol_VolumeDate.ds_Days = + volume->devicelist.dl_VolumeDate.ds_Days; + dl->dol_misc.dol_volume.dol_VolumeDate.ds_Minute = + volume->devicelist.dl_VolumeDate.ds_Minute; + dl->dol_misc.dol_volume.dol_VolumeDate.ds_Tick = + volume->devicelist.dl_VolumeDate.ds_Tick; + volume->locklist = NULL; + volume->volumenodeadded = FALSE; + } + volume->volumenode = dl; + return DOSTRUE; +} + +/******************************************* + Name : addDosVolume + Descr.: publish the volume node in the system DosList; retried from + the flush timer while the list stays contended + Input : volume - volume whose node to publish + Output: DOSTRUE when published (or nothing to do); DOSFALSE to retry +********************************************/ +LONG addDosVolume(struct AFSBase *afsbase, struct Volume *volume) +{ + if ((volume->volumenode == NULL) || volume->volumenodeadded) + return DOSTRUE; + /* don't block: a DosList holder may be waiting on this handler */ + if (AttemptLockDosList(LDF_WRITE | LDF_VOLUMES) == NULL) + return DOSFALSE; + UnLockDosList(LDF_WRITE | LDF_VOLUMES); + AddDosEntry(volume->volumenode); /* takes LDF_READ|LDF_ENTRY itself */ + volume->volumenodeadded = TRUE; + SendEvent(afsbase, IECLASS_DISKINSERTED); + return DOSTRUE; } /******************************************* Name : remDosVolume - Descr.: removes a volume added by addDosVolume - or if there are some locks active - set dol_LockList + Descr.: removes a volume's node, or parks it offline + while locks are active Input : volume - volume to remove Output: - ********************************************/ void remDosVolume(struct AFSBase *afsbase, struct Volume *volume) { struct DosList *dl; - - dl = volume->volumenode; - if (dl) { - if (volume->locklist != NULL) - { - D(bug("[AFS] VolumeNode in use, keeping as offline: 0x%08lX\n", volume)); - dl->dol_misc.dol_volume.dol_LockList = MKBADDR(volume->locklist); - } - else - { - D(bug("[AFS] Removing VolumeNode: 0x%08lX\n", volume)); - remDosNode(afsbase, dl); - } - volume->volumenode = NULL; - } +struct OfflineNode *on; + + dl = volume->volumenode; + if (dl) { + if (volume->locklist != NULL) + { + D(bug("[afs 0x%08lX] VolumeNode in use, keeping as offline\n", volume)); + dl->dol_misc.dol_volume.dol_LockList = MKBADDR(volume->locklist); + volume->locklist = NULL; + Forbid(); + dl->dol_Task = NULL; + Permit(); + afsbase->parkedvols++; + on = AllocMem(sizeof(struct OfflineNode), MEMF_PUBLIC | MEMF_CLEAR); + if (on != NULL) + { + on->dl = dl; + on->added = volume->volumenodeadded; + AddTail((struct List *)&afsbase->offlinevols, + (struct Node *)&on->node); + } + /* if the record could not be made the node stays + reachable through its handles only; a re-insert + then makes a fresh node */ + } + else + { + D(bug("[afs 0x%08lX] Removing VolumeNode\n", volume)); + if (volume->volumenodeadded) + remDosNode(afsbase, dl); + else + FreeDosEntry(dl); + } + volume->volumenode = NULL; + volume->volumenodeadded = FALSE; + } } /******************************************* Name : remDosNode - Descr.: removes a DOS volume node + Descr.: removes a DOS volume node; parked nodes that were never + published are only freed Input : dl - volume to remove Output: - ********************************************/ void remDosNode(struct AFSBase *afsbase, struct DosList *dl) { - RemDosEntry(dl); - FreeDosEntry(dl); - SendEvent(afsbase, IECLASS_DISKREMOVED); +struct OfflineNode *on; +BOOL added = TRUE; + + for (on = (struct OfflineNode *)afsbase->offlinevols.mlh_Head; + on->node.mln_Succ != NULL; + on = (struct OfflineNode *)on->node.mln_Succ) + { + if (on->dl == dl) + { + added = on->added; + Remove((struct Node *)&on->node); + FreeMem(on, sizeof(struct OfflineNode)); + break; + } + } + if (added) + { + RemDosEntry(dl); + SendEvent(afsbase, IECLASS_DISKREMOVED); + } + FreeDosEntry(dl); } LONG osMediumInit - (struct AFSBase *afsbase, struct Volume *volume, struct BlockCache *block) + (struct AFSBase *afsbase, struct Volume *volume, struct BlockCache *block) { - if (!initDeviceList(afsbase, volume, block)) - return ERROR_NO_FREE_STORE; - if (!attemptAddDosVolume(afsbase, volume)) - { - showError(afsbase, ERR_DOSENTRY); - remDosVolume(afsbase, volume); - return ERROR_UNKNOWN; - } - return 0; + UBYTE *name = (UBYTE *)block->buffer + BLK_DISKNAME_START(volume) * 4; + + if (name[0] > MAX_NAME_LENGTH) + return ERROR_DISK_NOT_VALIDATED; + if (!initDeviceList(afsbase, volume, block)) + return ERROR_NO_FREE_STORE; + if (!createDosVolume(afsbase, volume)) + { + showError(afsbase, ERR_DOSENTRY); + remDosVolume(afsbase, volume); + return ERROR_UNKNOWN; + } + addDosVolume(afsbase, volume); + return 0; } void osMediumFree(struct AFSBase *afsbase, struct Volume *volume, LONG all) { - remDosVolume(afsbase, volume); - if (all) - FreeVec(BADDR(volume->devicelist.dl_Name)); + remDosVolume(afsbase, volume); + if (all) + FreeVec(BADDR(volume->devicelist.dl_Name)); } /************************** I/O ******************************************/ struct IOExtTD *openDevice - ( - struct AFSBase *afsbase, - struct MsgPort *mp, - STRPTR device, - ULONG unit, - ULONG flags - ) + ( + struct AFSBase *afsbase, + struct MsgPort *mp, + STRPTR device, + ULONG unit, + ULONG flags + ) { struct IOExtTD *ioreq; - ioreq = (struct IOExtTD *)CreateIORequest(mp, sizeof(struct IOExtTD)); - if (ioreq != NULL) - { - if (OpenDevice(device, unit, (struct IORequest *)ioreq, flags) == 0) - { - return ioreq; - } - else - showError(afsbase, ERR_DEVICE, device); - DeleteIORequest((struct IORequest *)ioreq); - } - return NULL; + ioreq = (struct IOExtTD *)CreateIORequest(mp, sizeof(struct IOExtTD)); + if (ioreq != NULL) + { + if (OpenDevice(device, unit, (struct IORequest *)ioreq, flags) == 0) + { + return ioreq; + } + else + showError(afsbase, ERR_DEVICE, device); + DeleteIORequest((struct IORequest *)ioreq); + } + return NULL; } void closeDevice(struct AFSBase *afsbase, struct IOExtTD *ioreq) { - if (ioreq->iotd_Req.io_Device != NULL) - CloseDevice((struct IORequest *)&ioreq->iotd_Req); - DeleteIORequest((APTR)ioreq); + if (ioreq->iotd_Req.io_Device != NULL) + CloseDevice((struct IORequest *)&ioreq->iotd_Req); + DeleteIORequest((APTR)ioreq); } LONG getGeometry - (struct AFSBase *afsbase, struct IOHandle *ioh, struct DriveGeometry *dg) + (struct AFSBase *afsbase, struct IOHandle *ioh, struct DriveGeometry *dg) { - ioh->ioreq->iotd_Req.io_Command = TD_GETGEOMETRY; - ioh->ioreq->iotd_Req.io_Data = dg; - ioh->ioreq->iotd_Req.io_Length = sizeof(struct DriveGeometry); - return DoIO((struct IORequest *)&ioh->ioreq->iotd_Req); + ioh->ioreq->iotd_Req.io_Command = TD_GETGEOMETRY; + ioh->ioreq->iotd_Req.io_Data = dg; + ioh->ioreq->iotd_Req.io_Length = sizeof(struct DriveGeometry); + return DoIO((struct IORequest *)&ioh->ioreq->iotd_Req); } AROS_INTP(changeIntCode); -LONG addChangeInt(struct AFSBase *afsbase, struct IOHandle *ioh) -{ - D(bug("[AFS] AddChangeInt() Hook sent to exec device driver: 0x%08lX\n", ioh->mc_int.is_Code)); - - ioh->mc_int.is_Code = (VOID_FUNC)changeIntCode; - ioh->mc_int.is_Data = ioh; - ioh->iochangeint->iotd_Req.io_Command = TD_ADDCHANGEINT; - ioh->iochangeint->iotd_Req.io_Flags = 0; - ioh->iochangeint->iotd_Req.io_Length = sizeof(struct Interrupt); - ioh->iochangeint->iotd_Req.io_Data = &ioh->mc_int; - ioh->iochangeint->iotd_Req.io_Error = 0; - SendIO((struct IORequest *)&ioh->iochangeint->iotd_Req); - return ioh->iochangeint->iotd_Req.io_Error; +LONG addChangeInt(struct AFSBase *afsbase, struct IOHandle *ioh) { + + ioh->mc_int.is_Code = (VOID_FUNC)changeIntCode; + ioh->mc_int.is_Data = ioh; + ioh->iochangeint->iotd_Req.io_Command = TD_ADDCHANGEINT; + ioh->iochangeint->iotd_Req.io_Flags = 0; + ioh->iochangeint->iotd_Req.io_Length = sizeof(struct Interrupt); + ioh->iochangeint->iotd_Req.io_Data = &ioh->mc_int; + ioh->iochangeint->iotd_Req.io_Error = 0; + SendIO((struct IORequest *)&ioh->iochangeint->iotd_Req); + return ioh->iochangeint->iotd_Req.io_Error; } void remChangeInt(struct AFSBase *afsbase, struct IOHandle *ioh) { - if ( - (ioh->iochangeint != NULL) && - (ioh->iochangeint->iotd_Req.io_Error == 0) - ) - { - ioh->iochangeint->iotd_Req.io_Command = TD_REMCHANGEINT; - DoIO((struct IORequest *)&ioh->iochangeint->iotd_Req); - } + if ( + (ioh->iochangeint != NULL) && + (ioh->iochangeint->iotd_Req.io_Error == 0) + ) + { + ioh->iochangeint->iotd_Req.io_Command = TD_REMCHANGEINT; + DoIO((struct IORequest *)&ioh->iochangeint->iotd_Req); + } } void checkAddChangeInt(struct AFSBase *afsbase, struct IOHandle *ioh) { struct DriveGeometry dg; - if (!getGeometry(afsbase, ioh, &dg)) - { - if (dg.dg_Flags & DGF_REMOVABLE) - { - ioh->iochangeint = openDevice - (afsbase, ioh->mp, ioh->blockdevice, ioh->unit, ioh->flags); - if (ioh->iochangeint != NULL) - { - addChangeInt(afsbase, ioh); - } - } - ioh->sectorsize = dg.dg_SectorSize; - } + if (!getGeometry(afsbase, ioh, &dg)) + { + if (dg.dg_Flags & DGF_REMOVABLE) + { + ioh->iochangeint = openDevice + (afsbase, ioh->mp, ioh->blockdevice, ioh->unit, ioh->flags); + if (ioh->iochangeint != NULL) + { + addChangeInt(afsbase, ioh); + } + } + ioh->sectorsize = dg.dg_SectorSize; + } } UBYTE diskPresent(struct AFSBase *afsbase, struct IOHandle *ioh) { - ioh->ioreq->iotd_Req.io_Command = TD_CHANGESTATE; - DoIO((struct IORequest *)&ioh->ioreq->iotd_Req); - return ioh->ioreq->iotd_Req.io_Actual == 0; + ioh->ioreq->iotd_Req.io_Command = TD_CHANGESTATE; + DoIO((struct IORequest *)&ioh->ioreq->iotd_Req); + return ioh->ioreq->iotd_Req.io_Actual == 0; } BOOL diskWritable(struct AFSBase *afsbase, struct IOHandle *ioh) { - ioh->ioreq->iotd_Req.io_Command = TD_PROTSTATUS; - DoIO((struct IORequest *)&ioh->ioreq->iotd_Req); - return ioh->ioreq->iotd_Req.io_Actual == 0; -} - -ULONG sectorSize(struct AFSBase *afsbase, struct IOHandle *ioh) -{ - return ioh->sectorsize; + ioh->ioreq->iotd_Req.io_Command = TD_PROTSTATUS; + DoIO((struct IORequest *)&ioh->ioreq->iotd_Req); + return ioh->ioreq->iotd_Req.io_Actual == 0; } struct IOHandle *openBlockDevice(struct AFSBase *afsbase, struct IOHandle *ioh) { - ioh->mp = CreateMsgPort(); - if (ioh->mp != NULL) - { - ioh->ioreq = openDevice(afsbase, ioh->mp, ioh->blockdevice, ioh->unit, ioh->flags); - if (ioh->ioreq != NULL) - { - ioh->cmdread = CMD_READ; - ioh->cmdwrite = CMD_WRITE; - ioh->cmdseek = TD_SEEK; - ioh->cmdformat = TD_FORMAT; - ioh->afsbase = afsbase; - if (diskPresent(afsbase, ioh)) - ioh->ioflags |= IOHF_DISK_IN; - checkAddChangeInt(afsbase, ioh); - return ioh; - } - DeleteMsgPort(ioh->mp); - } - return NULL; + ioh->mp = CreateMsgPort(); + if (ioh->mp != NULL) + { + ioh->ioreq = openDevice(afsbase, ioh->mp, ioh->blockdevice, ioh->unit, ioh->flags); + if (ioh->ioreq != NULL) + { + ioh->cmdread = CMD_READ; + ioh->cmdwrite = CMD_WRITE; + ioh->cmdseek = TD_SEEK; + ioh->cmdformat = TD_FORMAT; + ioh->afsbase = afsbase; + if (diskPresent(afsbase, ioh)) + ioh->ioflags |= IOHF_DISK_IN; + checkAddChangeInt(afsbase, ioh); + return ioh; + } + DeleteMsgPort(ioh->mp); + } + return NULL; } void closeBlockDevice(struct AFSBase *afsbase, struct IOHandle *ioh) { - remChangeInt(afsbase, ioh); - if (ioh->iochangeint != NULL) - closeDevice(afsbase, ioh->iochangeint); - if (ioh->ioreq != NULL) - closeDevice(afsbase, ioh->ioreq); - if (ioh->mp != NULL) - DeleteMsgPort(ioh->mp); + remChangeInt(afsbase, ioh); + if (ioh->iochangeint != NULL) + closeDevice(afsbase, ioh->iochangeint); + if (ioh->ioreq != NULL) + closeDevice(afsbase, ioh->ioreq); + if (ioh->mp != NULL) + DeleteMsgPort(ioh->mp); } void motorOff(struct AFSBase *afsbase, struct IOHandle *ioh) { - ioh->ioreq->iotd_Req.io_Command = TD_MOTOR; - ioh->ioreq->iotd_Req.io_Length = 0; - DoIO((struct IORequest *)&ioh->ioreq->iotd_Req); + ioh->ioreq->iotd_Req.io_Command = TD_MOTOR; + ioh->ioreq->iotd_Req.io_Length = 0; + DoIO((struct IORequest *)&ioh->ioreq->iotd_Req); } -void checkDeviceFlags(struct AFSBase *afsbase) +LONG prepareMediumCache(struct AFSBase *afsbase, struct Volume *volume) { + ULONG *root; + LONG error = ERROR_DISK_NOT_VALIDATED; + + clearCleanCache(volume); + if (!volume->cachepending) + return 0; + root = AllocVec(BLOCK_SIZE(volume), MEMF_PUBLIC); + if (root == NULL) + return ERROR_NO_FREE_STORE; + /* The creation timestamp is the volume identity; do not consult the + * old cache or the mutable label when deciding where to retry writes. */ + if (readDisk(afsbase, volume, volume->rootblock, 1, root) == 0 + && calcChkSum(volume->SizeBlock, root) == 0 + && OS_BE2LONG(root[BLK_PRIMARY_TYPE]) == T_SHORT + && OS_BE2LONG(root[BLK_SECONDARY_TYPE(volume)]) == ST_ROOT + && OS_BE2LONG(root[BLK_CREATION_DAYS(volume)]) == volume->devicelist.dl_VolumeDate.ds_Days + && OS_BE2LONG(root[BLK_CREATION_MINS(volume)]) == volume->devicelist.dl_VolumeDate.ds_Minute + && OS_BE2LONG(root[BLK_CREATION_TICKS(volume)]) == volume->devicelist.dl_VolumeDate.ds_Tick) + { + volume->cachepending = FALSE; + if (flush(afsbase, volume)) + error = 0; + else + volume->cachepending = TRUE; + } + FreeVec(root); + if (error != 0 && showPtrArgsText(afsbase, + "Pending changes need the previous volume. Cancel to retain them for reinsertion, or Continue to discard them", + Req_ContinueCancel, NULL) == 1) + { + discardCache(volume); + return 0; + } + return error; +} + +void checkDeviceFlags(struct AFSBase *afsbase) { struct Volume *volume; struct IOHandle *ioh; - - volume = (struct Volume *)afsbase->device_list.lh_Head; - D(bug("[AFS] Check Device Flags: 0x%08lX\n", volume)); - - while (volume->ln.ln_Succ != NULL) - { - ioh = &volume->ioh; - if ((ioh->ioflags & IOHF_MEDIA_CHANGE) && (!volume->inhibitcounter)) - { - D(bug("[AFS] Media change signalled: 0x%08lX\n", volume)); - if (diskPresent(afsbase, ioh)) - { - if (!volume->inhibitcounter) - { - D(bug("[AFS] Media inserted: 0x%08lX\n", volume)); - newMedium(afsbase, volume); - } - ioh->ioflags |= IOHF_DISK_IN; - } - else - { - if (!volume->inhibitcounter) - { - flush(afsbase, volume); - remDosVolume(afsbase, volume); - } - ioh->ioflags &= ~IOHF_DISK_IN; - } - ioh->ioflags &= ~IOHF_MEDIA_CHANGE; - } - volume = (struct Volume *)volume->ln.ln_Succ; - } +UBYTE present; + + volume = (struct Volume *)afsbase->device_list.lh_Head; + while (volume->ln.ln_Succ != NULL) + { + ioh = &volume->ioh; + if ((ioh->ioflags & IOHF_MEDIA_CHANGE) && (!volume->inhibitcounter)) + { + D(bug("[afs 0x%08lX] Media change signalled\n", volume)); + present = diskPresent(afsbase, ioh); + + /* A direct disk swap may deliver only one change event, + * and no writes or updates may go to an absent medium. */ + clearCleanCache(volume); + volume->cachepending = cacheDirty(volume) || volume->writefailed; + remDosVolume(afsbase, volume); + if (present) + { + D(bug("[afs 0x%08lX] Media inserted\n", volume)); + ioh->ioflags |= IOHF_DISK_IN; + if (newMedium(afsbase, volume) != 0 && volume->cachepending) + { + ioh->ioflags &= ~IOHF_DISK_IN; + showText(afsbase, "Re-insert the previous volume to save pending changes"); + } + } + else + { + if (volume->cachepending && showPtrArgsText(afsbase, + "Re-insert the previous volume to save pending changes. Continue to discard them, or Cancel to retain them", + Req_ContinueCancel, NULL) == 1) + discardCache(volume); + ioh->ioflags &= ~IOHF_DISK_IN; + } + ioh->ioflags &= ~IOHF_MEDIA_CHANGE; + } + volume = (struct Volume *)volume->ln.ln_Succ; + } } void check64BitSupport(struct AFSBase *afsbase, struct Volume *volume) { struct NSDeviceQueryResult nsdq; UWORD *cmdcheck; - if ( - ( - (volume->startblock+(volume->countblocks))* /* last block */ - (volume->SizeBlock*4/512) /* 1 portion (block) equals 512 (bytes) */ - )>8388608) - { - nsdq.SizeAvailable = 0; - nsdq.DevQueryFormat = 0; - volume->ioh.ioreq->iotd_Req.io_Command = NSCMD_DEVICEQUERY; - volume->ioh.ioreq->iotd_Req.io_Data = &nsdq; - volume->ioh.ioreq->iotd_Req.io_Length = sizeof(struct NSDeviceQueryResult); - if (DoIO((struct IORequest *)volume->ioh.ioreq) == IOERR_NOCMD) - { - D(bug("[AFS] initVolume-NSD: device doesn't understand NSD-Query\n")); - } - else - { - if ( - (volume->ioh.ioreq->iotd_Req.io_Actual > sizeof(struct NSDeviceQueryResult)) || - (volume->ioh.ioreq->iotd_Req.io_Actual == 0) || - (volume->ioh.ioreq->iotd_Req.io_Actual != nsdq.SizeAvailable) - ) - { - D(bug("[AFS] initVolume-NSD: WARNING wrong io_Actual using NSD\n")); - } - else - { - D(bug("[AFS] initVolume-NSD: using NSD commands\n")); - if (nsdq.DeviceType != NSDEVTYPE_TRACKDISK) - D(bug("[AFS] initVolume-NSD: WARNING no trackdisk type\n")); - for (cmdcheck=nsdq.SupportedCommands; *cmdcheck; cmdcheck++) - { - if (*cmdcheck == NSCMD_TD_READ64) - volume->ioh.cmdread = NSCMD_TD_READ64; - if (*cmdcheck == NSCMD_TD_WRITE64) - volume->ioh.cmdwrite = NSCMD_TD_WRITE64; - if (*cmdcheck == NSCMD_TD_SEEK64) - volume->ioh.cmdseek = NSCMD_TD_SEEK64; - if (*cmdcheck == NSCMD_TD_FORMAT64) - volume->ioh.cmdformat = NSCMD_TD_FORMAT64; - } - if ( - (volume->ioh.cmdread != NSCMD_TD_READ64) || - (volume->ioh.cmdwrite != NSCMD_TD_WRITE64) - ) - D(bug("[AFS] initVolume-NSD: WARNING no READ64/WRITE64\n")); - } - } - } - else - { - D(bug("[AFS] initVolume-NSD: no need for NSD\n")); - } + if ( + ( + (volume->startblock+(volume->countblocks))* /* last block */ + (volume->SizeBlock*4/512) /* 1 portion (block) equals 512 (bytes) */ + )>8388608) + { + nsdq.SizeAvailable = 0; + nsdq.DevQueryFormat = 0; + volume->ioh.ioreq->iotd_Req.io_Command = NSCMD_DEVICEQUERY; + volume->ioh.ioreq->iotd_Req.io_Data = &nsdq; + volume->ioh.ioreq->iotd_Req.io_Length = sizeof(struct NSDeviceQueryResult); + if (DoIO((struct IORequest *)volume->ioh.ioreq) == IOERR_NOCMD) + { + D(bug("[afs] initVolume-NSD: device doesn't understand NSD-Query\n")); + } + else + { + if ( + (volume->ioh.ioreq->iotd_Req.io_Actual > sizeof(struct NSDeviceQueryResult)) || + (volume->ioh.ioreq->iotd_Req.io_Actual == 0) || + (volume->ioh.ioreq->iotd_Req.io_Actual != nsdq.SizeAvailable) + ) + { + D(bug("[afs] initVolume-NSD: WARNING wrong io_Actual using NSD\n")); + } + else + { + D(bug("[afs] initVolume-NSD: using NSD commands\n")); + if (nsdq.DeviceType != NSDEVTYPE_TRACKDISK) + D(bug("[afs] initVolume-NSD: WARNING no trackdisk type\n")); + for (cmdcheck=nsdq.SupportedCommands; *cmdcheck; cmdcheck++) + { + if (*cmdcheck == NSCMD_TD_READ64) + volume->ioh.cmdread = NSCMD_TD_READ64; + if (*cmdcheck == NSCMD_TD_WRITE64) + volume->ioh.cmdwrite = NSCMD_TD_WRITE64; + if (*cmdcheck == NSCMD_TD_SEEK64) + volume->ioh.cmdseek = NSCMD_TD_SEEK64; + if (*cmdcheck == NSCMD_TD_FORMAT64) + volume->ioh.cmdformat = NSCMD_TD_FORMAT64; + } + if ( + (volume->ioh.cmdread != NSCMD_TD_READ64) || + (volume->ioh.cmdwrite != NSCMD_TD_WRITE64) + ) + D(bug("[afs] initVolume-NSD: WARNING no READ64/WRITE64\n")); + } + } + } + else + { + D(bug("[afs] initVolume-NSD: no need for NSD\n")); + } } /******************************************* Name : flush Descr.: flush buffers and update disk (sync) Input : volume - volume to flush - Output: DOSTRUE + Output: DOSTRUE on success, DOSFALSE on write/update failure ********************************************/ BOOL flush(struct AFSBase *afsbase, struct Volume *volume) { - flushCache(afsbase, volume); - volume->ioh.ioreq->iotd_Req.io_Command = CMD_UPDATE; - DoIO((struct IORequest *)&volume->ioh.ioreq->iotd_Req); - clearCache(afsbase, volume->blockcache); - return DOSTRUE; + if (!mediumPresent(&volume->ioh)) + return !volume->cachepending && !volume->writefailed && !cacheDirty(volume); + if (!flushBlocks(afsbase, volume)) + return DOSFALSE; + volume->ioh.ioreq->iotd_Req.io_Command = CMD_UPDATE; + volume->ioh.ioreq->iotd_Req.io_Data = NULL; + volume->ioh.ioreq->iotd_Req.io_Length = 0; + if (DoIO((struct IORequest *)&volume->ioh.ioreq->iotd_Req) != 0) + { + /* Transfers succeeded; a failed commit alone needs no tree repair. */ + volume->writefailed = TRUE; + return DOSFALSE; + } + volume->writefailed = FALSE; + return DOSTRUE; } static ULONG readwriteDisk - ( - struct AFSBase *afsbase, - struct Volume *volume, - ULONG start, - ULONG count, - APTR mem, - ULONG cmd - ) + ( + struct AFSBase *afsbase, + struct Volume *volume, + ULONG start, + ULONG count, + APTR mem, + ULONG cmd + ) { LONG retval; struct IOHandle *ioh = &volume->ioh; UQUAD offset; - if (start + count <= volume->countblocks) - { - ioh->ioreq->iotd_Req.io_Command = cmd; - ioh->ioreq->iotd_Req.io_Length = count*BLOCK_SIZE(volume); - ioh->ioreq->iotd_Req.io_Data = mem; - - offset = (UQUAD)volume->startblock * volume->sectorsize - + (UQUAD)start * BLOCK_SIZE(volume); - - ioh->ioreq->iotd_Req.io_Offset = 0xFFFFFFFF & offset; - ioh->ioreq->iotd_Req.io_Actual = offset>>32; - retval = DoIO((struct IORequest *)&ioh->ioreq->iotd_Req); - ioh->flags |= IOHF_MOTOR_OFF; - } - else - { - showText(afsbase, "Attempted to read/write block outside range!\n\n" - "range: %lu-%lu, start: %lu, count: %lu", - volume->startblock, volume->lastblock, - volume->startblock + start * volume->blocksectors, - count * volume->blocksectors); - retval = 1; - } - return retval; + if (start + count <= volume->countblocks) + { + ioh->ioreq->iotd_Req.io_Command = cmd; + ioh->ioreq->iotd_Req.io_Length = count*BLOCK_SIZE(volume); + ioh->ioreq->iotd_Req.io_Data = mem; + + offset = (UQUAD)volume->startblock * volume->sectorsize + + (UQUAD)start * BLOCK_SIZE(volume); + + ioh->ioreq->iotd_Req.io_Offset = 0xFFFFFFFF & offset; + ioh->ioreq->iotd_Req.io_Actual = offset>>32; + retval = DoIO((struct IORequest *)&ioh->ioreq->iotd_Req); + ioh->flags |= IOHF_MOTOR_OFF; + } + else + { + showText(afsbase, "Attempted to read/write block outside range!\n\n" + "range: %lu-%lu, start: %lu, count: %lu", + volume->startblock, volume->lastblock, + volume->startblock + start * volume->blocksectors, + count * volume->blocksectors); + retval = 1; + } + return retval; } -LONG readDisk(struct AFSBase *afsbase, struct Volume *volume, ULONG start, ULONG count, APTR data) { +/* + * Issue a transfer in pieces no larger than the device's MaxTransfer, + * offering the usual Retry/Cancel requester for each failing piece. + */ +static LONG readwriteDiskChunked + ( + struct AFSBase *afsbase, + struct Volume *volume, + ULONG start, + ULONG count, + APTR data, + ULONG cmd, + CONST_STRPTR errtext + ) +{ LONG result = 0; -BOOL retry = TRUE; - - while (retry) - { - DB2(bug("[AFS] ReadDisk: reading blocks %lu to %lu\n", start, start+count-1)); - result = readwriteDisk(afsbase, volume, start, count, data, volume->ioh.cmdread); - if (result == 0) - retry = FALSE; - else - retry = showRetriableError(afsbase, "Read error %ld on block %lu", result, start) == 1; - } - - return result; +ULONG maxblocks = volume->maxtransfer / BLOCK_SIZE(volume); + + if (maxblocks == 0) + maxblocks = 1; + + while (count > 0) + { + ULONG chunk = (count < maxblocks) ? count : maxblocks; + BOOL retry = TRUE; + + while (retry) + { + DB2(bug("[afs] readwriteDisk: cmd %lu blocks %lu to %lu\n", cmd, start, start+chunk-1)); + result = readwriteDisk(afsbase, volume, start, chunk, data, cmd); + if (result == 0) + retry = FALSE; + else + retry = showRetriableError(afsbase, errtext, result, start) == 1; + } + if (result != 0) + return result; + + start += chunk; + count -= chunk; + data = (UBYTE *)data + chunk * BLOCK_SIZE(volume); + } + + return 0; +} + +LONG readDisk(struct AFSBase *afsbase, struct Volume *volume, ULONG start, ULONG count, APTR data) { + return readwriteDiskChunked(afsbase, volume, start, count, data, + volume->ioh.cmdread, "Read error %ld on block %lu"); } LONG writeDisk(struct AFSBase *afsbase, struct Volume *volume, ULONG start, ULONG count, APTR data) { -LONG result = 0; -BOOL retry = TRUE; - - while (retry) - { - DB2(bug("[AFS] EriteDisk: writing blocks %lu to %lu\n", start, start+count-1)); - result = readwriteDisk(afsbase, volume, start, count, data, volume->ioh.cmdwrite); - if (result == 0) - retry = FALSE; - else - retry = showRetriableError(afsbase, "Write error %ld on block %lu", result, start) == 1; - } - - return result; + return readwriteDiskChunked(afsbase, volume, start, count, data, + volume->ioh.cmdwrite, "Write error %ld on block %lu"); } #undef SysBase AROS_INTH1(changeIntCode, struct IOHandle *, ioh) { - AROS_INTFUNC_INIT + AROS_INTFUNC_INIT - ioh->ioflags |= IOHF_MEDIA_CHANGE; - Signal(ioh->afsbase->port.mp_SigTask, 1<afsbase->port.mp_SigBit); - D(bug("[AFS] ChangeIntCode INVOKED\n")); + ioh->ioflags |= IOHF_MEDIA_CHANGE; + Signal(ioh->afsbase->port.mp_SigTask, 1<afsbase->port.mp_SigBit); - return FALSE; + return FALSE; - AROS_INTFUNC_EXIT + AROS_INTFUNC_EXIT } diff --git a/rom/filesys/afs/os_aros_support.h b/rom/filesys/afs/os_aros_support.h index 88964bb7671..5720fa6f1ad 100644 --- a/rom/filesys/afs/os_aros_support.h +++ b/rom/filesys/afs/os_aros_support.h @@ -2,7 +2,7 @@ #define OS_AROS_H /* - Copyright � 1995-2020, The AROS Development Team. All rights reserved. + Copyright © 1995-2026, The AROS Development Team. All rights reserved. $Id$ */ @@ -24,14 +24,6 @@ #include "error.h" #include "afshandler.h" -#define DEBUG 0 -#if DEBUG -# define D(x) x -#else -# define D(x) -#endif -#define bug kprintf - #define OS_BE2LONG AROS_BE2LONG #define OS_LONG2BE AROS_LONG2BE @@ -64,27 +56,20 @@ enum showReqType; LONG showPtrArgsText(struct AFSBase *afsbase, const char *string, enum showReqType type, RAWARG args); LONG showError(struct AFSBase *afsbase, ULONG error, ...); -static inline LONG showText(struct AFSBase *afsbase, const char *format, ...) -{ - LONG ret; - - AROS_SLOWSTACKFORMAT_PRE(format); - ret = showPtrArgsText(afsbase, format, Req_Cancel, AROS_SLOWSTACKFORMAT_ARG(format)); - AROS_SLOWSTACKFORMAT_POST(format); - - return ret; -} - -static inline LONG showRetriableError(struct AFSBase *afsbase, const char *format, ...) -{ - LONG ret; - - AROS_SLOWSTACKFORMAT_PRE(format); - ret = showPtrArgsText(afsbase, format, Req_RetryCancel, AROS_SLOWSTACKFORMAT_ARG(format)); - AROS_SLOWSTACKFORMAT_POST(format); +/* Generic clients retain inline wrappers; constrained builds can select + * one shared implementation through their target build rules. */ +#ifndef AFS_INLINE_REQUESTERS +#define AFS_INLINE_REQUESTERS 1 +#endif - return ret; -} +#if AFS_INLINE_REQUESTERS +#define AFS_REQUESTER_LINKAGE static inline +#include "os_aros_requesters.h" +#undef AFS_REQUESTER_LINKAGE +#else +LONG showText(struct AFSBase *afsbase, const char *format, ...); +LONG showRetriableError(struct AFSBase *afsbase, const char *format, ...); +#endif void checkDeviceFlags(struct AFSBase *); void motorOff(struct AFSBase *afsbase, struct IOHandle *ioh); diff --git a/rom/filesys/afs/os_unix_support.c b/rom/filesys/afs/os_unix_support.c index 663afa18da5..356434a936b 100644 --- a/rom/filesys/afs/os_unix_support.c +++ b/rom/filesys/afs/os_unix_support.c @@ -1,6 +1,5 @@ /* - Copyright © 1995-2020, The AROS Development Team. All rights reserved. - $Id$ + Copyright (C) 1995-2026, The AROS Development Team. All rights reserved. */ /* @@ -19,6 +18,7 @@ #include "error.h" #include "errstrings.h" #include "volumes.h" +#include "cache.h" void showPtrArgsText(struct AFSBase *afsbase, const char *const string, va_list args) { @@ -101,11 +101,6 @@ BOOL diskWritable(struct AFSBase *afsbase, struct IOHandle *ioh) return ioh->fh ? 1 : 0; } -ULONG sectorSize(struct AFSBase *afsbase, struct IOHandle *ioh) -{ - return 512; -} - void check64BitSupport(struct AFSBase *afsbase, struct Volume *volume) { /* * This is a NOP, since we just access the image as a block device @@ -131,9 +126,16 @@ void closeBlockDevice(struct AFSBase *afsbase, struct IOHandle *ioh) { } BOOL flush(struct AFSBase *afsbase, struct Volume *volume) { - flushCache(afsbase, volume); - clearCache(afsbase, volume->blockcache); - return DOSFALSE; + clearerr(volume->ioh.fh); /* An explicit flush also retries earlier errors. */ + if (!flushBlocks(afsbase, volume)) + return DOSFALSE; + if (fflush(volume->ioh.fh) != 0) + { + volume->writefailed = TRUE; + return DOSFALSE; + } + volume->writefailed = FALSE; + return DOSTRUE; } /**************************************************************************** @@ -142,7 +144,7 @@ BOOL flush(struct AFSBase *afsbase, struct Volume *volume) { * so the functions are no-ops. ****************************************************************************/ -LONG attemptAddDosVolume(struct AFSBase *afsbase, struct Volume *volume) { +LONG addDosVolume(struct AFSBase *afsbase, struct Volume *volume) { return 0; } LONG osMediumInit(struct AFSBase *afsbase, struct Volume *volume, struct BlockCache *blockbuffer) { diff --git a/rom/filesys/afs/os_unix_support.h b/rom/filesys/afs/os_unix_support.h index f4d5b6c489f..2344ef34652 100644 --- a/rom/filesys/afs/os_unix_support.h +++ b/rom/filesys/afs/os_unix_support.h @@ -2,7 +2,7 @@ #define OS_UNIX_SUPPORT_H /* - Copyright � 1995-2020, The AROS Development Team. All rights reserved. + Copyright © 1995-2026, The AROS Development Team. All rights reserved. $Id$ */ @@ -70,6 +70,7 @@ struct Node {}; #define ERROR_OBJECT_NOT_FOUND 205 #define ERROR_INVALID_COMPONENT_NAME 210 #define ERROR_OBJECT_WRONG_TYPE 212 +#define ERROR_DISK_NOT_VALIDATED 213 #define ERROR_DISK_WRITE_PROTECTED 214 #define ERROR_DIRECTORY_NOT_EMPTY 216 #define ERROR_SEEK_ERROR 219 @@ -145,6 +146,7 @@ struct InfoData { #define ED_DATE 5 #define ED_COMMENT 6 #define ED_OWNER 7 +#define ED_SIZE64 8 struct ExAllData { struct ExAllData *ed_Next; UBYTE *ed_Name; @@ -157,6 +159,7 @@ struct ExAllData { UBYTE *ed_Comment; UWORD ed_OwnerUID; UWORD ed_OwnerGID; + uint64_t ed_Size64; }; struct ExAllControl { ULONG eac_Entries; @@ -198,25 +201,43 @@ struct DosEnvec { IPTR de_BootBlocks; }; +/* de_TableSize indices, mirroring dos/filehandler.h - the struct above has the + same fields in the same order, so the handler can test de_TableSize against + them on the host build exactly as it does on AROS. */ +#define DE_TABLESIZE 0 +#define DE_SIZEBLOCK 1 +#define DE_BLOCKSIZE 2 +#define DE_NUMHEADS 3 +#define DE_SECSPERBLOCK 4 +#define DE_BLKSPERTRACK 5 +#define DE_RESERVEDBLKS 6 +#define DE_PREFAC 7 +#define DE_INTERLEAVE 8 +#define DE_LOWCYL 9 +#define DE_HIGHCYL 10 +#define DE_UPPERCYL DE_HIGHCYL +#define DE_NUMBUFFERS 11 +#define DE_BUFMEMTYPE 12 +#define DE_MEMBUFTYPE DE_BUFMEMTYPE +#define DE_MAXTRANSFER 13 +#define DE_MASK 14 +#define DE_BOOTPRI 15 +#define DE_DOSTYPE 16 +#define DE_BAUD 17 +#define DE_CONTROL 18 +#define DE_BOOTBLOCKS 19 + /* dos/dos.h */ #define MODE_READWRITE 1004 #define MODE_OLDFILE 1005 #define MODE_NEWFILE 1006 /* aros/debug.h */ - -#if APOLLO_DEBUG -#define DEBUG 0 -#else -#define DEBUG 0 -#endif - #if DEBUG # define D(x) x #else # define D(x) #endif - #define bug kprintf #define kprintf printf diff --git a/rom/filesys/afs/validator.c b/rom/filesys/afs/validator.c index 95a53d5efe5..7d86f3cf202 100644 --- a/rom/filesys/afs/validator.c +++ b/rom/filesys/afs/validator.c @@ -1,6 +1,5 @@ /* - Copyright � 1995-2020, The AROS Development Team. All rights reserved. - $Id$ + Copyright (C) 1995-2026, The AROS Development Team. All rights reserved. */ /* @@ -8,7 +7,7 @@ * 02-jan-2008 [Tomasz Wiszkowski] created disk validation procedures * 03-jan-2008 [Tomasz Wiszkowski] updated procedure to strip fake dircache blocks * no directory cache handling present here. - * 04-jan-2008 [Tomasz Wiszkowski] corrected procedure to *ignore* data block sizes + * 04-jan-2008 [Tomasz Wiszkowski] corrected procedure to *ignore* data block sizes * for OFS volumes since DOSTYPE does not differentiate them, * corrected tabulation. * 07-jan-2008 [Tomasz Wiszkowski] partitioned procedures to prepare non-recursive scan @@ -16,6 +15,11 @@ #include "validator.h" #include "volumes.h" +#include "bitmap.h" + +#undef SDEBUG +#undef DEBUG +#define DEBUG 0 #ifdef __AROS__ #include @@ -31,6 +35,7 @@ #include #include "misc.h" #include "extstrings.h" +#include "os.h" #include "baseredef.h" #endif @@ -48,10 +53,12 @@ LONG checkValid(struct AFSBase *afsbase, struct Volume *vol) #ifdef __AROS__ struct BlockCache *blockbuffer; - if (vol == NULL) - return 0; + if (vol == NULL || vol->cachepending || vol->writefailed || !mediumPresent(&vol->ioh)) + return 0; blockbuffer = getBlock(afsbase, vol, vol->rootblock); + if (blockbuffer == NULL) + return 0; UBYTE n[vol->FNameMax + 1]; CONST_FSBSTR name; @@ -60,22 +67,23 @@ LONG checkValid(struct AFSBase *afsbase, struct Volume *vol) name=(CONST_FSBSTR)((char *)blockbuffer->buffer+(BLK_DISKNAME_START(vol)*4)); StrCpyFromBstr(name, n, sizeof(n) - 1); - while (vol->state == ID_WRITE_PROTECTED + while (vol->state == ID_WRITE_PROTECTED && showError(afsbase, ERR_WRITEPROTECT, n)); - if (vol->state == ID_VALIDATING) - { - if (showError(afsbase, ERR_DISKNOTVALID)) - { - if (vr_OK == launchValidator(afsbase, vol)) - return 1; - } - return 0; - } - - return (vol->state == ID_VALIDATED) ? 1 : 0; + if (vol->state == ID_VALIDATING) + { + if (showError(afsbase, ERR_DISKNOTVALID)) + { + if (vr_OK == launchValidator(afsbase, vol)) + return 1; + } + return 0; + } + + return (vol->state == ID_VALIDATED) ? 1 : 0; #else - return 1; + return vol != NULL && !vol->cachepending && !vol->writefailed + && vol->state != ID_VALIDATING; #endif } @@ -91,16 +99,19 @@ LONG checkValid(struct AFSBase *afsbase, struct Volume *vol) LONG launchValidator(struct AFSBase *afsbase, struct Volume *volume) { #ifdef __AROS__ - D(bug("[AFS]: flushing cache...\n")); - flushCache(afsbase, volume); - - /* - * initially this was meant to be a synchronous validation - * but due to obvious problems with IO commands idea was eventually given up - */ - return validate(afsbase, volume); + if (!diskWritable(afsbase, &volume->ioh)) + return vr_WriteError; + D(bug("[afs]: flushing cache...\n")); + if (!flush(afsbase, volume)) + return vr_WriteError; + + /* + * initially this was meant to be a synchronous validation + * but due to obvious problems with IO commands idea was eventually given up + */ + return validate(afsbase, volume); #else - return 0; + return 0; #endif } @@ -114,84 +125,108 @@ LONG launchValidator(struct AFSBase *afsbase, struct Volume *volume) LONG validate(struct AFSBase *afsbase, struct Volume *vol) { - DiskStructure ds; - ValidationResult res = vr_OK; - - /* - * fill in diskstructure. we will need it for the sake of validation. - */ - ds.vol = vol; - ds.afs = afsbase; - ds.flags = 0; - - /* - * we could use some inhibiting here - */ - if (0 == bm_allocate_bitmap(&ds)) - { - inhibit(afsbase, vol, 1); - res = start_superblock(&ds); - inhibit(afsbase, vol, 0); - } - bm_free_bitmap(&ds); - - switch (res) - { - case vr_OK: - D(bug("[afs validate]: Validation complete. \n")); - break; - case vr_NoAccess: - D(bug("[afs validate]: Could not create access point. \n")); - break; - case vr_ReadError: - D(bug("[afs validate]: Could not read disk. \n")); - break; - case vr_UnknownDiskType: - D(bug("[afs validate]: Unhandled disk type. \n")); - break; - case vr_InvalidChksum: - D(bug("[afs validate]: Invalid block checksum. \n")); - break; - case vr_StructureDamaged: - D(bug("[afs validate]: Structure damaged. \n")); - break; - case vr_OutOfMemory: - D(bug("[afs validate]: Could not allocate memory to complete operation. \n")); - break; - case vr_BlockUsedTwice: - D(bug("[afs validate]: Physical block used more than once. \n")); - break; - case vr_Aborted: - D(bug("[afs validate]: Aborted by user. \n")); - break; - case vr_BlockOutsideDisk: - D(bug("[afs validate]: Block outside volume boundaries. \n")); - break; - } - - { - struct BlockCache *bc = getBlock(afsbase, vol, vol->rootblock); - ULONG* mem = bc->buffer; - - if (res != vr_OK) - { - mem[BLK_BITMAP_VALID_FLAG(vol)] = 0; - vol->state = ID_VALIDATING; - } - else - vol->state = ID_VALIDATED; - - if (verify_checksum(&ds, mem) != 0) - { - D(bug("[afs validate]: block checksum does not match.\n")); - bc->flags |= BCF_WRITE; - } - } - /* - * it's not neccessary here, but res is holding validation result - * one may wish to open some requester at this point in the future - */ - return res; + DiskStructure ds; + ValidationResult res = vr_OutOfMemory; + + if (!diskWritable(afsbase, &vol->ioh)) + return vr_WriteError; + + /* + * fill in diskstructure. we will need it for the sake of validation. + */ + ds.vol = vol; + ds.afs = afsbase; + ds.flags = 0; + + /* + * we could use some inhibiting here + */ + if (0 == bm_allocate_bitmap(&ds)) + { + /* Validation is synchronous: do not unmount and remount the medium, + * which would launch validation recursively after a failure. */ + vol->inhibitcounter++; + res = start_superblock(&ds); + vol->inhibitcounter--; + } + bm_free_bitmap(&ds); + + switch (res) + { + case vr_OK: + D(bug("[afs validate]: Validation complete. \n")); + break; + case vr_NoAccess: + D(bug("[afs validate]: Could not create access point. \n")); + break; + case vr_ReadError: + D(bug("[afs validate]: Could not read disk. \n")); + break; + case vr_WriteError: + D(bug("[afs validate]: Could not write or update disk. \n")); + break; + case vr_UnknownDiskType: + D(bug("[afs validate]: Unhandled disk type. \n")); + break; + case vr_InvalidChksum: + D(bug("[afs validate]: Invalid block checksum. \n")); + break; + case vr_StructureDamaged: + D(bug("[afs validate]: Structure damaged. \n")); + break; + case vr_OutOfMemory: + D(bug("[afs validate]: Could not allocate memory to complete operation. \n")); + break; + case vr_BlockUsedTwice: + D(bug("[afs validate]: Physical block used more than once. \n")); + break; + case vr_Aborted: + D(bug("[afs validate]: Aborted by user. \n")); + break; + case vr_BlockOutsideDisk: + D(bug("[afs validate]: Block outside volume boundaries. \n")); + break; + } + + { + struct BlockCache *bc = getBlock(afsbase, vol, vol->rootblock); + ULONG* mem; + + if (bc == NULL) + { + vol->state = ID_VALIDATING; + return res == vr_OK ? vr_ReadError : res; + } + mem = bc->buffer; + if (res != vr_OK) + { + if (mem[BLK_BITMAP_VALID_FLAG(vol)] != 0) + { + mem[BLK_BITMAP_VALID_FLAG(vol)] = 0; + verify_checksum(&ds, mem); + bc->flags |= BCF_WRITE; + } + vol->state = ID_VALIDATING; + } + else + { + bc->flags |= BCF_USED; + vol->usedblockscount = countUsedBlocks(afsbase, vol); + vol->state = diskWritable(afsbase, &vol->ioh) + ? ID_VALIDATED : ID_WRITE_PROTECTED; + } + + if (verify_checksum(&ds, mem) != 0) + { + D(bug("[afs validate]: block checksum does not match.\n")); + bc->flags |= BCF_WRITE; + } + } + /* + * it's not neccessary here, but res is holding validation result + * one may wish to open some requester at this point in the future + */ + return res; } /* @@ -199,39 +234,64 @@ LONG validate(struct AFSBase *afsbase, struct Volume *vol) */ LONG check_block_range(DiskStructure *ds, ULONG num) { - if ((num < ds->vol->bstartblock) || (num >= ds->vol->countblocks)) - { - D(bug("[afs validate]: Block located outside volume range. Condition %lu <= %lu < %lu not met.\n", - ds->vol->bstartblock, - num, - ds->vol->countblocks)); - showError(ds->afs, ERR_BLOCK_OUTSIDE_RANGE, num); - return 0; - } - return 1; -} + if ((num < ds->vol->bootblocks) || (num >= ds->vol->countblocks)) + { + D(bug("[afs validate]: Block located outside volume range. Condition %lu <= %lu < %lu not met.\n", + (ULONG)ds->vol->bootblocks, + num, + ds->vol->countblocks)); + showError(ds->afs, ERR_BLOCK_OUTSIDE_RANGE, num); + return 0; + } + return 1; +} /* * begin */ ValidationResult start_superblock(DiskStructure *ds) { - ValidationResult res = vr_OK; - - res = collect_directory_blocks(ds, ds->vol->rootblock); - D(bug("[afs validate]: validation complete. Result: %ld\n", res)); - - /* - * record bitmap back to disk, set bitmap valid flag, and update checksum of the root sector - * please note: it is hell important to have this checksum valid ;) so you better keep an eye - * on all your changes - */ - if (res == vr_OK) - { - record_bitmap(ds); - } - - return res; + struct Volume *vol = ds->vol; + ValidationResult res; + struct BlockCache *root = getBlock(ds->afs, vol, vol->rootblock); + + if (root == NULL) + return vr_ReadError; + /* Keep the on-disk bitmap invalid throughout repair. */ + root->buffer[BLK_BITMAP_VALID_FLAG(vol)] = 0; + verify_checksum(ds, root->buffer); + if (!writeBlock(ds->afs, vol, root, -1) || !flush(ds->afs, vol)) + return vr_WriteError; + + res = collect_directory_blocks(ds, vol->rootblock); + if (res != vr_OK) + return res; + /* Persist tree repairs before publishing their rebuilt allocation map. */ + if (!flush(ds->afs, vol)) + return vr_WriteError; + res = record_bitmap(ds); + if (res != vr_OK) + return res; + if (!flush(ds->afs, vol)) + return vr_WriteError; + + root = getBlock(ds->afs, vol, vol->rootblock); + if (root == NULL) + return vr_ReadError; + root->buffer[BLK_BITMAP_VALID_FLAG(vol)] = ~0; + verify_checksum(ds, root->buffer); + if (!writeBlock(ds->afs, vol, root, -1) || !flush(ds->afs, vol)) + { + /* Do not leave a valid flag queued for a later timer retry. */ + root = getBlock(ds->afs, vol, vol->rootblock); + if (root != NULL) + { + root->buffer[BLK_BITMAP_VALID_FLAG(vol)] = 0; + writeBlockDeferred(ds->afs, vol, root, BLK_CHECKSUM); + } + return vr_WriteError; + } + return vr_OK; } /* @@ -239,282 +299,288 @@ ValidationResult start_superblock(DiskStructure *ds) */ ULONG verify_checksum(DiskStructure *ds, ULONG *block) { - ULONG sum = 0; - LONG i; - - D(bug("[afs validate]: verifying block checksum... ")); - - for (i=0; ivol->SizeBlock; i++) - { - sum += OS_BE2LONG(block[i]); - } - - if (sum != 0) - { - D(bug("checksum invalid!\n")); - sum -= OS_BE2LONG(block[BLK_CHECKSUM]); - D(bug("[afs validate]: current sum: %08lx, valid sum: %08lx. correcting\n", block[BLK_CHECKSUM], sum)); - block[BLK_CHECKSUM] = OS_LONG2BE(-sum); - return -sum; - } - - D(bug("checksum valid!\n")); - return 0; -} + ULONG sum = 0; + LONG i; + + D(bug("[afs validate]: verifying block checksum... ")); + + for (i=0; ivol->SizeBlock; i++) + { + sum += OS_BE2LONG(block[i]); + } + + if (sum != 0) + { + D(bug("checksum invalid!\n")); + sum -= OS_BE2LONG(block[BLK_CHECKSUM]); + D(bug("[afs validate]: current sum: %08lx, valid sum: %08lx. correcting\n", block[BLK_CHECKSUM], sum)); + block[BLK_CHECKSUM] = OS_LONG2BE(-sum); + return -sum; + } + + D(bug("checksum valid!\n")); + return 0; +} /* * verify_bm_checksum */ ULONG verify_bm_checksum(DiskStructure *ds, ULONG *block) { - ULONG sum = 0; - ULONG i; - - D(bug("[afs validate]: verifying bitmap checksum... ")); - - for (i=0; ivol->SizeBlock; i++) - { - sum += OS_BE2LONG(block[i]); - } - - if (sum != 0) - { - D(bug("checksum invalid!\n")); - sum -= OS_BE2LONG(block[0]); - D(bug("[afs validate]: current sum: %08lx, valid sum: %08lx. correcting\n", block[0], sum)); - block[0] = OS_LONG2BE(-sum); - return -sum; - } - - D(bug("checksum valid!\n")); - return 0; -} + ULONG sum = 0; + ULONG i; + + D(bug("[afs validate]: verifying bitmap checksum... ")); + + for (i=0; ivol->SizeBlock; i++) + { + sum += OS_BE2LONG(block[i]); + } + + if (sum != 0) + { + D(bug("checksum invalid!\n")); + sum -= OS_BE2LONG(block[0]); + D(bug("[afs validate]: current sum: %08lx, valid sum: %08lx. correcting\n", block[0], sum)); + block[0] = OS_LONG2BE(-sum); + return -sum; + } + + D(bug("checksum valid!\n")); + return 0; +} /* * check single block - this procedure should do as much as possible */ ValidationResult check_block(DiskStructure* ds, struct BlockCache* block) { - ULONG* mem; - ULONG id; - - /* - * first check cache validity - */ - if (0 == block) - { - D(bug("[afs validate] Error: no block passed.\n")); - return vr_ReadError; - } - - if (0 == block->blocknum) - { - D(bug("[afs validate] Block could not be read.\n")); - return vr_ReadError; - } - - mem = block->buffer; - - /* - * check types first: we expect block of T_SHORT (2) or T_LIST (16) type - */ - id = OS_BE2LONG(mem[BLK_PRIMARY_TYPE]); - if ((id != T_SHORT) && - (id != T_LIST)) - { - D(bug("[afs validate]: block is not of known-type (%08lx). asking whether to correct\n", id)); - - if (block->blocknum == ds->vol->rootblock) - { - if ((0 == (ds->flags & ValFlg_DisableReq_MaybeNotAFS)) && (0 == showError(ds->afs, ERR_POSSIBLY_NOT_AFS))) - return vr_Aborted; - ds->flags |= ValFlg_DisableReq_MaybeNotAFS; - D(bug("[afs validate]: will continue per user decision. faulty block will be removed from structure.\n")); - } - return vr_StructureDamaged; - } - - /* - * set bitmap block (mark as used) - */ - if (bm_mark_block(ds, block->blocknum)) - { - D(bug("[afs validate]: block %lu used twice! aborting!\n", block->blocknum)); - return vr_BlockUsedTwice; - } - - return vr_OK; + ULONG* mem; + ULONG id; + + /* + * first check cache validity + */ + if (0 == block) + { + D(bug("[afs validate] Error: no block passed.\n")); + return vr_ReadError; + } + + if (0 == block->blocknum) + { + D(bug("[afs validate] Block could not be read.\n")); + return vr_ReadError; + } + + mem = block->buffer; + + /* + * check types first: we expect block of T_SHORT (2) or T_LIST (16) type + */ + id = OS_BE2LONG(mem[BLK_PRIMARY_TYPE]); + if ((id != T_SHORT) && + (id != T_LIST)) + { + D(bug("[afs validate]: block is not of known-type (%08lx). asking whether to correct\n", id)); + + if (block->blocknum == ds->vol->rootblock) + { + if ((0 == (ds->flags & ValFlg_DisableReq_MaybeNotAFS)) && (0 == showError(ds->afs, ERR_POSSIBLY_NOT_AFS))) + return vr_Aborted; + ds->flags |= ValFlg_DisableReq_MaybeNotAFS; + D(bug("[afs validate]: will continue per user decision. faulty block will be removed from structure.\n")); + } + return vr_StructureDamaged; + } + + /* + * set bitmap block (mark as used) + */ + if (bm_mark_block(ds, block->blocknum)) + { + D(bug("[afs validate]: block %lu used twice! aborting!\n", block->blocknum)); + return vr_BlockUsedTwice; + } + + return vr_OK; } ValidationResult collect_bitmap(DiskStructure* ds, struct BlockCache* block) { - ULONG strt=BLK_BITMAP_POINTERS_START(ds->vol), - stop=BLK_BITMAP_POINTERS_END(ds->vol), - ext =BLK_BITMAP_EXTENSION(ds->vol), - i, blk; - - ULONG* mem = block->buffer; - - do - { - for (i=strt; i<=stop; ++i) - { - blk = OS_BE2LONG(mem[i]); - if (blk == 0) - continue; - - /* - * verify whether bitmap block resides on disk - * if the range validation fails, simply do not add the block to the list - * - * unfortunately bitmap block reallocation has not been implemented - * since this is the most unlikely happening issue - */ - if (0 == check_block_range(ds, blk)) - return vr_BlockOutsideDisk; - - /* - * mark block as used. - * the bitmap blocks *could be reallocated* (and in fact should be) - * if the bm_mark_block returns something else than st_OK (that is, - * in case, when block is out of range, or simply used twice). - * - * i'm sorry, but this has not been introduced yet. - */ - if (bm_mark_block(ds, blk) != st_OK) - { - showError(ds->afs, ERR_BLOCK_USED_TWICE, blk); - return vr_BlockUsedTwice; - } - - /* - * add bitmap block to bitmap block set - */ - bm_add_bitmap_block(ds, blk); - } - - /* - * collect bitmap extension blocks - */ - if ((blk = OS_BE2LONG(mem[ext])) != 0) - { - D(bug("[afs validate] Following to next bitmap extension block at %08lx\n", blk)); - if (0 == check_block_range(ds, blk)) - return vr_BlockOutsideDisk; - - if (bm_mark_block(ds, blk) != st_OK) - return vr_BlockUsedTwice; - - block = getBlock(ds->afs, ds->vol, blk); - mem = block->buffer; - strt = 0; - stop = ds->vol->SizeBlock-2; - ext = ds->vol->SizeBlock-1; - } - } - while (blk != 0); - - return vr_OK; + struct Volume *vol = ds->vol; + ULONG strt=BLK_BITMAP_POINTERS_START(vol), + stop=BLK_BITMAP_POINTERS_END(vol), + ext =BLK_BITMAP_EXTENSION(vol), + i, blk; + + ULONG* mem = block->buffer; + + do + { + for (i=strt; i<=stop; ++i) + { + blk = OS_BE2LONG(mem[i]); + if (blk == 0) + continue; + + /* + * verify whether bitmap block resides on disk + * if the range validation fails, simply do not add the block to the list + * + * unfortunately bitmap block reallocation has not been implemented + * since this is the most unlikely happening issue + */ + if (0 == check_block_range(ds, blk)) + return vr_BlockOutsideDisk; + + /* + * mark block as used. + * the bitmap blocks *could be reallocated* (and in fact should be) + * if the bm_mark_block returns something else than st_OK (that is, + * in case, when block is out of range, or simply used twice). + * + * i'm sorry, but this has not been introduced yet. + */ + if (bm_mark_block(ds, blk) != st_OK) + { + showError(ds->afs, ERR_BLOCK_USED_TWICE, blk); + return vr_BlockUsedTwice; + } + + /* + * add bitmap block to bitmap block set + */ + bm_add_bitmap_block(ds, blk); + } + + /* + * collect bitmap extension blocks + */ + if ((blk = OS_BE2LONG(mem[ext])) != 0) + { + D(bug("[afs validate] Following to next bitmap extension block at %08lx\n", blk)); + if (0 == check_block_range(ds, blk)) + return vr_BlockOutsideDisk; + + if (bm_mark_block(ds, blk) != st_OK) + return vr_BlockUsedTwice; + + block = getBlock(ds->afs, vol, blk); + if (block == NULL) + return vr_ReadError; + mem = block->buffer; + strt = 0; + stop = vol->SizeBlock-2; + ext = vol->SizeBlock-1; + } + } + while (blk != 0); + + return vr_OK; } ValidationResult collect_file_extensions(DiskStructure* ds, struct BlockCache* block) { - ULONG i, blk, clr=0; - ULONG* mem = block->buffer; - - ds->file_blocks = 0; - - do - { - for (i=BLK_TABLE_END(ds->vol); i>=BLK_TABLE_START; --i) - { - if (clr != 0) - { - mem[i] = 0; - block->flags |= BCF_WRITE; - continue; - } - - blk = OS_BE2LONG(mem[i]); - - /* - * if this was the last data block, purge rest - */ - if (blk == 0) - { - clr = 1; - continue; - } - - - /* - * verify if block still belongs to this disk, purge if it doesn't - */ - if (0 == check_block_range(ds, blk)) - { - D(bug("[afs validate] file data block outside range. truncating\n")); - block->flags |= BCF_WRITE; - clr = 1; - mem[i] = 0; - continue; - } - - /* - * mark block as used. - */ - if (bm_mark_block(ds, blk) != st_OK) - { - D(bug("[afs validate] file data block used twice. truncating\n")); - block->flags |= BCF_WRITE; - clr = 1; - mem[i] = 0; - continue; - } - - ++ds->file_blocks; - } - - /* - * if block is marked as 'write', make sure it holds correct sum. - */ - if (block->flags & BCF_WRITE) - verify_checksum(ds, block->buffer); - /* - * collect bitmap extension blocks - */ - if ((blk = OS_BE2LONG(mem[BLK_EXTENSION(ds->vol)])) != 0) - { - D(bug("[afs validate] Following to next file extension block at %08lx\n", blk)); - if (0 == check_block_range(ds, blk)) - { - D(bug("[afs validate] Extension block outside range. truncating file\n")); - mem[BLK_EXTENSION(ds->vol)] = 0; - block->flags |= BCF_WRITE; - blk = 0; - } - else if (bm_mark_block(ds, blk) != st_OK) - { - D(bug("[afs validate] Bitmap block already marked as used. truncating file\n")); - mem[BLK_EXTENSION(ds->vol)] = 0; - block->flags |= BCF_WRITE; - blk = 0; - } - else - { - block = getBlock(ds->afs, ds->vol, blk); - mem = block->buffer; - } - } - - /* - * update sum; if changed, mark block for writing - */ - if (0 != verify_checksum(ds, block->buffer)) - block->flags |= BCF_WRITE; - } - while (blk != 0); - - return vr_OK; + struct Volume *vol = ds->vol; + ULONG i, blk, clr=0; + ULONG* mem = block->buffer; + + ds->file_blocks = 0; + + do + { + for (i=BLK_TABLE_END(vol); i>=BLK_TABLE_START; --i) + { + if (clr != 0) + { + mem[i] = 0; + block->flags |= BCF_WRITE; + continue; + } + + blk = OS_BE2LONG(mem[i]); + + /* + * if this was the last data block, purge rest + */ + if (blk == 0) + { + clr = 1; + continue; + } + + + /* + * verify if block still belongs to this disk, purge if it doesn't + */ + if (0 == check_block_range(ds, blk)) + { + D(bug("[afs validate] file data block outside range. truncating\n")); + block->flags |= BCF_WRITE; + clr = 1; + mem[i] = 0; + continue; + } + + /* + * mark block as used. + */ + if (bm_mark_block(ds, blk) != st_OK) + { + D(bug("[afs validate] file data block used twice. truncating\n")); + block->flags |= BCF_WRITE; + clr = 1; + mem[i] = 0; + continue; + } + + ++ds->file_blocks; + } + + /* + * if block is marked as 'write', make sure it holds correct sum. + */ + if (block->flags & BCF_WRITE) + verify_checksum(ds, block->buffer); + /* + * collect bitmap extension blocks + */ + if ((blk = OS_BE2LONG(mem[BLK_EXTENSION(vol)])) != 0) + { + D(bug("[afs validate] Following to next file extension block at %08lx\n", blk)); + if (0 == check_block_range(ds, blk)) + { + D(bug("[afs validate] Extension block outside range. truncating file\n")); + mem[BLK_EXTENSION(vol)] = 0; + block->flags |= BCF_WRITE; + blk = 0; + } + else if (bm_mark_block(ds, blk) != st_OK) + { + D(bug("[afs validate] Bitmap block already marked as used. truncating file\n")); + mem[BLK_EXTENSION(vol)] = 0; + block->flags |= BCF_WRITE; + blk = 0; + } + else + { + block = getBlock(ds->afs, vol, blk); + if (block == NULL) + return vr_ReadError; + mem = block->buffer; + } + } + + /* + * update sum; if changed, mark block for writing + */ + if (0 != verify_checksum(ds, block->buffer)) + block->flags |= BCF_WRITE; + } + while (blk != 0); + + return vr_OK; } /* @@ -522,222 +588,312 @@ ValidationResult collect_file_extensions(DiskStructure* ds, struct BlockCache* b */ ValidationResult collect_directory_blocks(DiskStructure *ds, ULONG blk) { - struct BlockCache *bc; - LONG entry_type; - LONG primary_type; - ULONG id; - - D(bug("[afs validate]: analyzing block %lu\n", blk)); - - /* - * check range. Note that the whole process here is not 'reversible': - * if you mark bitmap blocks as used, and then just return in the middle, - * it won't get freed automagically, so mark it only when you know it should be there. - */ - if (0 == check_block_range(ds, blk)) - return vr_BlockOutsideDisk; - - /* - * we don't set block usage flags: we will re-read the block anyways. - */ - bc = getBlock(ds->afs, ds->vol, blk); - - /* - * initial block analysis - */ - id = check_block(ds, bc); - if (id != vr_OK) - return id; - - /* - * collect types - */ - entry_type = OS_BE2LONG(bc->buffer[BLK_SECONDARY_TYPE(ds->vol)]); - primary_type = OS_BE2LONG(bc->buffer[BLK_PRIMARY_TYPE]); - - switch (primary_type) { - case T_LIST: - break; - case T_SHORT: - break; - case T_DATA: - break; - default: - /* TODO: handle unknown primary type */ - break; - } - - /* - * for root block: collect all bitmap blocks now - */ - - /* - * i won't hide it: there's plenty of things to check here, but - * since it's just a validation task - * i have decided to remove the redundant code. - */ - - /* - * ok, if anyone wants to remove the bitmap allocations and re-allocate them by himself - * here's the good place to start doing it. myself, i think the best way is to rely on - * operating system in this matter: unless someone damaged the disk structure, it's - * perfectly safe to assume that number of allocated bitmap blocks is just enough for us - * to store the bitmap. Again, it's not a salvaging, repairing NOR reorganizing task. - */ - - /* - * oh, btw; we also want to collect the bitmap blocks here so we know where to save new bitmap. - */ - if (entry_type == 1) - { - D(bug("[afs validate]: Checking and collecting bitmap blocks\n")); - - id = collect_bitmap(ds, bc); - if (id != vr_OK) - return id; - - /* - * initially -- mark bitmap status as valid - */ - bc = getBlock(ds->afs, ds->vol, blk); - bc->buffer[BLK_BITMAP_VALID_FLAG(ds->vol)] = ~0; - verify_checksum(ds, bc->buffer); - bc->flags |= BCF_WRITE; - } - - /* - * this is the collection procedure - * we check for directories/files here only. if an entry is not a directory, - * check if it is a file and accumulate data blocks for it. - * here we are interested only in FOUR of SEVEN types: ROOT, DIRECTORY, FILE and FILE EXTENSION - */ - if ((entry_type == 1) || (entry_type == 2)) // 1 = root, which is handled already, 3 = symlink, which we don't need, 4 = hardlink, which we don't want - { - LONG i; - - /* - * clear directory cache block. - * fancy thing about directory cache: it is the best way to run into inconsistencies between file trees. - * two trees, one kept for compatibility (which is not kept btw as dostype is different), and the other - * for 'faster directory listing', but not always in sync - */ - if (bc->buffer[BLK_EXTENSION(ds->vol)] != 0) - { - D(bug("[afs validate]: clearing dircache pointer\n")); - bc->buffer[BLK_EXTENSION(ds->vol)] = 0; - verify_checksum(ds, bc->buffer); - bc->flags |= BCF_WRITE; - } - - for (i=BLK_TABLE_START; i<=BLK_TABLE_END(ds->vol); i++) - { - id = OS_BE2LONG(bc->buffer[i]); - if (id != 0) - { - /* - * proceed with block collection. unless user decides to stop validation - * move on and bug them about whatever is really bad - */ - id = collect_directory_blocks(ds, id); - if (id == vr_Aborted) - return id; - - /* - * restore current block - * this will work well if the modified block gets marked as BCF_WRITE - */ - bc = getBlock(ds->afs, ds->vol, blk); - - if (vr_OK != id) - { - /* it's a good idea to flag this requester, so it shows only once */ - if ((0 == (ds->flags & ValFlg_DisableReq_DataLossImminent)) && (0 == showError(ds->afs, ERR_DATA_LOSS_POSSIBLE))) - return vr_Aborted; - - ds->flags |= ValFlg_DisableReq_DataLossImminent; - bc->buffer[i] = 0; - verify_checksum(ds, bc->buffer); - bc->flags |= BCF_WRITE; - } - } - } - } - - /* - * collect file data blocks. - * some files are too large to fit in a single list of data blocks - * this covers scanning more blocks - * - * crap, i don't know if i should use entry_type=0 here, too :| - */ - if (entry_type == -3) - { - collect_file_extensions(ds, bc); - bc = getBlock(ds->afs, ds->vol, blk); - id = OS_BE2LONG(bc->buffer[BLK_BYTE_SIZE(ds->vol)]); - if (id > (ds->file_blocks * ds->vol->SizeBlock << 2)) - { - bc->buffer[BLK_BYTE_SIZE(ds->vol)] = OS_LONG2BE(ds->file_blocks * ds->vol->SizeBlock << 2); - verify_checksum(ds, bc->buffer); - bc->flags |= BCF_WRITE; - } - } - - /* - * finally, move on to next file in this hash chain. IF next file suffers anything, remove it and following files from hash chain. - */ - id = OS_BE2LONG(bc->buffer[BLK_HASHCHAIN(ds->vol)]); - if (id != 0) - { - D(bug("[afs validate]: collecting other items in this chain\n")); - - /* - * collect other elements - */ - id = collect_directory_blocks(ds, id); - - /* - * if aborted, simply quit - */ - if (id == vr_Aborted) - { - return id; - } - - /* - * otherwise alter structure - */ - if (id != 0) - { - D(bug("[afs validate]: removing faulty chain\n")); - bc = getBlock(ds->afs, ds->vol, blk); - bc->buffer[BLK_HASHCHAIN(ds->vol)] = 0; - verify_checksum(ds, bc->buffer); - bc->flags |= BCF_WRITE; - } - } - - return vr_OK; + struct Volume *vol = ds->vol; + struct BlockCache *bc; + LONG entry_type; + LONG primary_type; + ULONG id; + + D(bug("[afs validate]: analyzing block %lu\n", blk)); + + /* + * check range. Note that the whole process here is not 'reversible': + * if you mark bitmap blocks as used, and then just return in the middle, + * it won't get freed automagically, so mark it only when you know it should be there. + */ + if (0 == check_block_range(ds, blk)) + return vr_BlockOutsideDisk; + + /* + * we don't set block usage flags: we will re-read the block anyways. + */ + bc = getBlock(ds->afs, vol, blk); + + /* + * initial block analysis + */ + id = check_block(ds, bc); + if (id != vr_OK) + return id; + + /* + * collect types + */ + entry_type = OS_BE2LONG(bc->buffer[BLK_SECONDARY_TYPE(vol)]); + primary_type = OS_BE2LONG(bc->buffer[BLK_PRIMARY_TYPE]); + + switch (primary_type) { + case T_LIST: + break; + case T_SHORT: + break; + case T_DATA: + break; + default: + /* TODO: handle unknown primary type */ + break; + } + + /* + * for root block: collect all bitmap blocks now + */ + + /* + * i won't hide it: there's plenty of things to check here, but + * since it's just a validation task + * i have decided to remove the redundant code. + */ + + /* + * ok, if anyone wants to remove the bitmap allocations and re-allocate them by himself + * here's the good place to start doing it. myself, i think the best way is to rely on + * operating system in this matter: unless someone damaged the disk structure, it's + * perfectly safe to assume that number of allocated bitmap blocks is just enough for us + * to store the bitmap. Again, it's not a salvaging, repairing NOR reorganizing task. + */ + + /* + * oh, btw; we also want to collect the bitmap blocks here so we know where to save new bitmap. + */ + if (entry_type == 1) + { + D(bug("[afs validate]: Checking and collecting bitmap blocks\n")); + + id = collect_bitmap(ds, bc); + if (id != vr_OK) + return id; + + /* The valid flag is committed only after record_bitmap succeeds. */ + bc = getBlock(ds->afs, vol, blk); + if (bc == NULL) + return vr_ReadError; + } + + /* + * this is the collection procedure + * we check for directories/files here only. if an entry is not a directory, + * check if it is a file and accumulate data blocks for it. + * here we are interested only in FOUR of SEVEN types: ROOT, DIRECTORY, FILE and FILE EXTENSION + */ + if ((entry_type == 1) || (entry_type == 2)) // 1 = root, which is handled already, 3 = symlink, which we don't need, 4 = hardlink, which we don't want + { + LONG i; + + /* + * clear directory cache block. + * fancy thing about directory cache: it is the best way to run into inconsistencies between file trees. + * two trees, one kept for compatibility (which is not kept btw as dostype is different), and the other + * for 'faster directory listing', but not always in sync + */ + if (bc->buffer[BLK_EXTENSION(vol)] != 0) + { + D(bug("[afs validate]: clearing dircache pointer\n")); + bc->buffer[BLK_EXTENSION(vol)] = 0; + verify_checksum(ds, bc->buffer); + bc->flags |= BCF_WRITE; + } + + for (i=BLK_TABLE_START; i<=BLK_TABLE_END(vol); i++) + { + id = OS_BE2LONG(bc->buffer[i]); + if (id != 0) + { + /* + * proceed with block collection. unless user decides to stop validation + * move on and bug them about whatever is really bad + */ + id = collect_directory_blocks(ds, id); + if (id == vr_Aborted || id == vr_ReadError || id == vr_WriteError + || id == vr_OutOfMemory) + return id; + + /* + * restore current block + * this will work well if the modified block gets marked as BCF_WRITE + */ + bc = getBlock(ds->afs, vol, blk); + if (bc == NULL) + return vr_ReadError; + + if (vr_OK != id) + { + /* it's a good idea to flag this requester, so it shows only once */ + if ((0 == (ds->flags & ValFlg_DisableReq_DataLossImminent)) && (0 == showError(ds->afs, ERR_DATA_LOSS_POSSIBLE))) + return vr_Aborted; + + ds->flags |= ValFlg_DisableReq_DataLossImminent; + bc->buffer[i] = 0; + verify_checksum(ds, bc->buffer); + bc->flags |= BCF_WRITE; + } + } + } + } + + /* + * collect file data blocks. + * some files are too large to fit in a single list of data blocks + * this covers scanning more blocks + * + * crap, i don't know if i should use entry_type=0 here, too :| + */ + if (entry_type == -3) + { + id = collect_file_extensions(ds, bc); + if (id != vr_OK) + return id; + bc = getBlock(ds->afs, vol, blk); + if (bc == NULL) + return vr_ReadError; + id = OS_BE2LONG(bc->buffer[BLK_BYTE_SIZE(vol)]); + if (id > (ds->file_blocks * vol->SizeBlock << 2)) + { + bc->buffer[BLK_BYTE_SIZE(vol)] = OS_LONG2BE(ds->file_blocks * vol->SizeBlock << 2); + verify_checksum(ds, bc->buffer); + bc->flags |= BCF_WRITE; + } + } + + /* + * finally, move on to next file in this hash chain. IF next file suffers anything, remove it and following files from hash chain. + */ + id = OS_BE2LONG(bc->buffer[BLK_HASHCHAIN(vol)]); + if (id != 0) + { + D(bug("[afs validate]: collecting other items in this chain\n")); + + /* + * collect other elements + */ + id = collect_directory_blocks(ds, id); + + /* + * if aborted, simply quit + */ + if (id == vr_Aborted || id == vr_ReadError || id == vr_WriteError + || id == vr_OutOfMemory) + { + return id; + } + + /* + * otherwise alter structure + */ + if (id != 0) + { + D(bug("[afs validate]: removing faulty chain\n")); + bc = getBlock(ds->afs, vol, blk); + if (bc == NULL) + return vr_ReadError; + bc->buffer[BLK_HASHCHAIN(vol)] = 0; + verify_checksum(ds, bc->buffer); + bc->flags |= BCF_WRITE; + } + } + + return vr_OK; } /* * record bitmap: stores bitmap in RAM (if you redefine a little) and saves it to disk. + * + * The bitmap content is fully known in memory, so the on-disk blocks are + * built here and written out in runs of consecutive blocks, without first + * reading each block in. Bitmap data blocks are never pulled into the block + * cache deliberately, but read-ahead may have cached copies. Invalidate those + * copies before bypassing the cache; preserve all caller-owned buffers. */ -void record_bitmap(DiskStructure *ds) +#define BM_RECORDBATCHBYTES 65536 + +/* Direct bitmap writes must not evict buffers owned by the calling packet. */ +static BOOL invalidateBitmapCache(DiskStructure *ds, BOOL invalidate) { - struct BlockCache *bc; - ULONG *mem; - ULONG i; - - for (i=0; ibm_lastblk; i++) - { - bc = getBlock(ds->afs, ds->vol, ds->bm_blocks[i]); - mem = bc->buffer; - - CopyMemQuick(&((char*)ds->bitmap)[i*((ds->vol->SizeBlock-1)<<2)], &mem[1], (ds->vol->SizeBlock-1)<<2); - verify_bm_checksum(ds, mem); - bc->flags |= BCF_WRITE; - } + struct BlockCache *bc; + ULONG i; + for (bc = ds->vol->blockcache; bc != NULL; bc = bc->next) + for (i = 0; i < ds->bm_lastblk; i++) + if (bc->blocknum == ds->bm_blocks[i] + && (bc->flags & (BCF_USED | BCF_WRITE))) + return DOSFALSE; + if (!invalidate) + return DOSTRUE; + for (bc = ds->vol->blockcache; bc != NULL; bc = bc->next) + for (i = 0; i < ds->bm_lastblk; i++) + if (bc->blocknum == ds->bm_blocks[i]) + { + bc->blocknum = 0; + bc->newness = 0; + break; + } + return DOSTRUE; +} + +ValidationResult record_bitmap(DiskStructure *ds) +{ + struct Volume *vol = ds->vol; + ULONG bmap_blk_bytes = (vol->SizeBlock-1)<<2; + ULONG batchblocks = BM_RECORDBATCHBYTES / BLOCK_SIZE(vol); + UBYTE *buf = NULL; + ULONG i; + + if (!invalidateBitmapCache(ds, FALSE)) + return vr_NoAccess; + if (batchblocks > 1) + buf = AllocVec(batchblocks * BLOCK_SIZE(vol), MEMF_PUBLIC); + if (buf == NULL) + { + /* no memory for batching - write through the cache, one block at a time */ + struct BlockCache *bc; + ULONG *mem; + + for (i=0; ibm_lastblk; i++) + { + bc = getBlock(ds->afs, vol, ds->bm_blocks[i]); + if (bc == NULL) + return vr_ReadError; + mem = bc->buffer; + + CopyMemQuick(&((char*)ds->bitmap)[i*bmap_blk_bytes], &mem[1], bmap_blk_bytes); + verify_bm_checksum(ds, mem); + if (!writeBlock(ds->afs, vol, bc, -1)) + return vr_WriteError; + } + return vr_OK; + } + + /* Invalidate before bypassing the cache, also covering partial failure. */ + if (!invalidateBitmapCache(ds, TRUE)) + { + FreeVec(buf); + return vr_NoAccess; + } + i = 0; + while (i < ds->bm_lastblk) + { + ULONG runlen = 1; + ULONG n; + + while ((i + runlen < ds->bm_lastblk) && (runlen < batchblocks) + && (ds->bm_blocks[i + runlen] == ds->bm_blocks[i] + runlen)) + runlen++; + + for (n = 0; n < runlen; n++) + { + ULONG *mem = (ULONG *)(buf + n * BLOCK_SIZE(vol)); + + mem[0] = 0; + CopyMemQuick(&((char*)ds->bitmap)[(i + n) * bmap_blk_bytes], &mem[1], bmap_blk_bytes); + verify_bm_checksum(ds, mem); + } + if (writeDisk(ds->afs, vol, ds->bm_blocks[i], runlen, buf) != 0) + { + FreeVec(buf); + return vr_WriteError; + } + i += runlen; + } + FreeVec(buf); + return vr_OK; } /* @@ -745,96 +901,90 @@ void record_bitmap(DiskStructure *ds) */ LONG bm_allocate_bitmap(DiskStructure *ds) { - ULONG i; - ULONG bmap_blk_size; + ULONG i; + ULONG bmap_blk_size; - /* - * bitmap block size: blk_size - 4 - */ - bmap_blk_size = ((ds->vol->SizeBlock-1)<<2); + /* + * bitmap block size: blk_size - 4 + */ + bmap_blk_size = ((ds->vol->SizeBlock-1)<<2); - /* - * total bitmap size is calculated as follows: - * - total number of bits (rounded up to nearest multiple of 8) converted to bytes - * - the above rounded up to nearest size of a single block - 4 bytes - */ - i = (((ds->vol->countblocks + 7) >> 3) + (bmap_blk_size - 1)) / bmap_blk_size; + /* + * total bitmap size is calculated as follows: + * - total number of bits (rounded up to nearest multiple of 8) converted to bytes + * - the above rounded up to nearest size of a single block - 4 bytes + */ + i = (((ds->vol->countblocks + 7) >> 3) + (bmap_blk_size - 1)) / bmap_blk_size; - D(bug("[afs validate]: allocating bitmaps (%ld bytes)\n", i * bmap_blk_size)); - ds->bitmap = AllocVec(i * bmap_blk_size, MEMF_ANY); + D(bug("[afs validate]: allocating bitmaps (%ld bytes)\n", i * bmap_blk_size)); + ds->bitmap = AllocVec(i * bmap_blk_size, MEMF_ANY); - D(bug("[afs validate]: allocating storage for bitmap blocks (%ld bytes)\n", i * sizeof(ULONG))); - ds->bm_blocks = (ULONG*)AllocVec(i * sizeof(ULONG), MEMF_ANY | MEMF_CLEAR); + D(bug("[afs validate]: allocating storage for bitmap blocks (%ld bytes)\n", i * sizeof(ULONG))); + ds->bm_blocks = (ULONG*)AllocVec(i * sizeof(ULONG), MEMF_ANY | MEMF_CLEAR); - D(bug("[afs validate]: allocating storage for bitmap extension blocks (%ld bytes) - way more than we really need\n", i * sizeof(ULONG))); - ds->bme_blocks = (ULONG*)AllocVec(i * sizeof(ULONG), MEMF_ANY | MEMF_CLEAR); + D(bug("[afs validate]: allocating storage for bitmap extension blocks (%ld bytes) - way more than we really need\n", i * sizeof(ULONG))); + ds->bme_blocks = (ULONG*)AllocVec(i * sizeof(ULONG), MEMF_ANY | MEMF_CLEAR); - if ((ds->bitmap == 0) || (ds->bm_blocks == 0) || (ds->bme_blocks == 0)) - { - D(bug("[afs validate]: Unable to allocate memory for bitmap!\n")); - return -1; - } + if ((ds->bitmap == 0) || (ds->bm_blocks == 0) || (ds->bme_blocks == 0)) + { + D(bug("[afs validate]: Unable to allocate memory for bitmap!\n")); + return -1; + } - i *= bmap_blk_size; + i *= bmap_blk_size; - while (i--) - { - ((UBYTE*)ds->bitmap)[i] = ~0; - } + while (i--) + { + ((UBYTE*)ds->bitmap)[i] = ~0; + } - ds->bm_lastblk = 0; - ds->bme_lastblk = 0; + ds->bm_lastblk = 0; + ds->bme_lastblk = 0; - return 0; + return 0; } void bm_free_bitmap(DiskStructure* ds) { - D(bug("[afs validate]: freeing previously allocated bitmaps\n")); - FreeVec(ds->bitmap); - FreeVec(ds->bm_blocks); - FreeVec(ds->bme_blocks); + D(bug("[afs validate]: freeing previously allocated bitmaps\n")); + FreeVec(ds->bitmap); + FreeVec(ds->bm_blocks); + FreeVec(ds->bme_blocks); } BitmapResult bm_mark_block(DiskStructure *ds, ULONG block) { - if ((block < ds->vol->bstartblock) || (block >= ds->vol->countblocks)) - { - D(bug("block %ld is out of disk area range\n", block)); - return st_OutOfRange; - } + if ((block < ds->vol->bootblocks) || (block >= ds->vol->countblocks)) + { + D(bug("block %ld is out of disk area range\n", block)); + return st_OutOfRange; + } - block -= ds->vol->bootblocks; + block -= ds->vol->bootblocks; #if AROS_BIG_ENDIAN - if ((((ULONG*)ds->bitmap)[block >> 5] & (1 << (block & 31))) == 0) + if ((((ULONG*)ds->bitmap)[block >> 5] & (1 << (block & 31))) == 0) #else - if ((((ULONG*)ds->bitmap)[block >> 5] & (1 << ((block & 31)^24))) == 0) + if ((((ULONG*)ds->bitmap)[block >> 5] & (1 << ((block & 31)^24))) == 0) #endif - { - D(bug("Duplicate block allocation for block %ld! Overlapping files?\n", (block+ds->vol->bstartblock))); - return st_AlreadyInUse; - } - + { + D(bug("Duplicate block allocation for block %ld! Overlapping files?\n", (block+ds->vol->bootblocks))); + return st_AlreadyInUse; + } + #if AROS_BIG_ENDIAN - ((ULONG*)ds->bitmap)[block >> 5] &= ~(1 << (block & 31)); + ((ULONG*)ds->bitmap)[block >> 5] &= ~(1 << (block & 31)); #else - ((ULONG*)ds->bitmap)[block >> 5] &= ~(1 << ((block & 31)^24)); + ((ULONG*)ds->bitmap)[block >> 5] &= ~(1 << ((block & 31)^24)); #endif - return st_OK; + return st_OK; } void bm_add_bitmap_block(DiskStructure *ds, ULONG blk) { - ds->bm_blocks[ds->bm_lastblk] = blk; - ds->bm_lastblk++; -} - -void bm_add_bitmap_extension_block(DiskStructure *ds, ULONG blk) -{ - ds->bme_blocks[ds->bme_lastblk] = blk; - ds->bme_lastblk++; + ds->bm_blocks[ds->bm_lastblk] = blk; + ds->bm_lastblk++; } diff --git a/rom/filesys/afs/validator.h b/rom/filesys/afs/validator.h index 3712f026965..b7e2d84769f 100644 --- a/rom/filesys/afs/validator.h +++ b/rom/filesys/afs/validator.h @@ -1,6 +1,5 @@ /* - Copyright © 1995-2010, The AROS Development Team. All rights reserved. - $Id$ + Copyright (C) 1995-2026, The AROS Development Team. All rights reserved. */ /* @@ -58,6 +57,7 @@ typedef enum vr_BlockUsedTwice, vr_Aborted, vr_BlockOutsideDisk, + vr_WriteError, } ValidationResult; typedef enum @@ -111,7 +111,7 @@ ValidationResult collect_directory_blocks(DiskStructure *ds, ULONG ext); /* * record bitmap back to disk */ -void record_bitmap(DiskStructure* ds); +ValidationResult record_bitmap(DiskStructure* ds); /* * call to allocate bitmap in disk structure. @@ -130,7 +130,6 @@ BitmapResult bm_mark_block(DiskStructure *ds, ULONG block); * */ void bm_add_bitmap_block(DiskStructure *ds, ULONG blk); -void bm_add_bitmap_extension_block(DiskStructure *ds, ULONG blk); #endif /* __AROS__ */ #endif /* VALIDATOR_H */ diff --git a/rom/filesys/afs/volumes.c b/rom/filesys/afs/volumes.c index 8b95a7e1d3c..e1994f8c5f1 100644 --- a/rom/filesys/afs/volumes.c +++ b/rom/filesys/afs/volumes.c @@ -1,18 +1,22 @@ /* - Copyright � 1995-2020, The AROS Development Team. All rights reserved. - $Id$ + Copyright (C) 1995-2026, The AROS Development Team. All rights reserved. */ /* * -date------ -name------------------- -description----------------------------- * 26-dec-2007 [Tomasz Wiszkowski] added disk validation * 04-jan-2008 [Tomasz Wiszkowski] corrected tabulation - * 05-jan-2008 [Tomasz Wiszkowski] removed requester prompting for validation - * to allow volume validation during boot-up + * 05-jan-2008 [Tomasz Wiszkowski] removed requester prompting for validation + * to allow volume validation during boot-up */ #include +#ifdef DEBUG +#undef DEBUG +#endif +#define DEBUG 0 + #include "os.h" #include "bitmap.h" #include "checksums.h" @@ -23,7 +27,7 @@ BOOL mediumPresent(struct IOHandle *ioh) { - return (ioh->ioflags & IOHF_DISK_IN)==IOHF_DISK_IN; + return (ioh->ioflags & IOHF_DISK_IN)==IOHF_DISK_IN; } /******************************************* @@ -32,8 +36,7 @@ BOOL mediumPresent(struct IOHandle *ioh) { Input : volume - Output: 0 for success; error code otherwise ********************************************/ -LONG newMedium(struct AFSBase *afsbase, struct Volume *volume) -{ +LONG newMedium(struct AFSBase *afsbase, struct Volume *volume) { struct BlockCache *blockbuffer; UWORD i; BOOL gotdostype = FALSE; @@ -41,110 +44,114 @@ LONG error; ULONG dostype; UBYTE dosflags; - D(bug("[AFS] newMedium: START\n")); +#ifdef __AROS__ + error = prepareMediumCache(afsbase, volume); + if (error != 0) + return error; +#endif + volume->bitmapinvalid = FALSE; /* New media starts with an unknown root state. */ + /* Check validity of root block first, since boot block may be left over + from an overwritten partition of a different size + Read bootblock first to prevent multiple seeks when using floppies + */ + blockbuffer=getBlock(afsbase, volume,0); + volume->dostype = dostype = 0; + volume->dosflags = dosflags = 0; + if (blockbuffer != NULL) { + gotdostype = TRUE; + dostype = OS_BE2LONG(blockbuffer->buffer[0]) & 0xFFFFFF00; + dosflags = OS_BE2LONG(blockbuffer->buffer[0]) & 0xFF; + } + + blockbuffer=getBlock(afsbase, volume,volume->rootblock); + if (blockbuffer == NULL) { + volume->dostype = ID_UNREADABLE_DISK; + return ERROR_UNKNOWN; + } + if (calcChkSum(volume->SizeBlock, blockbuffer->buffer) != 0 || + OS_BE2LONG(blockbuffer->buffer[BLK_PRIMARY_TYPE]) != T_SHORT || + OS_BE2LONG(blockbuffer->buffer[BLK_SECONDARY_TYPE(volume)]) != ST_ROOT) + { + D(bug("[afs] newMedium: incorrect checksum or root block type (%d)\n", + OS_BE2LONG(blockbuffer->buffer[BLK_SECONDARY_TYPE(volume)]))); + volume->dostype = ID_NOT_REALLY_DOS; + return ERROR_NOT_A_DOS_DISK; + } + + if (gotdostype == FALSE) { + volume->dostype = ID_UNREADABLE_DISK; + return ERROR_UNKNOWN; + } + if ((dostype != ID_DOS_DISK) && (dostype != ID_DOS_muFS_DISK)) + { + blockbuffer = getBlock(afsbase, volume, 1); + if (blockbuffer == NULL) + return ERROR_UNKNOWN; + dostype = OS_BE2LONG(blockbuffer->buffer[0]) & 0xFFFFFF00; + dosflags = OS_BE2LONG(blockbuffer->buffer[0]) & 0xFF; + } + if ((dostype != ID_DOS_DISK) && (dostype != ID_DOS_muFS_DISK)) + { + D(bug("[afs] newMedium: incorrect DOS type (0x%x)\n", + volume->dostype)); + volume->dostype = ID_NOT_REALLY_DOS; + return ERROR_NOT_A_DOS_DISK; + } + blockbuffer=getBlock(afsbase, volume,volume->rootblock); + if (blockbuffer == NULL) { + volume->dostype = ID_UNREADABLE_DISK; + return ERROR_UNKNOWN; + } - /* Check validity of root block first, since boot block may be left over - from an overwritten partition of a different size - Read bootblock first to prevent multiple seeks when using floppies - */ - blockbuffer=getBlock(afsbase, volume,0); - volume->dostype = dostype = 0; - volume->dosflags = dosflags = 0; - if (blockbuffer != NULL) - { - gotdostype = TRUE; - dostype = OS_BE2LONG(blockbuffer->buffer[0]) & 0xFFFFFF00; - dosflags = OS_BE2LONG(blockbuffer->buffer[0]) & 0xFF; - } - D(bug("[AFS] newMedium: 1\n")); - blockbuffer=getBlock(afsbase, volume,volume->rootblock); - if (blockbuffer == NULL) - { - volume->dostype = ID_UNREADABLE_DISK; - return ERROR_UNKNOWN; - } - D(bug("[AFS] newMedium: 2\n")); - if (calcChkSum(volume->SizeBlock, blockbuffer->buffer) != 0 || - OS_BE2LONG(blockbuffer->buffer[BLK_PRIMARY_TYPE]) != T_SHORT || - OS_BE2LONG(blockbuffer->buffer[BLK_SECONDARY_TYPE(volume)]) != ST_ROOT) - { - D(bug("[AFS] newMedium: incorrect checksum or root block type (%ld)\n", - OS_BE2LONG(blockbuffer->buffer[BLK_SECONDARY_TYPE(volume)]))); - volume->dostype = ID_NOT_REALLY_DOS; - return ERROR_NOT_A_DOS_DISK; - } - D(bug("[AFS] newMedium: 3\n")); - if (gotdostype == FALSE) - { - volume->dostype = ID_UNREADABLE_DISK; - return ERROR_UNKNOWN; - } - D(bug("[AFS] newMedium: 4\n")); - if ((dostype != ID_DOS_DISK) && (dostype != ID_DOS_muFS_DISK)) - { - blockbuffer = getBlock(afsbase, volume, 1); - dostype = OS_BE2LONG(blockbuffer->buffer[0]) & 0xFFFFFF00; - dosflags = OS_BE2LONG(blockbuffer->buffer[0]) & 0xFF; - } - D(bug("[AFS] newMedium: 5\n")); - if ((dostype != ID_DOS_DISK) && (dostype != ID_DOS_muFS_DISK)) - { - D(bug("[AFS] newMedium: incorrect DOS type (0x%lx)\n", - volume->dostype)); - volume->dostype = ID_NOT_REALLY_DOS; - return ERROR_NOT_A_DOS_DISK; - } - D(bug("[AFS] newMedium: 6\n")); - blockbuffer=getBlock(afsbase, volume,volume->rootblock); - - if (blockbuffer == NULL) { - volume->dostype = ID_UNREADABLE_DISK; - return ERROR_UNKNOWN; - } + volume->dostype = dostype; + volume->dosflags = dosflags; - volume->dostype = dostype; - volume->dosflags = dosflags; - D(bug("[AFS] newMedium: 7\n")); - for (i=0;i<=24;i++) - { - volume->bitmapblockpointers[i]=OS_BE2LONG(blockbuffer->buffer[BLK_BITMAP_POINTERS_START(volume)+i]); - } - D(bug("[AFS] newMedium: 8\n")); - volume->bitmapextensionblock=OS_BE2LONG(blockbuffer->buffer[BLK_BITMAP_EXTENSION(volume)]); - D(bug("[AFS] newMedium: 9\n")); - if (!blockbuffer->buffer[BLK_BITMAP_VALID_FLAG(volume)]) - { - /* since our disk is invalid at this point, * - * we want to spawn a new process that will * - * perform disk validation while we move on */ + volume->bitmapinvalid = blockbuffer->buffer[BLK_BITMAP_VALID_FLAG(volume)] == 0; + for (i=0;i<=24;i++) + { + volume->bitmapblockpointers[i]=OS_BE2LONG + ( + blockbuffer->buffer[BLK_BITMAP_POINTERS_START(volume)+i] + ); + } + volume->bitmapextensionblock=OS_BE2LONG + ( + blockbuffer->buffer[BLK_BITMAP_EXTENSION(volume)] + ); + if (!blockbuffer->buffer[BLK_BITMAP_VALID_FLAG(volume)]) + { + /* since our disk is invalid at this point, * + * we want to spawn a new process that will * + * perform disk validation while we move on */ - volume->usedblockscount=0; - volume->state = ID_VALIDATING; + volume->usedblockscount=0; + volume->state = ID_VALIDATING; - launchValidator(afsbase, volume); - } - D(bug("[AFS] newMedium: 10\n")); - /* - * it's safe to assume that the block is still there - */ - blockbuffer=getBlock(afsbase, volume,volume->rootblock); - - if (blockbuffer->buffer[BLK_BITMAP_VALID_FLAG(volume)]) - { - blockbuffer->flags |= BCF_USED; // won't be cleared until volume is ejected - //volume->usedblockscount=countUsedBlocks(afsbase, volume); - volume->state = volume->state != ID_VALIDATING || diskWritable(afsbase, &volume->ioh) ? ID_VALIDATED : ID_WRITE_PROTECTED; - } + launchValidator(afsbase, volume); + } - D(bug("[AFS] newMedium: 11\n")); - error = osMediumInit(afsbase, volume, blockbuffer); - - if (error != 0) - return error; - - /* for free block searching */ - volume->lastaccess=volume->rootblock; - return 0; + /* + * it's safe to assume that the block is still there + */ + blockbuffer=getBlock(afsbase, volume,volume->rootblock); + if (blockbuffer == NULL) + return ERROR_UNKNOWN; + + if (blockbuffer->buffer[BLK_BITMAP_VALID_FLAG(volume)]) + { + blockbuffer->flags |= BCF_USED; // won't be cleared until volume is ejected + D(bug("[afs] counting used blocks...\n")); + //volume->usedblockscount=countUsedBlocks(afsbase, volume); + D(bug("[afs] %u blocks in use\n", volume->usedblockscount)); + volume->state = diskWritable(afsbase, &volume->ioh) ? + ID_VALIDATED : ID_WRITE_PROTECTED; + } + error = osMediumInit(afsbase, volume, blockbuffer); + if (error != 0) + return error; + /* for free block searching */ + volume->lastaccess=volume->rootblock; + return 0; } /******************************************* @@ -160,97 +167,105 @@ UBYTE dosflags; pointer to struct Volume on success ********************************************/ struct Volume *initVolume - ( - struct AFSBase *afsbase, - struct Device *device, - CONST_STRPTR blockdevice, - ULONG unit, - ULONG flags, - struct DosEnvec *devicedef, - LONG *error - ) + ( + struct AFSBase *afsbase, + struct Device *device, + CONST_STRPTR blockdevice, + ULONG unit, + ULONG flags, + struct DosEnvec *devicedef, + LONG *error + ) { - struct Volume *volume; + struct Volume *volume; - if (blockdevice == NULL) { - *error = ERROR_NO_DISK; - return NULL; - } + if (blockdevice == NULL) { + *error = ERROR_NO_DISK; + return NULL; + } - volume = AllocMem(sizeof(struct Volume) + strlen(blockdevice) + 1,MEMF_PUBLIC | MEMF_CLEAR); - if (volume != NULL) - { - volume->FNameMax = MAX_NAME_LENGTH; - D(bug("[AFS] initVolume: NameLen MAX =%d\n",volume->FNameMax)); - volume->device = device; - volume->ioh.blockdevice = (STRPTR)(&volume[1]); /* Data after the volume alloc */ - strcpy(volume->ioh.blockdevice, blockdevice); - volume->ioh.unit = unit; - volume->ioh.flags = flags; - volume->SizeBlock = devicedef->de_SizeBlock - * devicedef->de_SectorPerBlock; - volume->sectorsize = devicedef->de_SizeBlock << 2; - volume->blocksectors = devicedef->de_SectorPerBlock; - if (devicedef->de_TableSize>=20) - volume->bootblocks=devicedef->de_BootBlocks; - else - volume->bootblocks=devicedef->de_Reserved; - volume->numbuffers = devicedef->de_NumBuffers; - volume->blockcache=initCache(afsbase, volume, volume->numbuffers); - if (volume->blockcache != NULL) - { - if (openBlockDevice(afsbase, &volume->ioh)!= NULL) - { - volume->countblocks = - ( - ( - devicedef->de_HighCyl-devicedef->de_LowCyl+1 - )*devicedef->de_Surfaces*devicedef->de_BlocksPerTrack - / - devicedef->de_SectorPerBlock - ); - volume->rootblock =(volume->countblocks-1+devicedef->de_Reserved)/2; - volume->startblock= - devicedef->de_LowCyl* - devicedef->de_Surfaces* - devicedef->de_BlocksPerTrack; - volume->lastblock= - ( - (devicedef->de_HighCyl+1) - *devicedef->de_Surfaces - *devicedef->de_BlocksPerTrack - )-1; - check64BitSupport(afsbase, volume); - volume->ah.volume=volume; - if (mediumPresent(&volume->ioh)) - { - *error = newMedium(afsbase, volume); - } - else - *error = 0; - if ((*error == 0) || (*error == ERROR_NOT_A_DOS_DISK)) - { - D(bug("[AFS] initVolume: BootBlocks=%d\n",volume->bootblocks)); - D(bug("[AFS] initVolume: RootBlock=%ld\n",volume->rootblock)); - volume->ah.header_block = volume->rootblock; - return volume; - } - } - else - { - *error=ERROR_NO_FREE_STORE; - } - freeCache(afsbase, volume->blockcache); - } - else - { - *error=ERROR_NO_FREE_STORE; - } - FreeMem(volume,sizeof(struct Volume) + strlen(blockdevice) + 1); - } - else - *error=ERROR_NO_FREE_STORE; - return NULL; + volume = AllocMem(sizeof(struct Volume) + strlen(blockdevice) + 1,MEMF_PUBLIC | MEMF_CLEAR); + if (volume != NULL) + { + volume->FNameMax = MAX_NAME_LENGTH; + D(bug("[afs] initVolume: NameLen MAX =%d\n",volume->FNameMax)); + volume->device = device; + volume->ioh.blockdevice = (STRPTR)(&volume[1]); /* Data after the volume alloc */ + strcpy(volume->ioh.blockdevice, blockdevice); + volume->ioh.unit = unit; + volume->ioh.flags = flags; + volume->SizeBlock = devicedef->de_SizeBlock + * devicedef->de_SectorPerBlock; + volume->sectorsize = devicedef->de_SizeBlock << 2; + volume->blocksectors = devicedef->de_SectorPerBlock; + if (devicedef->de_TableSize>=20) + volume->bootblocks=devicedef->de_BootBlocks; + else + volume->bootblocks=devicedef->de_Reserved; + volume->numbuffers = devicedef->de_NumBuffers; + /* Respect the device's transfer limit, if one is given */ + volume->maxtransfer = 0xFFFFFFFF; + if ((devicedef->de_TableSize >= DE_MAXTRANSFER) + && (devicedef->de_MaxTransfer != 0)) + volume->maxtransfer = devicedef->de_MaxTransfer; + D(bug("[afs] initVolume: MaxTransfer=%lu\n", volume->maxtransfer)); + volume->blockcache=initCache(afsbase, volume, volume->numbuffers); + if (volume->blockcache != NULL) + { + initBulkBuffer(afsbase, volume); + if (openBlockDevice(afsbase, &volume->ioh)!= NULL) + { + volume->countblocks = + ( + ( + devicedef->de_HighCyl-devicedef->de_LowCyl+1 + )*devicedef->de_Surfaces*devicedef->de_BlocksPerTrack + / + devicedef->de_SectorPerBlock + ); + volume->rootblock =(volume->countblocks-1+devicedef->de_Reserved)/2; + volume->startblock= + devicedef->de_LowCyl* + devicedef->de_Surfaces* + devicedef->de_BlocksPerTrack; + volume->lastblock= + ( + (devicedef->de_HighCyl+1) + *devicedef->de_Surfaces + *devicedef->de_BlocksPerTrack + )-1; + check64BitSupport(afsbase, volume); + volume->ah.volume=volume; + if (mediumPresent(&volume->ioh)) + { + *error = newMedium(afsbase, volume); + } + else + *error = 0; + if ((*error == 0) || (*error == ERROR_NOT_A_DOS_DISK)) + { + D(bug("[afs] initVolume: BootBlocks=%d\n",volume->bootblocks)); + D(bug("[afs] initVolume: RootBlock=%d\n",volume->rootblock)); + volume->ah.header_block = volume->rootblock; + return volume; + } + } + else + { + *error=ERROR_NO_FREE_STORE; + } + freeCache(afsbase, volume->blockcache); + freeBulkBuffer(afsbase, volume); + } + else + { + *error=ERROR_NO_FREE_STORE; + } + FreeMem(volume,sizeof(struct Volume) + strlen(blockdevice) + 1); + } + else + *error=ERROR_NO_FREE_STORE; + return NULL; } /******************************************* @@ -262,11 +277,12 @@ struct Volume *initVolume ********************************************/ void uninitVolume(struct AFSBase *afsbase, struct Volume *volume) { - osMediumFree(afsbase, volume, TRUE); - if (volume->blockcache != NULL) - freeCache(afsbase, volume->blockcache); - closeBlockDevice(afsbase, &volume->ioh); - FreeMem(volume,sizeof(struct Volume) + strlen(volume->ioh.blockdevice) + 1); + osMediumFree(afsbase, volume, TRUE); + if (volume->blockcache != NULL) + freeCache(afsbase, volume->blockcache); + freeBulkBuffer(afsbase, volume); + closeBlockDevice(afsbase, &volume->ioh); + FreeMem(volume,sizeof(struct Volume) + strlen(volume->ioh.blockdevice) + 1); } @@ -277,7 +293,7 @@ LONG writeprotectVolume(struct AFSBase *afsbase, struct Volume *volume, BOOL on, if(on && (volume->state == ID_WRITE_PROTECTED)) { // Already write protected error = ERROR_DISK_WRITE_PROTECTED; - D(bug("[AFS] Volume: Already write protected (%l)\n", error)); + D(bug("[AFS] Volume: Already write protected (%d)\n", error)); } else { if(on) { // Attempt to write protect @@ -297,7 +313,7 @@ LONG writeprotectVolume(struct AFSBase *afsbase, struct Volume *volume, BOOL on, volume->key = 0; } else { // Key is incorrect error = ERROR_INVALID_COMPONENT_NAME; - D(bug("[AFS] Volume: Wrong key (%l)\n", error)); + D(bug("[AFS] Volume: Wrong key (%d)\n", error)); return error; } } else { // There is no key diff --git a/rom/filesys/afs/volumes.h b/rom/filesys/afs/volumes.h index ce861cc3814..59c8cceb5a1 100644 --- a/rom/filesys/afs/volumes.h +++ b/rom/filesys/afs/volumes.h @@ -2,7 +2,7 @@ #define VOLUMES_H /* - Copyright © 1995-2010, The AROS Development Team. All rights reserved. + Copyright © 1995-2026, The AROS Development Team. All rights reserved. $Id$ */ @@ -15,10 +15,12 @@ struct Volume { struct Device *device; /* the handler this volume uses */ struct DeviceList devicelist __attribute__((aligned(4))); /* BPTR compatible */ struct DosList *volumenode; + BOOL volumenodeadded; /* volumenode is in the system DosList */ ULONG SizeBlock; /* Block size in words */ ULONG blocksectors; /* nr of sectors per block */ ULONG sectorsize; /* nr of bytes per sector */ + ULONG maxtransfer; /* max bytes per device request (DE_MAXTRANSFER) */ ULONG FNameMax; @@ -28,6 +30,11 @@ struct Volume { struct IOHandle ioh; struct BlockCache *blockcache; LONG numbuffers; + APTR bulkbuffer; /* bounce buffer for multi-block reads */ + ULONG bulkblocks; /* blocks it holds (0 = none) */ + BOOL cachepending; /* dirty cache belongs to the removed medium */ + BOOL bitmapinvalid; /* last successful root write cleared its valid flag */ + BOOL writefailed; /* pause mutations/background retries after an I/O error */ ULONG cachecounter; /* Keeps track of cache usage */ ULONG state; /* Read-only, read/write or validating */ ULONG key; /* Lock key */ @@ -43,7 +50,8 @@ struct Volume { ULONG bitmapextensionblock; struct BlockCache *bitmapblock; /* last bitmap block used for marking */ - ULONG bstartblock; /* first block marked in "bitmapblock" */ + ULONG bstartblock; /* first block covered by "bitmapblock", as block + number minus bootblocks (0 = first bitmapped block) */ ULONG lastextensionblock; /* last used extensionblock (0=volume->bitmapblocks) */ ULONG lastposition; /* last position in extensionblock */ ULONG lastaccess; /* last marked block */ diff --git a/rom/filesys/pfs3/fs/directory.c b/rom/filesys/pfs3/fs/directory.c index 5b53a8187af..6f55b3e9bc8 100644 --- a/rom/filesys/pfs3/fs/directory.c +++ b/rom/filesys/pfs3/fs/directory.c @@ -1181,7 +1181,7 @@ static ULONG FillInData(struct ExAllData *buffer, LONG type, break; case ED_OWNER: -#if defined(__MORPHOS__) +#if defined(__MORPHOS__) || defined(__AROS__) size = offsetof(struct ExAllData, ed_Size64); break; @@ -1220,7 +1220,7 @@ static ULONG FillInData(struct ExAllData *buffer, LONG type, buffer->ed_Next = NULL; switch (type) { -#if defined(__MORPHOS__) +#if defined(__MORPHOS__) || defined(__AROS__) case ED_SIZE64: #if ROLLOVER if (direntry->type == ST_ROLLOVERFILE) @@ -1292,7 +1292,7 @@ BOOL ExamineAll(lockentry_t *object, UBYTE *buffer, ULONG buflen, } /* check type field */ -#if defined(__MORPHOS__) +#if defined(__MORPHOS__) || defined(__AROS__) if (type > ED_SIZE64 || type < ED_NAME) #else if (type > ED_OWNER || type < ED_NAME) @@ -4164,7 +4164,7 @@ static ULONG FillInDDEData(struct ExAllData *buffer, LONG type, size = offsetof(struct ExAllData, ed_OwnerUID); break; case ED_OWNER: -#if defined(__MORPHOS__) +#if defined(__MORPHOS__) || defined(__AROS__) size = offsetof(struct ExAllData, ed_Size64); break; case ED_SIZE64: @@ -4196,7 +4196,7 @@ static ULONG FillInDDEData(struct ExAllData *buffer, LONG type, buffer->ed_Next = NULL; switch (type) { -#if defined(__MORPHOS__) +#if defined(__MORPHOS__) || defined(__AROS__) case ED_SIZE64: buffer->ed_Size64 = GetDDFileSize(dde, g); #endif diff --git a/rom/mmakefile.src b/rom/mmakefile.src index 73a0e82cf7c..d3796775095 100644 --- a/rom/mmakefile.src +++ b/rom/mmakefile.src @@ -6,6 +6,7 @@ include $(SRCDIR)/config/aros.cfg #MM kernel-aros \ #MM kernel-disk \ #MM kernel-dos \ +#MM kernel-dos64 \ #MM kernel-debug \ #MM kernel-fs-con \ #MM kernel-graphics \ @@ -36,6 +37,7 @@ include $(SRCDIR)/config/aros.cfg #MM kernel-ata-includes \ #MM kernel-cia-includes \ #MM kernel-dos-includes \ +#MM kernel-dos64-includes \ #MM kernel-bootloader-includes \ #MM kernel-debug-includes \ #MM kernel-efi-includes \ @@ -77,6 +79,7 @@ include $(SRCDIR)/config/aros.cfg #MM kernel-aros \ #MM kernel-bootloader \ #MM kernel-dos \ +#MM kernel-dos64 \ #MM kernel-debug \ #MM kernel-dosboot \ #MM kernel-filesystem \ @@ -105,6 +108,7 @@ include $(SRCDIR)/config/aros.cfg #MM kernel-aros \ #MM kernel-bootloader \ #MM kernel-dos \ +#MM kernel-dos64 \ #MM kernel-dosboot \ #MM kernel-debug \ #MM kernel-filesystem \ @@ -132,7 +136,7 @@ include $(SRCDIR)/config/aros.cfg BASE_DEVICES := console input gameport keyboard BASE_HANDLERS := ram con BASE_HIDD := hiddclass gfx keyboard mouse -BASE_LIBS := aros debug dos graphics intuition keymap layers oop utility +BASE_LIBS := aros debug dos dos64 graphics intuition keymap layers oop utility BASE_RSRCS := bootloader dosboot FileSystem lddemon %make_package mmake=kernel-package-base file=$(AROS_BOOT)/aros-base.pkg \ diff --git a/workbench/c/List.c b/workbench/c/List.c index c88885f3bfd..5a222d6085e 100644 --- a/workbench/c/List.c +++ b/workbench/c/List.c @@ -139,7 +139,9 @@ #include #include #include +#include #include +#include #include #include #include @@ -545,6 +547,27 @@ int printLformat(STRPTR format, struct lfstruct *lf) } +/* dos64.library, NULL when it is not installed */ +struct Library *DOS64Base; + +/* The size of a file whose 32 bit size was clamped */ +static UQUAD fileSize64(CONST_STRPTR name, UQUAD size) +{ + if (DOS64Base != NULL) + { + struct FileInfoBlock *fib = AllocDosObject64(DOS64_FIB, NULL); + + if (fib != NULL) + { + if (ExamineName64(name, fib, NULL)) + size = fib->fib_Size64; + FreeDosObject64(DOS64_FIB, fib); + } + } + + return size; +} + int printFileData(struct AnchorPath *ap, BOOL showFiles, BOOL showDirs, STRPTR parsedPattern, ULONG *files, ULONG *dirs, ULONG *nBlocks, STRPTR lFormat, @@ -557,7 +580,7 @@ int printFileData(struct AnchorPath *ap, BOOL isDir = (ap->ap_Info.fib_DirEntryType >= 0); struct DateStamp *ds = &ap->ap_Info.fib_Date; ULONG protection = ap->ap_Info.fib_Protection; - UQUAD size = ap->ap_Info.fib_Size; + UQUAD size = (ULONG)ap->ap_Info.fib_Size; STRPTR filenote = ap->ap_Info.fib_Comment; ULONG diskKey = ap->ap_Info.fib_DiskKey; @@ -569,23 +592,9 @@ int printFileData(struct AnchorPath *ap, struct DateTime dt; -#if defined(ACTION_GET_FILE_SIZE64) - if (ap->ap_Info.fib_Size >= 0x7FFFFFFF) - { - BPTR flock = BNULL; - flock = Lock(filename, ACCESS_READ); - - if (flock) - { - UQUAD *size_ptr = (UQUAD *)DoPkt(((struct FileLock *)flock)->fl_Task, ACTION_GET_FILE_SIZE64, (IPTR)flock, 0, 0, 0, 0); - if (size_ptr) - { - size = *size_ptr; - } - UnLock(flock); - } - } -#endif + /* A size that fills 32 bits may be clamped: ask for the full one */ + if (!isDir && size >= 0x7FFFFFFF) + size = fileSize64(filename, size); /* Do the file match the time interval we are looking for? (ARG_SINCE and ARG_UPTO) -- any combination of these may be specified */ @@ -997,6 +1006,8 @@ int main(void) Statistics stats = { 0, 0, 0 }; + DOS64Base = OpenLibrary("dos64.library", 51); + rda = ReadArgs(ARG_TEMPLATE, args, NULL); if (rda != NULL) @@ -1186,7 +1197,7 @@ int main(void) (stats.nFiles || stats.nDirs)) { Printf("\nTOTAL: %ld files - %ld directories - %ld blocks used\n", - stats.nFiles, stats.nDirs, stats.nBlocks); + stats.nFiles, stats.nDirs, (ULONG)stats.nBlocks); } @@ -1218,5 +1229,10 @@ int main(void) Close(SelectOutput(oldOutput)); } + if (DOS64Base != NULL) + { + CloseLibrary(DOS64Base); + } + return result; } diff --git a/workbench/libs/asl/asl_init.c b/workbench/libs/asl/asl_init.c index 0a7239b91bd..4afe433d8e8 100644 --- a/workbench/libs/asl/asl_init.c +++ b/workbench/libs/asl/asl_init.c @@ -19,6 +19,7 @@ #include #include #include +#include #include "asl_intern.h" #include LC_LIBDEFS_FILE @@ -165,6 +166,9 @@ const struct IntFontReq def_fontreq = }; +/* dos64.library, NULL when it is not installed */ +struct Library *DOS64Base; + /* coolimages may fail to open */ LONG CoolImagesBase_version = -1; @@ -184,12 +188,26 @@ static int InitBase(LIBBASETYPEPTR LIBBASE) InitReqInfo(LIBBASE); + DOS64Base = OpenLibrary("dos64.library", 51); + + return TRUE; +} + +static int ExpungeBase(LIBBASETYPEPTR LIBBASE) +{ + if (DOS64Base != NULL) + { + CloseLibrary(DOS64Base); + DOS64Base = NULL; + } + return TRUE; } /*****************************************************************************************/ ADD2INITLIB(InitBase, 0); +ADD2EXPUNGELIB(ExpungeBase, 0); /*****************************************************************************************/ diff --git a/workbench/libs/asl/asl_intern.h b/workbench/libs/asl/asl_intern.h index 155e1c87525..385a7ab0b62 100644 --- a/workbench/libs/asl/asl_intern.h +++ b/workbench/libs/asl/asl_intern.h @@ -318,7 +318,7 @@ char *PooledCloneStringLen(const char *name1, ULONG len1, const char *name2, ULO char *VecCloneString(const char *name1, const char *name2, struct AslBase_intern *AslBase); char *VecPooledCloneString(const char *name1, const char *name2, APTR pool, struct AslBase_intern *AslBase); -char *PooledUIntegerToString(IPTR value, APTR pool, struct AslBase_intern *AslBase); +char *PooledUIntegerToString(UQUAD value, APTR pool, struct AslBase_intern *AslBase); void CloseWindowSafely(struct Window *window, struct AslBase_intern *AslBase); AROS_UFP3(ULONG, StringEditFunc, diff --git a/workbench/libs/asl/basicfuncs.c b/workbench/libs/asl/basicfuncs.c index f5b2aee4a57..6fc847a58f4 100644 --- a/workbench/libs/asl/basicfuncs.c +++ b/workbench/libs/asl/basicfuncs.c @@ -1042,25 +1042,41 @@ AROS_UFH2 (void, puttostr, /*****************************************************************************************/ -/* This is used for printing out fib_Size, which is why - * is takes a IPTR instead of a ULONG - */ -char *PooledUIntegerToString(IPTR value, APTR pool, struct AslBase_intern *AslBase) +/* Decimal string of a 64 bit value, cloned into the pool */ +char *PooledUIntegerToString(UQUAD value, APTR pool, struct AslBase_intern *AslBase) { - char buffer[30]; - char *str = buffer; + char buffer[24]; + char *str = buffer + sizeof(buffer) - 1; char *clone; WORD len; - /* Create the text */ + *str = '\0'; + + /* 32 bit division while the value fits, 64 bit only above 4 GiB */ + if ((ULONG)(value >> 32) == 0) + { + ULONG lo = (ULONG)value; - RawDoFmt("%iu", (RAWARG)&value, (VOID_FUNC)AROS_ASMSYMNAME(puttostr), &str); + do + { + *--str = '0' + (char)(lo % 10); + lo /= 10; + } while (lo); + } + else + { + do + { + *--str = '0' + (char)(value % 10); + value /= 10; + } while (value); + } - len = strlen(buffer) + 1; + len = strlen(str) + 1; if ((clone = AllocPooled(pool, len))) { - CopyMem(buffer, clone, len); + CopyMem(str, clone, len); } return clone; diff --git a/workbench/libs/asl/filereqsupport.c b/workbench/libs/asl/filereqsupport.c index 16965809e1a..d291c53c839 100644 --- a/workbench/libs/asl/filereqsupport.c +++ b/workbench/libs/asl/filereqsupport.c @@ -9,11 +9,13 @@ #include #include #include +#include #include #include #include #include #include +#include #include #include #include @@ -41,6 +43,29 @@ static WORD FRCompareDirectoryNodes(struct IntFileReq *ifreq, struct ASLLVFileRe struct ASLLVFileReqNode *node2, struct AslBase_intern *AslBase); +/*****************************************************************************************/ + +/* The real size of a file whose 32 bit size was clamped, name is relative to dirlock */ +static UQUAD FRFileSize64(BPTR dirlock, CONST_STRPTR name, UQUAD size) +{ + if (DOS64Base != NULL) + { + struct FileInfoBlock *fib64 = AllocDosObject64(DOS64_FIB, NULL); + + if (fib64 != NULL) + { + BPTR oldcd = CurrentDir(dirlock); + + if (ExamineName64(name, fib64, NULL)) + size = fib64->fib_Size64; + CurrentDir(oldcd); + FreeDosObject64(DOS64_FIB, fib64); + } + } + + return size; +} + /*****************************************************************************************/ static void fixpath(char *pathstring) @@ -517,6 +542,11 @@ BOOL FRGetDirectory(STRPTR path, struct LayoutData *ld, struct AslBase_intern *A struct DateTime dt; char datebuffer[LEN_DATSTRING]; char timebuffer[LEN_DATSTRING]; + UQUAD size = (ULONG)fib->fib_Size; + + /* a clamped size of a file: ask dos64.library for the real one */ + if (fib->fib_DirEntryType <= 0 && size == 0xFFFFFFFF) + size = FRFileSize64(lock, fib->fib_FileName, size); if (fib->fib_FileName[0]) { @@ -531,7 +561,7 @@ BOOL FRGetDirectory(STRPTR path, struct LayoutData *ld, struct AslBase_intern *A node->text[1] = GetString(MSG_FILEREQ_LV_DRAWER, GetIR(ifreq)->ir_Catalog, AslBase); node->dontfreetext |= (1 << 1); } else { - node->text[1] = PooledUIntegerToString(fib->fib_Size, + node->text[1] = PooledUIntegerToString(size, ld->ld_IntReq->ir_MemPool, AslBase); @@ -561,7 +591,7 @@ BOOL FRGetDirectory(STRPTR path, struct LayoutData *ld, struct AslBase_intern *A node->userdata = ld; node->date = fib->fib_Date; - node->filesize = fib->fib_Size; + node->filesize = size; node->type = ASLLV_FRNTYPE_DIRECTORY; node->subtype = fib->fib_DirEntryType; diff --git a/workbench/libs/asl/layout.h b/workbench/libs/asl/layout.h index 4fec74933cf..70928238a75 100644 --- a/workbench/libs/asl/layout.h +++ b/workbench/libs/asl/layout.h @@ -194,7 +194,7 @@ struct ASLLVFileReqNode char *text[ASLLV_MAXCOLUMNS]; struct DateStamp date; APTR userdata; - ULONG filesize; + UQUAD filesize; LONG type; LONG subtype; UWORD dontfreetext; diff --git a/workbench/libs/muimaster/classes/dirlist.c b/workbench/libs/muimaster/classes/dirlist.c index 5af61c46580..3d9b0b6348e 100644 --- a/workbench/libs/muimaster/classes/dirlist.c +++ b/workbench/libs/muimaster/classes/dirlist.c @@ -8,13 +8,17 @@ #include #include #include +#include #include #include #include +#include #include #include #include +#include + #include #include @@ -27,6 +31,90 @@ extern struct Library *MUIMasterBase; +/* dos64.library, NULL when it is not installed */ +struct Library *DOS64Base; + +static int Dirlist_OpenDOS64(void) +{ + DOS64Base = OpenLibrary("dos64.library", 51); + + return TRUE; +} + +static void Dirlist_CloseDOS64(void) +{ + if (DOS64Base != NULL) + CloseLibrary(DOS64Base); + DOS64Base = NULL; +} + +ADD2INIT(Dirlist_OpenDOS64, 0); +ADD2EXIT(Dirlist_CloseDOS64, 0); + +/* Decimal string of a UQUAD, end-aligned in the buffer */ +static UBYTE *UQUAD2string(UQUAD value, UBYTE *buffer, int buflen) +{ + UWORD w[4]; + BOOL more; + + /* long division by 10 on 16 bit words, no 64 bit divide (libgcc) */ + w[0] = (UWORD)(value >> 48); + w[1] = (UWORD)(value >> 32); + w[2] = (UWORD)(value >> 16); + w[3] = (UWORD)value; + + buffer[--buflen] = '\0'; + + do + { + ULONG rem = 0; + int i; + + more = FALSE; + for (i = 0; i < 4; i++) + { + ULONG cur = (rem << 16) | w[i]; + + w[i] = (UWORD)(cur / 10); + rem = cur % 10; + if (w[i] != 0) + more = TRUE; + } + buffer[--buflen] = '0' + (UBYTE)rem; + } while (more); + + return buffer + buflen; +} + +/* The saturated NumBytes attribute value */ +static IPTR NumBytesAttr(UQUAD numbytes) +{ + return (numbytes > (IPTR)-1) ? (IPTR)-1 : (IPTR)numbytes; +} + +/* The size of a file; a clamped 32 bit size is asked again from dos64 */ +static UQUAD FileSize(BPTR dirlock, struct FileInfoBlock *fib) +{ + UQUAD size = (ULONG)fib->fib_Size; + + if (size == 0xFFFFFFFF && DOS64Base != NULL) + { + struct FileInfoBlock *fib64 = AllocDosObject64(DOS64_FIB, NULL); + + if (fib64 != NULL) + { + BPTR olddir = CurrentDir(dirlock); + + if (ExamineName64(fib->fib_FileName, fib64, NULL)) + size = fib64->fib_Size64; + CurrentDir(olddir); + FreeDosObject64(DOS64_FIB, fib64); + } + } + + return size; +} + AROS_UFH3S(APTR, construct_func, AROS_UFHA(struct Hook *, hook, A0), AROS_UFHA(APTR, pool, A2), @@ -79,9 +167,8 @@ AROS_UFH3S(LONG, display_func, } else { - snprintf(data->size_string, sizeof(data->size_string), "%ld", - (long)entry->fib.fib_Size); - *array++ = data->size_string; + *array++ = UQUAD2string(entry->size, data->size_string, + sizeof(data->size_string)); } dt.dat_Stamp = entry->fib.fib_Date; @@ -178,6 +265,8 @@ static void ReadDirectory(Object *obj, struct Dirlist_DATA *data) struct FileInfoBlock *fib; BPTR lock; + data->numbytes = 0; + if ((fib = AllocDosObject(DOS_FIB, NULL))) { if ((lock = Lock(data->directory, SHARED_LOCK))) @@ -222,6 +311,8 @@ static void ReadDirectory(Object *obj, struct Dirlist_DATA *data) } else { + struct Dirlist_Entry entry; + if (isdir && data->filesonly) continue; if (!isdir && data->drawersonly) @@ -256,6 +347,9 @@ static void ReadDirectory(Object *obj, struct Dirlist_DATA *data) } } + entry.fib = *fib; + entry.size = 0; + if (isdir) { set(obj, MUIA_Dirlist_NumDrawers, @@ -263,13 +357,15 @@ static void ReadDirectory(Object *obj, struct Dirlist_DATA *data) } else { + entry.size = FileSize(lock, fib); + data->numbytes += entry.size; set(obj, MUIA_Dirlist_NumFiles, ++data->numfiles); set(obj, MUIA_Dirlist_NumBytes, - data->numbytes + fib->fib_Size); + NumBytesAttr(data->numbytes)); } - DoMethod(obj, MUIM_List_InsertSingle, (IPTR) fib, + DoMethod(obj, MUIM_List_InsertSingle, (IPTR) &entry, MUIV_List_Insert_Bottom); } /* no filterhook */ @@ -418,7 +514,7 @@ IPTR Dirlist__OM_GET(struct IClass *cl, Object *obj, struct opGet *msg) return 1; case MUIA_Dirlist_NumBytes: - STORE = data->numbytes; + STORE = NumBytesAttr(data->numbytes); return 1; case MUIA_Dirlist_NumFiles: diff --git a/workbench/libs/muimaster/classes/dirlist_private.h b/workbench/libs/muimaster/classes/dirlist_private.h index 05c700c91c2..1502953224a 100644 --- a/workbench/libs/muimaster/classes/dirlist_private.h +++ b/workbench/libs/muimaster/classes/dirlist_private.h @@ -14,7 +14,7 @@ struct Dirlist_DATA STRPTR acceptpattern; STRPTR rejectpattern; STRPTR directory; - IPTR numbytes; + UQUAD numbytes; ULONG numdrawers; ULONG numfiles; BOOL drawersonly; @@ -26,7 +26,7 @@ struct Dirlist_DATA BYTE sortdirs; BYTE sorttype; BYTE status; - UBYTE size_string[20]; + UBYTE size_string[24]; UBYTE date_string[20]; UBYTE time_string[20]; UBYTE prot_string[8]; @@ -36,6 +36,7 @@ struct Dirlist_DATA struct Dirlist_Entry { struct FileInfoBlock fib; + UQUAD size; }; #endif /* _DIRLIST_PRIVATE_H_ */ diff --git a/workbench/libs/reqtools/filereq.h b/workbench/libs/reqtools/filereq.h index 5e7d9a4ba16..717e42d8304 100644 --- a/workbench/libs/reqtools/filereq.h +++ b/workbench/libs/reqtools/filereq.h @@ -24,6 +24,8 @@ #include #include #include +#include +#include #include #include #include @@ -133,6 +135,7 @@ struct ReqEntry { struct Node re_Node; LONG re_Size; + ULONG re_SizeHi; /* upper 32 bits of a file size */ UBYTE re_Flags, re_Style; UBYTE re_SizeLenPix, diff --git a/workbench/libs/reqtools/filereqextra.c b/workbench/libs/reqtools/filereqextra.c index ed1db198257..aed1be0a0b5 100644 --- a/workbench/libs/reqtools/filereqextra.c +++ b/workbench/libs/reqtools/filereqextra.c @@ -167,12 +167,42 @@ static void REGARGS Ghost (struct RastPort *rp, UWORD pen, UWORD x, UWORD y, UWO /****************************************************************************************/ +/* Decimal string of a 64 bit value, end aligned in buf */ +static char *UQuadToStr (UQUAD value, char *buf, int buflen) +{ + buf[--buflen] = '\0'; + + /* 32 bit division while the value fits, 64 bit only above 4 GiB */ + if ((ULONG)(value >> 32) == 0) + { + ULONG lo = (ULONG)value; + + do + { + buf[--buflen] = '0' + (char)(lo % 10); + lo /= 10; + } while (lo); + } + else + { + do + { + buf[--buflen] = '0' + (char)(value % 10); + value /= 10; + } while (value); + } + + return (buf + buflen); +} + +/****************************************************************************************/ + void REGARGS PrintEntry (GlobData *glob, int i) { struct TextExtent extent; struct ReqEntry *entry; struct RastPort *reqrp = glob->reqrp; - char sizestr[16], tempstr[108], *volname = NULL, *str; + char sizestr[24], tempstr[108], *volname = NULL, *str; int apen = 0, bpen = 0, top, len = 0, sizelen = 0, sizelenpix = 0, type, rectpen, left, entrytop; LONG size; @@ -198,7 +228,17 @@ void REGARGS PrintEntry (GlobData *glob, int i) /* FIXME: AROS LocaleLibrary does not yet patch RawDoFmt. So "%lD" (uppercase D) does not work yet here! */ useLocFmt = FALSE; #endif - DofmtArgs (sizestr, useLocFmt ? " %lD" : " %ld", size); + if (type == glob->file_id) + { + /* RawDoFmt cannot print 64 bit */ + char numstr[24]; + + sizestr[0] = ' '; + strcpy (sizestr + 1, UQuadToStr (((UQUAD)entry->re_SizeHi << 32) | (ULONG)size, + numstr, sizeof (numstr))); + } + else + DofmtArgs (sizestr, useLocFmt ? " %lD" : " %ld", size); if (type == FONT) { @@ -442,6 +482,7 @@ struct ReqEntry *REGARGS AddEntry (GlobData *glob, struct BufferData *buff, if( ctype <= MAX_FILE_DIRECTORY ) { lastname->re_Size = size; + lastname->re_SizeHi = 0; return( lastname ); } @@ -461,6 +502,7 @@ struct ReqEntry *REGARGS AddEntry (GlobData *glob, struct BufferData *buff, newentry->re_Name = str; newentry->re_Size = size; + newentry->re_SizeHi = 0; newentry->re_Type = ctype; newentry->re_Next = lastname->re_Next; lastname->re_Next = ( struct Node * ) newentry; @@ -785,9 +827,17 @@ AddDisk( if( deventry->task && DoPkt1( deventry->task, ACTION_DISK_INFO, (SIPTR)MKBADDR( infodata ) ) ) { - size = ( infodata->id_NumBlocksUsed * 100 + - infodata->id_NumBlocks / 2 ) / - infodata->id_NumBlocks; + ULONG used = infodata->id_NumBlocksUsed; + ULONG total = infodata->id_NumBlocks; + + /* scale down so that used * 100 fits 32 bits */ + while( total > 40000000 ) + { + used >>= 1; + total >>= 1; + } + + size = ( used * 100 + total / 2 ) / total; } } diff --git a/workbench/libs/reqtools/filereqmain.c b/workbench/libs/reqtools/filereqmain.c index e36c61f6981..b01da9627f5 100644 --- a/workbench/libs/reqtools/filereqmain.c +++ b/workbench/libs/reqtools/filereqmain.c @@ -96,6 +96,33 @@ ExpandLink( GlobData *glob ) /****************************************************************************************/ +/* The real size of the current fib file, size is the clamped 32 bit one */ +static UQUAD FileSize64( GlobData *glob, UQUAD size ) +{ + if( DOS64Base != NULL ) + { + struct FileInfoBlock *fib64 = AllocDosObject64( DOS64_FIB, NULL ); + + *glob->winaddr = ( APTR ) -1; + + if( fib64 ) + { + BPTR oldcd = CurrentDir( glob->lock ); + + if( ExamineName64( glob->fib.fib_FileName, fib64, NULL ) ) + size = fib64->fib_Size64; + CurrentDir( oldcd ); + FreeDosObject64( DOS64_FIB, fib64 ); + } + + *glob->winaddr = glob->reqwin; + } + + return( size ); +} + +/****************************************************************************************/ + IPTR ASM SAVEDS PropReqHandler ( REGPARAM(a1, struct RealHandlerInfo *, glob), REGPARAM(d0, ULONG, sigs), @@ -506,14 +533,15 @@ IPTR ASM SAVEDS PropReqHandler ( { if ((glob->exnext = ExNext (glob->lock, &glob->fib))) { - ULONG size = glob->fib.fib_Size; + UQUAD size = ( ULONG ) glob->fib.fib_Size; + struct ReqEntry *newentry; ctype = glob->fib.fib_EntryType; /* Try to examine links */ if( ( glob->fib.fib_EntryType == ST_SOFTLINK ) && ExpandLink( glob ) ) { - size = glob->linkfib.fib_Size; + size = ( ULONG ) glob->linkfib.fib_Size; ctype = glob->linkfib.fib_EntryType; } @@ -541,7 +569,13 @@ IPTR ASM SAVEDS PropReqHandler ( ctype = ( ctype > 0 ) ? glob->directory_id : glob->file_id; - if( !AddEntry( glob, buff, glob->fib.fib_FileName, size, ctype ) ) + /* a clamped size of a file: ask dos64.library for the real one */ + if( ctype == glob->file_id && size == 0xFFFFFFFF ) + size = FileSize64( glob, size ); + + if( ( newentry = AddEntry( glob, buff, glob->fib.fib_FileName, ( ULONG ) size, ctype ) ) ) + newentry->re_SizeHi = ( ULONG )( size >> 32 ); + else glob->exnext = FALSE; skipfile: diff --git a/workbench/libs/reqtools/globalvars.h b/workbench/libs/reqtools/globalvars.h index de56958b50d..06351005213 100644 --- a/workbench/libs/reqtools/globalvars.h +++ b/workbench/libs/reqtools/globalvars.h @@ -5,6 +5,7 @@ extern struct ReqToolsBase *ReqToolsBase; extern struct Device *ConsoleDevice; extern struct IOStdReq iorequest; extern Class *ButtonImgClass; +extern struct Library *DOS64Base; /* NULL when not installed */ /* On AROS don't define the libbases because that will prevent autoinit */ #if !defined(__RT_DEFINEVARS) || !defined(__AROS__) diff --git a/workbench/libs/reqtools/rtfuncs.c b/workbench/libs/reqtools/rtfuncs.c index 6598683d8db..c15c792b21e 100644 --- a/workbench/libs/reqtools/rtfuncs.c +++ b/workbench/libs/reqtools/rtfuncs.c @@ -205,6 +205,10 @@ SAVEDS ASM struct ReqToolsBase *RTFuncs_Open(REGPARAM(a6, struct ReqToolsBase *, if(LocaleBase == NULL) return NULL; + /* optional */ + if(DOS64Base == NULL) + DOS64Base = OpenLibrary("dos64.library", 51); + D(bug("reqtools.library: Inside libopen func. Libraries opened successfully.\n")); if (ConsoleDevice == NULL) @@ -308,6 +312,7 @@ SAVEDS ASM BPTR RTFuncs_Expunge(REGPARAM(a6, struct ReqToolsBase *, RTBase)) CloseLibrary((struct Library *)LocaleBase); CloseLibrary(GadToolsBase); CloseLibrary(LayersBase); + if (DOS64Base) CloseLibrary(DOS64Base); D(bug("reqtools.library: Inside libexpunge func. Freeing libbase.\n")); diff --git a/workbench/network/smbfs/source_code/main.c b/workbench/network/smbfs/source_code/main.c index cb7453f6d02..f882a75ebeb 100755 --- a/workbench/network/smbfs/source_code/main.c +++ b/workbench/network/smbfs/source_code/main.c @@ -4427,7 +4427,7 @@ Action_ExamineAll( case ED_OWNER: - ec.ec_MinSize = sizeof(struct ExAllData); + ec.ec_MinSize = offsetof(struct ExAllData,ed_Size64); break; } diff --git a/workbench/system/Wanderer/Classes/iconlist.c b/workbench/system/Wanderer/Classes/iconlist.c index b4a933c034f..451f2aec45e 100644 --- a/workbench/system/Wanderer/Classes/iconlist.c +++ b/workbench/system/Wanderer/Classes/iconlist.c @@ -58,6 +58,9 @@ #include #include #include +#include +#include +#include #include #if defined(__AROS__) @@ -110,6 +113,9 @@ extern struct Library *MUIMasterBase; +/* dos64.library, NULL when it is not installed */ +struct Library *DOS64Base; + static struct Hook __iconlist_UpdateLabels_hook; // N.B: We Handle frame/background rendering so make sure icon.library doesnt do it .. @@ -348,8 +354,48 @@ const UBYTE MSG_MEM_M[] = "MB"; const UBYTE MSG_MEM_K[] = "KB"; const UBYTE MSG_MEM_B[] = "Bytes"; +///IconList__FileSize64() +/* The size of a file whose 32 bit size was clamped */ +static UQUAD IconList__FileSize64(CONST_STRPTR name, UQUAD size) +{ + if (DOS64Base != NULL) + { + struct FileInfoBlock *fib64 = AllocDosObject64(DOS64_FIB, NULL); + + if (fib64 != NULL) + { + if (ExamineName64(name, fib64, NULL)) + size = fib64->fib_Size64; + FreeDosObject64(DOS64_FIB, fib64); + } + } + + return size; +} + +/* Open and close the optional dos64.library with the class */ +static int IconList__OpenDOS64(struct Library *lh) +{ + DOS64Base = OpenLibrary("dos64.library", 51); + return TRUE; +} + +static int IconList__CloseDOS64(struct Library *lh) +{ + if (DOS64Base != NULL) + { + CloseLibrary(DOS64Base); + DOS64Base = NULL; + } + return TRUE; +} + +ADD2INITLIB(IconList__OpenDOS64, 0) +ADD2EXPUNGELIB(IconList__CloseDOS64, 0) +/// + ///FmtSizeToString() -static void FmtSizeToString(UBYTE *buf, ULONG num) +static void FmtSizeToString(UBYTE *buf, UQUAD num) { UQUAD d; const UBYTE *ch; @@ -359,38 +405,38 @@ static void FmtSizeToString(UBYTE *buf, ULONG num) ULONG dec; } array = { - num, + (ULONG)num, 0 }; if (num >= 1073741824) { //Gigabytes - array.val = num >> 30; - d = ((UQUAD)num * 10 + 536870912) / 1073741824; - array.dec = d % 10; + array.val = (ULONG)(num >> 30); + d = (num * 10 + 536870912) / 1073741824; + array.dec = (ULONG)(d % 10); ch = MSG_MEM_G; } else if (num >= 1048576) { //Megabytes - array.val = num >> 20; - d = ((UQUAD)num * 10 + 524288) / 1048576; - array.dec = d % 10; + array.val = (ULONG)(num >> 20); + d = (num * 10 + 524288) / 1048576; + array.dec = (ULONG)(d % 10); ch = MSG_MEM_M; } else if (num >= 1024) { //Kilobytes - array.val = num >> 10; + array.val = (ULONG)(num >> 10); d = (num * 10 + 512) / 1024; - array.dec = d % 10; + array.dec = (ULONG)(d % 10); ch = MSG_MEM_K; } else { //Bytes - array.val = num; + array.val = (ULONG)num; array.dec = 0; d = 0; ch = MSG_MEM_B; @@ -4421,13 +4467,18 @@ IPTR IconList__MUIM_IconList_CreateEntry(struct IClass *CLASS, Object *obj, stru { CopyMem(message->fib, entry->ie_FileInfoBlock, sizeof(struct FileInfoBlock)); + entry->ie_FileSize64 = (ULONG)entry->ie_FileInfoBlock->fib_Size; + if (entry->ie_FileInfoBlock->fib_DirEntryType > 0) { strcpy(entry->ie_TxtBuf_SIZE, "Drawer"); } else { - FmtSizeToString(entry->ie_TxtBuf_SIZE, entry->ie_FileInfoBlock->fib_Size); + /* 0xFFFFFFFF is the clamp, ask dos64 for the real size */ + if (entry->ie_FileSize64 == 0xFFFFFFFF) + entry->ie_FileSize64 = IconList__FileSize64(message->filename, entry->ie_FileSize64); + FmtSizeToString(entry->ie_TxtBuf_SIZE, entry->ie_FileSize64); } dt.dat_Stamp = entry->ie_FileInfoBlock->fib_Date; @@ -7509,7 +7560,10 @@ IPTR IconList__MUIM_IconList_Sort(struct IClass *CLASS, Object *obj, struct MUIP else if (data->icld_SortFlags & MUIV_IconList_Sort_BySize) { /* Sort by Size .. */ - i = entry->ie_FileInfoBlock->fib_Size - icon1->ie_FileInfoBlock->fib_Size; + if (entry->ie_FileSize64 > icon1->ie_FileSize64) + i = 1; + else if (entry->ie_FileSize64 < icon1->ie_FileSize64) + i = -1; } else if ((data->icld_SortFlags & MUIV_IconList_Sort_ByType) && ((entry->ie_IconListEntry.type == ST_FILE) || (entry->ie_IconListEntry.type == ST_USERDIR))) { diff --git a/workbench/system/Wanderer/Classes/iconlist.h b/workbench/system/Wanderer/Classes/iconlist.h index 5da4059135e..9e7573c1135 100644 --- a/workbench/system/Wanderer/Classes/iconlist.h +++ b/workbench/system/Wanderer/Classes/iconlist.h @@ -106,6 +106,7 @@ struct IconEntry struct DiskObject *ie_DiskObj; /* The icons disk objects */ struct FileInfoBlock *ie_FileInfoBlock; + UQUAD ie_FileSize64; /* Full file size, FIB size is clamped to 32 bits */ LONG ie_IconX, /* Top Left Co-ords of Icons "AREA" */ ie_IconY, diff --git a/workbench/system/Wanderer/Tools/Info/main.c b/workbench/system/Wanderer/Tools/Info/main.c index 3fea56e4506..a83b85aeb8e 100644 --- a/workbench/system/Wanderer/Tools/Info/main.c +++ b/workbench/system/Wanderer/Tools/Info/main.c @@ -13,11 +13,13 @@ #include #include #include +#include #include #include #include #include +#include #include #include #include @@ -85,6 +87,47 @@ BOOL file_altered = FALSE; BOOL icon_altered = FALSE; char loadedcomment[MAXCOMMENTLENGTH]; +/* dos64.library, NULL when it is not installed */ +struct Library *DOS64Base; + +/* The size of a file whose 32 bit size was clamped */ +static UQUAD fileSize64(CONST_STRPTR name, UQUAD size) +{ + if (DOS64Base != NULL) + { + struct FileInfoBlock *fib = AllocDosObject64(DOS64_FIB, NULL); + + if (fib != NULL) + { + if (ExamineName64(name, fib, NULL)) + size = fib->fib_Size64; + FreeDosObject64(DOS64_FIB, fib); + } + } + + return size; +} + +/* The size of a directory entry, the real one when the 32 bit size was clamped */ +static UQUAD entrySize64(CONST_STRPTR directory, CONST_STRPTR name, UQUAD size) +{ + if ((size == 0xFFFFFFFF) && (DOS64Base != NULL)) + { + ULONG pathlen = strlen(directory) + strlen(name) + 2; + STRPTR path = AllocVec(pathlen, MEMF_CLEAR); + + if (path != NULL) + { + strcpy(path, directory); + AddPart(path, name, pathlen); + size = fileSize64(path, size); + FreeVec(path); + } + } + + return size; +} + void getReadableSize(UBYTE *buf, UQUAD size, BOOL accurate) { UQUAD d; @@ -99,31 +142,23 @@ void getReadableSize(UBYTE *buf, UQUAD size, BOOL accurate) 0 }; - /*if (size >= (1024 * 1024 * 1024 * 1024 * 1024 * 1024)) - { - //Exabytes - array.val = size >> 60; - d = (size * 10 + ((1024 * 1024 * 1024 * 1024 * 1024 * 1024) / 2)) / (1024 * 1024 * 1024 * 1024 * 1024 * 1024); - array.dec = d % 10; - ch = "EiB"; - } - else if (size >= (1024 * 1024 * 1024 * 1024 * 1024)) + if (size >= ((UQUAD)1 << 50)) { //Petabytes array.val = size >> 50; - d = (size * 10 + ((1024 * 1024 * 1024 * 1024 * 1024) / 2)) / (1024 * 1024 * 1024 * 1024 * 1024); + d = (size * 10 + (((UQUAD)1 << 50) / 2)) / ((UQUAD)1 << 50); array.dec = d % 10; ch = "PiB"; } - else if (size >= (1024 * 1024 * 1024 * 1024)) + else if (size >= ((UQUAD)1 << 40)) { //Terabytes array.val = size >> 40; - d = (size * 10 + ((1024 * 1024 * 1024 * 1024) / 2)) / (1024 * 1024 * 1024 * 1024); + d = (size * 10 + (((UQUAD)1 << 40) / 2)) / ((UQUAD)1 << 40); array.dec = d % 10; ch = "TiB"; - }*/ - if (size >= (1024 * 1024 * 1024)) + } + else if (size >= (1024 * 1024 * 1024)) { //Gigabytes array.val = size >> 30; @@ -215,7 +250,7 @@ D(bug("[WBInfo] calculateDirectorySize('%s')\n", directory)); { if (ead->ed_Type == ST_FILE) { - directorySize += ead->ed_Size; + directorySize += entrySize64(directory, (CONST_STRPTR)ead->ed_Name, ead->ed_Size); /* Refresh size only every 25% grow */ if ((((base + directorySize) * 100) / (*lastrefreshsize)) > 125) /* 25 % */ { @@ -720,6 +755,7 @@ int main(int argc, char **argv) char stack[16]; char deftool[MAX_PATH_LEN]; char size[64]; + UQUAD fsize; char date[LEN_DATSTRING]; char time[LEN_DATSTRING]; char dow[LEN_DATSTRING]; @@ -743,7 +779,9 @@ int main(int argc, char **argv) char pathname[1024]; int retval = RETURN_OK; - + + DOS64Base = OpenLibrary("dos64.library", 51); + if (argc != 0) { /* start from wanderer only */ @@ -844,7 +882,10 @@ D(bug("[WBInfo] scan file\n")); sprintf(datetime, "%s %s", time, date); /* fill size */ - getReadableSize(size, ap->ap_Info.fib_Size, TRUE); + fsize = (ULONG)ap->ap_Info.fib_Size; + if (fsize == 0xFFFFFFFF) + fsize = fileSize64(name, fsize); + getReadableSize(size, fsize, TRUE); /* fill protection */ protection = ap->ap_Info.fib_Protection; @@ -1453,5 +1494,7 @@ D(bug("[WBInfo: Couldn't create app\n")); FreeVec(ap); FreeVec(file); FreeVec(name); + if (DOS64Base != NULL) + CloseLibrary(DOS64Base); return retval; } diff --git a/workbench/system/Wanderer/filesystems.c b/workbench/system/Wanderer/filesystems.c index b161b2bfbe5..f106e9eecfb 100644 --- a/workbench/system/Wanderer/filesystems.c +++ b/workbench/system/Wanderer/filesystems.c @@ -402,6 +402,28 @@ static BOOL deleteFile(char *file) } /// +///fileSize64() +/* The size of a file, the real one when the 32 bit size was clamped */ +static UQUAD fileSize64(CONST_STRPTR name, ULONG size) +{ + UQUAD full = size; + + if ((size == 0xFFFFFFFF) && (DOS64Base != NULL)) + { + struct FileInfoBlock *fib64 = AllocDosObject64(DOS64_FIB, NULL); + + if (fib64 != NULL) + { + if (ExamineName64(name, fib64, NULL)) + full = fib64->fib_Size64; + FreeDosObject64(DOS64_FIB, fib64); + } + } + + return full; +} +/// + ///copyFile() static BOOL copyFile(APTR pool, char *file, char *destpath, struct FileInfoBlock *fileinfo, struct Hook *displayHook, @@ -411,7 +433,7 @@ static BOOL copyFile(APTR pool, char *file, char *destpath, char *to; LONG clen, wlen; LONG bufferlen = COPYLEN; - LONG filelen = 0; + UQUAD filelen = 0; BOOL quit = TRUE; BPTR in, out; BYTE *buffer; @@ -421,8 +443,8 @@ static BOOL copyFile(APTR pool, char *file, char *destpath, if (display != NULL) display->actlen = 0; if (fileinfo) { - filelen = fileinfo->fib_Size; - if (fileinfo->fib_Size <= COPYLEN) bufferlen = fileinfo->fib_Size; + filelen = fileSize64(file, (ULONG) fileinfo->fib_Size); + if (filelen <= COPYLEN) bufferlen = (LONG) filelen; if (bufferlen < 8192) bufferlen = 8192; fib = fileinfo; } @@ -440,8 +462,8 @@ static BOOL copyFile(APTR pool, char *file, char *destpath, return TRUE; } UnLock(nLock); - filelen = fib->fib_Size; - if (fib->fib_Size <= COPYLEN) bufferlen = fib->fib_Size; + filelen = fileSize64(file, (ULONG) fib->fib_Size); + if (filelen <= COPYLEN) bufferlen = (LONG) filelen; if (bufferlen < 8192) bufferlen = 8192; } } @@ -643,7 +665,7 @@ static BOOL actionDir(APTR pool, ULONG flags, char *source, char *dest, askDisplay.spath = FIB->fib_FileName; askDisplay.file = NULL; askDisplay.type = 0; - askDisplay.filelen = FIB->fib_Size; + askDisplay.filelen = (ULONG) FIB->fib_Size; if (dmode != OPMODE_ALL) dmode = CallHook(opModes->askhook, (Object *) &askDisplay, NULL); if ((dmode == OPMODE_ALL) || (dmode == OPMODE_YES)) { @@ -709,7 +731,7 @@ static BOOL actionDir(APTR pool, ULONG flags, char *source, char *dest, if (dHook) { display.file = FIB->fib_FileName; - display.filelen = FIB->fib_Size; + display.filelen = fileSize64(FIB->fib_FileName, (ULONG) FIB->fib_Size); display.spath = source; display.dpath = dest; display.flags = (flags &= ~ACTION_UPDATE); @@ -788,7 +810,7 @@ static BOOL actionDir(APTR pool, ULONG flags, char *source, char *dest, askDisplay.spath = source; askDisplay.file = FIB->fib_FileName; askDisplay.type = 0; - askDisplay.filelen = FIB->fib_Size; + askDisplay.filelen = (ULONG) FIB->fib_Size; if (dmode != OPMODE_ALL) dmode = CallHook(opModes->askhook, (Object *) &askDisplay, NULL); if ((dmode == OPMODE_ALL) || (dmode == OPMODE_YES)) { diff --git a/workbench/system/Wanderer/filesystems.h b/workbench/system/Wanderer/filesystems.h index f221636c590..a18695ed5f7 100644 --- a/workbench/system/Wanderer/filesystems.h +++ b/workbench/system/Wanderer/filesystems.h @@ -26,6 +26,8 @@ #include #include #include +#include +#include #if defined(__AMIGA__) && !defined(__PPC__) #define NO_INLINE_STDARG #endif @@ -74,9 +76,9 @@ struct dCopyStruct char *file; APTR userdata; ULONG flags; - ULONG filelen; + UQUAD filelen; ULONG actlen; - ULONG totallen; + UQUAD totallen; UWORD type; unsigned int difftime; }; diff --git a/workbench/system/Wanderer/main.c b/workbench/system/Wanderer/main.c index 8cd8dd27a4a..7b62008f687 100644 --- a/workbench/system/Wanderer/main.c +++ b/workbench/system/Wanderer/main.c @@ -88,6 +88,9 @@ struct CyberGfxIFace *ICyberGfx; Object *_WandererIntern_AppObj = NULL; Class *_WandererIntern_CLASS = NULL; +/* dos64.library, NULL when it is not installed */ +struct Library *DOS64Base = NULL; + /* Don't output errors to the console, open requesters instead */ int __forceerrorrequester = 1; @@ -412,6 +415,8 @@ int main(void) return retval; #endif + DOS64Base = OpenLibrary("dos64.library", 51); + D( struct Task *me = (struct Task *)FindTask(NULL); @@ -435,6 +440,9 @@ int main(void) D(bug("[Wanderer] %s: Exiting .. \n", __PRETTY_FUNCTION__)); + if (DOS64Base != NULL) + CloseLibrary(DOS64Base); + #ifndef __AROS__ deInitLibs(); #endif diff --git a/workbench/system/Wanderer/panel_statusbar.c b/workbench/system/Wanderer/panel_statusbar.c index 97e4052245f..fc799aebb84 100644 --- a/workbench/system/Wanderer/panel_statusbar.c +++ b/workbench/system/Wanderer/panel_statusbar.c @@ -103,7 +103,7 @@ const UBYTE MSG_MEM_K[] = "KB"; const UBYTE MSG_MEM_B[] = "Bytes"; ///FmtSizeToString() -static void FmtSizeToString(UBYTE *buf, ULONG num) +static void FmtSizeToString(UBYTE *buf, UQUAD num) { UQUAD d; const UBYTE *ch; @@ -113,38 +113,38 @@ static void FmtSizeToString(UBYTE *buf, ULONG num) ULONG dec; } array = { - num, + (ULONG)num, 0 }; if (num >= 1073741824) { //Gigabytes - array.val = num >> 30; - d = ((UQUAD)num * 10 + 536870912) / 1073741824; - array.dec = d % 10; + array.val = (ULONG)(num >> 30); + d = (num * 10 + 536870912) / 1073741824; + array.dec = (ULONG)(d % 10); ch = MSG_MEM_G; } else if (num >= 1048576) { //Megabytes - array.val = num >> 20; - d = ((UQUAD)num * 10 + 524288) / 1048576; - array.dec = d % 10; + array.val = (ULONG)(num >> 20); + d = (num * 10 + 524288) / 1048576; + array.dec = (ULONG)(d % 10); ch = MSG_MEM_M; } else if (num >= 1024) { //Kilobytes - array.val = num >> 10; + array.val = (ULONG)(num >> 10); d = (num * 10 + 512) / 1024; - array.dec = d % 10; + array.dec = (ULONG)(d % 10); ch = MSG_MEM_K; } else { //Bytes - array.val = num; + array.val = (ULONG)num; array.dec = 0; d = 0; ch = MSG_MEM_B; @@ -204,7 +204,7 @@ HOOKPROTO(panelStatusBar__HookFunc_UpdateStatusFunc, void, APTR *obj, APTR param UBYTE size_str[256]; int files = 0, dirs = 0, hidden = 0; - ULONG size = 0; + UQUAD size = 0; GET(data->iwd_IconListObj, MUIA_Family_List, &iconList); if (iconList) @@ -222,7 +222,7 @@ HOOKPROTO(panelStatusBar__HookFunc_UpdateStatusFunc, void, APTR *obj, APTR param files += 1; if (icon->ie_FileInfoBlock) { - size += icon->ie_FileInfoBlock->fib_Size; + size += icon->ie_FileSize64; D(bug("[IW.statusbar] %s: '%s' FIB Size = %d bytes\n", __PRETTY_FUNCTION__, icon->ie_IconNode.ln_Name, icon->ie_FileInfoBlock->fib_Size)); } } diff --git a/workbench/system/find/findgroup_class.c b/workbench/system/find/findgroup_class.c index 8e50684d91d..1d10241ca0d 100644 --- a/workbench/system/find/findgroup_class.c +++ b/workbench/system/find/findgroup_class.c @@ -4,6 +4,7 @@ */ #include +#include #include #include #include @@ -19,6 +20,8 @@ #include #include +#include + #include #include "findgroup_class.h" @@ -46,6 +49,7 @@ struct Listentry STRPTR fullname; ULONG namebuflen; struct FileInfoBlock fib; + UQUAD size; }; static struct Hook list_display_hook, list_constr_hook, list_destr_hook, list_compare_hook; @@ -53,6 +57,40 @@ static struct Hook list_display_hook, list_constr_hook, list_destr_hook, list_co // ======================================================================================= +// Decimal string of a UQUAD, end-aligned in the buffer +static TEXT *UQUAD2string(UQUAD value, TEXT *buffer, int buflen) +{ + buffer[--buflen] = '\0'; + + do + { + buffer[--buflen] = '0' + (value % 10); + value /= 10; + } while (value); + + return buffer + buflen; +} + +// The size of a file; a clamped 32 bit size is asked again from dos64 +static UQUAD file_size(CONST_STRPTR name, struct FileInfoBlock *fib) +{ + UQUAD size = (ULONG)fib->fib_Size; + + if (size == 0xFFFFFFFF && DOS64Base != NULL) + { + struct FileInfoBlock *fib64 = AllocDosObject64(DOS64_FIB, NULL); + + if (fib64 != NULL) + { + if (ExamineName64(name, fib64, NULL)) + size = fib64->fib_Size64; + FreeDosObject64(DOS64_FIB, fib64); + } + } + + return size; +} + static void display_doserror(Object *app, ULONG error) { TEXT buffer[255]; @@ -170,6 +208,7 @@ AROS_UFH3(APTR, list_constr_func, CopyMem(li->fullname, newentry->fullname, buflen); } newentry->fib = li->fib; + newentry->size = li->size; } return newentry; @@ -202,9 +241,10 @@ AROS_UFH3S(LONG, list_display_func, if (li) { - static TEXT protbuf[8], sizebuf[20]; + static TEXT protbuf[8], sizebuf[24]; static TEXT datebuf[20], timebuf[20]; struct DateTime dt; + TEXT *sizestr; // Protection bits protbuf[0] = li->fib.fib_Protection & FIBF_SCRIPT ? 's' : '-'; @@ -219,7 +259,7 @@ AROS_UFH3S(LONG, list_display_func, protbuf[7] = '\0'; // Size - snprintf(sizebuf, sizeof sizebuf, "%lu", (long unsigned int)li->fib.fib_Size); + sizestr = UQUAD2string(li->size, sizebuf, sizeof sizebuf); // Date datebuf[0] = '\0'; @@ -233,7 +273,7 @@ AROS_UFH3S(LONG, list_display_func, DateToStr(&dt); *array++ = li->fullname; - *array++ = sizebuf; + *array++ = sizestr; *array++ = protbuf; *array++ = datebuf; *array++ = timebuf; @@ -723,6 +763,7 @@ IPTR FindGroup__MUIM_Process_Process(Class *CLASS, Object *self, struct MUIP_Pro { entry->fullname = StrDup(anchorpath->ap_Buf); CopyMem(&anchorpath->ap_Info, &entry->fib, sizeof (entry->fib)); + entry->size = file_size(anchorpath->ap_Buf, &entry->fib); // we must use PushMethod because we are in a sub process methodid2 = DoMethod(_app(self), MUIM_Application_PushMethod, diff --git a/workbench/system/find/main.c b/workbench/system/find/main.c index 22da5b85f63..2d3d1d122fc 100644 --- a/workbench/system/find/main.c +++ b/workbench/system/find/main.c @@ -9,6 +9,7 @@ #include #include #include +#include #include #include @@ -37,12 +38,17 @@ static struct DiskObject *dobj; static struct RDArgs *rda; static IPTR args[ARG_COUNT]; +// dos64.library, NULL when it is not installed +struct Library *DOS64Base; + int main(int argc, char **argv) { STRPTR path = NULL; STRPTR pattern = NULL; STRPTR contents = NULL; + DOS64Base = OpenLibrary("dos64.library", 51); + dobj = GetDiskObject("PROGDIR:Find"); if (argc) // started from CLI @@ -115,5 +121,6 @@ static void cleanup_exit(CONST_STRPTR str) if (dobj) FreeDiskObject(dobj); if (rda) FreeArgs(rda); + if (DOS64Base) CloseLibrary(DOS64Base); exit(0); }