summaryrefslogtreecommitdiffstats
path: root/perl-install/diskdrake/hd_gtk.pm
blob: 6bd61bd24cf53a53a4ce5fb38ac897045c9c6cb6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
package diskdrake::hd_gtk; # $Id$

use diagnostics;
use strict;

use common;
use resize_fat::main;
use ugtk2 qw(:helpers :wrappers :create);
use partition_table qw(:types);
use partition_table::raw;
use detect_devices;
use diskdrake::interactive;
use run_program;
use loopback;
use devices;
use raid;
use any;
use log;
use fsedit;
use fs;

my ($width, $height, $minwidth) = (400, 50, 5);
my ($all_hds, $in, $do_force_reload, $current_kind, $current_entry, $update_all);
my ($w, @notebook, $done_button);

=begin


=head1 SYNOPSYS

struct {
  string name      # which is displayed in tab of the notebook
  bool no_auto     # wether the kind can disappear after creation
  string type      # one of { 'hd', 'raid', 'lvm', 'loopback', 'removable', 'nfs', 'smb' }
  hd | hd_lvm | part_raid[] | part_loopback[] | raw_hd[]  val

  # 
  widget main_box
  widget display_box
  widget action_box
  widget info_box
} current_kind

part current_entry

notebook current_kind[]

=cut

sub main {
    ($in, $all_hds, my $nowizard, $do_force_reload) = @_;

    @notebook = ();

    local $in->{grab} = 1;

    $w = ugtk2->new('DiskDrake');
    $::main_window = $w->{rwindow} if !$::isEmbedded && !$::isInstall;
    my $rc = "/usr/share/libDrakX/diskdrake.rc";
    -r $rc or $rc = dirname(__FILE__) . "/../diskdrake.rc";
    -r $rc or $rc = dirname(__FILE__) . "/../share/diskdrake.rc";
    Gtk2::Rc->parse($rc);

    # TODO
#    is_empty_array_ref($all_hds->{raids}) or raid::stopAll;
#    updateLoopback();

    gtkadd($w->{window},
	   gtkpack_(Gtk2::VBox->new(0,7),
		    0, filesystems_button_box(),
		    1, (my $notebook_widget = Gtk2::Notebook->new),
		    0, (my $per_kind_action_box = Gtk2::HBox->new(0,0)),
		    0, (my $general_action_box  = Gtk2::HBox->new(0,0)),
		   ),
	  );
    my $lock;
    $update_all = sub {
	$lock and return;
	$lock = 1;
	partition_table::assign_device_numbers($_) foreach fsedit::all_hds($all_hds);
	create_automatic_notebooks($notebook_widget);
	general_action_box($general_action_box, $nowizard);
	per_kind_action_box($per_kind_action_box, $current_kind);
	current_kind_changed($in, $current_kind);
	current_entry_changed($current_kind, $current_entry);
	$lock = 0;
    };
    create_automatic_notebooks($notebook_widget);

    $notebook_widget->signal_connect(switch_page => sub {
	$current_kind = $notebook[$_[2]];
	$current_entry = '';
	$update_all->();
    });
    $w->sync;
    $done_button->grab_focus;
    $in->ask_okcancel(N("Read carefully!"), N("Please make a backup of your data first"), 1) or return
      if $::isStandalone;
    $in->ask_warn('', 
N("If you plan to use aboot, be carefull to leave a free space (2048 sectors is enough)
at the beginning of the disk")) if arch() eq 'alpha' and !$::isEmbedded;

    $w->main;
}

sub try {
    my ($name, @args) = @_;
    my $f = $diskdrake::interactive::{$name} or die "unknown function $name";
    try_($name, \&{$f}, @args);
}
sub try_ {
    my ($name, $f, @args) = @_;

    fsedit::undo_prepare($all_hds) if $name ne 'Undo';

    my $v = eval { $f->($in, @args, $all_hds) };
    if (my $err = $@) {
	$in->ask_warn(N("Error"), formatError($err));
    }
    if ($v eq 'force_reload') {	
	$all_hds = $do_force_reload->();
    }

    $current_entry = '' if !diskdrake::interactive::is_part_existing($current_entry, $all_hds);
    $update_all->();

    if ($v && member($name, 'Done', 'Wizard')) {
	$::isEmbedded ? kill('USR1', $::CCPID) : Gtk2->main_quit; 
    }
}

################################################################################
# generic: helpers
################################################################################
sub add_kind2notebook {
    my ($notebook_widget, $kind) = @_;
    die if $kind->{main_box};

    $kind->{display_box} = gtkset_size_request(Gtk2::HBox->new(0,0), $width, $height);
    $kind->{action_box} = gtkset_size_request(Gtk2::VBox->new(0,0), 150, 180);
    $kind->{info_box} = Gtk2::VBox->new(0,0);
    $kind->{main_box} =
      gtkpack_(Gtk2::VBox->new(0,7),
	       0, $kind->{display_box},
	       1, gtkpack_(Gtk2::HBox->new(0,7),
			   0, $kind->{action_box},
			   1, $kind->{info_box}));
    ugtk2::add2notebook($notebook_widget, $kind->{name}, $kind->{main_box});
    push @notebook, $kind;
    $kind;
}

sub general_action_box {
    my ($box, $nowizard) = @_;
    $_->widget->destroy foreach $box->children;

    gtkadd($box, gtksignal_connect(Gtk2::Button->new(N("Help")), clicked => $in->{interactive_help})) if $in->{interactive_help};

    my @actions = (if_($::isInstall && !$nowizard, N_("Wizard")), 
		   diskdrake::interactive::general_possible_actions($in, $all_hds), 
		   N_("Done"));
    foreach my $s (@actions) {
	my $button = Gtk2::Button->new(translate($s));
	$done_button = $button if $s eq 'Done';
	gtkadd($box, gtksignal_connect($button, clicked => sub { try($s) }));
    }
}
sub per_kind_action_box {
    my ($box, $kind) = @_;
    $_->widget->destroy foreach $box->children;

    $kind->{type} =~ /hd|lvm/ or return;

    foreach my $s (diskdrake::interactive::hd_possible_actions($in, kind2hd($kind), $all_hds)) {
	gtkadd($box, 
	       gtksignal_connect(Gtk2::Button->new(translate($s)),
				 clicked => sub { try($s, kind2hd($kind)) }));
    }
}
sub per_entry_action_box {
    my ($box, $kind, $entry) = @_;
    $_->widget->destroy foreach $box->children;

    if ($entry) {
	my @buttons = map { 
	    my $s = $_;
	    my $w = Gtk2::Button->new(translate($s));
	    $w->signal_connect(clicked => sub { try($s, kind2hd($kind), $entry) });
	    $w;
	} diskdrake::interactive::part_possible_actions($in, kind2hd($kind), $entry, $all_hds);

	gtkadd($box, gtkadd(Gtk2::Frame->new(N("Choose action")),
			    create_scrolled_window(gtkpack__(Gtk2::VBox->new(0,0), @buttons)))) if @buttons;
    } else {
	my $txt = !$::isStandalone && fsedit::is_one_big_fat_or_NT($all_hds->{hds}) ?
N("You have one big MicroSoft Windows partition.
I suggest you first resize that partition
(click on it, then click on \"Resize\")") : N("Please click on a partition");
	gtkpack($box, gtktext_insert(Gtk2::TextView->new, $txt));
    }
}

sub per_entry_info_box {
    my ($box, $kind, $entry) = @_;
    $_->widget->destroy foreach $box->children;
    my $info;
    if ($entry) {
	$info = diskdrake::interactive::format_part_info(kind2hd($kind), $entry);
    } elsif ($kind->{type} =~ /hd|lvm/) {
	$info = diskdrake::interactive::format_hd_info($kind->{val});
    }
    gtkpack($box, gtkadd(Gtk2::Frame->new(N("Details")), gtkset_justify(Gtk2::Label->new($info), 'left')));
}

sub current_kind_changed {
    my ($_in, $kind) = @_;

    $_->widget->destroy foreach $kind->{display_box}->children;

    my $v = $kind->{val};
    my @parts = 
      $kind->{type} eq 'raid' ? grep { $_ } @$v :
      $kind->{type} eq 'loopback' ? @$v : fsedit::get_fstab_and_holes($v);
    my $totalsectors = 
      $kind->{type} =~ /raid|loopback/ ? sum(map { $_->{size} } @parts) : $v->{totalsectors};
    create_buttons4partitions($kind, $totalsectors, @parts);
}

sub current_entry_changed {
    my ($kind, $entry) = @_;
    $current_entry = $entry;
    if ($kind) {
	per_entry_action_box($kind->{action_box}, $kind, $entry);
	per_entry_info_box($kind->{info_box}, $kind, $entry);
    }
}

sub create_automatic_notebooks {
    my ($notebook_widget) = @_;

    $_->{marked} = 0 foreach @notebook;
    my $may_add = sub {
	my ($kind) = @_;
	my @l = grep { $kind->{val} == $_->{val} } @notebook;
	@l > 1 and log::l("weird: create_automatic_notebooks");
	$kind = $l[0] || add_kind2notebook($notebook_widget, $kind);
	$kind->{marked} = 1;
    };
    $may_add->(hd2kind($_)) foreach @{$all_hds->{hds}};
    $may_add->(lvm2kind($_)) foreach @{$all_hds->{lvms}};
    $may_add->(raid2kind()) if any { $_ } @{$all_hds->{raids}};
    $may_add->(loopback2kind()) if @{$all_hds->{loopbacks}};

    @notebook = grep_index {
	my $b = $_->{marked} or $notebook_widget->remove_page($::i);
	$b;
    } @notebook;
    @notebook or die N("No hard drives found");
}

################################################################################
# parts: helpers
################################################################################
sub create_buttons4partitions {
    my ($kind, $totalsectors, @parts) = @_;

    $width = max($width, 0.9 * second($w->{window}->window->get_size)) if $w->{window}->window;

    my $ratio = $totalsectors ? ($width - @parts * $minwidth) / $totalsectors : 1;
    while (1) {
	my $totalwidth = sum(map { $_->{size} * $ratio + $minwidth } @parts);
	$totalwidth <= $width and last;
	$ratio /= $totalwidth / $width * 1.1;
    }

    foreach my $entry (@parts) {
	my $w = Gtk2::Button->new($entry->{mntpoint} || '') or die '';
	$w->signal_connect(focus_in_event     => sub { current_entry_changed($kind, $entry) });
	$w->signal_connect(button_press_event => sub { current_entry_changed($kind, $entry) });
	$w->signal_connect(key_press_event => sub {
	    my (undef, $event) = @_;
	    member('control-mask', @{$event->state}) or return; 
	    my $c = chr $event->keyval;

	    foreach my $s (diskdrake::interactive::part_possible_actions($in, kind2hd($kind), $entry, $all_hds)) {
		${{
		    Create => 'c', Delete => 'd', Format => 'f', 
		    Loopback => 'l', Resize => 'r', Type => 't', 
		    Mount => 'M', Unmount => 'u', 'Mount point' => 'm',
		    'Add to LVM' => 'L', 'Remove from LVM' => 'L', 
		    'Add to RAID' => 'R', 'Remove from RAID' => 'R',
		}}{$s} eq $c or next;

		try($s, kind2hd($kind), $entry);
		last;
	    }
	});
	$w->set_name("PART_" . type2name($entry->{type}));
	$w->set_size_request($entry->{size} * $ratio + $minwidth, 0);
	gtkpack__($kind->{display_box}, $w);
	$w->grab_focus if $current_entry && fsedit::is_same_part($current_entry, $entry);
    }
}


################################################################################
# disks: helpers
################################################################################
sub current_hd { 
    $current_kind->{type} eq 'hd' or die 'current_hd called but $current_kind is not an hd';
    $current_kind->{val};
}
sub current_part {
    current_hd();
    $current_entry;
}

sub kind2hd {
    my ($kind) = @_;
    $kind->{type} =~ /hd|lvm/ ? $kind->{val} : {}
}

sub hd2kind {
    my ($hd) = @_;
    { type => 'hd', name => $hd->{device}, val => $hd };
}

sub filesystems_button_box() {
    my @types = (N_("Ext2"), N_("Journalised FS"), N_("Swap"), arch() =~ /sparc/ ? N_("SunOS") : arch() eq "ppc" ? N_("HFS") : N_("Windows"),
		 N_("Other"), N_("Empty"));
    my %name2type = (Ext2 => 0x83, 'Journalised FS' => 0x483, Swap => 0x82, Other => 1, "Windows" => 0xb, HFS => 0x402);

    gtkpack(Gtk2::HBox->new(0,0), 
	    N("Filesystem types:"),
	    map { my $w = Gtk2::Button->new(translate($_));
		  my $t = $name2type{$_};
		  $w->signal_connect(clicked => sub { try_('', \&createOrChangeType, $t, current_hd(), current_part()) });
		  $w->can_focus(0);
		  $w->set_name($_); 
		  $w;
	    } @types);
}

sub createOrChangeType {
    my ($in, $type, $hd, $part, $all_hds) = @_;

    $part ||= !fsedit::get_fstab($hd) && 
              { type => 0, start => 1, size => $hd->{totalsectors} - 1 };
    $part or return;
    if ($type == 1) {
	$in->ask_warn('', N("Use ``%s'' instead", $part->{type} ? N("Type") : N("Create")));
    } elsif (!$type) {
	$in->ask_warn('', N("Use ``%s'' instead", N("Delete"))) if $part->{type};
    } elsif ($part->{type}) {
	return if $type == $part->{type};
	$in->ask_warn('', isBusy($part) ? N("Use ``Unmount'' first") : N("Use ``%s'' instead", N("Type")));
    } else {
	$part->{type} = $type;
	diskdrake::interactive::Create($in, $hd, $part, $all_hds);
    }
}

################################################################################
# lvms: helpers
################################################################################
sub lvm2kind {
    my ($lvm) = @_;
    { type => 'lvm', name => $lvm->{VG_name}, val => $lvm };
}

################################################################################
# raids: helpers
################################################################################
sub raid2kind {
    { type => 'raid', name => 'raid', val => $all_hds->{raids} };
}

################################################################################
# loopbacks: helpers
################################################################################
sub loopback2kind {
    { type => 'loopback', name => 'loopback', val => $all_hds->{loopbacks} };
}

1;
span>device_windobe}; sprintf "%s%s (%s%s%s%s)", $hd->{device}, $win && " [$win:]", formatXiB($hd->{totalsectors} || $hd->{size}, 512), $hd->{info} && ", $hd->{info}", $hd->{mntpoint} && ", " . $hd->{mntpoint}, $hd->{type} && ", " . type2name($hd->{type}); } sub isPrimary { my ($part, $hd) = @_; foreach (@{$hd->{primary}{raw}}) { $part eq $_ and return 1; } 0; } sub adjustStartAndEnd { my ($hd, $part) = @_; $hd->adjustStart($part); $hd->adjustEnd($part); } sub verifyNotOverlap { my ($a, $b) = @_; $a->{start} + $a->{size} <= $b->{start} || $b->{start} + $b->{size} <= $a->{start}; } sub verifyInside { my ($a, $b) = @_; $b->{start} <= $a->{start} && $a->{start} + $a->{size} <= $b->{start} + $b->{size}; } sub verifyParts_ { foreach my $i (@_) { foreach (@_) { next if !$i || !$_ || $i == $_ || isWholedisk($i) || isExtended($i); #- avoid testing twice for simplicity :-) if (isWholedisk($_)) { verifyInside($i, $_) or cdie sprintf("partition sector #$i->{start} (%s) is not inside whole disk (%s)!", formatXiB($i->{size}, 512), formatXiB($_->{size}, 512)); } elsif (isExtended($_)) { verifyNotOverlap($i, $_) or log::l(sprintf("warning partition sector #$i->{start} (%s) is overlapping with extended partition!", formatXiB($i->{size}, 512))); #- only warning for this one is acceptable } else { verifyNotOverlap($i, $_) or cdie sprintf("partitions sector #$i->{start} (%s) and sector #$_->{start} (%s) are overlapping!", formatXiB($i->{size}, 512), formatXiB($_->{size}, 512)); } } } } sub verifyParts { my ($hd) = @_; verifyParts_(get_normal_parts($hd)); } sub verifyPrimary { my ($pt) = @_; $_->{start} > 0 || arch() =~ /^sparc/ || die "partition must NOT start at sector 0" foreach @{$pt->{normal}}; verifyParts_(@{$pt->{normal}}, $pt->{extended}); } sub assign_device_numbers { my ($hd) = @_; my $i = 1; my $start = 1; #- on PPC we need to assign device numbers to the holes too - big FUN! #- not if it's an IBM machine using a DOS partition table though if (arch() =~ /ppc/ && detect_devices::get_mac_model() !~ /^IBM/) { #- first sort the normal parts $hd->{primary}{normal} = [sort { $a->{start} <=> $b->{start} } @{$hd->{primary}{normal}} ]; #- now loop through them, assigning partition numbers - reserve one for the holes foreach (@{$hd->{primary}{normal}}) { if ($_->{start} > $start) { log::l("PPC: found a hole on $hd->{prefix} before $_->{start}, skipping device..."); $i++; } $_->{device} = $hd->{prefix} . $i++; $start = $_->{start} + $_->{size}; } } else { foreach (@{$hd->{primary}{raw}}) { my $dev = $hd->{prefix} . $i++; $_->{device} = $dev; } foreach (map { $_->{normal} } @{$hd->{extended} || []}) { my $dev = $hd->{prefix} . $i++; push @{$hd->{partitionsRenumbered}}, [ $_->{device}, $dev ] if $_->{device} && $dev ne $_->{device}; $_->{device} = $dev; } } #- try to figure what the windobe drive letter could be! # #- first verify there's at least one primary dos partition, otherwise it #- means it is a secondary disk and all will be false :( my ($c, @others) = grep { isFat($_) } @{$hd->{primary}{normal}}; $i = ord 'C'; $c->{device_windobe} = chr($i++) if $c; $_->{device_windobe} = chr($i++) foreach grep { isFat($_) } map { $_->{normal} } @{$hd->{extended}}; $_->{device_windobe} = chr($i++) foreach @others; } sub remove_empty_extended { my ($hd) = @_; my $last = $hd->{primary}{extended} or return; @{$hd->{extended}} = grep { if ($_->{normal}) { $last = $_; } else { %{$last->{extended}} = $_->{extended} ? %{$_->{extended}} : (); } $_->{normal}; } @{$hd->{extended}}; adjust_main_extended($hd); } sub adjust_main_extended { my ($hd) = @_; if (!is_empty_array_ref $hd->{extended}) { my ($l, @l) = @{$hd->{extended}}; # the first is a special case, must recompute its real size my $start = round_down($l->{normal}{start} - 1, $hd->{geom}{sectors}); my $end = $l->{normal}{start} + $l->{normal}{size}; my $only_linux = 1; my $has_win_lba = 0; foreach (map $_->{normal}, $l, @l) { $start = min($start, $_->{start}); $end = max($end, $_->{start} + $_->{size}); $only_linux &&= isTrueFS($_) || isSwap($_); $has_win_lba ||= $_->{type} == 0xc || $_->{type} == 0xe; } $l->{start} = $hd->{primary}{extended}{start} = $start; $l->{size} = $hd->{primary}{extended}{size} = $end - $start; } unless (@{$hd->{extended} || []} || !$hd->{primary}{extended}) { %{$hd->{primary}{extended}} = (); #- modify the raw entry delete $hd->{primary}{extended}; } verifyParts($hd); #- verify everything is all right } sub adjust_local_extended { my ($hd, $part) = @_; foreach (@{$hd->{extended} || []}) { $_->{normal} == $part or next; $_->{size} = $part->{size} + $part->{start} - $_->{start}; last; } } sub get_normal_parts { my ($hd) = @_; @{$hd->{primary}{normal} || []}, map { $_->{normal} } @{$hd->{extended} || []} } sub get_normal_parts_and_holes { my ($hd) = @_; my ($start, $last) = ($hd->first_usable_sector, $hd->last_usable_sector); ref($hd) or print("get_normal_parts_and_holes: bad hd" . backtrace(), "\n"); my @l = map { my $current = $start; $start = $_->{start} + $_->{size}; my $hole = { start => $current, size => $_->{start} - $current, type => 0, rootDevice => $hd->{device} }; $hole, $_; } sort { $a->{start} <=> $b->{start} } grep { !isWholedisk($_) } get_normal_parts($hd); push @l, { start => $start, size => $last - $start, type => 0, rootDevice => $hd->{device} }; grep { $_->{type} || $_->{size} >= $hd->cylinder_size } @l; } sub read_one($$) { my ($hd, $sector) = @_; my ($pt, $info); #- it can be safely considered that the first sector is used to probe the partition table #- but other sectors (typically for extended partition ones) have to match this type! if (!$sector) { my @parttype = ( if_(arch() =~ /^ia64/, 'gpt'), arch() =~ /^sparc/ ? ('sun', 'bsd', 'unknown') : ('dos', 'bsd', 'sun', 'mac', 'unknown'), ); foreach ('empty', @parttype) { /unknown/ and die "unknown partition table format"; eval { require("partition_table_$_.pm"); bless $hd, "partition_table_$_"; ($pt, $info) = $hd->read($sector); log::l("found a $_ partition table on $hd->{file} at sector $sector"); }; $@ or last; } } else { #- keep current blessed object for that, this means it is neccessary to read sector 0 before. ($pt, $info) = $hd->read($sector); } my @extended = $hd->hasExtended ? grep { isExtended($_) } @$pt : (); my @normal = grep { $_->{size} && $_->{type} && !isExtended($_) } @$pt; @extended > 1 and die "more than one extended partition"; $_->{rootDevice} = $hd->{device} foreach @normal, @extended; { raw => $pt, extended => $extended[0], normal => \@normal, info => $info }; } sub read($;$) { my ($hd, $clearall) = @_; if ($clearall) { partition_table_raw::zero_MBR_and_dirty($hd); return 1; } my $pt = read_one($hd, 0) or return 0; $hd->{primary} = $pt; undef $hd->{extended}; verifyPrimary($pt); eval { my $need_removing_empty_extended; $pt->{extended} and read_extended($hd, $pt->{extended}, \$need_removing_empty_extended) || return 0; if ($need_removing_empty_extended) { #- special case when hda5 is empty, it must be skipped #- (windows XP generates such partition tables) remove_empty_extended($hd); #- includes adjust_main_extended } }; die "extended partition: $@" if $@; assign_device_numbers($hd); remove_empty_extended($hd); 1; } sub read_extended { my ($hd, $extended, $need_removing_empty_extended) = @_; my $pt = read_one($hd, $extended->{start}) or return 0; $pt = { %$extended, %$pt }; push @{$hd->{extended}}, $pt; @{$hd->{extended}} > 100 and die "oops, seems like we're looping here :( (or you have more than 100 extended partitions!)"; if (@{$pt->{normal}} == 0) { $$need_removing_empty_extended = 1; delete $pt->{normal}; print "need_removing_empty_extended\n"; } elsif (@{$pt->{normal}} > 1) { die "more than one normal partition in extended partition"; } else { $pt->{normal} = $pt->{normal}[0]; #- in case of extended partitions, the start sector is local to the partition or to the first extended_part! $pt->{normal}{start} += $pt->{start}; #- the following verification can broke an existing partition table that is #- correctly read by fdisk or cfdisk. maybe the extended partition can be #- recomputed to get correct size. if (!verifyInside($pt->{normal}, $extended)) { $extended->{size} = $pt->{normal}{start} + $pt->{normal}{size}; verifyInside($pt->{normal}, $extended) or die "partition $pt->{normal}{device} is not inside its extended partition"; } } if ($pt->{extended}) { $pt->{extended}{start} += $hd->{primary}{extended}{start}; return read_extended($hd, $pt->{extended}, $need_removing_empty_extended); } else { 1; } } # write the partition table sub write { my ($hd) = @_; $hd->{isDirty} or return; #- set first primary partition active if no primary partitions are marked as active. if (my @l = @{$hd->{primary}{raw}}) { foreach (@l) { $_->{local_start} = $_->{start}; $_->{active} ||= 0; } $l[0]{active} = 0x80 if !grep { $_->{active} } @l; } #- last chance for verification, this make sure if an error is detected, #- it will never be writed back on partition table. verifyParts($hd); $hd->write(0, $hd->{primary}{raw}, $hd->{primary}{info}) or die "writing of partition table failed"; #- should be fixed but a extended exist with no real extended partition, that blanks mbr! if (arch() !~ /^sparc/) { foreach (@{$hd->{extended}}) { # in case of extended partitions, the start sector must be local to the partition $_->{normal}{local_start} = $_->{normal}{start} - $_->{start}; $_->{extended} and $_->{extended}{local_start} = $_->{extended}{start} - $hd->{primary}{extended}{start}; $hd->write($_->{start}, $_->{raw}) or die "writing of partition table failed"; } } $hd->{isDirty} = 0; $hd->{hasBeenDirty} = 1; #- used in undo (to know if undo should believe isDirty or not) if ($hd->{needKernelReread} && ref($hd->{needKernelReread}) eq 'ARRAY' && $::isStandalone) { #- we've only been adding partitions. Try special add_partition (using BLKPG_ADD_PARTITION) local *F; partition_table_raw::openit($hd, *F) or goto force_reread; foreach (@{$hd->{needKernelReread}}) { c::add_partition(fileno F, $_->{start}, $_->{size}, $_->{device} =~ /(\d+)$/) or goto force_reread; } } elsif ($hd->{needKernelReread}) { force_reread: #- now sync disk and re-read the partition table common::sync(); my @magic_parts = grep { $_->{isMounted} && $_->{real_mntpoint} } get_normal_parts($hd); foreach (@magic_parts) { syscall_('umount', $_->{real_mntpoint}) or log::l(_("error unmounting %s: %s", $_->{real_mntpoint}, "$!")); } $hd->kernel_read; foreach (@magic_parts) { syscall_('mount', , $_->{real_mntpoint}, type2fs($_), c::MS_MGC_VAL()) or log::l(_("mount failed: ") . "$!"); } } $hd->{needKernelReread} = 0; } sub active { my ($hd, $part) = @_; $_->{active} = 0 foreach @{$hd->{primary}{normal}}; $part->{active} = 0x80; $hd->{isDirty} = 1; } # remove a normal partition from hard drive hd sub remove { my ($hd, $part) = @_; my $i; #- first search it in the primary partitions $i = 0; foreach (@{$hd->{primary}{normal}}) { if ($_ eq $part) { splice(@{$hd->{primary}{normal}}, $i, 1); %$_ = (); #- blank it $hd->raw_removed($hd->{primary}{raw}); return $hd->{isDirty} = $hd->{needKernelReread} = 1; } $i++; } my ($first, $second, $third) = map { $_->{normal} } @{$hd->{extended} || []}; if ($third && $first eq $part) { die "Can't handle removing hda5 when hda6 is not the second partition" if $second->{start} > $third->{start}; } #- otherwise search it in extended partitions foreach (@{$hd->{extended} || []}) { $_->{normal} eq $part or next; delete $_->{normal}; #- remove it remove_empty_extended($hd); assign_device_numbers($hd); return $hd->{isDirty} = $hd->{needKernelReread} = 1; } 0; } # create of partition at starting at `start', of size `size' and of type `type' (nice comment, uh?) sub add_primary { my ($hd, $part) = @_; { local $hd->{primary}{normal}; #- save it to fake an addition of $part, that way add_primary do not modify $hd if it fails push @{$hd->{primary}{normal}}, $part; adjust_main_extended($hd); #- verify $hd->raw_add($hd->{primary}{raw}, $part); } push @{$hd->{primary}{normal}}, $part; #- really do it } sub add_extended { arch() =~ /^sparc|ppc/ and die _("Extended partition not supported on this platform"); my ($hd, $part, $extended_type) = @_; $extended_type =~ s/Extended_?//; my $e = $hd->{primary}{extended}; if ($e && !verifyInside($part, $e)) { #-die "sorry, can't add outside the main extended partition" unless $::unsafe; my $end = $e->{start} + $e->{size}; my $start = min($e->{start}, $part->{start}); $end = max($end, $part->{start} + $part->{size}) - $start; { #- faking a resizing of the main extended partition to test for problems local $e->{start} = $start; local $e->{size} = $end - $start; eval { verifyPrimary($hd->{primary}) }; $@ and die _("You have a hole in your partition table but I can't use it. The only solution is to move your primary partitions to have the hole next to the extended partitions"); } } if ($e && $part->{start} < $e->{start}) { my $l = first (@{$hd->{extended}}); #- the first is a special case, must recompute its real size $l->{start} = round_down($l->{normal}{start} - 1, $hd->cylinder_size()); $l->{size} = $l->{normal}{start} + $l->{normal}{size} - $l->{start}; my $ext = { %$l }; unshift @{$hd->{extended}}, { type => 5, raw => [ $part, $ext, {}, {} ], normal => $part, extended => $ext }; #- size will be autocalculated :) } else { my ($ext, $ext_size) = is_empty_array_ref($hd->{extended}) ? ($hd->{primary}, -1) : #- -1 size will be computed by adjust_main_extended (top(@{$hd->{extended}}), $part->{size}); my %ext = ( type => $extended_type || 5, start => $part->{start}, size => $ext_size ); $hd->raw_add($ext->{raw}, \%ext); $ext->{extended} = \%ext; push @{$hd->{extended}}, { %ext, raw => [ $part, {}, {}, {} ], normal => $part }; } $part->{start}++; $part->{size}--; #- let it start after the extended partition sector adjustStartAndEnd($hd, $part); adjust_main_extended($hd); } sub add { my ($hd, $part, $primaryOrExtended, $forceNoAdjust) = @_; get_normal_parts($hd) >= ($hd->{device} =~ /^rd/ ? 7 : $hd->{device} =~ /^(sd|ida|cciss|ataraid)/ ? 15 : 63) and cdie "maximum number of partitions handled by linux reached"; $part->{notFormatted} = 1; $part->{isFormatted} = 0; $part->{rootDevice} = $hd->{device}; $part->{start} ||= 1 if arch() !~ /^sparc/; #- starting at sector 0 is not allowed adjustStartAndEnd($hd, $part) unless $forceNoAdjust; my $e = $hd->{primary}{extended}; my $nb_primaries = $hd->{device} =~ /^rd/ ? 3 : 1; if (arch() =~ /^sparc|ppc/ || $primaryOrExtended eq 'Primary' || $primaryOrExtended !~ /Extended/ && @{$hd->{primary}{normal} || []} < $nb_primaries) { eval { add_primary($hd, $part) }; goto success if !$@; } eval { add_extended($hd, $part, $primaryOrExtended) } if $hd->hasExtended; #- try adding extended if ($@ || !$hd->hasExtended) { eval { add_primary($hd, $part) }; die $@ if $@; #- send the add extended error which should be better } success: assign_device_numbers($hd); $hd->{isDirty} = 1; push @{$hd->{needKernelReread} ||= []}, $part if !$hd->{needKernelReread} || ref($hd->{needKernelReread}) eq 'ARRAY' } # search for the next partition sub next { my ($hd, $part) = @_; first( sort { $a->{start} <=> $b->{start} } grep { $_->{start} >= $part->{start} + $part->{size} } get_normal_parts($hd) ); } sub next_start { my ($hd, $part) = @_; my $next = &next($hd, $part); $next ? $next->{start} : $hd->{totalsectors}; } sub load { my ($hd, $file, $force) = @_; local *F; open F, $file or die _("Error reading file %s", $file); my $h; { local $/ = "\0"; eval <F>; } $@ and die _("Restoring from file %s failed: %s", $file, $@); ref $h eq 'ARRAY' or die _("Bad backup file"); my %h; @h{@fields2save} = @$h; $h{totalsectors} == $hd->{totalsectors} or $force or cdie "bad totalsectors"; #- unsure we don't modify totalsectors local $hd->{totalsectors}; @{$hd}{@fields2save} = @$h; delete @$_{qw(isMounted isFormatted notFormatted toFormat toFormatUnsure)} foreach get_normal_parts($hd); $hd->{isDirty} = $hd->{needKernelReread} = 1; } sub save { my ($hd, $file) = @_; my @h = @{$hd}{@fields2save}; local *F; require Data::Dumper; open F, ">$file" and print F Data::Dumper->Dump([\@h], ['$h']), "\0" or die _("Error writing to file %s", $file); }