1 # Pintos helper subroutines.
3 # Number of bytes available for the loader at the beginning of the MBR.
4 # Kernel command-line arguments follow the loader.
5 our $LOADER_SIZE = 314;
8 my (%role2type) = (KERNEL => 0x20,
12 my (%type2role) = reverse %role2type;
14 # Order of roles within a given disk.
15 our (@role_order) = qw (KERNEL FILESYS SCRATCH SWAP);
19 # Valid keys are KERNEL, FILESYS, SCRATCH, SWAP. Only those
20 # partitions which are in use are included.
22 # Each value is a reference to a hash. If the partition's contents
23 # are to be obtained from a file (that will be copied into a new
24 # virtual disk), then the hash contains:
26 # FILE => name of file from which the partition's contents are copied
27 # (perhaps "/dev/zero"),
28 # OFFSET => offset in bytes in FILE,
29 # BYTES => size in bytes of contents from FILE,
31 # If the partition is taken from a virtual disk directly, then it
32 # contains the following. The same keys are also filled in once a
33 # file-based partition has been copied into a new virtual disk:
35 # DISK => name of virtual disk file,
36 # START => sector offset of start of partition within DISK,
37 # SECTORS => number of sectors of partition within DISK, which is usually
38 # greater than round_up (BYTES, 512) due to padding.
41 # set_part($opt, $arg)
43 # For use as a helper function for Getopt::Long::GetOptions to set
47 my ($role, $source) = $opt =~ /^([a-z]+)(?:-([a-z]+))?/ or die;
50 $source = 'FILE' if $source eq '';
52 die "can't have two sources for \L$role\E partition"
53 if exists $parts{$role};
55 do_set_part ($role, $source, $arg);
58 # do_set_part($role, $source, $arg)
60 # Sets partition $role as coming from $source (one of 'file', 'from',
61 # or 'size'). $arg is a file name for 'file' or 'from', a size in
62 # megabytes for 'size'.
64 my ($role, $source, $arg) = @_;
66 my ($p) = $parts{$role} = {};
67 if ($source eq 'file') {
68 if (read_mbr ($arg)) {
69 print STDERR "warning: $arg looks like a partitioned disk ";
70 print STDERR "(did you want --$role-from=$arg or --disk=$arg?)\n"
75 $p->{BYTES} = -s $arg;
76 } elsif ($source eq 'from') {
77 my (%pt) = read_partition_table ($arg);
78 my ($sp) = $pt{$role};
79 die "$arg: does not contain \L$role\E partition\n" if !defined $sp;
82 $p->{OFFSET} = $sp->{START} * 512;
83 $p->{BYTES} = $sp->{SECTORS} * 512;
84 } elsif ($source eq 'size') {
85 $arg =~ /^\d+(\.\d+)?|\.\d+$/ or die "$arg: not a valid size in MB\n";
87 $p->{FILE} = "/dev/zero";
89 $p->{BYTES} = ceil ($arg * 1024 * 1024);
95 # set_geometry('HEADS,SPT')
98 # For use as a helper function for Getopt::Long::GetOptions to set
103 @geometry{'H', 'S'} = (64, 32);
105 @geometry{'H', 'S'} = /^(\d+)[,\s]+(\d+)$/
106 or die "bad syntax for geometry\n";
107 $geometry{H} <= 255 or die "heads limited to 255\n";
108 $geometry{S} <= 63 or die "sectors per track limited to 63\n";
112 # set_align('bochs|full|none')
114 # For use as a helper function for Getopt::Long::GetOptions to set
115 # partition alignment.
118 die "unknown alignment type \"$align\"\n"
119 if $align ne 'bochs' && $align ne 'full' && $align ne 'none';
122 # assemble_disk(%args)
124 # Creates a virtual disk $args{DISK} containing the partitions
125 # described by @args{KERNEL, FILESYS, SCRATCH, SWAP}.
127 # Required arguments:
128 # DISK => output disk file name
129 # HANDLE => output file handle (will be closed)
131 # Normally at least one of the following is included:
132 # KERNEL, FILESYS, SCRATCH, SWAP => {input:
133 # FILE => file to read,
134 # OFFSET => byte offset in file,
135 # BYTES => byte count from file,
138 # DISK => output disk file name,
139 # START => sector offset in DISK,
140 # SECTORS => sector count in DISK},
142 # Optional arguments:
143 # ALIGN => 'bochs' (default), 'full', or 'none'
144 # GEOMETRY => {H => heads, S => sectors per track} (default 16, 63)
145 # FORMAT => 'partitioned' (default) or 'raw'
146 # LOADER => $LOADER_SIZE-byte string containing the loader binary
147 # ARGS => ['arg 1', 'arg 2', ...]
151 my (%geometry) = $args{GEOMETRY} || (H => 16, S => 63);
153 my ($align); # Align partition start, end to cylinder boundary?
154 my ($pad); # Pad end of disk out to cylinder boundary?
155 if (!defined ($args{ALIGN}) || $args{ALIGN} eq 'bochs') {
158 } elsif ($args{ALIGN} eq 'full') {
161 } elsif ($args{ALIGN} eq 'none') {
167 my ($format) = $args{FORMAT} || 'partitioned';
168 die if $format ne 'partitioned' && $format ne 'raw';
170 # Check that we have apartitions to copy in.
171 my $part_cnt = grep (defined ($args{$_}), keys %role2type);
172 die "must have exactly one partition for raw output\n"
173 if $format eq 'raw' && $part_cnt != 1;
175 # Calculate the disk size.
176 my ($total_sectors) = 0;
177 if ($format eq 'partitioned') {
178 $total_sectors += $align ? $geometry{S} : 1;
180 for my $role (@role_order) {
181 my ($p) = $args{$role};
186 my ($bytes) = $p->{BYTES};
187 my ($start) = $total_sectors;
188 my ($end) = $start + div_round_up ($bytes, 512);
189 $end = round_up ($end, cyl_sectors (%geometry)) if $align;
191 $p->{DISK} = $args{DISK};
192 $p->{START} = $start;
193 $p->{SECTORS} = $end - $start;
194 $total_sectors = $end;
198 my ($disk_fn) = $args{DISK};
199 my ($disk) = $args{HANDLE};
200 if ($format eq 'partitioned') {
201 # Pack loader into MBR.
202 my ($loader) = $args{LOADER} || "\xcd\x18";
203 my ($mbr) = pack ("a$LOADER_SIZE", $loader);
205 $mbr .= make_kernel_command_line (@{$args{ARGS}});
207 # Pack partition table into MBR.
208 $mbr .= make_partition_table (\%geometry, \%args);
210 # Add signature to MBR.
211 $mbr .= pack ("v", 0xaa55);
213 die if length ($mbr) != 512;
214 write_fully ($disk, $disk_fn, $mbr);
215 write_zeros ($disk, $disk_fn, 512 * ($geometry{S} - 1)) if $align;
217 for my $role (@role_order) {
218 my ($p) = $args{$role};
222 my ($fn) = $p->{FILE};
223 open ($source, '<', $fn) or die "$fn: open: $!\n";
225 sysseek ($source, $p->{OFFSET}, 0) == $p->{OFFSET}
226 or die "$fn: seek: $!\n";
228 copy_file ($source, $fn, $disk, $disk_fn, $p->{BYTES});
229 close ($source) or die "$fn: close: $!\n";
231 write_zeros ($disk, $disk_fn, $p->{SECTORS} * 512 - $p->{BYTES});
234 my ($pad_sectors) = round_up ($total_sectors, cyl_sectors (%geometry));
235 write_zeros ($disk, $disk_fn, ($pad_sectors - $total_sectors) * 512);
237 close ($disk) or die "$disk: close: $!\n";
240 # make_partition_table({H => heads, S => sectors}, {KERNEL => ..., ...})
242 # Creates and returns a partition table for the given partitions and
244 sub make_partition_table {
245 my ($geometry, $partitions) = @_;
247 for my $role (@role_order) {
248 defined (my $p = $partitions->{$role}) or next;
250 my $end = $p->{START} + $p->{SECTORS} - 1;
251 my $bootable = $role eq 'KERNEL';
253 $table .= pack ("C", $bootable ? 0x80 : 0); # Bootable?
254 $table .= pack_chs ($p->{START}, $geometry); # CHS of partition start
255 $table .= pack ("C", $role2type{$role}); # Partition type
256 $table .= pack_chs($end, $geometry); # CHS of partition end
257 $table .= pack ("V", $p->{START}); # LBA of partition start
258 $table .= pack ("V", $p->{SECTORS}); # Length in sectors
259 die if length ($table) % 16;
261 return pack ("a64", $table);
264 # make_kernel_command_line(@args)
266 # Returns the raw bytes to write to an MBR at offset $LOADER_SIZE to
267 # set a Pintos kernel command line.
268 sub make_kernel_command_line {
270 my ($args) = join ('', map ("$_\0", @args));
271 die "command line exceeds 128 bytes" if length ($args) > 128;
272 return pack ("V a128", scalar (@args), $args);
275 # copy_file($from_handle, $from_file_name, $to_handle, $to_file_name, $size)
277 # Copies $size bytes from $from_handle to $to_handle.
278 # $from_file_name and $to_file_name are used in error messages.
280 my ($from_handle, $from_file_name, $to_handle, $to_file_name, $size) = @_;
283 my ($chunk_size) = 4096;
284 $chunk_size = $size if $chunk_size > $size;
285 $size -= $chunk_size;
287 my ($data) = read_fully ($from_handle, $from_file_name, $chunk_size);
288 write_fully ($to_handle, $to_file_name, $data);
292 # read_fully($handle, $file_name, $bytes)
294 # Reads exactly $bytes bytes from $handle and returns the data read.
295 # $file_name is used in error messages.
297 my ($handle, $file_name, $bytes) = @_;
299 my ($read_bytes) = sysread ($handle, $data, $bytes);
300 die "$file_name: read: $!\n" if !defined $read_bytes;
301 die "$file_name: unexpected end of file\n" if $read_bytes != $bytes;
305 # write_fully($handle, $file_name, $data)
307 # Write $data to $handle.
308 # $file_name is used in error messages.
310 my ($handle, $file_name, $data) = @_;
311 my ($written_bytes) = syswrite ($handle, $data);
312 die "$file_name: write: $!\n" if !defined $written_bytes;
313 die "$file_name: short write\n" if $written_bytes != length $data;
317 my ($handle, $file_name, $size) = @_;
320 my ($chunk_size) = 4096;
321 $chunk_size = $size if $chunk_size > $size;
322 $size -= $chunk_size;
324 write_fully ($handle, $file_name, "\0" x $chunk_size);
328 # div_round_up($x,$y)
330 # Returns $x / $y, rounded up to the nearest integer.
331 # $y must be an integer.
334 return int ((ceil ($x) + $y - 1) / $y);
339 # Returns $x rounded up to the nearest multiple of $y.
340 # $y must be an integer.
343 return div_round_up ($x, $y) * $y;
346 # cyl_sectors(H => heads, S => sectors)
348 # Returns the number of sectors in a cylinder of a disk with the given
352 return $geometry{H} * $geometry{S};
355 # read_loader($file_name)
357 # Reads and returns the first $LOADER_SIZE bytes in $file_name.
358 # If $file_name is undefined, tries to find the default loader.
359 # Makes sure that the loader is a reasonable size.
362 $name = find_file ("loader.bin") if !defined $name;
363 die "Cannot find loader\n" if !defined $name;
366 open ($handle, '<', $name) or die "$name: open: $!\n";
367 -s $handle == $LOADER_SIZE || -s $handle == 512
368 or die "$name: must be exactly $LOADER_SIZE or 512 bytes long\n";
369 $loader = read_fully ($handle, $name, $LOADER_SIZE);
370 close ($handle) or die "$name: close: $!\n";
374 # pack_chs($lba, {H => heads, S => sectors})
376 # Converts logical sector $lba to a 3-byte packed geometrical sector
377 # in the format used in PC partition tables (see [Partitions]) and
378 # returns the geometrical sector as a 3-byte string.
380 my ($lba, $geometry) = @_;
381 my ($cyl, $head, $sect) = lba_to_chs ($lba, $geometry);
382 return pack ("CCC", $head, $sect | (($cyl >> 2) & 0xc0), $cyl & 0xff);
385 # lba_to_chs($lba, {H => heads, S => sectors})
387 # Returns the geometrical sector corresponding to logical sector $lba
388 # given the specified geometry.
390 my ($lba, $geometry) = @_;
391 my ($hpc) = $geometry->{H};
392 my ($spt) = $geometry->{S};
395 # http://en.wikipedia.org/wiki/CHS_conversion
397 my $cyl = $lba / ($hpc * $spt);
398 my $temp = $lba % ($hpc * $spt);
399 my $head = $temp / $spt;
400 my $sect = $temp % $spt + 1;
403 # http://www.cgsecurity.org/wiki/Intel_Partition_Table
405 return ($cyl, $head, $sect);
407 return (1023, 254, 63); ## or should this be (1023, $hpc, $spt)?
413 # Tries to read an MBR from $file. Returns the 512-byte MBR if
414 # successful, otherwise numeric 0.
418 open (FILE, '<', $file) or die "$file: open: $!\n";
420 die "$file: file has zero size\n";
421 } elsif (-s FILE >= 512) {
423 sysread (FILE, $mbr, 512) == 512 or die "$file: read: $!\n";
424 $retval = $mbr if unpack ("v", substr ($mbr, 510)) == 0xaa55;
430 # interpret_partition_table($mbr, $disk)
432 # Parses the partition-table in the specified 512-byte $mbr and
433 # returns the partitions. $disk is used for error messages.
434 sub interpret_partition_table {
435 my ($mbr, $disk) = @_;
438 my ($bootable, $valid, $type, $lba_start, $lba_length)
439 = unpack ("C X V C x3 V V", substr ($mbr, 446 + 16 * $i, 16));
442 (print STDERR "warning: invalid partition entry $i in $disk\n"),
443 next if $bootable != 0 && $bootable != 0x80;
445 my ($role) = $type2role{$type};
446 (printf STDERR "warning: non-Pintos partition type 0x%02x in %s\n",
448 next if !defined $role;
450 (print STDERR "warning: duplicate \L$role\E partition in $disk\n"),
451 next if exists $parts{$role};
453 $parts{$role} = {START => $lba_start,
454 SECTORS => $lba_length};
459 # find_file($base_name)
461 # Looks for a file named $base_name in a couple of likely spots. If
462 # found, returns the name; otherwise, returns undef.
464 my ($base_name) = @_;
465 -e && return $_ foreach $base_name, "build/$base_name";
469 # read_partition_table($file)
471 # Reads a partition table from $file and returns the parsed
472 # partitions. Dies if partitions can't be read.
473 sub read_partition_table {
475 my ($mbr) = read_mbr ($file);
476 die "$file: not a partitioned disk\n" if !$mbr;
477 return interpret_partition_table ($mbr, $file);
482 # Returns the numerically largest value in @args.
485 foreach (@_[1..$#_]) {
486 $max = $_ if $_ > $max;