LizardLad_1
Posts: 26
Joined: Sat Jan 13, 2018 12:29 am

Creating a way to read files

Sat Jan 13, 2018 12:33 am

I have written a simple operating system for my Raspberry Pi B+ . It is based of the Baking Pi tutorial series. Now I am trying to find a way to access files on the sd card and create a forth interpreter. Is there any way I can mount the boot partition in my kernel so I can load other files?

bzt
Posts: 98
Joined: Sat Oct 14, 2017 9:57 pm

Re: Creating a way to read files

Sun Jan 14, 2018 6:11 pm

Actually, since your program is running bare metal, you don't have such a fancy thing like mount system call, unless you've already implemented it in your kernel. Which is not the case I assume, 'cos you are here asking about it. On bare metal, we have to do everything on our own.

First of all, you'll need a readsector() function by talking to the EMMC. With that you can read raw data from your sd card (in 512 bytes units, so called sectors).

Second, you'll have to read the absolute first sector on your card and interpret the MBR partition table in it. This will give you the starting sector address of the FAT partition (assuming you have only one partition this is as easy as reading an int at offset 0x1C6). After that you'll have to read the volume boot record, the first sector of the partition, which holds the BPB (BIOS Parameter Block). That structure has all the information you'll need for locating a file on the card.

Third, you'll have to load and interpret the root directory, which will give you the starting cluster of the file you're looking for. (Forget the table about Cluster sizes on the linked page, always use the BPB instead.)

Finally, you'll have to walk the cluster chain (File Allocation Table) to load your file into memory. This is simple, you convert the cluster number into sector address (secaddr = partition start + fat data start + (cluster-2) * bpb.sectorspercluster), and you read bpb.sectorsperluster sectors into memory from that address. Then you get the new cluster from cluster = fat[cluster] and repeat the whole process until you reach the last cluster marker.

That sums it up. I wrote a tutorial on how to do this (in C, should compile on 32 bit). If you want to handle sub-directories, the whole process became a little bit trickier. You split your path by the separator '\'. You take the first path item, and look it up in the root directory to get it's cluster number. Next, you read the directory entries for that cluster (same way as you would read a file), and you look for the second path item in it. You repeat this process till you have items in your path. The last item will give you the starting cluster for your file.

Good luck,
bzt

Return to “Bare metal”

Who is online

Users browsing this forum: No registered users and 2 guests