home *** CD-ROM | disk | FTP | other *** search
/ CP/M / CPM_CDROM.iso / jsage / znode3 / tcj / tcj35bmm.ws < prev    next >
Encoding:
Text File  |  1994-09-02  |  37.6 KB  |  917 lines

  1. TCJ #35
  2. _words in italics_
  3. .h1  main headings
  4. .h2  secondary headings
  5.  
  6.  
  7.                 Advanced CP/M
  8.  
  9.             ZSDOS and File Systems
  10.  
  11.                Bridger Mitchell
  12. {usual sidebar on Bridger}
  13.  
  14. .h1 DAWN OF A NEW DOS
  15.  
  16. Think of it as CP/M 4.0 -- an all-new, feature-packed,
  17. high-performance BDOS replacement for all Z80 computers running CP/M
  18. 2.2, ZRDOS, or other compatible dos's.
  19.  
  20. ZSDOS is its final name -- the cooperative product of Hal Bower, Cam
  21. Cotrill, and Carson Wilson that fuses their initially separate
  22. efforts.  The result is explosive: improved disk function performance,
  23. file datestamping with no reduction in program memory, files
  24. automatically accessible from other directories, and elimination of
  25. some notorious CP/M bugs.  Benefitting from Ten Brugge's P2DOS and
  26. Carson's first forays into Z80DOS, the finely-tuned final product is
  27. fully compatible with BackGrounder ii, NZ-COM and ZCPR34.  And the
  28. authors' thorough, extensive testing means highest quality; we are
  29. unlikely to ever see a ZSDOS 2.2, or 1.9!
  30.  
  31. ZSDOS is, foremost, an up-to-date DOS.  It fully supports the
  32. established DateStamper standard, and comes with preassembled
  33. relocatable clock routines from the Plu*Perfect Systems library to
  34. read virtually all of the popular (and many obscure) clocks.  And it
  35. breaks new ground, adding BDOS functions to get and set file
  36. datestamps as well as to get and set the system realtime clock.  In
  37. addition to Plu*Perfect's PUTDS, SDD, and DATSWEEP utilities, it is
  38. shipped with some nifty new tools that display files sorted by date
  39. and that automatically copy datestamps.  Best of all, perhaps, is that
  40. the "trim" version of ZSDOS includes datestamping within the BDOS with
  41. no loss of TPA memory (except possibly for BIOS space to hold a clock
  42. routine)!
  43.  
  44. The "full-up" ZSDOS version adds internal path-searching to the BDOS,
  45. enabling _programs_ to do what until now only the ZCPR command processor has
  46. been able to achieve when loading a command -- scan a path of
  47. directories to locate a needed file.  To do this, it places the
  48. datestamping code in a separate small, relocatable module somewhere --
  49. in or above the user's BIOS, in NZCOM's user buffer area, or in a
  50. resident system extension.
  51.  
  52. Both versions of ZSDOS provide English-language error messages
  53. complete with the name of the associated file, if one.  Error
  54. reporting is configurable, so that a program can field any error
  55. itself, if it chooses.  Other significant features include
  56. noticeably faster warmboots and disk resets on hard-disk machines.
  57.  
  58. The development team has made upgrading an existing CP/M or ZRDOS
  59. system a snap -- menu-driven installation and configuration utilities
  60. do all the work.  And the documentation is top-notch.
  61.  
  62. I'm enthusiastic!  ZSDOS boosts CP/M 2.2 computing to a new level of
  63. performance, increases reliability, and makes datestamping available
  64. to every Z80 computer.  If you are a CP/M 2.2 or ZRDOS user, you will
  65. benefit most by upgrading to ZSDOS without delay.  It's
  66. available from Plu*Perfect Systems.
  67.  
  68. .h1 BackGrounder ii Update
  69.  
  70. BackGrounder ii, as many readers of Jay Sage's column know, is a
  71. task-switching operating system system extension of CP/M 2.2, ZSDOS,
  72. and ZRDOS.  Simply put, it allows you to switch back and forth between
  73. virtually any two applications programs, literally in mid-sentence!
  74. One reviewer described it as windows for CP/M, other users refer to it
  75. a super-Sidekick (it provides a calculator, notepad, screendump and
  76. background printing).
  77.  
  78. As TCJ rolls off the press I expect to have BackGrounder ii updated to
  79. full compatibility with ZCPR version 3.4.  This will become the
  80. standard version, and currently licensed users can order
  81. an update from Plu*Perfect Systems.
  82.  
  83.  
  84.  
  85.  
  86. .h1 FILE SYSTEMS
  87.  
  88. The main topic for this issue's Advanced CP/M column is file systems.
  89. Operating systems separate the organization and maintenance of a _file
  90. system_ from the storage and retrieval of data on physical media.
  91. Files are most often stored on magnetic disks, and the portion of the
  92. CP/M operating system responsible for the file system is indeed called
  93. the basic _disk_ operating system (BDOS).
  94.  
  95. In contrast, the lower-level tasks of actually writing data to, and
  96. reading them from, the physical disk is delegated to a _disk driver_,
  97. code that is part of the BIOS -- the basic input/output system that
  98. must know the particulars of the specific hardware of the host
  99. computer.
  100.  
  101. The separation of file system functions and hardware-specific
  102. functions is fundamental to the design of any major operating system,
  103. and it has far-reaching implications.
  104.  
  105. First, it makes it possible to use the same programs on different
  106. computers, with different physical disk drives, provided that they run
  107. the same operating system.
  108.  
  109. Second, by keeping the logical organization of a "disk" and its
  110. physical realization in separate layers of the operating system, we
  111. can use a wide variety of storage media with the same file system.  A
  112. ram "disk", after all, doesn't spin at 300 rpm, and a cassette tape or
  113. local area network is hardly a conventional disk, either.  Yet, to a
  114. program and the BDOS, a file is a file is a file.
  115.  
  116. Third, with some extensions of the operating system, it is possible to
  117. mount a _different_ file system on the same computer.  For example,
  118. some FORTH operating systems run on top of CP/M and provide access to
  119. both FORTH file screens and CP/M files.  In a different way, DosDisk
  120. provides direct, transparent program access to MSDOS files in a CP/M
  121. environment.
  122.  
  123.  
  124. .h1 FORMAT PROLIFERATION
  125.  
  126. The earliest CP/M computers had only a single format, the single-sided
  127. single-density 8" IBM "standard", and no provision for anything else.
  128. Then, as a few higher-performance and higher-capacity formats were
  129. introduced, they were hard-coded into the BIOS.  Each new format
  130. required re-coding and reassembly of a new system.
  131.  
  132. Today, CP/M suffers from a surfeit of physical floppy disk formats.
  133. It seems that every manufacturer felt impelled to put his own label on
  134. yet another non-compatible format, to the point where we have well
  135. over 100 different ways of storing the same file on one 5 1/4" disk!
  136. This has also created something of an identity crisis, because it is
  137. not always possible to unambiguously determine a disk's format by
  138. magnetically reading the data on it.
  139.  
  140. The most modern BIOSes rise above this morass with flexibility and a
  141. degree of intelligence.  They are able to identify a set of "native"
  142. formats, and automatically adapt themselves to the disk in each drive.
  143. In addition, they allow an external utility to set a drive to a
  144. "foreign" format, one that the BIOS cannot identify from its built-in
  145. data, but is known to the utility.
  146.  
  147. One such BIOS is the Advent TurboRom, written by Plu*Perfect Systems
  148. for the family of Kaypro computers.  It automatically identifies 11
  149. formats (Kaypro, Advent, Osborne, Ampro, Xerox, etc.).  A companion
  150. program, MULTICPY (sold separately), allow TurboRom-equipped Kaypros
  151. to format disks in foreign formats, and to make exact copies of entire
  152. disks in those formats.  And the TURBOSET utility allow the user to
  153. specify some 90 foreign formats, making nearly every 5 1/4" MFM-coded
  154. soft-sector format disk directly usable on a Kaypro computer.
  155.  
  156. MULTICPY and TURBOSET use a database (in dBase II format) of physical
  157. and logical disk formats.  Because the database is extensible, new
  158. formats can be added.  At Plu*Perfect Systems we use MULTICPY to
  159. produce distribution disks in many popular formats.  If you have
  160. an unusual one, and can supply the physical and logical disk
  161. parameters and a sample disk, we can probably add it.
  162.  
  163. If your BIOS isn't this up-to-date, it is possible to temporarily
  164. replace its disk driver functions with a special application program
  165. long enough to copy files to or from a foreign format disk.  Such a
  166. program must be written for your specific computer's hardware.  Two
  167. popular utilities of this sort are UniForm (MicroSolutions) and Media
  168. Master (Intersecting Concepts).
  169.  
  170. You will find a cross-format tool is essential if you need to exchange
  171. data on a format not supported by your computer.  The TURBOSET
  172. approach is the most flexible.  It lets you use the foreign format
  173. disk with any regular CP/M program, just like your native-format
  174. disks.  With the other tools you load the format-conversion utility,
  175. copy the needed file(s) to or from your native-format disk, remove the
  176. utility, and then run your regular programs.
  177.  
  178. There are a host of challenges that confront the programmer who seeks
  179. to upgrade his or her BIOS to this modern level of performance, and
  180. perhaps we can explore them in another column.  In the remainder of
  181. this issue, however, we will have our hands full covering the file
  182. system and its implementation in the CP/M BDOS.
  183.  
  184.  
  185. .h1 FILE STRUCTURE
  186.  
  187. Every file structure has two key properties -- a method of naming
  188. files, and a method of allocating space for storing data.
  189.  
  190. Each file has a unique name within the filename space on the disk.
  191. (In CP/M, the filename space is a user number; in MSDOS and UNIX it is
  192. a subdirectory).  With the name are usually a set of file attributes
  193. that may control permissions on access to the file, and perhaps
  194. datestamps as well.
  195.  
  196. Storage of data for the file is allocated in blocks -- chunks of 128
  197. or more bytes of data.  With each filename the file system associates
  198. an ordered list of blocks, and a total length of the file.
  199.  
  200. The file system must maintain this information in an orderly fashion
  201. for each file on the disk.  To do so, it uses a _directory_ of
  202. filenames, a _free list_ of unused data blocks, and an _allocated
  203. list_ of blocks in use by the files.
  204.  
  205. The directory contains (at least) one entry for each filename.  The
  206. entry will usually include permissions or attributes that control
  207. access to the file itself, and perhaps the datestamps for the file.
  208. And it will include some type of link to the file's data blocks.
  209.  
  210. The free list is some type of data structure that indicates which data
  211. blocks on the disk are not in use and can be allocated for writing
  212. data.  On a fresh disk it will include all blocks of the disk not
  213. reserved for the directory, the boot code, or other operating system
  214. purposes.  As a file is written, blocks are transferred from the free
  215. list to the allocated list and assigned to the file.
  216.  
  217. .h2 The Allocated List
  218.  
  219. I haven't said anything yet about how the directory and allocated
  220. list are actually stored.  Those are key choices made by the
  221. designer of the operating system, and it's instructive to
  222. see how they can differ.
  223.  
  224. In MSDOS, the list of blocks is encoded in a file allocation table
  225. (FAT).  The FAT has an entry for each data block (called a cluster in
  226. MSDOS) on the disk.  An entry indicates that the block is unallocated
  227. (and is thus part of the free list), is allocated to a file, or
  228. is otherwise reserved.
  229.  
  230. The FAT is encoded in a way that allows it to serve two functions --
  231. it records the allocated and free blocks, and it shows which blocks are
  232. associated with which files.  Blocks that are allocated to one file
  233. form a _linked list_.  Each entry in the FAT is a pointer to the next
  234. block in that file's list, and the last entry is a special end-of-list
  235. mark.
  236.  
  237. The MSDOS directory entry includes only a pointer to the _first_ block
  238. of the file.  The rest of the blocks are obtained by following the
  239. linked list in the FAT.  The FAT itself is stored on the disk, and the
  240. MSDOS system keeps a copy of it in working system memory.  Thus,
  241. there are two separate data structures on an MSDOS disk -- the FAT
  242. (which is actually stored in duplicate) and the directory.
  243.  
  244. CP/M takes a different approach -- it includes the storage information
  245. as well as the filename information in the directory entry.  Each
  246. directory entry contains a set of data block numbers and there is no file
  247. allocation table.  To obtain the data blocks for a CP/M file, the
  248. system finds the first directory entry and reads off the block
  249. numbers.
  250.  
  251. Where is CP/M's free list?  It is implicit in the directory.  When a
  252. disk is logged in, the CP/M BDOS reads through the directory of a disk
  253. and keeps track of each data block that is allocated to a file.  It
  254. encodes this information in an _allocation bitmap_ for the disk,
  255. setting one bit for each block that is in use.  The bits that are not
  256. set then represent the free blocks.
  257.  
  258. The UNIX system uses aspects of each approach.  Each UNIX directory
  259. entry includes the filename and an _i-node_ number; this is much like
  260. MS-DOS.  An i-node is a list of the first 10 (512-byte) data blocks of
  261. a file, plus links to indirect lists of additional blocks.  Directly
  262. including the list of the first 10 blocks in the i-node (a bit like
  263. including the block numbers in the first CP/M directory entry) allows
  264. UNIX to rapidly retrieve smaller files and yet use linked lists to
  265. extend files to very large sizes.
  266.  
  267. .h2 How Much Space Left?
  268.  
  269. One perennial disaster with many early CP/M programs, famous and
  270. obscure alike, was writing a file to an almost-full disk, running out
  271. of space during the operation, and having the program quit with the
  272. precious data lost forever.  Of course, a well-written program
  273. wouldn't quit when a BDOS error occurs; it would clean up its
  274. incomplete file, allow the user to change disks, reset the disk
  275. system, and re-write the file.
  276.  
  277. But a really well-crafted program wouldn't even attempt to write to
  278. the almost-full disk.  Instead, before writing, it would determine
  279. whether there is enough space left on the disk to hold the file.
  280.  
  281. To do this, the program must obtain the total number of free blocks.
  282. This is a natural function for the disk operating system to perform,
  283. and in CP/M Plus there is a system call for this purpose (46).  But it
  284. wouldn't fit into the space on the system tracks of the original 8"
  285. CP/M 2.2 systems, and so the BDOS includes another system call (27) to
  286. return the address of the drive's bitmap, and programs must count up
  287. the free blocks themselves.
  288.  
  289. Figure 1 show the Z80 routine, get_freek, that returns the number of
  290. unallocated kilobytes of space on the currently logged drive.  It is
  291. portable -- it works under CP/M 2.2, CP/M Plus and even for an MS-DOS
  292. disk when running DosDisk.  The code includes contributions from Jay
  293. Sage, Joe Wright, and others, and is used, in a slightly varied form,
  294. in the SP (space) command in Z3PLUS and NZ-COM.
  295.  
  296. The routine first determines which version of CP/M is running.
  297. If the system is CP/M Plus, the BDOS will do all of the work.  In
  298. fact, it's necessary to let it do the work, because in most CP/M Plus
  299. systems the allocation bitmap will be stored in a different memory bank
  300. and therefore not readily accessible to the program.  (If the routine
  301. did attempt to use the bitmap address, it would add up bits of
  302. whatever program or data happen to be in that part of the main memory,
  303. resulting in an incorrect value).
  304.  
  305. CP/M Plus function 46 returns the space remaining on the disk as a
  306. 24-bit number in the first three bytes of the dma, in units of
  307. 128-byte records.  So, to use this function, get_freek first sets the
  308. dma address to the temporary buffer at 80h and calls function 46.  The
  309. divide-by-8 code then converts this to kilobyte units.
  310.  
  311. If the routine is running under CP/M 2.2, it first calls function 31
  312. to get several disk parameters for the logged-in drive -- the
  313. block-shift factor, the extent mask, and the maximum number of blocks
  314. on the drive.  Next, it calls function 27 to get the address of the
  315. bitmap (allocation vector).  The code at label "cntfree" then counts the
  316. number of unset bits in the bitmap, accumulating the count in register
  317. DE.
  318.  
  319. Since each block represents some multiple of 1K (1024 = 2**10 bytes),
  320. the code at label "free2k" multiplies the free block count by the size
  321. of one data block.  The block shift factor is the base-2 logarithm of
  322. the number of 128-byte records per data block.  In other words, it is
  323. the exponent in this equation:
  324.  
  325.     block size in records = 2 ** block-shift-factor
  326.  
  327. If the block size is 1K (8 records), the block shift factor is 3
  328. (i.e., 8 = 2**3), and the number of free blocks is already in 1K
  329. units.  Otherwise, we multiply by the number of K in one block; this
  330. calculation is simply a 16-bit left shift that results from doubling
  331. HL (blkshf-3) times.
  332.  
  333.  
  334. .h1 A CLOSER LOOK AT THE CP/M FILE STRUCTURE
  335.  
  336. One CP/M directory entry contains the following components:
  337.  
  338.     user number - a logical partition of the volume (disk)
  339.     file name
  340.     file attributes
  341.     directory entry number
  342.     size of (the portion of) file indexed by this entry
  343.     the data block numbers for this entry
  344.  
  345. A single directory entry can hold either 16 8-bit data block numbers,
  346. or 8 16-bit directory numbers.  A CP/M data block can be 1K, 2K, 4K,
  347. or 16K bytes (the blocking factor is part of the disk format
  348. specification), and the large blocks require 16-bit numbers.  So a
  349. single directory entry may refer to a maximum of from 16*1K to 8*16K =
  350. 128K bytes of data, depending on the blocking factor for the disk.
  351.  
  352. Clearly, a file might be larger than the number of bytes that can be
  353. recorded in a single directory entry.  To handle this case, CP/M
  354. creates _additional_ directory entries to hold additional data block
  355. numbers.  These entries have the same filename, user number and
  356. attributes as the initial entry, but they have unique directory entry
  357. numbers.  (Contrast this with MS-DOS, which has just one directory
  358. entry, but a longer linked list of FAT clusters for a large file.)
  359.  
  360. .h2 Reading a file.
  361.  
  362. The actual numbering of CP/M directory entries is somewhat torturous, and
  363. so we will discuss it later.  First, let's get a grip on the details.
  364. Assume we already have a large file and consider first what
  365. the operating system does when an application program is reading the file.
  366.  
  367. First, the program calls the BDOS to open the file named in the
  368. indicated file control block (fcb).  The CP/M BDOS searches for the
  369. initial directory entry, finds it, and stores the entry data,
  370. including the data block numbers, in the user's fcb.
  371.  
  372. Next, the program repeatedly calls the BDOS to read the file
  373. sequentially from the beginning.  The (CP/M 2.2) BDOS gets the first
  374. data block number from the fcb, converts that value to track and
  375. sector numbers, and calls the BIOS to read one 128-byte record.  Next,
  376. it increments the sector number (adjusting for reaching the end of a
  377. track) and calls the BIOS again, repeating for the number of records
  378. in a data block (8 in a 1K block, etc.).  It then gets the second data
  379. block number from the fcb, converts to track/sector, and reads another
  380. set of records.
  381.  
  382. Eventually (after processing 8 or 16 blocks) all of the first
  383. directory entry's data blocks have been used, and the BDOS must search
  384. for and read in the next directory entry.  (At this point, on a
  385. physical disk the movement of the disk heads back to the directory
  386. track can often be heard; this extra motion significantly slows down
  387. access to large CP/M files.)  The BDOS then repeats the process of
  388. computing track/sector numbers and calling the BIOS to read records.
  389.  
  390.  
  391. .h2 Writing a file.
  392.  
  393. Writing a file involves reversing these steps, with a few key
  394. additions, because disk space must be allocated.  Let's assume
  395. our program is writing a new file.
  396.  
  397. First, the program calls the BDOS to create the file
  398. with the name stored in the fcb.  The BDOS searches the directory
  399. for an empty (unused) directory entry.  It then writes the
  400. new filename into that entry, with zeros for block numbers.
  401.  
  402. Now consider what the BDOS must do as the program sequentially writes
  403. the file. First, the BDOS must find a free data block on the disk.  To
  404. do this it consults its free list for the disk (the allocation bit
  405. map) and assigns one block to the new file.  It marks that block as
  406. used and puts the block number into the file control block.  Now that
  407. the block number known, the next steps are much like reading -- the
  408. BDOS translates from block number to track/sector numbers and calls
  409. the BIOS to write 128-byte records, until a block is full.  Then, when
  410. a new block is needed, the BDOS gets the next free block from the free
  411. list, and repeats the process.
  412.  
  413. Eventually, the file control block is filled up with 8 or 16 data
  414. block numbers, and the BDOS must make a second directory entry.  But
  415. before doing so, it "closes" the initial entry by writing the file
  416. control block values to that directory entry on the disk.  Then, it
  417. searches for another empty entry, creates the second directory entry
  418. for the file (with the same name, but a different entry number), and
  419. finally resumes the process of allocating a data block and writing
  420. records.
  421.  
  422. At last, when the entire file has been written, the program calls the
  423. BDOS to close the file.  Just as it did for the "internal" close of
  424. the initial directory entry, the BDOS writes the data block numbers in
  425. the file control block to the final directory entry on disk.
  426.  
  427. If an error occurs during the process of writing the file, you may see
  428. some residue of the incomplete process.  Quickie Quiz: Explain how
  429. each of the following might result:
  430.  
  431. 1. Filename in directory, file is shown as 0K.
  432. 2. Filename in directory, file is shown as 16K (or 32K or ...),
  433.    but the end of the file is missing.
  434.  
  435.  
  436.  
  437.  
  438.  
  439. .h1 INTERNALS OF THE DIRECTORY ENTRY.
  440.  
  441. Now we turn to the nitty-grity, and it is unavoidably confusing!  It's
  442. also essential if you intend to really understand CP/M files.
  443.  
  444. The CP/M directory structure is like a tree house that grew as the
  445. kids got bigger.  First it was a simple platform (for CP/M 1.4 files).
  446. Rooms got rebuilt to handle larger files and larger disks, and the
  447. file control block got extended to provide random access (CP/M 2.2).
  448. And small passageways were crammed with filesize, datestamps, and
  449. passwords (CP/M 3).
  450.  
  451. Some of the confusion is simply terminological.  One directory entry
  452. is 32 bytes of data. Sometimes it is also called a physical directory
  453. extent -- "physical" because it refers to actual bytes on the disk.
  454. Whenever you see this topic discussed, read carefully -- I suggest you
  455. translate all references from "physical extents" to "directory entries",
  456. and reserve the term "extents" exclusively for "logical extents,"
  457. which we will examine soon.
  458.  
  459. The directory entry has several fields, shown in Figure 2.  The
  460. information is densly packed.  You can look at an actual sector, which
  461. contains 4 directory entries, with the DU (or DU3) utility, or by
  462. running the following bit of code under a debugger and then displaying
  463. the default buffer at 0080h.
  464.  
  465.     ld    c,11
  466.     ld    de,5C
  467.     ld    a,3F
  468.     ld    (de),a
  469.     call    5
  470.     rst    38
  471.  
  472. Byte 0 of a directory entry (labeled "u") is the file's user number.
  473. A value of E5 hex indicates that the entry is unused.  Otherwise, it
  474. can have a value of 0 to 31 in CP/M 2.2.  In CP/M Plus user numbers
  475. are restricted to 0 to 15, and higher numbers indicate special
  476. datestamp, password, and volume label entries.
  477.  
  478. Bytes 1-8 are the filename and bytes 9-11 the filetype.  They must be
  479. uppercase, 7-bit letters, numbers, or a few other symbols. Each of the
  480. 11 high (eighth) bits of the filename and filetype are file
  481. attributes.  Attributes 5-11 are reserved for the system to designate
  482. files are read-only, archived, and so forth.
  483.  
  484. The next four bytes encode the entry number and the length of the
  485. file.  They will get our full attention in a moment.
  486.  
  487. Bytes 16-31 (10h-1Fh) are where the data block numbers are stored.
  488. These are either 16 1-byte values, or 8 2-byte values, depending on
  489. the disk format.  If there are no more than 255 (FF hex) block numbers
  490. on a disk (for example, on a single-sided single density disk), it's
  491. possible to use 1-byte values.  Otherwise, 2-byte values are needed.
  492.  
  493.  
  494. .h2 The directory entry number.
  495.  
  496. Now, had the tree house been built in one day, the directory number
  497. would be a 16-bit word. Instead, we have to climb through some tangled
  498. vines.  So, hold on!
  499.  
  500. The CP/M file system has two fundamental units of measurement:
  501.  
  502.     1 record = 128 bytes
  503.     1 logical extent = 128 records = 16K bytes
  504.  
  505. Records and logical extents are numbered sequentially, beginning with
  506. 0.
  507.  
  508. Now consider a 17K file, with copies on several types of disks.
  509. Things might look like this.
  510.  
  511. On Disk #1, 16K of data blocks fill up one directory entry.  Then one
  512. entry corresponds to one logical extent.  The 17K file will have
  513. 2 logical extents, and 2 directory entries.
  514.  
  515. On Disk #2, 32K of data blocks fill up one directory entry.  (How
  516. might this occur?  Suppose a block is 4K, and block numbers are 2-byte
  517. values. 8*4K = 32K.)  Now, one entry can hold two logical extents.
  518. The 17K file will have 2 logical extents, but only one directory
  519. entry.
  520.  
  521. CP/M keeps track of logical extents with the EXtent byte, which
  522. can hold 0 to 31 (0 to 1F hex). After 31, it must again be 0.
  523.  
  524. Why, you may well ask, does CP/M not allow more than 32 extent values
  525. in this field?  Well, the tree house architect wasn't that farsighted.
  526. In the directory search functions, the BDOS uses a '?' character to
  527. indicate a "wild-card" search.  When a '?' appears in the EXtent byte
  528. of an fcb, the BDOS will match any extent number.  And since the '?'
  529. byte is 3F hex = 00111111 binary, only 5 bits are available to number
  530. logical extents!
  531.  
  532. If five bits were indeed all that is available, CP/M files would be
  533. restricted to a maximum size of 32*block size.  To allow larger files,
  534. the tree house added the S2 byte.  It holds the "overflow" from the
  535. EXtent byte.  Each unit of S2 thus represents 32 logical extents, and
  536. the the S2 byte can take a value from 0 to 3F hex.
  537.  
  538. The full logical extent number is, therefore obtained by combining
  539. the EXtent byte and the S2 byte as follows:
  540.  
  541.     log_ext = (EXT & 1Fh) + ((S2 & 3Fh) << 5)
  542.  
  543. (I use the c language operators: '&' is bitwise and, '<<' is shift-left).
  544.  
  545. Note well that the high-order bits must really be masked; while the
  546. directory entry is active in the fcb, the BDOS uses the higher bits of
  547. the EXTent and S2 bytes for internal BDOS flags.
  548.  
  549. Now, what is the directory entry number (the "physical extent")?  It is
  550. the logical extent number, divided by the number of logical extents
  551. per directory entry.  And that depends on the format, information that
  552. is _not_ in the directory, but in the BIOS's data structure for the
  553. drive -- the disk parameter block (dpb).
  554.  
  555.     entry_no = log_ext / extents_per_entry
  556.  
  557. The _extent mask_ byte in the dpb encodes the number of logical
  558. extents per directory entry.  Its value is
  559.  
  560.     extent_mask = 2 ** extents_per_entry - 1
  561.  
  562. A strange, but handy, representation, because it gives the number of
  563. times to right-shift the log_ext value to calculate the directory
  564. entry number.  And, simultaneously, it is a bitmask that, applied to
  565. the EXTent byte, yields the number of logical extents within
  566. the current directory entry that are in use.
  567.  
  568.     entry_no = log_ext >> extent_mask
  569.  
  570.              = ((EXT & 1fh) >> extmask) + ((s2 & 1fh) << (5 - extmask))
  571.  
  572.  
  573. .h1 FAST FILESIZE COMPUTATIONS.
  574.  
  575. How big is a file?  What is its size in records, or equivalently, what
  576. is the record number of the file?  It is the record count in the last
  577. directory entry (the number of records in the final logical extent),
  578. plus the size, in records, of all prior extents.  Since the RC byte
  579. may be 80 hex, we must mask it.  The formula is:
  580.  
  581.     recno = log_ext << 7 + (RC & 7Fh)
  582.  
  583. Before considering practical answers to that question, let's consider
  584. how large a record number can ever be.  The record count is 7 bits, the
  585. EXtent byte is 5 bits, and the S2 byte can be 6 bits, a total of 18
  586. bits.  The largest possible record number is therefore 2**18.  Since
  587. there are 8 = 2*3 records in 1 kilobyte, the maximum filesize is 2**15
  588. K = 32 MB, a large file indeed!
  589.  
  590. This is the limit under CP/M Plus and ZSDOS.  Regular CP/M 2.2, however, 
  591. limited the record number to a 16-bit quantity (with the largest S2 value
  592. being 0F hex), and thus a maximum filesize of 4 MB.  And I'm afraid
  593. most CP/M application programs expect that limit not to be exceeded.
  594.  
  595. We can determine a file's size in several ways.  BDOS function 35 will
  596. return the filesize in the random record number field of the fcb.
  597. This is the easiest method; the BDOS does all of the tedious
  598. arithmetic, and the random record number field is 3 bytes, so it will
  599. hold a full 18-bit record number, should we ever have a file so huge.
  600. But it's slow, because the BDOS must search the directory from the
  601. beginning each time it is called.
  602.  
  603. A second method is to have the program read the complete directory,
  604. storing the directory entries for the file as it goes, and then
  605. find the last one.  This is no faster for a single file, but it is
  606. a clear winner if the program is reading the complete directory anyway
  607. (in order to display it, for example).  In this case, the file size
  608. calculation is made after the entries are stored and sorted by entry
  609. number (as well as alphabetically, perhaps).
  610.  
  611. .h2 A single file's size
  612.  
  613. Often enough, a program needs a file's size as an adjunct to other
  614. file operations.  In this situation, the file can first be opened, or
  615. searched-for, and then its size quickly computed from the directory
  616. entry data.  Figure 3 shows the routine, get_filesize, to perform this
  617. service.
  618.  
  619. If the file has only one directory entry, all of the information
  620. needed to calculate its size in records is available in the EXtent,
  621. S2, and RecordCount bytes returned in the fcb by an open call, or in
  622. the dma buffer by a search-first call.  The routine first checks that
  623. that the fcb information is, indeed, for entry number 0.  It then
  624. determines that there are no others by checking the record count,
  625. because if it is 80h (128), the entry is full, and there may be
  626. another one.
  627.  
  628. If all of these tests get passed, it calculates:
  629.  
  630.     records = RecordCount + 128 * number of prior logical extents
  631.  
  632. Otherwise, it calls the BDOS, which returns the number of records in
  633. the random-record number field of the fcb.
  634.  
  635. The get_filesize routine returns the filesize as a 3-byte value in the
  636. A, H, and L registers.  Except for very large files, A will be zero,
  637. and the filesize can be used as the 16-bit value in the HL register pair.
  638.  
  639.  
  640. .h2 A list of file sizes
  641.  
  642. What if you need to get the sizes of several files?  If your routine
  643. has a lot of memory available to hold a large list of directory
  644. entries you can process them in a single batch.  But in some
  645. applications memory must be conserved.  The routine might be just a
  646. small part of a large program that need memory for other functions.
  647. Or perhaps it is a component of a Z-System resident command processor
  648. that wants to keep the TPA intact for the next GO command.
  649.  
  650. The most basic directory routine looks like this:
  651.  
  652.     set fcb to a wildcard mask
  653.     set dma to a buffer
  654.     search-first
  655.       if not found, quit
  656. loop:    if entry number is 0, display entry at offset in buffer
  657.     search-next
  658.       if found, loop
  659.  
  660. How can we add the fast filesize calculation to this routine?  Here's
  661. the sketch of the approach I used in the DIRectory command built into
  662. BackGrounder ii , and also later in JetFind.  That command must be
  663. able to run when a regular program has been suspended, without
  664. molesting that program's memory.  This is the special challenge.
  665.  
  666. We plan to modify the "loop" line to be:
  667.  
  668.     if directory-entry is not full, calculate filesize from entry.
  669.     else use BDOS function 35.
  670.  
  671. Hmmm.  Initially, this looks like it would be ok.  In fact, we're in
  672. trouble as soon as it's necessary to use the BDOS filesize function,
  673. because that call will change the BDOS's internal directory pointers
  674. and mess up the next search-next call.  This requires some discussion.
  675.  
  676. The BDOS search-first/search-next functions are unlike any other file
  677. functions, in that they are logically a single function that is called
  678. repeatedly at two entry points.  This operation says, in effect: Find
  679. the first entry in the directory matching the supplied fcb and return
  680. it in the dma buffer.  Thereafter, when entered at the search-next
  681. point, continue the search for the next matching entry.
  682.  
  683. The BDOS uses internal pointers to keep track of both the fcb and
  684. where it is in the directory search, and it presumes that there will be
  685. no intervening file operations except more search-next calls.
  686.  
  687. But, with some cleverness, we can get modify our routine further to
  688. get around this complication.  After making the BDOS 35 call, we do a
  689. search-first call for entry 0 of that file.  This resets the internal
  690. pointers to the spot where the previous search had last matched.
  691. Then, we search-next for the next entry.
  692.  
  693. The routine now looks like this:
  694.  
  695.     set fcb to a wildcard mask
  696.     set dma to a buffer
  697.     search-first
  698.       if not found, quit
  699. loop:    If directory-entry is not full, calculate filesize from entry.
  700.     Else
  701.         call BDOS function 35
  702.         set fcb to last-found entry
  703.         search-first
  704.     search-next
  705.       if found, loop
  706.  
  707. .h1 What's next?
  708.  
  709. File systems are a big topic, we're out of space, and coding the
  710. little directory routine must be left as "an exercise for the reader."
  711.  
  712. I appreciate your comments and welcome suggestions for future columns.
  713. Topics I have in mind include stack and interrupt management and
  714. environmentally-aware programming.  What else would you like to see?
  715. Drop me a line at Plu*Perfect!
  716.  
  717.  
  718.  
  719.            Figure 1.  Free Space on a Disk
  720.                _______________________________
  721.  
  722.  
  723. bdos    equ    5
  724. tbuff    equ    0080h
  725.  
  726.  
  727. ; Enter:    a  = drive (0=A:, ..., 15=P:)
  728. ; Exit:        hl = free space on drive, in Kilobytes
  729. ;
  730. get_freek:
  731.     ld    (spacedrv),a    ; save drive
  732.     ld    e,a
  733.     ld    c,14        ; BDOS select disk function
  734.     call    bdos
  735. ;
  736. ; check for CP/M Plus
  737. ;
  738.     ld    c,12        ; get bdos version
  739.     call    bdos        ; if not cp/m 3 system
  740.     cp    30h
  741.     jr    c,dparams    ; ..jump to calculate from alv
  742. ;
  743. ; calculate free space for CP/M Plus
  744. ;
  745.     ld    de,tbuff    ; set default dma
  746.     ld    c,26
  747.     call    bdos
  748.     ld    c,46        ; get disk freespace
  749.     ld    a,(spacedrv)
  750.     ld    e,a        ; ..on this drive
  751.     call    bdos
  752. ;
  753. ; Disk space is returned by CPM+ at dma for 3 bytes.
  754. ;
  755.     ld    hl,(tbuff)    ; Low to L, Mid to H
  756.     ld    a,(tbuff+2)    ; High to A
  757.     ld    b,3        ; Divide by 8 (SHR 3)
  758. ;
  759. ; Shift everything right into HL (64 MB max reportable)
  760. ;
  761. div:    or    a        ; Clear carry
  762.     rra            ; High
  763.     rr    h        ; Mid
  764.     rr    l        ; Low
  765.     djnz    div
  766.     ret            ; hl = space free in Kbytes
  767.  
  768. ;
  769. ; For CP/M 2 use this method:
  770. ;
  771. dparams:
  772.     ld    c,31        ; BDOS get disk parameters function
  773.     call    bdos
  774.     inc    hl        ; point to block shift-factor byte
  775.     inc    hl
  776.     ld    a,(hl)        ; Get value and
  777.     ld    (blkshf),a    ; ..save it
  778.     inc    hl        ; point to max data block number
  779.     inc    hl
  780.     ld    a,(hl)
  781.     ld    (extmsk),a    ; save it 
  782.     inc    hl
  783.     ld    e,(hl)        ; Get (word) value into DE
  784.     inc    hl
  785.     ld    d,(hl)
  786.     inc    de        ; Add 1 for max number of blocks
  787.  
  788. ; Compute amount of free space left on disk
  789.  
  790. dfree:    ld    c,27        ; BDOS get allocation vector function
  791.     push    de        ; Save BLKMAX value
  792.     call    bdos        ; Get allocation vector into 
  793.     ld    b,h        ; ..BC
  794.     ld    c,l
  795.     pop    hl        ; Restore BLKMAX value to HL
  796.     ld    de,0        ; Inititialize count of free blocks
  797.  
  798. ; At this point we have
  799. ;    BC = allocation vector address
  800. ;    DE = free block count
  801. ;    HL = number of data blocks on disk
  802.  
  803. cntfree:
  804.     push    bc        ; Save allocation map ptr
  805.     ld    a,(bc)        ; Get bit pattern of allocation byte
  806.     ld    b,8        ; Set to process 8 blocks
  807. ;
  808. cnt2:    rla            ; Rotate allocated block bit into carry flag
  809.     jr    c,cnt3        ; If set (bit=1), block is allocated
  810.     inc    de        ; If not set, block is not allocated, so
  811.                 ; ..increment free block count
  812. ;
  813. cnt3:    ld    c,a        ; Save remaining allocation bits in C
  814.     dec    hl        ; Count down number of blocks on disk
  815.     ld    a,l        ; if down to zero
  816.     or    h
  817.     jr    z,cnt4        ; ..branch
  818.     ld    a,c        ; Get back current allocation bit pattern
  819.     djnz    cnt2        ; Loop through 8 bits
  820.     pop    bc        ; Get ptr to allocation vector
  821.     inc    bc        ; Point to next allocation byte
  822.     jr    cntfree        ; Process next allocation byte
  823.  
  824. cnt4:    pop    bc        ; clear stack
  825.     ex    de,hl        ; Free block count to HL
  826. ;
  827.     ld    a,(blkshf)    ; Get block shift factor
  828.     sub    3        ; Convert to log2 of K per block
  829.     ret    z        ; Done if 1K per block
  830.  
  831. ; Convert for data blocks of more than 1K each
  832.  
  833. free2k:    add    hl,hl
  834.     dec    a
  835.     jr    nz,free2k
  836.     ret            ; HL = amount of free space on disk in K
  837. ;
  838. spacedrv:ds    1
  839. blkshf:    ds    1
  840. extmsk:    ds    1
  841.  
  842.  
  843.  
  844.  
  845.           Figure 2 . A CP/M Directory Entry
  846.                   _________________________________
  847.  
  848.  
  849.             + user number           +----EXtent byte
  850.            /                       / +---S1 byte
  851.           /                       / / +--S2 byte
  852.          /     filename   type   / / / + record count
  853.         / --------------- ----- / / / /
  854. 00     u f i l e n a m  e t y p x 1 2 r
  855. 10     - - - - - - - -  - - - - - - - -  data blocks
  856.  
  857.  
  858.  
  859.  
  860.  
  861.         Figure 3.  Calculate a Single Filesize
  862.             ______________________________________
  863.  
  864. ;
  865. ; Enter:    de -> fcb (36 bytes), freshly opened or
  866. ;              copied from search-first buffer
  867. ;        extmsk contains extent mask for file's drive
  868. ;
  869. ; Exit:        a,hl = 24-bit file size value in 128-byte records
  870. ;
  871. get_filesize:
  872.     ld    hl,12        ; point to EXtent byte
  873.     add    hl,de
  874.     ld    a,(extmsk)    ; if not directory entry #0
  875.     cpl
  876.     and    (hl)
  877.     jr    nz,g_rd        ; ..call bdos
  878.     ld    b,(hl)        ; save logical extent #
  879.     inc    hl        ; point to S2
  880.     inc    hl
  881.     ld    a,(hl)        ; or if overflow into S2
  882.     and    7fh        ; (not directory entry #0)
  883.     jr    nz,g_rd        ; ..call bdos
  884.     inc    hl        ; or if Record Count
  885.     ld    a,(hl)
  886.     cp    80h        ; ..is full
  887.     jr    z,g_rd        ; ..call bdos
  888. ;
  889. ; calculate filesize from fcb data
  890. ;
  891.     ld    l,a        ; hl = rec. cnt. of last log. extent 
  892.     inc    b
  893.     ld    de,80h        ; + 80h = size of each prior log. extent
  894.     ld    h,d        ; h = 0
  895.     jr    g_dj
  896. g_lp:    add    hl,de
  897. g_dj:    djnz    g_lp
  898.     xor    a        ; clear high bits
  899.     ret
  900. ;
  901. ; call bdos to calculate filesize
  902. ;
  903. g_rd:    push    de        ; save fcb ptr
  904.     ld    c,35        ; call bdos for filesize 
  905.     call    bdos
  906.     pop    de
  907.     ld    hl,33        ; point to random record #
  908.     add    hl,de
  909.     ld    e,(hl)        ; get it
  910.     inc    hl
  911.     ld    d,(hl)
  912.     inc    hl
  913.     ld    a,(hl)        ; high bits to A
  914.     ex    de,hl        ; low 16 bits in HL
  915.     ret
  916. ;-------------
  917.