summaryrefslogtreecommitdiffstats
path: root/perl-install/partition_table.pm
blob: f6fe086c0184f45843122d78f54e16e52b2195e9 (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
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
package partition_table; # $Id$

use diagnostics;
use strict;

use common;
use fs::type;
use partition_table::raw;
use detect_devices;
use log;

our @fields2save = qw(primary extended totalsectors isDirty will_tell_kernel);


sub hd2minimal_part {
    my ($hd) = @_;
    { 
	rootDevice => $hd->{device}, 
	if_($hd->{usb_media_type}, is_removable => 1),
    };
}

#- works for both hard drives and partitions ;p
sub description {
    my ($hd) = @_;
    my $win = $hd->{device_windobe};

    sprintf "%s%s (%s)", 
      $hd->{device}, 
      $win && " [$win:]", 
	join(', ', 
	     grep { $_ } 
	       formatXiB($hd->{totalsectors} || $hd->{size}, 512),
	       $hd->{info}, $hd->{mntpoint}, $hd->{fs_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 compute_device_name {
    my ($part, $hd) = @_;
    $part->{device} = $hd->{prefix} . $part->{part_number};
    $part->{devfs_device} = $hd->{devfs_prefix} . '/part' . $part->{part_number};
}

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++;
	    }
	    $_->{part_number} = $i;
	    compute_device_name($_, $hd);
	    $start = $_->{start} + $_->{size};
	    $i++;
	}
    } else {
	foreach (@{$hd->{primary}{raw}}) {
	    $_->{part_number} = $i;
	    compute_device_name($_, $hd);
	    $i++;
	}
	foreach (map { $_->{normal} } @{$hd->{extended} || []}) {
	    my $dev = $hd->{prefix} . $i;
	    my $renumbered = $_->{device} && $dev ne $_->{device};
	    if ($renumbered) {
		require fs;
		eval { fs::umount_part($_) }; #- at least try to umount it
		will_tell_kernel($hd, del => $_, 'delay_del');
		push @{$hd->{partitionsRenumbered}}, [ $_->{device}, $dev ];
	    }
	    $_->{part_number} = $i;
	    compute_device_name($_, $hd);
	    if ($renumbered) {
		will_tell_kernel($hd, add => $_, 'delay_add');
	    }
	    $i++;
	}
    }

    #- 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_or_NTFS($_) } @{$hd->{primary}{normal}};

    $i = ord 'C';
    $c->{device_windobe} = chr($i++) if $c;
    $_->{device_windobe} = chr($i++) foreach grep { isFat_or_NTFS($_) } 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 &&= isTrueLocalFS($_) || isSwap($_);
	    $has_win_lba ||= $_->{pt_type} == 0xc || $_->{pt_type} == 0xe;
	}
	$l->{start} = $hd->{primary}{extended}{start} = $start;
	$l->{size} = $hd->{primary}{extended}{size} = $end - $start;
    }
    if (!@{$hd->{extended} || []} && $hd->{primary}{extended}) {
	will_tell_kernel($hd, del => $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) = @_;

    my $extended = find { $_->{normal} == $part } @{$hd->{extended} || []} or return;
    $extended->{size} = $part->{size} + $part->{start} - $extended->{start};

    #- must write it there too because values are not shared
    my $prev = find { $_->{extended}{start} == $extended->{start} } @{$hd->{extended} || []} or return;
    $prev->{extended}{size} = $part->{size} + $part->{start} - $prev->{extended}{start};
}

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 $minimal_hole = put_in_hash({ pt_type => 0 }, hd2minimal_part($hd));

    my @l = map {
	my $current = $start;
	$start = $_->{start} + $_->{size};
	my $hole = { start => $current, size => $_->{start} - $current, %$minimal_hole };
	put_in_hash($hole, hd2minimal_part($hd));
	$hole, $_;
    } sort { $a->{start} <=> $b->{start} } grep { !isWholedisk($_) } get_normal_parts($hd);

    push @l, { start => $start, size => $last - $start, %$minimal_hole };
    grep { !isEmpty($_) || $_->{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') : ('dos', 'bsd', 'sun', 'mac'),
	);
	foreach ('empty', @parttype, 'unknown') {
	    /unknown/ and die "unknown partition table format on disk " . $hd->{file};
	    eval {
		# perl_checker: require partition_table::bsd
		# perl_checker: require partition_table::dos
		# perl_checker: require partition_table::empty
		# perl_checker: require partition_table::gpt
		# perl_checker: require partition_table::mac
		# perl_checker: require partition_table::sun
		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} && !isEmpty($_) && !isExtended($_) } @$pt;
    my $nb_special_empty = int(grep { $_->{size} && isEmpty($_) } @$pt);

    @extended > 1 and die "more than one extended partition";

    put_in_hash($_, hd2minimal_part($hd)) foreach @normal, @extended;
    { raw => $pt, extended => $extended[0], normal => \@normal, info => $info, nb_special_empty => $nb_special_empty };
}

sub read {
    my ($hd) = @_;
    my $pt = read_one($hd, 0) or return 0;
    $hd->{primary} = $pt;
    undef $hd->{extended};
    verifyPrimary($pt);
    eval {
	my $need_removing_empty_extended;
	if ($pt->{extended}) {
	    read_extended($hd, $pt->{extended}, \$need_removing_empty_extended) or 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);

    $hd->set_best_geometry_for_the_partition_table;
    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;
    }
}

sub will_tell_kernel {
    my ($hd, $action, $o_part, $o_delay) = @_;

    if ($action eq 'resize') {
	will_tell_kernel($hd, del => $o_part);
	will_tell_kernel($hd, add => $o_part);
    } else {
	my $part_number;
	if ($o_part) {
	    ($part_number) = $o_part->{device} =~ /(\d+)$/ or
	      #- do not die, it occurs when we zero_MBR_and_dirty a raw_lvm_PV
	      log::l("ERROR: will_tell_kernel bad device " . description($o_part)), return;
	}

	my @para =
	  $action eq 'force_reboot' ? () :
	  $action eq 'add' ? ($part_number, $o_part->{start}, $o_part->{size}) :
	  $action eq 'del' ? $part_number :
	  internal_error("unknown action $action");

	push @{$hd->{'will_tell_kernel' . ($o_delay || '')} ||= []}, [ $action, @para ];
    }
    if (!$o_delay) {
	foreach my $delay ('delay_del', 'delay_add') {
	    my $l = delete $hd->{"will_tell_kernel$delay"} or next;
	    push @{$hd->{will_tell_kernel} ||= []}, @$l;
	}
    }
    $hd->{isDirty} = 1;
}

sub tell_kernel {
    my ($hd, $tell_kernel) = @_;

    my $F = partition_table::raw::openit($hd);

    my $force_reboot = any { $_->[0] eq 'force_reboot' } @$tell_kernel;
    if (!$force_reboot) {
	foreach (@$tell_kernel) {
	    my ($action, $part_number, $o_start, $o_size) = @$_;
	    
	    if ($action eq 'add') {
		$force_reboot ||= !c::add_partition(fileno $F, $part_number, $o_start, $o_size);
	    } elsif ($action eq 'del') {
		$force_reboot ||= !c::del_partition(fileno $F, $part_number);
	    }
	    log::l("tell kernel $action ($hd->{device} $part_number $o_start $o_size), rebootNeeded is now " . bool2text($hd->{rebootNeeded}));
	}
    }
    if ($force_reboot) {
	my @magic_parts = grep { $_->{isMounted} && $_->{real_mntpoint} } get_normal_parts($hd);
	foreach (@magic_parts) {
	    syscall_('umount', $_->{real_mntpoint}) or log::l(N("error unmounting %s: %s", $_->{real_mntpoint}, $!));
	}
	$hd->{rebootNeeded} = !ioctl($F, c::BLKRRPART(), 0);
	log::l("tell kernel force_reboot ($hd->{device}), rebootNeeded is now $hd->{rebootNeeded}.");

	foreach (@magic_parts) {
	    syscall_('mount', $_->{real_mntpoint}, $_->{fs_type}, c::MS_MGC_VAL()) or log::l(N("mount failed: ") . $!);
	}
    }
}

# write the partition table
sub write {
    my ($hd) = @_;
    $hd->{isDirty} or return;
    $hd->{readonly} and die "a read-only partition table should not be dirty!";

    #- 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 !any { $_->{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 (my $tell_kernel = delete $hd->{will_tell_kernel}) {
	tell_kernel($hd, $tell_kernel);
    }
}

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) {
	    will_tell_kernel($hd, del => $_);

	    splice(@{$hd->{primary}{normal}}, $i, 1);
	    %$_ = (); #- blank it

	    $hd->raw_removed($hd->{primary}{raw});
	    return 1;
	}
	$i++;
    }

    my ($first, $second, $third) = map { $_->{normal} } @{$hd->{extended} || []};
    if ($third && $first eq $part) {
	die "Can not 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);

	will_tell_kernel($hd, del => $part);
	return 1;
    }
    0;
}

# create of partition at starting at `start', of size `size' and of type `pt_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 N("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 not 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
N("You have a hole in your partition table but I can not 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}}, { pt_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 = (pt_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, $b_primaryOrExtended, $b_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";

    set_isFormatted($part, 0);
    put_in_hash($part, hd2minimal_part($hd));
    $part->{start} ||= 1 if arch() !~ /^sparc/; #- starting at sector 0 is not allowed
    adjustStartAndEnd($hd, $part) unless $b_forceNoAdjust;

    my $nb_primaries = $hd->{device} =~ /^rd/ ? 3 : 1;

    if (arch() =~ /^sparc|ppc/ ||
	$b_primaryOrExtended eq 'Primary' ||
	$b_primaryOrExtended !~ /Extended/ && @{$hd->{primary}{normal} || []} < $nb_primaries) {
	eval { add_primary($hd, $part) };
	goto success if !$@;
    }
    if ($hd->hasExtended) {
	eval { add_extended($hd, $part, $b_primaryOrExtended) };
	goto success if !$@;
    }
    {
	add_primary($hd, $part);
    }
  success:
    assign_device_numbers($hd);
    will_tell_kernel($hd, add => $part);
}

# 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, $b_force) = @_;

    my $F;
    if (ref $file) {
	$F = $file;
    } else {
	open($F, $file) or die N("Error reading file %s", $file);
    }

    my $h;
    {
	local $/ = "\0";
	eval <$F>;
    }
    $@ and die N("Restoring from file %s failed: %s", $file, $@);

    ref($h) eq 'ARRAY' or die N("Bad backup file");

    my %h; @h{@fields2save} = @$h;

    $h{totalsectors} == $hd->{totalsectors} or $b_force or cdie "bad totalsectors";

    #- unsure we do not modify totalsectors
    local $hd->{totalsectors};

    @$hd{@fields2save} = @$h;

    delete @$_{qw(isMounted isFormatted notFormatted toFormat toFormatUnsure)} foreach get_normal_parts($hd);
    will_tell_kernel($hd, 'force_reboot'); #- just like undo, do not force write_partitions so that user can see the new partition table but can still discard it
}

sub save {
    my ($hd, $file) = @_;
    my @h = @$hd{@fields2save};
    require Data::Dumper;
    eval { output($file, Data::Dumper->Dump([\@h], ['$h']), "\0") }
      or die N("Error writing to file %s", $file);
}

1;
span class="hl kwa">sub getXenBlk() { -d '/sys/bus/xen/devices' or return; map { s/block://; { device => basename($_), info => "Xen block device", media_type => 'hd', bus => 'xen' }; } glob("/sys/block/xvd*"); } =item getVirtIO() Returns a list of all VirtIO block devices (/dev/C<vd*>). =cut sub getVirtIO() { -d '/sys/bus/virtio/devices' or return; map { { device => basename($_), info => "VirtIO block device", media_type => 'hd', bus => 'virtio' }; } glob("/sys/bus/virtio/devices/*/block/*"); } sub getMmcBlk() { -d '/sys/bus/mmc/devices' or return; map { { device => basename($_), info => "MMC block device", media_type => 'hd', bus => 'mmc' }; } glob("/sys/bus/mmc/devices/*/block/*"); } =item getCPUs() Returns a list of all CPUs. =cut sub getCPUs() { my (@cpus, $cpu); foreach (cat_("/proc/cpuinfo")) { if (/^processor/) { # ix86 specific push @cpus, $cpu if $cpu; $cpu = {}; } $cpu->{$1} = $2 if /^([^\t]+).*:\s(.*)$/; $cpu->{processor}++ if $1 eq "processor"; } push @cpus, $cpu; @cpus; } sub ix86_cpu_frequency() { cat_('/proc/cpuinfo') =~ /cpu MHz\s*:\s*(\d+)/ && $1; } =item probe_category($category) Returns a list of devices which drivers are in the asked category. eg: my @eth_cards = probe_category('network/ethernet'); =cut sub probe_category { my ($category) = @_; require list_modules; my @modules = list_modules::category2modules($category); grep { if ($category eq 'network/isdn') { my $b = $_->{driver} =~ /ISDN:([^,]*),?([^,]*)(?:,firmware=(.*))?/; if ($b) { $_->{driver} = $1; $_->{type} = $2; $_->{type} =~ s/type=//; $_->{firmware} = $3; $_->{driver} eq "hisax" and $_->{options} .= " id=HiSax"; } $b; } else { member($_->{driver}, @modules); } } probeall(); } sub getSoundDevices() { probe_category('multimedia/sound'); } sub isTVcardConfigurable { member($_[0]{driver}, qw(bttv cx88 saa7134)) } sub getTVcards() { probe_category('multimedia/tv') } sub getInputDevices() { my (@devices, $device); my $event; foreach (cat_('/proc/bus/input/devices')) { if (/^I:/) { $device = {}; $device->{vendor} = /Vendor=(\w+)/ && $1; $device->{id} = /Product=(\w+)/ && $1; $device->{bustype} = /Bus=(\w+)/ && $1; } elsif (/N: Name="(.*)"/) { my $descr = $1; $device->{description} = "|$descr"; #- I: Bus=0011 Vendor=0002 Product=0008 Version=7321 #- N: Name="AlpsPS/2 ALPS GlidePoint" #- P: Phys=isa0060/serio1/input0 #- H: Handlers=mouse1 event2 ts1 #- B: EV=f #- B: KEY=420 0 70000 0 0 0 0 0 0 0 0 #=> BTN_LEFT BTN_RIGHT BTN_MIDDLE BTN_TOOL_FINGER BTN_TOUCH #- or B: KEY=420 0 670000 0 0 0 0 0 0 0 0 #=> same with BTN_BACK #- B: REL=3 #=> X Y #- B: ABS=1000003 #=> X Y PRESSURE #- I: Bus=0011 Vendor=0002 Product=0008 Version=2222 #- N: Name="AlpsPS/2 ALPS DualPoint TouchPad" #- P: Phys=isa0060/serio1/input0 #- S: Sysfs=/class/input/input2 #- H: Handlers=mouse1 ts1 event2 #- B: EV=f #- B: KEY=420 0 70000 0 0 0 0 0 0 0 0 #- B: REL=3 #- B: ABS=1000003 #- I: Bus=0011 Vendor=0002 Product=0007 Version=0000 #- N: Name="SynPS/2 Synaptics TouchPad" #- P: Phys=isa0060/serio1/input0 #- S: Sysfs=/class/input/input1 #- H: Handlers=mouse0 event1 ts0 #- B: EV=b #- B: KEY=6420 0 70000 0 0 0 0 0 0 0 0 #=> BTN_LEFT BTN_RIGHT BTN_MIDDLE BTN_TOOL_FINGER BTN_TOUCH BTN_TOOL_DOUBLETAP BTN_TOOL_TRIPLETAP #- or B: KEY=6420 0 670000 0 0 0 0 0 0 0 0 #=> same with BTN_BACK #- or B: KEY=420 30000 670000 0 0 0 0 0 0 0 0 #=> same without BTN_TOOL_TRIPLETAP but with BTN_B #- B: ABS=11000003 #=> X Y PRESSURE TOOL_WIDTH #- I: Bus=0003 Vendor=056a Product=0065 Version=0108 #- N: Name="Wacom Bamboo" #- B: KEY=1c63 0 70033 0 0 0 0 0 0 0 0 #=> BTN_0 BTN_1 BTN_4 BTN_5 BTN_LEFT BTN_RIGHT BTN_MIDDLE TOOL_PEN TOOL_RUBBER TOOL_BRUSH TOOL_FINGER TOOL_MOUSE TOUCH STYLUS STYLUS2 #- B: ABS=100 3000103 #=> X Y WHEEL PRESSURE DISTANCE MISC #- I: Bus=0003 Vendor=056a Product=0011 Version=0201 #- N: Name="Wacom Graphire2 4x5" #- B: KEY=1c43 0 70000 0 0 0 0 0 0 0 0 #=> BTN_LEFT BTN_RIGHT BTN_MIDDLE TOOL_PEN TOOL_RUBBER TOOL_FINGER TOOL_MOUSE TOUCH STYLUS STYLUS2 #- B: ABS=100 3000003 #=> X Y PRESSURE DISTANCE MISC #I: Bus=0003 Vendor=049f Product=0024 Version=0001 #N: Name="Compaq Compaq Numeric Keypad" #P: Phys=usb-0000:00:03.2-2/input0 #S: Sysfs=/class/input/input7 #H: Handlers=kbd event3 #B: EV=120003 #B: KEY=10000 7 ff800000 7ff febeffdf ffefffff ffffffff fffffffe #B: LED=1f $device->{Synaptics} = $descr eq 'SynPS/2 Synaptics TouchPad'; $device->{ALPS} = $descr =~ m!^AlpsPS/2 ALPS!; $device->{Elantech} = $descr eq 'ETPS/2 Elantech Touchpad'; $device->{Numpad} = $descr =~ /Numeric Keypad/; } elsif (/H: Handlers=(.*)/) { my @l = split(' ', $1); $device->{driver} = $l[0]; #- keep it for compatibility $device->{Handlers} = +{ map { (/^(.*?)\d*$/ ? $1 : $_, $_) } split(' ', $1) }; $event = $device->{Handlers}{event}; } elsif (/S: Sysfs=(.+)/) { $device->{sysfs_path} = $1; } elsif (/P: Phys=(.*)/) { $device->{location} = $1; $device->{bus} = 'isa' if $device->{location} =~ /^isa/; $device->{bus} = 'usb' if $device->{location} =~ /^usb/i; } elsif (/B: REL=(.* )?(.*)/) { #- REL=3 #=> X Y #- REL=103 #=> X Y WHEEL #- REL=143 #=> X Y HWHEEL WHEEL #- REL=1c3 #=> X Y HWHEEL DIAL WHEEL my $REL = hex($2); $device->{HWHEEL} = 1 if $REL & (1 << 6); $device->{WHEEL} = 1 if $REL & (1 << 8); #- not reliable ("Mitsumi Apple USB Mouse" says REL=103 and KEY=1f0000 ...) } elsif (/B: KEY=(\S+)/) { #- some KEY explained: #- (but note that BTN_MIDDLE can be reported even if missing) #- (and "Mitsumi Apple USB Mouse" reports 1f0000) #- KEY=30000 0 0 0 0 0 0 0 0 #=> BTN_LEFT BTN_RIGHT #- KEY=70000 0 0 0 0 0 0 0 0 #=> BTN_LEFT BTN_RIGHT BTN_MIDDLE #- KEY=1f0000 0 0 0 0 0 0 0 0 #=> BTN_LEFT BTN_RIGHT BTN_MIDDLE BTN_SIDE BTN_EXTRA if (!$> && ! -f "/dev/input/$event") { devices::make("/dev/input/$event"); } if (-r "/dev/input/$event") { my @KEYS = c::EVIocGBitKey("/dev/input/$event"); $device->{SIDE} = 1 if $KEYS[0] & (1 << 0x13); } else { my $KEY = hex($1); $device->{SIDE} = 1 if $KEY & (1 << 0x13); } } elsif (/^\s*$/) { push @devices, $device if $device; undef $device; } } @devices; } sub getInputDevices_and_usb() { my @l = getInputDevices(); foreach my $usb (usb_probe()) { if (my $e = find { hex($_->{vendor}) == $usb->{vendor} && hex($_->{id}) == $usb->{id} } @l) { $e->{usb} = $usb; } } @l; } sub serialPorts() { map { "ttyS$_" } 0..7 } sub serialPort2text { $_[0] =~ /ttyS(\d+)/ ? "$_[0] / COM" . ($1 + 1) : $_[0]; } =back =head1 Network =over =cut sub getSerialModem { my ($modules_conf, $o_mouse) = @_; my $mouse = $o_mouse || {}; $mouse->{device} = readlink "/dev/mouse"; my $serdev = arch() =~ /mips/ ? "8250" : "serial"; eval { modules::load($serdev) }; my @modems; probeSerialDevices(); foreach my $port (serialPorts()) { next if $mouse->{device} =~ /$port/; my $device = "/dev/$port"; next if !-e $device || !hasModem($device); $serialprobe{$device}{device} = $device; push @modems, $serialprobe{$device}; } my @devs = pcmcia_probe(); foreach my $modem (@modems) { foreach (@devs) { $_->{device} and $modem->{device} = $_->{device} } } @modems; } =item getModem() Return list of modems (serial, WinModems) =cut our $detect_serial_modem = 1; sub getModem { my ($modules_conf) = @_; ($detect_serial_modem ? getSerialModem($modules_conf, {}) : ()), get_winmodems(); } sub get_winmodems() { matching_driver__regexp('www\.linmodems\.org'), matching_driver(list_modules::category2modules('network/modem'), list_modules::category2modules('network/slmodem')); } sub getBewan() { matching_desc__regexp('Bewan Systems\|.*ADSL|BEWAN ADSL USB|\[Unicorn\]'); } # generate from the following from eci driver sources: # perl -e 'while (<>) { print qq("$1$2",\n"$3$4",\n) if /\b([a-z\d]*)\s*([a-z\d]*)\s*([a-z\d]*)\s*([a-z\d]*)$/ }' <modems.db|sort|uniq sub getECI() { my @ids = ( "05090801", "05472131", "06590915", "071dac81", "08ea00c9", "09150001", "09150002", "091500ca", "091500e7", "09150101", "09150102", "09150204", "09150206", "09150802", "09150916", "09158000", "09158001", "0915ac82", "0baf00e6", "0e600100", "0e600101", "0fe88000", "16900203", "16900205", ); grep { member(sprintf("%04x%04x%04x%04x", $_->{vendor}, $_->{id}, $_->{subvendor}, $_->{subid}), @ids) } usb_probe(); } =item get_xdsl_usb_devices() Return list of xDSL devices. =cut sub get_xdsl_usb_devices() { my @bewan = detect_devices::getBewan(); $_->{driver} = $_->{bus} eq 'USB' ? 'unicorn_usb_atm' : 'unicorn_pci_atm' foreach @bewan; my @eci = detect_devices::getECI(); $_->{driver} = 'eciusb' foreach @eci; my @usb = detect_devices::probe_category('network/usb_dsl'); $_->{description} = "USB ADSL modem (eagle chipset)" foreach grep { $_->{driver} eq 'ueagle_atm' && $_->{description} eq '(null)' } @usb; @usb, @bewan, @eci; } =item is_lan_interface($device) Is it a LAN interface (blacklist some interfaces (PPP, ...)? =cut sub is_lan_interface { #- we want LAN like interfaces here (eg: ath|br|eth|fddi|plip|ra|tr|usb|wlan). #- there's also bnep%d for bluetooth, bcp%d... #- we do this by blacklisting the following interfaces: #- hso%d are created by drivers/net/usb/hso.c #- ippp|isdn|plip|ppp (initscripts suggest that isdn%d can be created but kernel sources claim not) #- ippp%d are created by drivers/isdn/i4l/isdn_ppp.c #- plip%d are created by drivers/net/plip.c #- ppp%d are created by drivers/net/ppp_generic.c #- pan%d are created by bnep is_useful_interface($_[0]) && $_[0] !~ /^(?:hso|ippp|isdn|plip|ppp|pan)/; } =item is_useful_interface($device) Is it a usefull interface (blacklist some interfaces (loopback, sit, wifi, ...)? =cut sub is_useful_interface { #- sit0 which is *always* created by net/ipv6/sit.c, thus is always created since net.agent loads ipv6 module #- wifi%d are created by 3rdparty/hostap/hostap_hw.c (pseudo statistics devices, #14523) #- wmaster%d are created by net/mac80211/ieee80211.c ("master" 802.11 device) #- ax*, rose*, nr*, bce* and scc* are Hamradio devices (#28776) $_[0] !~ /^(?:lo|sit0|wifi|wmaster|ax|rose|nr|bce|scc)/; } =item is_wireless_interface($device) Is it a WiFi interface? =cut sub is_wireless_interface { my ($interface) = @_; #- some wireless drivers don't always support the SIOCGIWNAME ioctl #- ralink devices need to be up to support it #- wlan-ng (prism2_*) need some special tweaks to support it #- use sysfs as fallback to detect wireless interfaces, #- i.e interfaces for which get_wireless_stats() is available c::isNetDeviceWirelessAware($interface) || -e "/sys/class/net/$interface/wireless" || -e "/sys/class/net/$interface/phy80211"; } =item get_all_net_devices() Returns list of all network devices =cut sub get_all_net_devices() { #- we need both detection schemes since: #- get_netdevices() use the SIOCGIFCONF ioctl that does not list interfaces that are down #- /proc/net/dev does not list VLAN and IP aliased interfaces uniq( (map { if_(/^\s*([A-Za-z0-9:\.]*):/, $1) } cat_("/proc/net/dev")), c::get_netdevices(), ); } =item get_lan_interfaces() Returns list of all LAN devices =cut sub get_lan_interfaces() { grep { is_lan_interface($_) } get_all_net_devices() } =item get_net_interfaces() Returns list of all useful network devices =cut sub get_net_interfaces() { grep { is_useful_interface($_) } get_all_net_devices() } =item get_wireless_interface() Returns list of all Wireless devices =cut sub get_wireless_interface() { find { is_wireless_interface($_) } get_lan_interfaces() } =item is_bridge_interface($interface) Is it a bridge? =cut sub is_bridge_interface { my ($interface) = @_; -f "/sys/class/net/$interface/bridge/bridge_id"; } =back =head1 Enumerating devices =over =cut sub get_ids_from_sysfs_device { my ($dev_path) = @_; my $dev_cat = sub { chomp_(cat_("$dev_path/$_[0]")) }; my $usb_root = -f "$dev_path/bInterfaceNumber" && "../" || -f "$dev_path/idVendor" && ""; my $is_pcmcia = -f "$dev_path/card_id"; my $sysfs_ids; my $bus = get_sysfs_field_from_link($dev_path, "subsystem"); #- FIXME: use $bus if ($is_pcmcia) { $sysfs_ids = { modalias => $dev_cat->('modalias') }; } else { $sysfs_ids = $bus eq 'ieee1394' ? { version => "../vendor_id", specifier_id => "specifier_id", specifier_version => "version", } : defined $usb_root ? { id => $usb_root . 'idProduct', vendor => $usb_root . 'idVendor' } : { id => "device", subid => "subsystem_device", vendor => "vendor", subvendor => "subsystem_vendor" }; $_ = hex($dev_cat->($_)) foreach values %$sysfs_ids; if ($bus eq 'pci') { my $device = basename(readlink $dev_path); my @ids = $device =~ /^(.{4}):(.{2}):(.{2})\.(.+)$/; @$sysfs_ids{qw(pci_domain pci_bus pci_device pci_function)} = map { hex($_) } @ids if @ids; } } $sysfs_ids; } sub device_matches_sysfs_ids { my ($device, $sysfs_ids) = @_; every { defined $device->{$_} && member($device->{$_}, $sysfs_ids->{$_}, 0xffff) } keys %$sysfs_ids; } sub device_matches_sysfs_device { my ($device, $dev_path) = @_; device_matches_sysfs_ids($device, get_ids_from_sysfs_device($dev_path)); } sub getUPS() { # MGE serial PnP devices: (map { $_->{port} = $_->{DEVICE}; $_->{bus} = "Serial"; $_->{driver} = "mge-utalk" if $_->{MODEL} =~ /0001/; $_->{driver} = "mge-shut" if $_->{MODEL} =~ /0002/; $_->{media_type} = 'UPS'; $_->{description} = "MGE UPS SYSTEMS|UPS - Uninterruptible Power Supply" if $_->{MODEL} =~ /000[12]/; $_; } grep { $_->{DESCRIPTION} =~ /MGE UPS/ } values %serialprobe), # USB UPSs; (map { ($_->{name} = $_->{description}) =~ s/.*\|//; $_ } map { if ($_->{description} =~ /Back-UPS/ && $_->{driver} eq 'usbhid') { #- FIXME: should not be hardcoded, use $_->{sysfs_device} . */usb:(hiddev\d+) #- the device should also be assigned to the ups user $_->{port} = "/dev/hiddev0"; $_->{driver} = 'hidups'; $_; } elsif ($_->{description} =~ /^MGE UPS Systems\|/ && $_->{driver} =~ /ups$/) { $_->{port} = "auto"; $_->{media_type} = 'UPS'; $_->{driver} = 'newhidups'; $_; } else { (); } } usb_probe()); } $pcitable_addons = <<'EOF'; # add here lines conforming the pcitable format (0xXXXX\t0xXXXX\t"\w+"\t".*") EOF $usbtable_addons = <<'EOF'; # add here lines conforming the usbtable format (0xXXXX\t0xXXXX\t"\w+"\t".*") EOF sub install_addons { my ($prefix) = @_; #- this test means install_addons can only be called after ldetect-lst has been installed. if (-d "$prefix/usr/share/ldetect-lst") { my $update = 0; foreach ([ 'pcitable.d', $pcitable_addons ], [ 'usbtable.d', $usbtable_addons ]) { my ($dir, $str) = @$_; -d "$prefix/usr/share/ldetect-lst/$dir" && $str =~ /^[^#]/m and $update = 1 and output "$prefix/usr/share/ldetect-lst/$dir/95drakx.lst", $str; } $update and run_program::rooted($prefix, "/usr/sbin/update-ldetect-lst"); } } sub add_addons { my ($addons, @l) = @_; foreach (split "\n", $addons) { /^\s/ and die qq(bad detect_devices::probeall_addons line "$_"); s/^#.*//; s/"(.*?)"/$1/g; next if /^$/; my ($vendor, $id, $driver, $description) = split("\t", $_, 4) or die qq(bad detect_devices::probeall_addons line "$_"); foreach (@l) { $_->{vendor} == hex $vendor && $_->{id} == hex $id or next; put_in_hash($_, { driver => $driver, description => $description }); } } @l; } sub get_pci_sysfs_path { my ($l) = @_; sprintf('%04x:%02x:%02x.%d', $l->{pci_domain}, $l->{pci_bus}, $l->{pci_device}, $l->{pci_function}); } my (@pci, @usb); sub pci_probe__real() { add_addons($pcitable_addons, map { my $l = $_; $l->{bus} = 'PCI'; $l->{sysfs_device} = '/sys/bus/pci/devices/' . get_pci_sysfs_path($l); $l; } c::pci_probe()); } =item pci_probe() Cache the result of C<c::pci_probe()> and return the list of items in the PCI devices. =cut sub pci_probe() { state $done; if (!$done) { @pci = pci_probe__real() if !@pci; foreach (@pci) { $_->{nice_bus} = $_->{is_pciexpress} ? "PCI Express" : "PCI"; } } @pci; } sub usb_probe__real() { -e "/sys/kernel/debug/usb/devices" or return; add_addons($usbtable_addons, map { my $l = $_; $l->{media_type} = join('|', grep { $_ ne '(null)' } split('\|', $l->{media_type})); $l->{sysfs_device} = "/sys/bus/usb/devices/$l->{pci_bus}-" . ($l->{usb_port} + 1); $l->{bus} = 'USB'; $l; } c::usb_probe()); } =item usb_probe() Cache the result of C<c::usb_probe()> and return the list of items in the USB devices. =cut sub usb_probe() { if ($::isStandalone && @usb) { @usb; } else { @usb = usb_probe__real(); } } =item firewire_probe() Return list of Firewire controllers =cut sub firewire_probe() { my $dev_dir = '/sys/bus/ieee1394/devices'; my @l = map { my $dir = "$dev_dir/$_"; my $get = sub { chomp_(cat_($_[0])) }; { version => hex($get->("$dir/../vendor_id")), specifier_id => hex($get->("$dir/specifier_id")), specifier_version => hex($get->("$dir/version")), bus => 'Firewire', sysfs_device => $dir, }; } grep { -f "$dev_dir/$_/specifier_id" } all($dev_dir); my $e; foreach (cat_('/proc/bus/ieee1394/devices')) { if (m!Vendor/Model ID: (.*) \[(\w+)\] / (.*) \[(\w+)\]!) { push @l, $e = { vendor => hex($2), id => hex($4), description => join('|', $1, $3), bus => 'Firewire', }; } elsif (/Software Specifier ID: (\w+)/) { $e->{specifier_id} = hex $1; } elsif (/Software Version: (\w+)/) { $e->{specifier_version} = hex $1; } } foreach (@l) { if ($_->{specifier_id} == 0x00609e && $_->{specifier_version} == 0x010483) { add2hash($_, { driver => 'sbp2', description => "Generic Firewire Storage Controller" }); } elsif ($_->{specifier_id} == 0x00005e && $_->{specifier_version} == 0x000001) { add2hash($_, { driver => 'eth1394', description => "IEEE 1394 IPv4 Driver (IPv4-over-1394 as per RFC 2734)" }); } } @l; } =item pcmcia_controller_probe() Return list of PCMCIA controllers =cut sub pcmcia_controller_probe() { my ($controller) = probe_category('bus/pcmcia'); if (!$controller && !$::testing && !$::noauto && arch() =~ /i.86/) { my $driver = c::pcmcia_probe(); $controller = { driver => $driver, description => "PCMCIA controller ($driver)" } if $driver; } $controller; } =item pcmcia_probe() Return list of PCMCIA devices (eg: Ethernet PCMCIA cards, ...) =cut sub pcmcia_probe() { require modalias; require modules; my $dev_dir = '/sys/bus/pcmcia/devices'; map { my $dir = "$dev_dir/$_"; my $get = sub { chomp_(cat_("$dir/$_[0]")) }; my $class_dev = first(glob_("$dir/tty/tty*")); my $device = $class_dev && basename($class_dev); my $modalias = $get->('modalias'); my $driver = get_sysfs_field_from_link($dir, 'driver'); #- fallback on modalias result #- but only if the module isn't loaded yet (else, it would already be binded) #- this prevents from guessing the wrong driver for multi-function devices my $module = $modalias && first(modalias::get_modules($modalias)); $driver ||= !member($module, modules::loaded_modules()) && $module; { description => join(' ', grep { $_ } map { $get->("prod_id$_") } 1 .. 4), driver => $driver, if_($modalias, modalias => $modalias), if_($device, device => $device), bus => 'PCMCIA', sysfs_device => $dir, }; } all($dev_dir); } =item dmi_probe() Cache the result of c::dmi_probe() (aka C<dmidecode>) and return the list of items in the DMI table =cut sub dmi_probe() { state $dmi_probe; if (arch() !~ /86/) { return []; } $dmi_probe ||= $> ? [] : [ c::dmi_probe() ]; @$dmi_probe; } =item probeall() Returns a list of all PCI/USB/Firewire/PCMCIA/DMI/HID devices. It's usually called through a higher level filtering function. =cut # pcmcia_probe provides field "device", used in network.pm # => probeall with $probe_type is unsafe sub probeall() { return if $::noauto; pci_probe(), usb_probe(), firewire_probe(), pcmcia_probe(), dmi_probe(), getInputDevices_and_usb(); } sub probeall_update_cache() { return if $::noauto; @pci = pci_probe__real(), @usb = usb_probe__real(), firewire_probe(), pcmcia_probe(), dmi_probe(); } sub matching_desc__regexp { my ($regexp) = @_; grep { $_->{description} =~ /$regexp/i } probeall(); } sub matching_driver__regexp { my ($regexp) = @_; grep { $_->{driver} =~ /$regexp/i } probeall(); } sub matching_driver { my (@list) = @_; grep { member($_->{driver}, @list) } probeall(); } sub probe_name { my ($name) = @_; map { $_->{driver} =~ /^$name:(.*)/ } probeall(); } sub probe_unique_name { my ($name) = @_; my @l = uniq(probe_name($name)); if (@l > 1) { log::l("oops, more than one $name from probe: ", join(' ', @l)); } $l[0]; } sub stringlist { my ($b_verbose) = @_; map { my $ids = $b_verbose || $_->{description} eq '(null)' ? sprintf("vendor:%04x device:%04x", $_->{vendor}, $_->{id}) : ''; my $subids = $_->{subid} && $_->{subid} != 0xffff ? sprintf("subv:%04x subd:%04x", $_->{subvendor}, $_->{subid}) : ''; sprintf("%-16s: %s%s%s", $_->{driver} || 'unknown', $_->{description}, $_->{media_type} ? sprintf(" [%s]", $_->{media_type}) : '', $ids || $subids ? " ($ids" . ($ids && $subids && " ") . "$subids)" : '', ); } probeall(); } sub tryOpen($) { my $F; sysopen($F, devices::make($_[0]), c::O_NONBLOCK()) && $F; } sub tryWrite($) { my $F; sysopen($F, devices::make($_[0]), 1 | c::O_NONBLOCK()) && $F; } my @dmesg; sub syslog() { if (-r "/tmp/syslog") { map { /<\d+>(.*)/ } cat_("/tmp/syslog"); } else { @dmesg = `/bin/dmesg` if !@dmesg; @dmesg; } } sub get_mac_model() { my $mac_model = cat_("/proc/device-tree/model") || die "Cannot open /proc/device-tree/model"; log::l("Mac model: $mac_model"); $mac_model; } sub get_mac_generation() { cat_('/proc/cpuinfo') =~ /^pmac-generation\s*:\s*(.*)/m ? $1 : "Unknown Generation"; } sub hasSMP() { return if $::testing; (any { /NR_CPUS limit of 1 reached/ } syslog()) || (any { /^processor\s*:\s*(\d+)/ && $1 > 0 } cat_('/proc/cpuinfo')) || any { /\bProcessor #(\d+)\s+(\S*)/ && $1 > 0 && $2 ne 'invalid' } syslog(); } sub hasPCMCIA() { $::o->{pcmcia} } my (@dmis, $dmidecode_already_runned); =item dmidecode() Return list of DMI categories from DMI table =cut # we return a list b/c several DMIs have the same name: sub dmidecode() { return @dmis if $dmidecode_already_runned; return if $>; my ($ver, @l) = arch() =~ /86/ ? run_program::get_stdout('dmidecode') : (); my $tab = "\t"; my ($major, $minor) = $ver =~ /(\d+)\.(\d+)/; if ($major > 2 || $major == 2 && $minor > 7) { #- new dmidecode output is less indented $tab = ''; #- drop header shift @l while @l && $l[0] ne "\n"; } foreach (@l) { next if /TRUNCATED/; if (/^$tab\t(.*)/) { $dmis[-1]{string} .= "$1\n"; $dmis[-1]{$1} = $2 if /^$tab\t(.*): (.*)$/; } elsif (my ($s) = /^$tab(.*)/) { next if $s =~ /^$/ || $s =~ /\bDMI type \d+/; $s =~ s/ Information$//; push @dmis, { name => $s }; } } $dmidecode_already_runned = 1; @dmis; } =item dmi_detect_memory($category) Return only one category from DMI table =cut sub dmidecode_category { my ($cat) = @_; my @l = grep { $_->{name} eq $cat } dmidecode(); wantarray() ? @l : $l[0] || {}; } =item dmi_detect_memory() Return RAM size in MB according to DMI table =cut sub dmi_detect_memory() { my @l1 = map { $_->{'Enabled Size'} =~ /(\d+) MB/ && $1 } dmidecode_category('Memory Module'); my @l2 = map { $_->{'Form Factor'} =~ /^(SIMM|SIP|DIP|DIMM|FB-DIMM|RIMM|SODIMM|SRIMM)$/ && ($_->{Size} =~ /(\d+) MB/ && $1 || $_->{Size} =~ /(\d+) kB/ && $1 * 1024); } dmidecode_category('Memory Device'); max(sum(@l1), sum(@l2)); } =back =head1 Test helpers =over =item computer_info() Analyse "Chassis" & "Bios" in dmidecode output and return a hash of flags/values (isLaptop, isServer, BIOS_Year) =cut sub computer_info() { my $Chassis = dmidecode_category('Chassis')->{Type} =~ /(\S+)/ && $1; my $date = dmidecode_category('BIOS')->{'Release Date'} || ''; my $BIOS_Year = $date =~ m!(\d{4})! && $1 || $date =~ m!\d\d/\d\d/(\d\d)! && "20$1"; +{ isLaptop => member($Chassis, 'Portable', 'Laptop', 'Notebook', 'Hand Held', 'Sub Notebook', 'Docking Station'), isServer => member($Chassis, 'Pizza Box', 'Main Server Chassis', 'Rack Mount Chassis', 'Blade'), if_($BIOS_Year, BIOS_Year => $BIOS_Year), }; } =item isLaptop() try to detect a laptop. We assume the following is an indication of a laptop: =over 4 =item * pcmcia service =item * C<computer_info()> (really C<dmidecode>) telling us it's a laptop =item * ACPI lid button =item * a regexp to match graphics card apparently only used for such systems. =item * Mobility CPU =item * having Type as Laptop in some device =item * Intel ipw2100/2200/3945 Wireless =back =cut sub isLaptop() { computer_info()->{isLaptop} || glob_("/sys/bus/acpi/devices/PNP0C0D:*") #- ACPI lid button || (matching_desc__regexp('C&T.*655[45]\d') || matching_desc__regexp('C&T.*68554') || matching_desc__regexp('Neomagic.*Magic(Media|Graph)') || matching_desc__regexp('ViRGE.MX') || matching_desc__regexp('S3.*Savage.*[IM]X') || matching_desc__regexp('Intel Corporation\|Mobile') || matching_desc__regexp('\bATI\b.*(Mobility|\bLT\b)')) || (any { $_->{'model name'} =~ /\b(mobile|C7-M)\b/i } getCPUs()) || probe_unique_name("Type") eq 'laptop' #- ipw2100/2200/3945 are Mini-PCI (Express) adapters || (any { member($_->{driver}, qw(ipw2100 ipw2200 ipw3945)) } pci_probe()); } =item isServer() Is it a server? =cut sub isServer() { computer_info()->{isServer} || (any { $_->{Type} =~ /ECC/ } dmidecode_category('Memory Module')) || dmidecode_category('System Information')->{Manufacturer} =~ /Supermicro/i || dmidecode_category('System Information')->{'Product Name'} =~ /NetServer|Proliant|PowerEdge|eServer|IBM System x|ThinkServer/i