xref: /netbsd-src/usr.sbin/sysinst/arch/mac68k/md.c (revision 2e9df72ec394f443f02e2e3b5922bfdfe348dab9)
1 /*	$NetBSD: md.c,v 1.12 2022/04/07 19:33:38 andvar Exp $ */
2 
3 /*
4  * Copyright 1997 Piermont Information Systems Inc.
5  * All rights reserved.
6  *
7  * Based on code written by Philip A. Nelson for Piermont Information
8  * Systems Inc.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. The name of Piermont Information Systems Inc. may not be used to endorse
19  *    or promote products derived from this software without specific prior
20  *    written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY PIERMONT INFORMATION SYSTEMS INC. ``AS IS''
23  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED. IN NO EVENT SHALL PIERMONT INFORMATION SYSTEMS INC. BE
26  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
27  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
28  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
29  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
30  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
31  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
32  * THE POSSIBILITY OF SUCH DAMAGE.
33  */
34 
35 /* md.c -- mac68k machine specific routines */
36 
37 #include <stdio.h>
38 #include <util.h>
39 #include <unistd.h>
40 #include <fcntl.h>
41 #include <sys/ioctl.h>
42 #include <sys/utsname.h>
43 #include <machine/int_fmtio.h>
44 
45 #include "defs.h"
46 #include "md.h"
47 #include "msg_defs.h"
48 #include "menu_defs.h"
49 
50 static int	stricmp(const char *c1, const char *c2);
51 static void	setpartition(struct apple_part_map_entry *, char *, int);
52 static int	getFreeLabelEntry(char *);
53 static char	*getFstype(struct apple_part_map_entry *, int, char *);
54 static char	*getUse(struct apple_part_map_entry *, int, char *);
55 static char	*getName(struct apple_part_map_entry *, int, char *);
56 static int	findStdType(int, char *, int, int *, int);
57 static int	check_for_errors(void);
58 static int	edit_diskmap(void);
59 #ifdef MD_DEBUG_SORT_MERGE
60 static int	md_debug_dump(char *);
61 #endif
62 
63 int blk_size;
64 
65 MAP_TYPE map_types[] = {
66 	{MAP_RESERVED, APPLE_PART_TYPE_DRIVER},
67 	{MAP_RESERVED, APPLE_PART_TYPE_DRIVER43},
68 	{MAP_RESERVED, APPLE_PART_TYPE_DRIVERATA},
69 	{MAP_RESERVED, APPLE_PART_TYPE_FWB_COMPONENT},
70 	{MAP_MACOS,    APPLE_PART_TYPE_MAC},
71 	{MAP_NETBSD,   APPLE_PART_TYPE_NETBSD},
72 	{MAP_RESERVED, APPLE_PART_TYPE_PARTMAP},
73 	{MAP_OTHER,    APPLE_PART_TYPE_SCRATCH},
74 	{MAP_NETBSD,   APPLE_PART_TYPE_UNIX},
75 	{MAP_EOL,      NULL}
76 };
77 
78 MAP map = {0, 0, 0, 0, 0, 0, 0, 0, {0}, NULL};
79 
80 struct apple_part_map_entry new_map[] =
81 {
82 	{ APPLE_PART_MAP_ENTRY_MAGIC, 0xa5a5, 6, 1, NEW_MAP_SIZE & 0x7e,
83 	  "Apple", "Apple_Partition_Map", 0, NEW_MAP_SIZE, 0x37,
84 	  0, 0, 0, 0, 0, 0, 0, {0}, {0}, {0}},
85 	{ APPLE_PART_MAP_ENTRY_MAGIC, 0, 6, 64, 32,
86 	  "Macintosh", "Apple_Driver", 0, 0, 0x37,
87 	  0, 0, 0, 0, 0, 0, 0, {0}, {0}, {0}},
88 	{ APPLE_PART_MAP_ENTRY_MAGIC, 0, 6, 96, 64,
89 	  "Macintosh", "Apple_Driver43", 0, 0, 0x37,
90 	  0, 0, 0, 0, 0, 0, 0, {0}, {0}, {0}},
91 	{ APPLE_PART_MAP_ENTRY_MAGIC, 0, 6, 160, 64,
92 	  "Macintosh", "Apple_Driver_ATA", 0, 0, 0x37,
93 	  0, 0, 0, 0, 0, 0, 0, {0}, {0}, {0}},
94 	{ APPLE_PART_MAP_ENTRY_MAGIC, 0, 6, 224, 4096,
95 	  "untitled", "Apple_HFS", 0, 0, 0x37,
96 	  0, 0, 0, 0, 0, 0, 0, {0}, {0}, {0}},
97 	{ APPLE_PART_MAP_ENTRY_MAGIC, 0, 6,4320, 0,
98 	  "untitled", "Apple_Free", 0, 0, 0x37,
99 	  0, 0, 0, 0, 0, 0, 0, {0}, {0}, {0}}
100 };
101 
102 void
md_init(void)103 md_init(void)
104 {
105 }
106 
107 void
md_init_set_status(int flags)108 md_init_set_status(int flags)
109 {
110        struct utsname instsys;
111 
112 	(void)flags;
113 
114 	/*
115 	 * Get the name of the Install Kernel we are running under and
116 	 * enable the installation of the corresponding GENERIC kernel.
117 	 *
118 	 * Note:  In md.h the two kernels are disabled.  If they are
119 	 *        enabled there the logic here needs to be switched.
120 	 */
121         uname(&instsys);
122         if (strstr(instsys.version, "(INSTALLSBC)"))
123 		/*
124 		 * Running the SBC Installation Kernel, so enable GENERICSBC
125 		 */
126 		set_kernel_set(SET_KERNEL_2);
127         else
128 		/*
129 		 * Running the GENERIC Installation Kernel, so enable GENERIC
130 		 */
131 		set_kernel_set(SET_KERNEL_1);
132 }
133 
134 bool
md_get_info(struct install_partition_desc * install)135 md_get_info(struct install_partition_desc *install)
136 {
137 	struct disklabel disklabel;
138 	int fd, i;
139 	char dev_name[100];
140 	struct apple_part_map_entry block;
141 
142 	snprintf(dev_name, sizeof(dev_name), "/dev/r%s%c",
143 		pm->diskdev, 'a' + getrawpartition());
144 
145 	/*
146 	 * Open the disk as a raw device
147 	 */
148 	fd = open(dev_name, O_RDONLY, 0);
149 	if (fd < 0) {
150 		endwin();
151 		fprintf (stderr, "Can't open %s\n", dev_name);
152 		exit(1);
153 	}
154 	/*
155 	 * Try to get the default disklabel info for the device
156 	 */
157 	if (ioctl(fd, DIOCGDINFO, &disklabel) == -1) {
158 		endwin();
159 		fprintf (stderr, "Can't read disklabel on %s\n", dev_name);
160 		close(fd);
161 		exit(1);
162 	}
163 	/*
164 	 * Get the disk parameters from the disk driver.  It should have
165 	 *  obained them by querying the disk itself.
166 	 */
167 	blk_size = disklabel.d_secsize;
168 	pm->dlcyl = disklabel.d_ncylinders;
169 	pm->dlhead = disklabel.d_ntracks;
170 	pm->dlsec = disklabel.d_nsectors;
171 	/*
172 	 * Just in case, initialize the structures we'll need if we
173 	 *  need to completely initialize the disk.
174 	 */
175 	pm->dlsize = disklabel.d_secperunit;
176 /*
177  * XXX this code is broken: it accesses off the end of new_map[],
178  * because NEW_MAP_SIZE is substantially larger than the number of
179  * entries in new_map[]. Based on the description of struct
180  * apple_part_map_entry in sys/bootblock.h, and the usage of it in
181  * new_map[], NEW_MAP_SIZE is expected to be a block count, not an
182  * entry count. As far I can tell the logic here is just wrong; it
183  * needs someone with platform knowledge to sort it out.
184  *
185  * Note that nothing uses the data this writes into new_map[] so
186  * disabling it should have no adverse consequences.
187  *
188  *   - dholland 20160530
189  */
190 #if 0 /* XXX broken */
191 	for (i=0;i<NEW_MAP_SIZE;i++) {
192 	   if (i > 0)
193 		new_map[i].pmPyPartStart = new_map[i-1].pmPyPartStart +
194 			new_map[i-1].pmPartBlkCnt;
195 	   new_map[i].pmDataCnt = new_map[i].pmPartBlkCnt;
196 	   if (new_map[i].pmPartBlkCnt == 0) {
197 		new_map[i].pmPartBlkCnt = pm->dlsize;
198 		new_map[i].pmDataCnt = pm->dlsize;
199 		break;
200 	   }
201 	   pm->dlsize -= new_map[i].pmPartBlkCnt;
202 	}
203 #endif /* 0 - broken */
204 	pm->dlsize = disklabel.d_secperunit;
205 #if 0
206 	msg_fmt_display(MSG_dldebug, "%d%d%d%d%d",
207 	    blk_size, pm->dlcyl, pm->dlhead, pm->dlsec, pm->dlsize);
208 	process_menu(MENU_ok, NULL);
209 #endif
210 	map.size = 0;
211 	/*
212 	 * Verify the disk has been initialized for MacOS use by checking
213 	 *  to see if the disk have a Boot Block
214 	 */
215 	if (lseek(fd, (off_t)0 * blk_size, SEEK_SET) < 0 ||
216 	    read(fd,  &block, sizeof(block)) - sizeof(block) != 0 ||
217 	    block.pmSig != 0x4552) {
218              process_menu(MENU_nodiskmap, NULL);
219         }
220 	else {
221 	   /*
222 	    * Scan for the Partition Map entry that describes the Partition
223 	    *  Map itself.  We need to know the number of blocks allocated
224 	    *  to it and the number currently in use.
225 	    */
226 	   for (i=0;i<MAXMAXPARTITIONS;i++) {
227 		lseek(fd, (off_t)(i+1) * blk_size, SEEK_SET);
228 		read(fd, &block, sizeof(block));
229 		if (stricmp("Apple_partition_map", (char *)block.pmPartType) == 0) {
230 		    map.size = block.pmPartBlkCnt;
231 		    map.in_use_cnt = block.pmMapBlkCnt;
232 		    map.blk = (struct apple_part_map_entry *)malloc(map.size * blk_size);
233 		    break;
234 	        }
235             }
236 	    lseek(fd, (off_t)1 * blk_size, SEEK_SET);
237 	    read(fd, map.blk, map.size * blk_size);
238 	}
239 	close(fd);
240 
241 	return edit_diskmap();
242 }
243 
244 /*
245  * md back-end code for menu-driven BSD disklabel editor.
246  */
247 int
md_make_bsd_partitions(struct install_partition_desc * install)248 md_make_bsd_partitions(struct install_partition_desc *install)
249 {
250 	int i, j, rv;
251 	EBZB *bzb;
252 	struct disk_part_info info;
253 	uint fs_type;
254 	const char *mountpoint;
255 	part_id pid;
256 	size_t ndx;
257 
258 	/*
259 	 * Scan for any problems and report them before continuing.
260 	 *  The user can abort installation and we'll take them back
261 	 *  to the main menu; continue ignoring the warnings, or
262 	 *  ask to reedit the Disk Partition Map.
263 	 */
264 	while (1) {
265 	    if (check_for_errors()) {
266 	        process_menu (MENU_sanity, &rv);
267 	        if (rv < 0)
268 		    return 0;
269 	        else if (rv)
270 		    break;
271 	        edit_diskmap();
272 	    } else
273 		break;
274 	}
275 
276 	/* Start with empty fake disklabel partitions */
277 	pm->parts->pscheme->delete_all_partitions(pm->parts);
278 
279 	/*
280 	 * Now, scan through the Disk Partition Map and transfer the
281 	 *  information into the incore disklabel.
282 	 */
283 	for (i=0;i<map.usable_cnt;i++) {
284 	    j = map.mblk[i];
285 	    bzb = (EBZB *)&map.blk[j].pmBootArgs[0];
286 	    if (bzb->flags.part) {
287 		mountpoint = NULL;
288 		fs_type = FS_UNUSED;
289 		switch (whichType(&map.blk[j])) {
290 		    case HFS_PART:
291 			fs_type = FS_HFS;
292 			mountpoint = (const char*)bzb->mount_point;
293 			break;
294 		    case ROOT_PART:
295 		    case UFS_PART:
296 			fs_type = FS_BSDFFS;
297 			mountpoint = (const char*)bzb->mount_point;
298 			break;
299 		    case SWAP_PART:
300 			fs_type = FS_SWAP;
301 			break;
302 		    case SCRATCH_PART:
303 			fs_type = FS_OTHER;
304 			mountpoint = (const char*)bzb->mount_point;
305 			break;
306 		    default:
307 			continue;
308 		}
309 		if (fs_type != FS_UNUSED) {
310 			memset(&info, 0, sizeof info);
311 			info.start = map.blk[j].pmPyPartStart;
312 			info.size = map.blk[j].pmPartBlkCnt;
313 			info.fs_type = fs_type;
314 			info.last_mounted = mountpoint;
315 			info.nat_type = pm->parts->pscheme->get_fs_part_type(
316 			    PT_root, fs_type, 0);
317 			pid = pm->parts->pscheme->add_outer_partition(pm->parts,
318 			    &info, NULL);
319 			if (pid == NO_PART)
320 				return 0;
321 		}
322 	    }
323 	}
324 
325 	/* Disk name  - don't bother asking, just use the physical name*/
326 	pm->parts->pscheme->set_disk_pack_name(pm->parts, pm->diskdev);
327 
328 	/* Write the converted partitions */
329 	if (!pm->parts->pscheme->write_to_disk(pm->parts))
330 		return 0;
331 
332 	/* now convert to install info */
333 	if (!install_desc_from_parts(install, pm->parts))
334 		return 0;
335 
336 	/* set newfs flag for all FFS partitions */
337 	for (ndx = 0; ndx < install->num; ndx++) {
338 		if (install->infos[ndx].fs_type == FS_BSDFFS &&
339 		    install->infos[ndx].size > 0 &&
340 		    (install->infos[ndx].instflags & PUIINST_MOUNT))
341 			install->infos[ndx].instflags |= PUIINST_NEWFS;
342 	}
343 
344 	return 1;
345 }
346 
347 /*
348  * any additional partition validation
349  */
350 bool
md_check_partitions(struct install_partition_desc * install)351 md_check_partitions(struct install_partition_desc *install)
352 {
353 	return true;
354 }
355 
356 /*
357  * hook called before writing new disklabel.
358  */
359 bool
md_pre_disklabel(struct install_partition_desc * install,struct disk_partitions * parts)360 md_pre_disklabel(struct install_partition_desc *install,
361     struct disk_partitions *parts)
362 {
363     int fd;
364     char dev_name[100];
365     struct disklabel lp;
366     Block0 new_block0 = {APPLE_DRVR_MAP_MAGIC, 512,
367 	 		 0, 0, 0, 0, 0, 0, 0, 0, {0}};
368 
369     /*
370      * Danger Will Robinson!  We're about to turn that nice MacOS disk
371      *  into an expensive doorstop...
372      */
373     printf ("%s", msg_string (MSG_dodiskmap));
374 
375     snprintf (dev_name, sizeof(dev_name), "/dev/r%sc", pm->diskdev);
376     /*
377      * Open the disk as a raw device
378      */
379     if ((fd = open(dev_name, O_WRONLY, 0)) < 0) {
380 	endwin();
381 	fprintf(stderr, "Can't open %s to rewrite the Disk Map\n", dev_name);
382 	exit (1);
383     }
384     /*
385      *  First check the pmSigPad field of the first block in the incore
386      *  Partition Map.  It should be zero, but if it's 0xa5a5 that means
387      *  we need to write out Block0 too.
388      */
389     if (map.blk[0].pmSigPad == 0xa5a5) {
390 	if (lseek (fd, (off_t)0 * blk_size, SEEK_SET) < 0) {
391 	    endwin();
392 	    fprintf (stderr, "Can't position to write Block0\n");
393 	    close (fd);
394 	    exit (1);
395 	}
396 	new_block0.sbBlkCount = pm->dlsize;		/* Set disk size */
397 	if (write (fd, &new_block0, blk_size) != blk_size) {
398 	    endwin();
399 	    fprintf (stderr, "I/O error writing Block0\n");
400 	    close (fd);
401 	    exit (1);
402 	}
403 	map.blk[0].pmSigPad = 0;
404     }
405     if (lseek (fd, (off_t)1 * blk_size, SEEK_SET) < 0) {
406 	endwin();
407 	fprintf (stderr, "Can't position disk to rewrite Disk Map\n");
408 	close (fd);
409 	exit (1);
410     }
411     if (write (fd, map.blk, map.size * blk_size) != (map.size * blk_size)) {
412 	endwin();
413 	fprintf(stderr, "I/O error writing Disk Map\n");
414 	close (fd);
415 	exit (1);
416     }
417     fsync(fd);
418     /*
419      * Well, if we get here the dirty deed has been done.
420      *
421      * Now we need to force the incore disk table to get updated. This
422      * should be done by disklabel -- which is normally called right after
423      * we return -- but may be commented out for the mac68k port. We'll
424      * instead update the incore table by forcing a dummy write here. This
425      * relies on a change in the mac68k-specific write_disklabel() routine.
426      * If that change doesn't exist nothing bad happens here. If disklabel
427      * properly updates the ondisk and incore labels everything still
428      * works. Only if we fail here and if disklabel fails are we in
429      * in a state where we've updated the disk but not the incore and
430      * a reboot is necessary.
431      *
432      * First, we grab a copy of the incore label as it existed before
433      * we did anything to it. Then we invoke the "write label" ioctl to
434      * rewrite it to disk. As a result, the ondisk partition map is
435      * re-read and the incore label is reconstructed from it. If
436      * disklabel() is then called to update again, either that fails
437      * because the mac68k port doesn't support native disklabels, or it
438      * succeeds and writes out a new ondisk copy.
439      */
440     ioctl(fd, DIOCGDINFO, &lp);    /* Get the current disk label */
441     ioctl(fd, DIOCWDINFO, &lp);    /* Write it out again */
442 
443     close (fd);
444     return true;
445 }
446 
447 /*
448  * hook called after writing disklabel to new target disk.
449  */
450 bool
md_post_disklabel(struct install_partition_desc * install,struct disk_partitions * parts)451 md_post_disklabel(struct install_partition_desc *install,
452     struct disk_partitions *parts)
453 {
454 #if 0	// XXX
455     struct disklabel updated_label;
456     int fd, i, no_match;
457     char dev_name[100], buf[80];
458     const char *fst[] = {"free", "swap", " v6 ", " v7 ", "sysv", "v71k",
459 			" v8 ", "ffs ", "dos ", "lfs ", "othr", "hpfs",
460 			"9660", "boot", "ados", "hfs ", "fcor", "ex2f",
461 			"ntfs", "raid", "ccd "};
462 
463     snprintf(dev_name, sizeof(dev_name), "/dev/r%sc", pm->diskdev);
464     /*
465      * Open the disk as a raw device
466      */
467     if ((fd = open(dev_name, O_RDONLY, 0)) < 0)
468        return false;
469     /*
470      * Get the "new" label to see if we were successful.  If we aren't
471      *  we'll return an error to keep from destroying the user's disk.
472      */
473     ioctl(fd, DIOCGDINFO, &updated_label);
474     close(fd);
475     /*
476      * Make sure the in-core label matches the on-disk one
477      */
478     no_match = 0;
479     for (i=0;i<MAXPARTITIONS;i++) {
480         if (i > updated_label.d_npartitions)
481            break;
482         if (pm->bsdlabel[i].pi_size != updated_label.d_partitions[i].p_size)
483            no_match = 1;
484         if (pm->bsdlabel[i].pi_size) {
485            if (pm->bsdlabel[i].pi_offset != updated_label.d_partitions[i].p_offset)
486                no_match = 1;
487            if (pm->bsdlabel[i].pi_fstype != updated_label.d_partitions[i].p_fstype)
488                no_match = 1;
489         }
490         if (no_match)
491            break;
492     }
493     /*
494      * If the labels don't match, tell the user why
495      */
496     if (no_match) {
497        msg_clear();
498        msg_display(MSG_label_error);
499        msg_fmt_table_add(MSG_dump_line, "%s",
500            " in-core: offset      size type on-disk: offset      size type");
501        for (i=0;i<MAXPARTITIONS;i++) {
502            snprintf(buf, sizeof(buf),
503 	      " %c:%13.8x%10.8x%5s%16.8x%10.8x%5s", i+'a',
504               pm->bsdlabel[i].pi_offset, pm->bsdlabel[i].pi_size,
505               fst[pm->bsdlabel[i].pi_fstype],
506               updated_label.d_partitions[i].p_offset,
507               updated_label.d_partitions[i].p_size,
508               fst[updated_label.d_partitions[i].p_fstype]);
509            msg_fmt_table_add(MSG_dump_line, "%s", buf);
510        }
511        process_menu(MENU_ok2, NULL);
512     }
513     return no_match == 0;
514 #else
515 	return true;
516 #endif
517 }
518 
519 /*
520  * hook called after upgrade() or install() has finished setting
521  * up the target disk but immediately before the user is given the
522  * ``disks are now set up'' message.
523  */
524 int
md_post_newfs(struct install_partition_desc * install)525 md_post_newfs(struct install_partition_desc *install)
526 {
527 	return 0;
528 }
529 
530 int
md_post_extract(struct install_partition_desc * install,bool upgrade)531 md_post_extract(struct install_partition_desc *install, bool upgrade)
532 {
533 	return 0;
534 }
535 
536 void
md_cleanup_install(struct install_partition_desc * install)537 md_cleanup_install(struct install_partition_desc *install)
538 {
539 #ifndef DEBUG
540 	enable_rc_conf();
541 #endif
542 }
543 
544 int
md_pre_update(struct install_partition_desc * install)545 md_pre_update(struct install_partition_desc *install)
546 {
547 	return 1;
548 }
549 
550 /* Upgrade support */
551 int
md_update(struct install_partition_desc * install)552 md_update(struct install_partition_desc *install)
553 {
554 	md_post_newfs(install);
555 	return 1;
556 }
557 
558 /*
559  * Compare lexigraphically two strings
560  */
561 static int
stricmp(s1,s2)562 stricmp(s1, s2)
563 	const char *s1;
564 	const char *s2;
565 {
566 	char c1, c2;
567 
568 	while (1) {
569 	    c1 = tolower((unsigned char)*s1++);
570 	    c2 = tolower((unsigned char)*s2++);
571 	    if (c1 < c2) return -1;
572 	    if (c1 > c2) return 1;
573 	    if (c1 == 0) return 0;
574 	}
575 }
576 
577 static void
setpartition(part,in_use,slot)578 setpartition(part, in_use, slot)
579 	struct apple_part_map_entry *part;
580 	char in_use[];
581 	int slot;
582 {
583 	EBZB *bzb;
584 
585 	bzb = (EBZB *)&part->pmBootArgs[0];
586 	in_use[slot] = 1;
587 	bzb->flags.used = 1;
588 	bzb->flags.part = 'a' + slot;
589 }
590 
591 /*
592  * Find an entry in a use array that is unused and return it or
593  *  -1 if no entry is available
594  */
595 static int
getFreeLabelEntry(slots)596 getFreeLabelEntry(slots)
597 	char *slots;
598 {
599 	int i;
600 
601 	for ( i = 0; i < MAXPARTITIONS; i++) {
602 		if (i != RAW_PART && slots[i] == 0)
603 			return i;
604 	}
605 	return -1;
606 }
607 
608 /*
609  * Figure out what type type of the given partition is and return it.
610  */
611 int
whichType(part)612 whichType(part)
613 	struct apple_part_map_entry *part;
614 {
615 	MAP_TYPE *map_entry = (MAP_TYPE *)&map_types;
616 	EBZB *bzb;
617 	char partyp[32];
618 	int type, maxsiz, entry_type = MAP_OTHER;
619 
620 	bzb = (EBZB *)&part->pmBootArgs[0];
621 	if (part->pmSig != APPLE_PART_MAP_ENTRY_MAGIC)
622 	    return 0;
623 	maxsiz = sizeof(part->pmPartType);
624 	if (maxsiz > (int)sizeof(partyp))
625 	    maxsiz = sizeof(partyp);
626 	strncpy(partyp, (char *)part->pmPartType, maxsiz);
627 	partyp[maxsiz-1] = '\0';
628 
629 	/*
630 	 * Find out how to treat the partition type under NetBSD
631 	 */
632 	while (map_entry->type != MAP_EOL) {
633 	    if (stricmp(map_entry->name, partyp) == 0) {
634 		entry_type = map_entry->type;
635 		break;
636 	    }
637 	    map_entry++;
638 	}
639 
640 	/*
641 	 * Now classify the use for NetBSD
642 	 */
643 	if (entry_type == MAP_RESERVED)
644 		type = 0;
645 	else if (entry_type == MAP_NETBSD) {
646 	    if (bzb->magic != APPLE_BZB_MAGIC)
647 		type = 0;
648 	    else if (bzb->type == APPLE_BZB_TYPEFS) {
649 		if (bzb->flags.root)
650 		    type = ROOT_PART;
651 		else if (bzb->flags.usr)
652 		    type = UFS_PART;
653 		else
654 		    type = SCRATCH_PART;
655 	    } else if (bzb->type == APPLE_BZB_TYPESWAP)
656 		type = SWAP_PART;
657 	    else
658 		type = SCRATCH_PART;
659 	} else if (entry_type == MAP_MACOS)
660 	    type = HFS_PART;
661 	else
662 	    type = SCRATCH_PART;
663 	return type;
664 }
665 
666 static char *
getFstype(part,len_type,type)667 getFstype(part, len_type, type)
668 	struct apple_part_map_entry *part;
669 	int len_type;
670 	char *type;
671 {
672 	*type = '\0';
673 	switch(whichType(part)) {
674 	    case ROOT_PART:
675 	    case UFS_PART:
676 		strncpy(type, "4.2BSD", len_type);
677 		break;
678 	    case SWAP_PART:
679 		strncpy(type, "swap", len_type);
680 		break;
681 	    case HFS_PART:
682 		strncpy(type, "HFS", len_type);
683 		break;
684 	    case SCRATCH_PART:
685 	    default:
686 		break;
687 	}
688 	return (type);
689 }
690 
691 static char *
getUse(part,len_use,use)692 getUse(part, len_use, use)
693 	struct apple_part_map_entry *part;
694 	int len_use;
695 	char *use;
696 {
697 	EBZB *bzb;
698 	char partyp[32];
699 
700 	*use = '\0';
701 	bzb = (EBZB *)&part->pmBootArgs[0];
702 	switch(whichType(part)) {
703 	    case ROOT_PART:
704 		if (bzb->flags.usr)
705 		    strncpy(use, "Root&Usr", len_use);
706 		else
707 		    strncpy(use, "Root", len_use);
708 		break;
709 	    case UFS_PART:
710 		strncpy(use, "Usr", len_use);
711 		break;
712 	    case SWAP_PART:
713 		break;
714 	    case HFS_PART:
715 		strncpy(use, "MacOS", len_use);
716 		break;
717 	    case SCRATCH_PART:
718 		strncpy(partyp, (char *)part->pmPartType, sizeof(partyp));
719 		partyp[sizeof(partyp)-1] = '\0';
720 		if (stricmp("Apple_Free", partyp) == 0)
721 		    strncpy(use, "Free", len_use);
722 		else if (stricmp("Apple_Scratch", partyp) == 0)
723 		    strncpy(use, "Scratch", len_use);
724 		else if (stricmp("Apple_MFS", partyp) == 0)
725 		    strncpy(use, "MFS", len_use);
726 		else if (stricmp("Apple_PRODOS", partyp) == 0)
727 		    strncpy(use, "PRODOS", len_use);
728 		else
729 		    strncpy(use, "unknown", len_use);
730 	    default:
731 		break;
732 	}
733 	return(use);
734 }
735 
736 static char *
getName(part,len_name,name)737 getName(part, len_name, name)
738 	struct apple_part_map_entry *part;
739 	int len_name;
740 	char *name;
741 {
742 	EBZB *bzb;
743 	int fd;
744 	off_t seek;
745 	char dev_name[100], macosblk[512];
746 
747 	*name = '\0';
748 	bzb = (EBZB *)&part->pmBootArgs[0];
749 	switch(whichType(part)) {
750 	    case SCRATCH_PART:
751 	    case ROOT_PART:
752 	    case UFS_PART:
753 		strncpy(name, (char *)bzb->mount_point, len_name);
754 		break;
755 	    case SWAP_PART:
756 		break;
757 	    case HFS_PART:
758 		/*
759 		 * OK, this is stupid but it's damn nice to know!
760 		 */
761 		snprintf (dev_name, sizeof(dev_name), "/dev/r%sc", pm->diskdev);
762 		/*
763 		 * Open the disk as a raw device
764 		 */
765 		if ((fd = open(dev_name, O_RDONLY, 0)) >= 0) {
766 		    seek = (off_t)part->pmPyPartStart + (off_t)2;
767 		    seek *= (off_t)blk_size;
768 		    lseek(fd, seek, SEEK_SET);
769 		    read(fd, &macosblk, sizeof(macosblk));
770 		    macosblk[37+32] = '\0';
771 		    strncpy(name, (char *)bzb->mount_point, len_name);
772 		    strncat(name, " (", len_name-strlen(name));
773 		    strncat(name, &macosblk[37], len_name-strlen(name));
774 		    strncat(name, ")", len_name-strlen(name));
775 		    close(fd);
776 		}
777 		break;
778 	    default:
779 		break;
780 	}
781 	return(name);
782 }
783 
784 /*
785  * Find the first occurrence of a Standard Type partition and
786  *  mark it for use along with the default mount slot.
787  */
788 static int
findStdType(num_parts,in_use,type,count,alt)789 findStdType(num_parts, in_use, type, count, alt)
790 	int num_parts;
791 	char in_use[];
792 	int type;
793 	int *count;
794 	int alt;
795 {
796 	EBZB *bzb;
797 	int i;
798 
799 	for (i = 0; i < num_parts; i++) {
800 		bzb = (EBZB *)&map.blk[i].pmBootArgs[0];
801 		if (whichType(&map.blk[i]) != type || bzb->flags.used)
802 			continue;
803 		if (type == ROOT_PART) {
804 			if (alt >= 0 && alt != bzb->cluster)
805 				continue;
806 			setpartition(&map.blk[i], in_use, 0);
807 			strcpy ((char *)bzb->mount_point, "/");
808 			*count += 1;
809 		} else if (type == UFS_PART) {
810 			if (alt >= 0 && alt != bzb->cluster)
811 				continue;
812 			setpartition(&map.blk[i], in_use, 6);
813 			if (bzb->mount_point[0] == '\0')
814 				strcpy ((char *)bzb->mount_point, "/usr");
815 			*count += 1;
816 		} else if (type == SWAP_PART) {
817 			setpartition(&map.blk[i], in_use, 1);
818 			*count += 1;
819 		}
820 		return 0;
821 	}
822 	return -1;
823 }
824 
825 /*
826  * Reset the flags and reserved fields in the selected partition.
827  * This functions isn't called to process any of the reserved partitions
828  * where the boot code for MacOS is stored, so (hopefully) we won't
829  * do more damage that we're trying to avoid.  Eventually the NetBSD
830  * Boot Code will need to go into a partition too, but that should go
831  * into a reserved partition as well.  I'd suggest using a partition
832  * named something like "NetBSD_Boot" with a pmPartName of "Macintosh".
833  * The Apple Start Manager (in ROM) will then recognize the partition
834  * as the one containing the system bootstrip for the volume.
835  */
836 void
reset_part_flags(part)837 reset_part_flags(part)
838 	struct apple_part_map_entry *part;
839 {
840 	EBZB *bzb;
841 
842 	/*
843 	 * Clear out the MacOS fields that might be used for booting just
844 	 *  in case we've clobbered the boot code.
845 	 */
846 	part->pmLgDataStart = 0;
847 	part->pmPartStatus = 0x77;  /* make sure the partition shows up */
848 	part->pmLgBootStart = 0;
849 	part->pmBootSize = 0;
850 	part->pmBootLoad = 0;
851 	part->pmBootLoad2 = 0;
852 	part->pmBootEntry = 0;
853 	part->pmBootEntry2 = 0;
854 	part->pmBootCksum = 0;
855 
856 	/*
857 	 * Clear out all the NetBSD fields too.  We only clear out the ones
858 	 *  that should get reset during our processing.
859 	 */
860 	bzb = (EBZB *)&part->pmBootArgs[0];
861 	bzb->magic = 0;
862 	bzb->cluster = 0;
863 	bzb->inode = 0;
864 	bzb->type = 0;
865 	bzb->flags.root = 0;
866 	bzb->flags.usr = 0;
867 	bzb->flags.crit = 0;
868 	bzb->flags.slice = 0;
869 	bzb->flags.used = 0;
870 	return;
871 }
872 
873 /*
874  * sortmerge:
875  *  1) Moves all the Partition Map entries to the front of the Map.
876  *     This is required because some disk formatters leave holes.
877  *  2) Sorts all entries by ascending start block number.
878  *     Needed so the NetBSD algorithm for finding partitions works
879  *     consistently from a user perspective.
880  *  3) Collapse multiple adjected "free" entries into a single entry.
881  *  4) Identify the NetBSD mount_points.
882  */
883 void
sortmerge(void)884 sortmerge(void)
885 {
886     struct apple_part_map_entry tmp_blk;
887     char in_use[MAXPARTITIONS];
888     int i, j;
889     EBZB *bzb;
890 
891     /*
892      * Step 1, squeeze out the holes that some disk formatters leave in
893      *  the Map.  Also convert any "old" Map entries to the new entry
894      *  type. Also clear out our used flag which is used to indicte
895      *  we've mapped the partition.
896      */
897     map.in_use_cnt = 0;
898     for (i=0;i<map.size-1;i++) {
899 	if (map.blk[i].pmSig == 0x5453)
900 	    map.blk[i].pmSig = APPLE_PART_MAP_ENTRY_MAGIC;
901 	if (map.blk[i].pmSig != APPLE_PART_MAP_ENTRY_MAGIC) {
902 	    for (j=i+1;j<map.size;j++) {
903 		if (map.blk[j].pmSig == 0x5453)
904 		    map.blk[j].pmSig = APPLE_PART_MAP_ENTRY_MAGIC;
905 		if (map.blk[j].pmSig == APPLE_PART_MAP_ENTRY_MAGIC) {
906 		    memcpy (&map.blk[i], &map.blk[j], sizeof(map.blk[i]));
907 		    map.blk[j].pmSig = 0;
908 		    break;
909 		}
910 	    }
911 	} else {
912 	    map.in_use_cnt += 1;
913 	    bzb = (EBZB *)&map.blk[i].pmBootArgs[0];
914 	    bzb->flags.used = 0;
915 	    bzb->flags.part = 0;
916 	}
917     }
918 
919     /*
920      * Step 2, sort by ascending starting block number.  Since
921      *         we've already removed the holes we only need to
922      *         deal with the in_use count of blocks.
923      */
924     for (i=0;i<map.in_use_cnt-1;i++) {
925 	for (j=i+1;j<map.in_use_cnt;j++) {
926 	    if (map.blk[i].pmPyPartStart > map.blk[j].pmPyPartStart) {
927 		memcpy (&tmp_blk, &map.blk[i], sizeof(tmp_blk));
928 		memcpy (&map.blk[i], &map.blk[j], sizeof(map.blk[i]));
929 		memcpy (&map.blk[j], &tmp_blk, sizeof(map.blk[j]));
930 	    }
931 	}
932     }
933 
934     /*
935      * Step 3, merge adjacent free space
936      */
937     for (i=0;i<map.in_use_cnt-1;i++) {
938         if (stricmp("Apple_Free", (char *)map.blk[i].pmPartType) == 0 &&
939 	    stricmp("Apple_Free", (char *)map.blk[i+1].pmPartType) == 0) {
940 	    map.blk[i].pmPartBlkCnt += map.blk[i+1].pmPartBlkCnt;
941 	    map.blk[i].pmDataCnt += map.blk[i+1].pmDataCnt;
942 	    map.blk[i+1].pmSig = 0;
943 	    for (j=i+1;j<map.in_use_cnt-1;j++) {
944 		memcpy (&map.blk[j], &map.blk[j+1], sizeof(map.blk[j]));
945 		map.blk[j+1].pmSig = 0;
946 	    }
947 	    map.in_use_cnt -= 1;
948 	}
949     }
950 
951     /*
952      * Step 4, try to identify the mount points for the partitions
953      *         and adjust the pmMapBlkCnt in each Map entry.  Set
954      *         up the display array for the non-reserved partitions,
955      *         and count the number of NetBSD usable partitions
956      */
957     map.hfs_cnt = 0;
958     map.root_cnt = 0;
959     map.swap_cnt = 0;
960     map.usr_cnt = 0;
961     map.usable_cnt = 0;
962     /*
963      * Clear out record of partition slots already in use
964      */
965     memset(&in_use, 0, sizeof(in_use));
966     for (i=0,j=0;i<map.in_use_cnt;i++) {
967         map.blk[i].pmSig = APPLE_PART_MAP_ENTRY_MAGIC;
968         map.blk[i].pmMapBlkCnt = map.in_use_cnt;
969 	/*
970 	 * Since MAXPARTITIONS == 8 for mac68k, and we do not display
971 	 * the c partition, we only need 7 partition slots on the screen.
972 	 * If/when MAXPARTITIONS is changed, the "Edit Disk Partition Map"
973 	 * needs to be a scrollable view of the partition table.
974 	 */
975         if (whichType(&map.blk[i]) && (j < MAXPARTITIONS - 1)) {
976 		map.mblk[j++] = i;
977 		map.usable_cnt += 1;
978 	}
979     }
980     /*
981      * Fill in standard partitions.  Look for a Cluster "0" first and use
982      *  it, otherwise take any Cluster value.
983      */
984     if (findStdType(map.in_use_cnt, in_use, ROOT_PART, &map.root_cnt, 0))
985 	findStdType(map.in_use_cnt, in_use, ROOT_PART, &map.root_cnt, -1);
986     if (findStdType(map.in_use_cnt, in_use, UFS_PART, &map.usr_cnt, 0))
987 	findStdType(map.in_use_cnt, in_use, UFS_PART, &map.usr_cnt, -1);
988     if (findStdType(map.in_use_cnt, in_use, SWAP_PART, &map.swap_cnt, 0))
989 	findStdType(map.in_use_cnt, in_use, SWAP_PART, &map.swap_cnt, -1);
990 
991 #ifdef MD_DEBUG_SORT_MERGE
992 	md_debug_dump("After marking Standard Types");
993 #endif
994     /*
995      * Now fill in the remaining partitions counting them by type and
996      *  assigning them the slot the where the kernel should map them.
997      * This will be where they are displayed in the Edit Map.
998      */
999     for (i=0; i < map.in_use_cnt; i++) {
1000 	bzb = (EBZB *)&map.blk[i].pmBootArgs[0];
1001 	if (bzb->flags.used == 0) {
1002 	    if ((j = getFreeLabelEntry(in_use)) < 0)
1003 		break;
1004 	    switch (whichType(&map.blk[i])) {
1005 		case ROOT_PART:
1006 		    map.root_cnt += 1;
1007 		    setpartition(&map.blk[i], in_use, j);
1008 		    break;
1009 		case UFS_PART:
1010 		    map.usr_cnt += 1;
1011 		    setpartition(&map.blk[i], in_use, j);
1012 		    break;
1013 		case SWAP_PART:
1014 		    map.swap_cnt += 1;
1015 		    setpartition(&map.blk[i], in_use, j);
1016 		    break;
1017 		case HFS_PART:
1018 		    map.hfs_cnt += 1;
1019 		    setpartition(&map.blk[i], in_use, j);
1020 		    break;
1021 		case SCRATCH_PART:
1022 		    setpartition(&map.blk[i], in_use, j);
1023 		default:
1024 		    break;
1025 	    }
1026 	}
1027     }
1028 #ifdef MD_DEBUG_SORT_MERGE
1029 	md_debug_dump("After sort merge");
1030 #endif
1031     return;
1032 }
1033 
1034 void
disp_selected_part(sel)1035 disp_selected_part(sel)
1036 	int sel;
1037 {
1038 	int i,j;
1039 	char fstyp[16], use[16], name[32];
1040 	EBZB *bzb;
1041 
1042 	msg_table_add(MSG_mac68k_part_header);
1043 	for (i=0;i<map.usable_cnt;i++) {
1044 	    if (i == sel) msg_standout();
1045 	    j = map.mblk[i];
1046 	    getFstype(&map.blk[j], sizeof(fstyp), fstyp);
1047 	    getUse(&map.blk[j], sizeof(use), use);
1048 	    getName(&map.blk[j], sizeof(name), name);
1049 	    bzb = (EBZB *)&map.blk[j].pmBootArgs[0];
1050 	    msg_fmt_table_add(MSG_part_row, "%s%c%d%d%s%s%s",
1051 		pm->diskdev,
1052 		bzb->flags.part, map.blk[j].pmPyPartStart,
1053                  map.blk[j].pmPartBlkCnt, fstyp, use, name);
1054 	    if (i == sel) msg_standend();
1055 	}
1056 	return;
1057 }
1058 
1059 /*
1060  * check for any anomalies on the requested setup
1061  */
1062 static int
check_for_errors()1063 check_for_errors()
1064 {
1065     int i, j;
1066     int errs = 0;
1067 
1068     errs = (!map.root_cnt) || (map.root_cnt > 1) || (!map.swap_cnt) ||
1069 	   (map.swap_cnt > 1);
1070 
1071     for (i=0;i<map.usable_cnt;i++) {
1072 	j = map.mblk[i];
1073 	if (map.blk[j].pmPyPartStart > pm->dlsize)
1074 		errs++;
1075 	if ((map.blk[j].pmPyPartStart + map.blk[j].pmPartBlkCnt) > pm->dlsize + 1)
1076 		errs++;
1077     }
1078     return(errs);
1079 }
1080 
1081 /*
1082  * check for and report anomalies on the requested setup
1083  */
1084 void
report_errors()1085 report_errors()
1086 {
1087     int i, j;
1088     int errs = 0;
1089     EBZB *bzb;
1090 
1091     if (!map.root_cnt) {
1092 	msg_display_add(MSG_disksetup_no_root);
1093 	errs++;
1094     }
1095     if (map.root_cnt > 1) {
1096 	msg_display_add(MSG_disksetup_multiple_roots);
1097 	errs++;
1098     }
1099     if (!map.swap_cnt) {
1100 	msg_display_add(MSG_disksetup_no_swap);
1101 	errs++;
1102     }
1103     if (map.swap_cnt > 1) {
1104 	msg_display_add(MSG_disksetup_multiple_swaps);
1105 	errs++;
1106     }
1107     for (i=0;i<map.usable_cnt;i++) {
1108 	j = map.mblk[i];
1109 	if (map.blk[j].pmPyPartStart > pm->dlsize) {
1110 	    bzb = (EBZB *)&map.blk[j].pmBootArgs[0];
1111 	    msg_fmt_display_add(MSG_disksetup_part_beginning, "%s%c",
1112 		pm->diskdev, bzb->flags.part);
1113 	    errs++;
1114 	}
1115 	if ((map.blk[j].pmPyPartStart + map.blk[j].pmPartBlkCnt) > pm->dlsize) {
1116 	    bzb = (EBZB *)&map.blk[j].pmBootArgs[0];
1117 	    msg_fmt_display_add(MSG_disksetup_part_size, "%s%c",
1118 		pm->diskdev, bzb->flags.part);
1119 	    errs++;
1120 	}
1121     }
1122     if (!errs)
1123 	msg_display_add(MSG_disksetup_noerrors);
1124     return;
1125 }
1126 
1127 static int
edit_diskmap(void)1128 edit_diskmap(void)
1129 {
1130     int i;
1131 
1132 	/* Ask full/part */
1133 	msg_fmt_display (MSG_mac68k_fullpart, "%s", pm->diskdev);
1134 	process_menu (MENU_fullpart, NULL);
1135 
1136 	map.selected = 0;
1137 	sortmerge();
1138 
1139 	/* If blowing away the whole disk, let user know if there
1140 	 *  are any active disk partitions */
1141 	if (usefull) {
1142 	    if (map.usable_cnt > (map.root_cnt+map.swap_cnt+map.usr_cnt)) {
1143 		msg_display (MSG_mac68k_ovrwrite);
1144 		if (!ask_noyes(NULL)) {
1145 			endwin();
1146 			return 0;
1147 		}
1148 	    }
1149 	    /*
1150 	     * mark all non-reserved partitions as "free"
1151 	     *  then sort and merge the map into something sensible
1152 	     */
1153 	    for (i=0;i<map.size;i++)
1154 		if (whichType(&map.blk[i]))
1155 		    strcpy ((char *)map.blk[i].pmPartType, "Apple_Free");
1156 	    sortmerge();
1157 	}
1158 	process_menu (MENU_editparttable, NULL);
1159 	return 1;
1160 }
1161 
1162 #ifdef MD_DEBUG_SORT_MERGE
1163 static int
md_debug_dump(title)1164 md_debug_dump(title)
1165 	char *title;
1166 {
1167 	char buf[96], type;
1168 	char fstyp[16], use[16], name[64];
1169 	int i, j, rv;
1170 	EBZB *bzb;
1171 
1172 	msg_clear();
1173 	sprintf(buf, "Apple Disk Partition Map: %s", title);
1174 	msg_fmt_table_add(MSG_dump_line, "%s", buf);
1175 	msg_fmt_table_add(MSG_dump_line, "%s",
1176            "slot      base   fstype        use name");
1177 	for (i=0;i<map.in_use_cnt;i++) {
1178 	   j = whichType(&map.blk[i]);
1179 	   getFstype(&map.blk[i], sizeof(fstyp), fstyp);
1180 	   getUse(&map.blk[i], sizeof(use), use);
1181 	   getName(&map.blk[i], sizeof(name), name);
1182 	   bzb = (EBZB *) &map.blk[i].pmBootArgs[0];
1183 	   type = bzb->flags.part;
1184 	   if (type < 'a' || type > 'h') type = '?';
1185 	   if (j == 0) strcpy (name, "reserved for Apple");
1186            sprintf(buf, " %02d:%c %08x %8s %10s %s", i+1,  type,
1187 		map.blk[i].pmPyPartStart, fstyp, use, name);
1188            msg_fmt_table_add(MSG_dump_line, "%s", buf);
1189 	}
1190 	process_menu(MENU_okabort, &rv);
1191 	msg_clear();
1192 	return rv;
1193 }
1194 #endif /* MD_DEBUG_SORT_MERGE */
1195 
1196 int
md_pre_mount(struct install_partition_desc * install,size_t ndx)1197 md_pre_mount(struct install_partition_desc *install, size_t ndx)
1198 {
1199 	return 0;
1200 }
1201 
1202 bool
md_parts_use_wholedisk(struct disk_partitions * parts)1203 md_parts_use_wholedisk(struct disk_partitions *parts)
1204 {
1205 	return parts_use_wholedisk(parts, 0, NULL);
1206 }
1207 
1208 #ifdef HAVE_GPT
1209 bool
md_gpt_post_write(struct disk_partitions * parts,part_id root_id,bool root_is_new,part_id efi_id,bool efi_is_new)1210 md_gpt_post_write(struct disk_partitions *parts, part_id root_id,
1211     bool root_is_new, part_id efi_id, bool efi_is_new)
1212 {
1213 	/* no GPT boot support, nothing needs to be done here */
1214 	return true;
1215 }
1216 #endif
1217 
1218