|
root / base / usr / src / cmd / fs.d / pcfs / common
common Plain Text 1010 lines 26.7 KB
   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
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License, Version 1.0 only
 * (the "License").  You may not use this file except in compliance
 * with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */
/*
 * Copyright (c) 1999 by Sun Microsystems, Inc.
 * All rights reserved.
 * Copyright 2024 MNX Cloud, Inc.
 */

#ifndef _PCFS_BPB_H
#define	_PCFS_BPB_H

#ifdef __cplusplus
extern "C" {
#endif

/*
 * Common Bios Parameter Block definitions for the pcfs user-level utilities
 */
#define	MINBPS		512
#define	MAXBPS		4096

#define	OPCODE1		0xE9
#define	OPCODE2		0xEB
#define	BOOTSECSIG	0xAA55

/*
 * Offset (in bytes) from address of boot sector to where we put
 * the backup copy of that sector.  (FAT32 only)
 */
#define	BKUP_BOOTSECT_OFFSET	0xC00

#define	uppercase(c)	((c) >= 'a' && (c) <= 'z' ? (c) - 'a' + 'A' : (c))

#define	FAT12_TYPE_STRING	"FAT12   "
#define	FAT16_TYPE_STRING	"FAT16   "
#define	FAT32_TYPE_STRING	"FAT32   "

#define	FAT12_ENTSPERSECT	341
#define	FAT16_ENTSPERSECT	256
#define	FAT32_ENTSPERSECT	128

#ifndef	SUNIXOSBOOT
#define	SUNIXOSBOOT	190	/* Solaris UNIX boot partition */
#endif

/*
 *	MS-DOS Disk layout:
 *
 *	---------------------
 *	|    Boot sector    |
 *	|-------------------|
 *	|   Reserved area   |
 *	|-------------------|
 *	|	FAT #1      |
 *	|-------------------|
 *	|	FAT #2      |
 *	|-------------------|
 *	|   Root directory  |
 *	|-------------------|
 *	|                   |
 *	|     File area     |
 *	|___________________|
 */
#ifdef _LITTLE_ENDIAN
#pragma	pack(1)
#endif
struct _orig_bios_param_blk {
	uint16_t bytes_per_sector;
	uchar_t	 sectors_per_cluster;
	uint16_t resv_sectors;
	uchar_t	 num_fats;
	uint16_t num_root_entries;
/*
 *  The sectors_in_volume field will be zero on larger volumes (>32Mb)
 *  and newer file systems (>=MSDOS4.0).  In these cases the
 *  sectors_in_logical_volume field should be used instead.
 */
	uint16_t sectors_in_volume;
	uchar_t	 media;
	uint16_t sectors_per_fat;
	uint16_t sectors_per_track;
	uint16_t heads;
/*
 *  Number of sectors in the partition prior to the start of the logical disk
 */
	uint32_t hidden_sectors;
	uint32_t sectors_in_logical_volume;
};
#ifdef _LITTLE_ENDIAN
#pragma pack()
#endif

#ifdef _LITTLE_ENDIAN
#pragma	pack(1)
#endif
struct _bpb32_extensions {
	uint32_t big_sectors_per_fat;
	uint16_t ext_flags;
	uchar_t	 fs_vers_lo;
	uchar_t	 fs_vers_hi;
	uint32_t root_dir_clust;
	uint16_t fsinfosec;
	uint16_t backupboot;
	uint16_t reserved[6];
};
#ifdef _LITTLE_ENDIAN
#pragma pack()
#endif

#ifdef _LITTLE_ENDIAN
#pragma	pack(1)
#endif
struct _bpb_extensions {
	uchar_t  phys_drive_num;
	uchar_t  reserved;
	uchar_t  ext_signature;
	uint32_t volume_id;
	uchar_t  volume_label[11];
	uchar_t  type[8];
};
#ifdef _LITTLE_ENDIAN
#pragma pack()
#endif

#ifdef _LITTLE_ENDIAN
#pragma	pack(1)
#endif
struct _sun_bpb_extensions {
	uint16_t  bs_offset_high;
	uint16_t  bs_offset_low;
};
#ifdef _LITTLE_ENDIAN
#pragma pack()
#endif

/*
 * bpb_t is a conglomeration of all the fields a bpb can have.  Every
 * bpb will have the orig_bios struct, but only FAT32's will have bpb32,
 * and only Solaris boot diskettes will have the sunbpb structure.
 */
typedef struct _bios_param_blk {
	struct _orig_bios_param_blk bpb;
	struct _bpb32_extensions    bpb32;
	struct _bpb_extensions	    ebpb;
	struct _sun_bpb_extensions  sunbpb;
} bpb_t;

#ifdef _LITTLE_ENDIAN
#pragma	pack(1)
struct _bpb_head {
	uchar_t			    bs_jump_code[3];
	uchar_t			    bs_oem_name[8];
	struct _orig_bios_param_blk bs_bpb;
};
#pragma pack()

#pragma	pack(1)
struct _boot_sector {
	struct _bpb_head	    bs_front;
	struct _bpb_extensions	    bs_ebpb;
	struct _sun_bpb_extensions  bs_sebpb;
	uchar_t			    bs_bootstrap[444];
	uchar_t			    bs_signature[2];
};
#pragma pack()

#pragma	pack(1)
struct _boot_sector32 {
	struct _bpb_head	    bs_front;
	struct _bpb32_extensions    bs_bpb32;
	struct _bpb_extensions	    bs_ebpb;
	uchar_t			    bs_bootstrap[420];
	uchar_t			    bs_signature[2];
};
#pragma pack()
#else
#define	ORIG_BPB_START_INDEX	8	/* index into filler field */
#define	EXT_BPB_START_INDEX	33	/* index into filler field */
#define	BPB_32_START_INDEX	33	/* index into filler field */
#define	EXT_BPB_32_START_INDEX	61	/* index into filler field */
struct _boot_sector {
	uchar_t	 bs_jump_code[3];
	uchar_t  bs_filler[59];
	uchar_t  bs_sun_bpb[4];
	uchar_t	 bs_bootstrap[444];
	uchar_t  bs_signature[2];
};

struct _boot_sector32 {
	uchar_t	 bs_jump_code[3];
	uchar_t  bs_filler[87];
	uchar_t	 bs_bootstrap[420];
	uchar_t  bs_signature[2];
};
#endif

typedef union _ubso {
	struct _boot_sector	bs;
	struct _boot_sector32	bs32;
	struct mboot		mb;
	uchar_t			buf[MAXBPS];
} boot_sector_t;

#ifdef __cplusplus
}
#endif

#endif /* _PCFS_BPB_H */
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License (the "License").
 * You may not use this file except in compliance with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */
/*
 * Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 * Copyright (c) 2011 Gary Mills
 * Copyright 2024 MNX Cloud, Inc.
 */

/*
 * common functions used by pcfs tools.
 */
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <err.h>
#include <unistd.h>
#include <stdlib.h>
#include <libintl.h>
#include <locale.h>
#include <langinfo.h>
#include <regex.h>
#include <sys/isa_defs.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/fcntl.h>
#include <sys/dktp/fdisk.h>
#include <sys/dkio.h>
#include <sys/fs/pc_fs.h>
#include <sys/fs/pc_dir.h>
#include <sys/fs/pc_label.h>
#include "pcfs_common.h"
#include "pcfs_bpb.h"

/*
 *	The assumption here is that _BIG_ENDIAN implies sparc, and
 *	so in addition to swapping bytes we also have to construct
 *	packed structures by hand to avoid bus errors due to improperly
 *	aligned pointers.
 */
#ifdef _BIG_ENDIAN
void swap_pack_grab32bpb(bpb_t *wbpb, struct _boot_sector *bsp);
void swap_pack_grabbpb(bpb_t *wbpb, struct _boot_sector *bsp);
#endif /* _BIG_ENDIAN */

/*
 * Validate sector size.
 */
bool
is_sector_size_valid(size_t size)
{
	if (size != 512 && size != 1024 && size != 2048 && size != 4096)
		return (false);
	return (true);
}

/*
 * Use DKIOCGMEDIAINFO to get sector size.
 */
int
get_media_sector_size(int fd, size_t *sizep)
{
	struct dk_minfo dkminfo;

	if (ioctl(fd, DKIOCGMEDIAINFO, &dkminfo) != -1) {
		*sizep = dkminfo.dki_lbsize;
		return (0);
	}
	/* In case the DKIOCGMEDIAINFO is not supported, return MINBPS. */
	if (errno == ENOTTY) {
		*sizep = MINBPS;
		return (0);
	}

	return (errno);
}

/*
 * store_16_bits
 *	Save the lower 16 bits of a 32 bit value (v) into the provided
 *	buffer (pointed at by *bp), and increment the buffer pointer
 *	as well.  This way the routine can be called multiple times in
 *	succession to fill buffers.  The value is stored in little-endian
 *	order.
 */
void
store_16_bits(uchar_t **bp, uint32_t v)
{
	uchar_t *l = *bp;

	*l++ = v & 0xff;
	*l = (v >> 8) & 0xff;
	*bp += 2;
}

void
read_16_bits(uchar_t *bp, uint32_t *value)
{
	*value = *bp++;
	*value += *bp << 8;
}

/*
 * store_32_bits
 *	Save the 32 bit value (v) into the provided buffer (pointed
 *	at by *bp), and increment the buffer pointer as well.  This way
 *	the routine can be called multiple times in succession to fill
 *	buffers.  The value is stored in little-endian order.
 */
void
store_32_bits(uchar_t **bp, uint32_t v)
{
	uchar_t *l = *bp;
	int b;

	for (b = 0; b < 4; b++) {
		*l++ = v & 0xff;
		v = v >> 8;
	}
	*bp += 4;
}

void
read_32_bits(uchar_t *bp, uint32_t *value)
{
	*value = *bp++;
	*value += *bp++ << 8;
	*value += *bp++ << 16;
	*value += *bp++ << 24;
}

/*
 *  dump_bytes  -- display bytes as hex numbers.
 *		   b is the pointer to the byte buffer
 *		   n is the number of bytes in the buffer
 */
/* Note: BPL = bytes to display per line */
#define	BPL 16

void
dump_bytes(uchar_t *buf, int n)
{
	int printedCount;
	int countdown = n;
	int countup = 0;
	int offset = 0;
	int byte;

	/* Display offset, 16 bytes per line, and printable ascii version */
	while (countdown > 0) {
		printedCount = 0;
		(void) fprintf(stderr, "\n%06x: ", offset);
		/*
		 * Print Hex value of characters in columns on left
		 */
		for (byte = 0; byte < BPL; byte++) {
			if (countup + byte < n) {
				(void) fprintf(stderr,
				    "%02x ", (buf[countup + byte] & 0xff));
				printedCount++;
			} else {
				(void) fprintf(stderr, "   ");
			}
		}
		/*
		 * Right side has the printable character or '.' for
		 * unprintable for each column of the left.
		 */
		for (byte = 0; byte < BPL; byte++) {
			if ((countup + byte < n) &&
			    ((buf[countup + byte] >= ' ') &&
			    (buf[countup + byte] <= '~'))) {
				(void) fprintf(stderr, "%c",
				    buf[countup + byte]);
			} else {
				(void) fprintf(stderr, ".");
			}
		}
		countup += printedCount;
		offset += printedCount;
		countdown -= printedCount;
	}
	(void) fprintf(stderr, "\n\n");
}

/*
 *  header_for_dump  --  display simple header over what will be output.
 */
void
header_for_dump(void)
{
	int byte;

	(void) fprintf(stderr, "\n        ");
	for (byte = 0; byte < BPL; byte++)
		(void) fprintf(stderr, "%02x ", byte);
	(void) fprintf(stderr, "\n       ");
	byte = 3 * BPL;
	while (byte-- > 0)
		(void) fprintf(stderr, "-");
}

/*
 *  We are basically (incorrectly) assuming that if you aren't running
 *  on x86 the BPB has to be packed by hand AND that the bytes must
 *  be swapped.  One or both of these assumptions may one day be invalid.
 *  (if they aren't already :-))
 */
#ifdef _BIG_ENDIAN
/*
 *  swap_pack_grab{32}bpb
 *	If not on an x86 we assume the structures making up the bpb
 *	were not packed and that longs and shorts need to be byte swapped
 *	(we've kept everything in host order up until now).  A new architecture
 *	might not need to swap or might not need to pack, in which case
 *	new routines will have to be written.  Of course if an architecture
 *	supports both packing and little-endian host order, it can follow the
 *	same path as the x86 code.
 */
void
swap_pack_grabbpb(bpb_t *wbpb, struct _boot_sector *bsp)
{
	uchar_t *grabp;

	grabp = (uchar_t *)&(bsp->bs_filler[ORIG_BPB_START_INDEX]);

	((uchar_t *)&(wbpb->bpb.bytes_per_sector))[1] = *grabp++;
	((uchar_t *)&(wbpb->bpb.bytes_per_sector))[0] = *grabp++;
	wbpb->bpb.sectors_per_cluster = *grabp++;
	((uchar_t *)&(wbpb->bpb.resv_sectors))[1] = *grabp++;
	((uchar_t *)&(wbpb->bpb.resv_sectors))[0] = *grabp++;
	wbpb->bpb.num_fats = *grabp++;
	((uchar_t *)&(wbpb->bpb.num_root_entries))[1] = *grabp++;
	((uchar_t *)&(wbpb->bpb.num_root_entries))[0] = *grabp++;
	((uchar_t *)&(wbpb->bpb.sectors_in_volume))[1] = *grabp++;
	((uchar_t *)&(wbpb->bpb.sectors_in_volume))[0] = *grabp++;
	wbpb->bpb.media = *grabp++;
	((uchar_t *)&(wbpb->bpb.sectors_per_fat))[1] = *grabp++;
	((uchar_t *)&(wbpb->bpb.sectors_per_fat))[0] = *grabp++;
	((uchar_t *)&(wbpb->bpb.sectors_per_track))[1] = *grabp++;
	((uchar_t *)&(wbpb->bpb.sectors_per_track))[0] = *grabp++;
	((uchar_t *)&(wbpb->bpb.heads))[1] = *grabp++;
	((uchar_t *)&(wbpb->bpb.heads))[0] = *grabp++;
	((uchar_t *)&(wbpb->bpb.hidden_sectors))[3] = *grabp++;
	((uchar_t *)&(wbpb->bpb.hidden_sectors))[2] = *grabp++;
	((uchar_t *)&(wbpb->bpb.hidden_sectors))[1] = *grabp++;
	((uchar_t *)&(wbpb->bpb.hidden_sectors))[0] = *grabp++;
	((uchar_t *)&(wbpb->bpb.sectors_in_logical_volume))[3] = *grabp++;
	((uchar_t *)&(wbpb->bpb.sectors_in_logical_volume))[2] = *grabp++;
	((uchar_t *)&(wbpb->bpb.sectors_in_logical_volume))[1] = *grabp++;
	((uchar_t *)&(wbpb->bpb.sectors_in_logical_volume))[0] = *grabp++;
	wbpb->ebpb.phys_drive_num = *grabp++;
	wbpb->ebpb.reserved = *grabp++;
	wbpb->ebpb.ext_signature = *grabp++;
	((uchar_t *)&(wbpb->ebpb.volume_id))[3] = *grabp++;
	((uchar_t *)&(wbpb->ebpb.volume_id))[2] = *grabp++;
	((uchar_t *)&(wbpb->ebpb.volume_id))[1] = *grabp++;
	((uchar_t *)&(wbpb->ebpb.volume_id))[0] = *grabp++;

	(void) strncpy((char *)wbpb->ebpb.volume_label, (char *)grabp, 11);
	grabp += 11;
	(void) strncpy((char *)wbpb->ebpb.type, (char *)grabp, 8);
}

void
swap_pack_grab32bpb(bpb_t *wbpb, struct _boot_sector *bsp)
{
	uchar_t *grabp;

	grabp = (uchar_t *)&(bsp->bs_filler[BPB_32_START_INDEX]);

	((uchar_t *)&(wbpb->bpb32.big_sectors_per_fat))[3] = *grabp++;
	((uchar_t *)&(wbpb->bpb32.big_sectors_per_fat))[2] = *grabp++;
	((uchar_t *)&(wbpb->bpb32.big_sectors_per_fat))[1] = *grabp++;
	((uchar_t *)&(wbpb->bpb32.big_sectors_per_fat))[0] = *grabp++;
	((uchar_t *)&(wbpb->bpb32.ext_flags))[1] = *grabp++;
	((uchar_t *)&(wbpb->bpb32.ext_flags))[0] = *grabp++;
	wbpb->bpb32.fs_vers_lo = *grabp++;
	wbpb->bpb32.fs_vers_hi = *grabp++;
	((uchar_t *)&(wbpb->bpb32.root_dir_clust))[3] = *grabp++;
	((uchar_t *)&(wbpb->bpb32.root_dir_clust))[2] = *grabp++;
	((uchar_t *)&(wbpb->bpb32.root_dir_clust))[1] = *grabp++;
	((uchar_t *)&(wbpb->bpb32.root_dir_clust))[0] = *grabp++;
	((uchar_t *)&(wbpb->bpb32.fsinfosec))[1] = *grabp++;
	((uchar_t *)&(wbpb->bpb32.fsinfosec))[0] = *grabp++;
	((uchar_t *)&(wbpb->bpb32.backupboot))[1] = *grabp++;
	((uchar_t *)&(wbpb->bpb32.backupboot))[0] = *grabp++;
	((uchar_t *)&(wbpb->bpb32.reserved[0]))[1] = *grabp++;
	((uchar_t *)&(wbpb->bpb32.reserved[0]))[0] = *grabp++;
	((uchar_t *)&(wbpb->bpb32.reserved[1]))[1] = *grabp++;
	((uchar_t *)&(wbpb->bpb32.reserved[1]))[0] = *grabp++;
	((uchar_t *)&(wbpb->bpb32.reserved[2]))[1] = *grabp++;
	((uchar_t *)&(wbpb->bpb32.reserved[2]))[0] = *grabp++;
	((uchar_t *)&(wbpb->bpb32.reserved[3]))[1] = *grabp++;
	((uchar_t *)&(wbpb->bpb32.reserved[3]))[0] = *grabp++;
	((uchar_t *)&(wbpb->bpb32.reserved[4]))[1] = *grabp++;
	((uchar_t *)&(wbpb->bpb32.reserved[4]))[0] = *grabp++;
	((uchar_t *)&(wbpb->bpb32.reserved[5]))[1] = *grabp++;
	((uchar_t *)&(wbpb->bpb32.reserved[5]))[0] = *grabp++;
}
#endif	/* _BIG_ENDIAN */

char *
stat_actual_disk(const char *diskname, struct stat *info, char **suffix)
{
	char *actualdisk;

	if (stat(diskname, info) != 0) {
		/*
		 *  Device named on command line doesn't exist.  That
		 *  probably means there is a partition-specifying
		 *  suffix attached to the actual disk name.
		 */
		if ((actualdisk = strdup(diskname)) == NULL) {
			(void) fprintf(stderr,
			    gettext("Out of memory for disk name.\n"));
			exit(2);
		}
		if ((*suffix = strchr(actualdisk, ':')) != NULL) {
			**suffix = '\0';
			(*suffix)++;
		}

		if (stat(actualdisk, info)) {
			err(2, "Failed to stat disk device %s",
			    actualdisk);
		}
	} else {
		if ((actualdisk = strdup(diskname)) == NULL) {
			(void) fprintf(stderr,
			    gettext("Out of memory for disk name.\n"));
			exit(2);
		}
	}

	return (actualdisk);
}

extern void usage(void);

void
bad_arg(char *option)
{
	(void) fprintf(stderr,
	    gettext("Unrecognized option -o %s.\n"), option);
	usage();
	exit(2);
}

void
missing_arg(char *option)
{
	(void) fprintf(stderr,
	    gettext("Option %s requires a value.\n"), option);
	usage();
	exit(3);
}

static int
parse_drvnum(char *pn)
{
	int drvnum;

	/*
	 * Determine logical drive to seek after.
	 */
	if ((strlen(pn) == 1) && ((*pn >= 'c') && (*pn <= 'z'))) {
		drvnum = *pn - 'c' + 1;
	} else if ((*pn >= '0') && (*pn <= '9')) {
		char *d;
		int v = 0;

		d = pn;
		while ((*d != '\0') && (*d >= '0') && (*d <= '9')) {
			v *= 10;
			v += *d - '0';
			d++;
		}
		if ((*d != '\0') || (v > 24)) {
			(void) fprintf(stderr,
			    gettext("%s: bogus logical drive specification.\n"),
			    pn);
			return (-1);
		}
		drvnum = v;
	} else if (strcmp(pn, "boot") == 0) {
		drvnum = 99;
	} else {
		(void) fprintf(stderr,
		    gettext("%s: bogus logical drive specification.\n"), pn);
		return (-1);
	}

	return (drvnum);
}

/*
 * isDosDrive()
 *	Boolean function.  Give it the systid field for an fdisk partition
 *	and it decides if that's a systid that describes a DOS drive.  We
 *	use systid values defined in sys/dktp/fdisk.h.
 */
static int
isDosDrive(uchar_t checkMe)
{
	return ((checkMe == DOSOS12) || (checkMe == DOSOS16) ||
	    (checkMe == DOSHUGE) || (checkMe == FDISK_WINDOWS) ||
	    (checkMe == FDISK_EXT_WIN) || (checkMe == FDISK_FAT95) ||
	    (checkMe == DIAGPART));
}

/*
 * isDosExtended()
 *	Boolean function.  Give it the systid field for an fdisk partition
 *	and it decides if that's a systid that describes an extended DOS
 *	partition.
 */
static int
isDosExtended(uchar_t checkMe)
{
	return ((checkMe == EXTDOS) || (checkMe == FDISK_EXTLBA));
}

/*
 * isBootPart()
 *	Boolean function.  Give it the systid field for an fdisk partition
 *	and it decides if that's a systid that describes a Solaris boot
 *	partition.
 */
static int
isBootPart(uchar_t checkMe)
{
	return (checkMe == X86BOOT);
}

off64_t
findPartitionOffset(int fd, size_t bpsec, char *ldrive)
{
	struct ipart part[FD_NUMPART];
	struct mboot extmboot;
	struct mboot mb;
	diskaddr_t xstartsect;
	off64_t nextseek = 0;
	off64_t lastseek = 0;
	off64_t found = 0;
	off64_t error = -1;
	int logicalDriveCount = 0;
	int extendedPart = -1;
	int primaryPart = -1;
	int bootPart = -1;
	uint32_t xnumsect = 0;
	int drvnum;
	int driveIndex;
	int i;
	/*
	 * Count of drives in the current extended partition's
	 * FDISK table, and indexes of the drives themselves.
	 */
	int extndDrives[FD_NUMPART];
	int numDrives = 0;
	/*
	 * Count of drives (beyond primary) in master boot record's
	 * FDISK table, and indexes of the drives themselves.
	 */
	int extraDrives[FD_NUMPART];
	int numExtraDrives = 0;

	if ((drvnum = parse_drvnum(ldrive)) < 0)
		return (error);

	if (read(fd, &mb, bpsec) != (ssize_t)bpsec) {
		(void) fprintf(stderr,
		    gettext("Couldn't read a Master Boot Record\n"));
		return (error);
	}

	if (ltohs(mb.signature) != BOOTSECSIG) {
		(void) fprintf(stderr,
		    gettext("Bad signature on master boot record (%x)\n"),
		    ltohs(mb.signature));
		return (error);
	}

	/*
	 * Copy partition table into memory
	 */
	(void) memcpy(part, mb.parts, sizeof (part));

	/*
	 * Get a summary of what is in the Master FDISK table.
	 * Normally we expect to find one partition marked as a DOS drive.
	 * This partition is the one Windows calls the primary dos partition.
	 * If the machine has any logical drives then we also expect
	 * to find a partition marked as an extended DOS partition.
	 *
	 * Sometimes we'll find multiple partitions marked as DOS drives.
	 * The Solaris fdisk program allows these partitions
	 * to be created, but Windows fdisk no longer does.  We still need
	 * to support these, though, since Windows does.  We also need to fix
	 * our fdisk to behave like the Windows version.
	 *
	 * It turns out that some off-the-shelf media have *only* an
	 * Extended partition, so we need to deal with that case as
	 * well.
	 *
	 * Only a single (the first) Extended or Boot Partition will
	 * be recognized.  Any others will be ignored.
	 */
	for (i = 0; i < FD_NUMPART; i++) {
		if (isDosDrive(part[i].systid)) {
			if (primaryPart < 0) {
				logicalDriveCount++;
				primaryPart = i;
			} else {
				extraDrives[numExtraDrives++] = i;
			}
			continue;
		}
		if ((extendedPart < 0) && isDosExtended(part[i].systid)) {
			extendedPart = i;
			continue;
		}
		if ((bootPart < 0) && isBootPart(part[i].systid)) {
			bootPart = i;
			continue;
		}
	}

	if (drvnum == BOOT_PARTITION_DRIVE) {
		if (bootPart < 0) {
			(void) fprintf(stderr,
			    gettext("No boot partition found on drive\n"));
			return (error);
		}
		found = ltohi(part[bootPart].relsect) * bpsec;
		return (found);
	}

	if (drvnum == PRIMARY_DOS_DRIVE && primaryPart >= 0) {
		found = ltohi(part[primaryPart].relsect) * bpsec;
		return (found);
	}

	/*
	 * We are not looking for the C: drive (or there was no primary
	 * drive found), so we had better have an extended partition or
	 * extra drives in the Master FDISK table.
	 */
	if ((extendedPart < 0) && (numExtraDrives == 0)) {
		(void) fprintf(stderr,
		    gettext("No such logical drive "
		    "(missing extended partition entry)\n"));
		return (error);
	}

	if (extendedPart >= 0) {
		nextseek = xstartsect = ltohi(part[extendedPart].relsect);
		xnumsect = ltohi(part[extendedPart].numsect);
		do {
			/*
			 *  If the seek would not cause us to change
			 *  position on the drive, then we're out of
			 *  extended partitions to examine.
			 */
			if (nextseek == lastseek)
				break;
			logicalDriveCount += numDrives;
			/*
			 *  Seek the next extended partition, and find
			 *  logical drives within it.
			 */
			if (lseek64(fd, nextseek * bpsec, SEEK_SET) < 0 ||
			    read(fd, &extmboot, sizeof (extmboot)) !=
			    sizeof (extmboot)) {
				perror(gettext("Unable to read extended "
				    "partition record"));
				return (error);
			}
			(void) memcpy(part, extmboot.parts, sizeof (part));
			lastseek = nextseek;
			if (ltohs(extmboot.signature) != MBB_MAGIC) {
				(void) fprintf(stderr,
				    gettext("Bad signature on "
				    "extended partition\n"));
				return (error);
			}
			/*
			 *  Count up drives, and track where the next
			 *  extended partition is in case we need it.  We
			 *  are expecting only one extended partition.  If
			 *  there is more than one we'll only go to the
			 *  first one we see, but warn about ignoring.
			 */
			numDrives = 0;
			for (i = 0; i < FD_NUMPART; i++) {
				if (isDosDrive(part[i].systid)) {
					extndDrives[numDrives++] = i;
					continue;
				} else if (isDosExtended(part[i].systid)) {
					if (nextseek != lastseek) {
						/*
						 * Already found an extended
						 * partition in this table.
						 */
						(void) fprintf(stderr,
						    gettext("WARNING: "
						    "Ignoring unexpected "
						    "additional extended "
						    "partition"));
						continue;
					}
					nextseek = xstartsect +
					    ltohi(part[i].relsect);
					continue;
				}
			}
		} while (drvnum > logicalDriveCount + numDrives);

		if (drvnum <= logicalDriveCount + numDrives) {
			/*
			 * The number of logical drives we've found thus
			 * far is enough to get us to the one we were
			 * searching for.
			 */
			driveIndex = logicalDriveCount + numDrives - drvnum;
			found =
			    ltohi(part[extndDrives[driveIndex]].relsect) +
			    lastseek;
			if (found > (xstartsect + xnumsect)) {
				(void) fprintf(stderr,
				    gettext("Logical drive start sector (%d) "
				    "is not within the partition!\n"), found);
				return (error);
			} else {
				found *= bpsec;
			}
			return (found);
		} else {
			/*
			 * We ran out of extended dos partition
			 * drives.  The only hope now is to go
			 * back to extra drives defined in the master
			 * fdisk table.  But we overwrote that table
			 * already, so we must load it in again.
			 */
			logicalDriveCount += numDrives;
			(void) memcpy(part, mb.parts, sizeof (part));
		}
	}
	/*
	 *  Still haven't found the drive, is it an extra
	 *  drive defined in the main FDISK table?
	 */
	if (drvnum <= logicalDriveCount + numExtraDrives) {
		driveIndex = logicalDriveCount + numExtraDrives - drvnum;
		found = ltohi(part[extraDrives[driveIndex]].relsect) * bpsec;
		return (found);
	}
	return (error);
}
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License, Version 1.0 only
 * (the "License").  You may not use this file except in compliance
 * with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */
/*
 * Copyright (c) 1999 by Sun Microsystems, Inc.
 * All rights reserved.
 * Copyright (c) 2011 Gary Mills
 * Copyright 2024 MNX Cloud, Inc.
 */

#ifndef _PCFS_COMMON_H
#define	_PCFS_COMMON_H

/*
 * Common routines for the pcfs user-level utilities
 */

#ifdef __cplusplus
extern "C" {
#endif

#include <stdbool.h>
#include <sys/isa_defs.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/sysmacros.h>
#include "pcfs_bpb.h"

#define	IN_RANGE(n, x, y) (((n) >= (x)) && ((n) <= (y)))

/*
 *  A macro implementing a ceiling function for integer divides.
 */
#define	idivceil(dvend, dvsor) \
	((dvend)/(dvsor) + (((dvend)%(dvsor) == 0) ? 0 : 1))

/*
 * These defines should move into a kernel header file eventually
 * and pcfs_mount may want to refuse to mount FAT32's that aren't "clean"
 *
 *	If Windows shuts down properly it sets the fourth bit of the 8th
 *	and final reserved byte at the start of the FAT.
 */
#define	WIN_SHUTDOWN_STATUS_BYTE	7
#define	WIN_SHUTDOWN_BIT_MASK		0x8

/*
 *  Define some special logical drives we use.
 */
#define	BOOT_PARTITION_DRIVE	99
#define	PRIMARY_DOS_DRIVE	1

/*
 * Function prototypes
 */
extern off64_t findPartitionOffset(int fd, size_t bpsec, char *ldrive);
extern char *stat_actual_disk(const char *diskname, struct stat *info,
	char **suffix);
extern void header_for_dump(void);
extern void store_16_bits(uchar_t **bp, uint32_t v);
extern void store_32_bits(uchar_t **bp, uint32_t v);
extern void read_16_bits(uchar_t *bp, uint32_t *value);
extern void read_32_bits(uchar_t *bp, uint32_t *value);
extern void missing_arg(char *option);
extern void dump_bytes(uchar_t *b, int n);
extern void bad_arg(char *option);
extern void usage(void);
extern bool is_sector_size_valid(size_t size);
extern int  get_media_sector_size(int fd, size_t *sizep);

/*
 *	The assumption here is that _BIG_ENDIAN implies sparc, and
 *	so in addition to swapping bytes we also have to construct
 *	packed structures by hand to avoid bus errors due to improperly
 *	aligned pointers.
 */
#ifdef _BIG_ENDIAN
extern void swap_pack_grab32bpb(bpb_t *wbpb, struct _boot_sector *bsp);
extern void swap_pack_grabbpb(bpb_t *wbpb, struct _boot_sector *bsp);
#endif	/* _BIG_ENDIAN */

#ifdef __cplusplus
}
#endif

#endif /* _PCFS_COMMON_H */