b4a7ef451d22a8ed8ba17072e00b5e4a0e86a54d
[dragonfly.git] / sys / kern / subr_diskmbr.c
1 /*-
2  * Copyright (c) 1994 Bruce D. Evans.
3  * All rights reserved.
4  *
5  * Copyright (c) 1982, 1986, 1988 Regents of the University of California.
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. All advertising materials mentioning features or use of this software
17  *    must display the following acknowledgement:
18  *      This product includes software developed by the University of
19  *      California, Berkeley and its contributors.
20  * 4. Neither the name of the University nor the names of its contributors
21  *    may be used to endorse or promote products derived from this software
22  *    without specific prior written permission.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34  * SUCH DAMAGE.
35  *
36  *      from: @(#)ufs_disksubr.c        7.16 (Berkeley) 5/4/91
37  *      from: ufs_disksubr.c,v 1.8 1994/06/07 01:21:39 phk Exp $
38  * $FreeBSD: src/sys/kern/subr_diskmbr.c,v 1.45 2000/01/28 10:22:07 bde Exp $
39  */
40
41 #include <sys/param.h>
42 #include <sys/systm.h>
43 #include <sys/buf.h>
44 #include <sys/conf.h>
45 #include <sys/diskslice.h>
46 #define DOSPTYP_EXTENDED        5
47 #define DOSPTYP_EXTENDEDX       15
48 #define DOSPTYP_ONTRACK         84
49 #include <sys/diskmbr.h>
50 #include <sys/disk.h>
51 #include <sys/malloc.h>
52 #include <sys/syslog.h>
53 #include <sys/device.h>
54
55 #define TRACE(str)      do { if (dsi_debug) kprintf str; } while (0)
56
57 static volatile u_char dsi_debug;
58
59 /*
60  * This is what we have embedded in every boot1 for supporting the bogus
61  * "Dangerously Dedicated" mode. However, the old table is broken because
62  * it has an illegal geometry in it - it specifies 256 heads (heads = end
63  * head + 1) which causes nasty stuff when that wraps to zero in bios code.
64  * eg: divide by zero etc. This caused the dead-thinkpad problem, numerous
65  * SCSI bios crashes, EFI to crash, etc.
66  *
67  * We still have to recognize the old table though, even though we stopped
68  * inflicting it upon the world.
69  */
70 static struct dos_partition historical_bogus_partition_table[NDOSPART] = {
71         { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, },
72         { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, },
73         { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, },
74         { 0x80, 0, 1, 0, DOSPTYP_386BSD, 255, 255, 255, 0, 50000, },
75 };
76 static struct dos_partition historical_bogus_partition_table_fixed[NDOSPART] = {
77         { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, },
78         { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, },
79         { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, },
80         { 0x80, 0, 1, 0, DOSPTYP_386BSD, 254, 255, 255, 0, 50000, },
81 };
82
83 static int check_part (char *sname, struct dos_partition *dp,
84                            u_int64_t offset, int nsectors, int ntracks,
85                            u_int64_t mbr_offset);
86 static void mbr_extended (cdev_t dev, struct disk_info *info,
87                               struct diskslices *ssp, u_int64_t ext_offset,
88                               u_int64_t ext_size, u_int64_t base_ext_offset,
89                               int nsectors, int ntracks, u_int64_t mbr_offset,
90                               int level);
91 static int mbr_setslice (char *sname, struct disk_info *info,
92                              struct diskslice *sp, struct dos_partition *dp,
93                              u_int64_t br_offset);
94
95
96 int
97 mbrinit(cdev_t dev, struct disk_info *info, struct diskslices **sspp)
98 {
99         struct buf *bp;
100         u_char  *cp;
101         int     dospart;
102         struct dos_partition *dp;
103         struct dos_partition *dp0;
104         struct dos_partition dpcopy[NDOSPART];
105         int     error;
106         int     max_ncyls;
107         int     max_nsectors;
108         int     max_ntracks;
109         u_int64_t mbr_offset;
110         char    partname[2];
111         u_long  secpercyl;
112         char    *sname = "tempname";
113         struct diskslice *sp;
114         struct diskslices *ssp;
115         cdev_t wdev;
116
117         mbr_offset = DOSBBSECTOR;
118 reread_mbr:
119         /*
120          * Don't bother if the block size is weird or the
121          * media size is 0 (probably means no media present).
122          */
123         if (info->d_media_blksize & DEV_BMASK)
124                 return (EIO);
125         if (info->d_media_size == 0)
126                 return (EIO);
127
128         /*
129          * Read master boot record.
130          */
131         wdev = dev;
132         bp = geteblk((int)info->d_media_blksize);
133         bp->b_bio1.bio_offset = (off_t)mbr_offset * info->d_media_blksize;
134         bp->b_bio1.bio_done = biodone_sync;
135         bp->b_bio1.bio_flags |= BIO_SYNC;
136         bp->b_bcount = info->d_media_blksize;
137         bp->b_cmd = BUF_CMD_READ;
138         dev_dstrategy(wdev, &bp->b_bio1);
139         if (biowait(&bp->b_bio1, "mbrrd") != 0) {
140                 if ((info->d_dsflags & DSO_MBRQUIET) == 0) {
141                         diskerr(&bp->b_bio1, wdev,
142                                 "reading primary partition table: error",
143                                 LOG_PRINTF, 0);
144                         kprintf("\n");
145                 }
146                 error = EIO;
147                 goto done;
148         }
149
150         /* Weakly verify it. */
151         cp = bp->b_data;
152         sname = dsname(dev, 0, 0, 0, NULL);
153         if (cp[0x1FE] != 0x55 || cp[0x1FF] != 0xAA) {
154                 if (bootverbose)
155                         kprintf("%s: invalid primary partition table: no magic\n",
156                                sname);
157                 error = EINVAL;
158                 goto done;
159         }
160
161         /* Make a copy of the partition table to avoid alignment problems. */
162         memcpy(&dpcopy[0], cp + DOSPARTOFF, sizeof(dpcopy));
163
164         dp0 = &dpcopy[0];
165
166         /*
167          * Check for "Ontrack Diskmanager" or GPT.  If a GPT is found in
168          * the first dos partition, ignore the rest of the MBR and go
169          * to GPT processing.
170          */
171         for (dospart = 0, dp = dp0; dospart < NDOSPART; dospart++, dp++) {
172                 if (dospart == 0 &&
173                     (dp->dp_typ == DOSPTYP_PMBR || dp->dp_typ == DOSPTYP_GPT)) {
174                         if (bootverbose)
175                                 kprintf(
176             "%s: Found GPT in slice #%d\n", sname, dospart + 1);
177                         error = gptinit(dev, info, sspp);
178                         goto done;
179                 }
180
181                 if (dp->dp_typ == DOSPTYP_ONTRACK) {
182                         if (bootverbose)
183                                 kprintf(
184             "%s: Found \"Ontrack Disk Manager\" on this disk.\n", sname);
185                         bp->b_flags |= B_INVAL | B_AGE;
186                         brelse(bp);
187                         mbr_offset = 63;
188                         goto reread_mbr;
189                 }
190         }
191
192         if (bcmp(dp0, historical_bogus_partition_table,
193                  sizeof historical_bogus_partition_table) == 0 ||
194             bcmp(dp0, historical_bogus_partition_table_fixed,
195                  sizeof historical_bogus_partition_table_fixed) == 0) {
196 #if 0
197                 TRACE(("%s: invalid primary partition table: historical\n",
198                        sname));
199 #endif /* 0 */
200                 if (bootverbose)
201                         kprintf(
202      "%s: invalid primary partition table: Dangerously Dedicated (ignored)\n",
203                                sname);
204                 error = EINVAL;
205                 goto done;
206         }
207
208         /* Guess the geometry. */
209         /*
210          * TODO:
211          * Perhaps skip entries with 0 size.
212          * Perhaps only look at entries of type DOSPTYP_386BSD.
213          */
214         max_ncyls = 0;
215         max_nsectors = 0;
216         max_ntracks = 0;
217         for (dospart = 0, dp = dp0; dospart < NDOSPART; dospart++, dp++) {
218                 int     ncyls;
219                 int     nsectors;
220                 int     ntracks;
221
222                 ncyls = DPCYL(dp->dp_ecyl, dp->dp_esect) + 1;
223                 if (max_ncyls < ncyls)
224                         max_ncyls = ncyls;
225                 nsectors = DPSECT(dp->dp_esect);
226                 if (max_nsectors < nsectors)
227                         max_nsectors = nsectors;
228                 ntracks = dp->dp_ehd + 1;
229                 if (max_ntracks < ntracks)
230                         max_ntracks = ntracks;
231         }
232
233         /*
234          * Check that we have guessed the geometry right by checking the
235          * partition entries.
236          */
237         /*
238          * TODO:
239          * As above.
240          * Check for overlaps.
241          * Check against d_secperunit if the latter is reliable.
242          */
243         error = 0;
244         for (dospart = 0, dp = dp0; dospart < NDOSPART; dospart++, dp++) {
245                 if (dp->dp_scyl == 0 && dp->dp_shd == 0 && dp->dp_ssect == 0
246                     && dp->dp_start == 0 && dp->dp_size == 0)
247                         continue;
248                 //sname = dsname(dev, dkunit(dev), BASE_SLICE + dospart,
249                 //             WHOLE_SLICE_PART, partname);
250
251                 /*
252                  * Temporarily ignore errors from this check.  We could
253                  * simplify things by accepting the table eariler if we
254                  * always ignore errors here.  Perhaps we should always
255                  * accept the table if the magic is right but not let
256                  * bad entries affect the geometry.
257                  */
258                 check_part(sname, dp, mbr_offset, max_nsectors, max_ntracks,
259                            mbr_offset);
260         }
261         if (error != 0)
262                 goto done;
263
264         /*
265          * Accept the DOS partition table.
266          *
267          * Adjust the disk information structure with updated CHS
268          * conversion parameters, but only use values extracted from
269          * the primary partition table.
270          *
271          * NOTE!  Regardless of our having to deal with this old cruft,
272          * we do not screw around with the info->d_media* parameters.
273          */
274         secpercyl = (u_long)max_nsectors * max_ntracks;
275         if (secpercyl != 0 && mbr_offset == DOSBBSECTOR) {
276                 info->d_secpertrack = max_nsectors;
277                 info->d_nheads = max_ntracks;
278                 info->d_secpercyl = secpercyl;
279                 info->d_ncylinders = info->d_media_blocks / secpercyl;
280         }
281
282         /*
283          * We are passed a pointer to a suitably initialized minimal
284          * slices "struct" with no dangling pointers in it.  Replace it
285          * by a maximal one.  This usually oversizes the "struct", but
286          * enlarging it while searching for logical drives would be
287          * inconvenient.
288          */
289         kfree(*sspp, M_DEVBUF);
290         ssp = dsmakeslicestruct(MAX_SLICES, info);
291         *sspp = ssp;
292
293         /* Initialize normal slices. */
294         sp = &ssp->dss_slices[BASE_SLICE];
295         for (dospart = 0, dp = dp0; dospart < NDOSPART; dospart++, dp++, sp++) {
296                 sname = dsname(dev, dkunit(dev), BASE_SLICE + dospart,
297                                WHOLE_SLICE_PART, partname);
298                 (void)mbr_setslice(sname, info, sp, dp, mbr_offset);
299         }
300         ssp->dss_nslices = BASE_SLICE + NDOSPART;
301
302         /* Handle extended partitions. */
303         sp -= NDOSPART;
304         for (dospart = 0; dospart < NDOSPART; dospart++, sp++) {
305                 if (sp->ds_type == DOSPTYP_EXTENDED ||
306                     sp->ds_type == DOSPTYP_EXTENDEDX) {
307                         mbr_extended(wdev, info, ssp,
308                                      sp->ds_offset, sp->ds_size, sp->ds_offset,
309                                      max_nsectors, max_ntracks, mbr_offset, 1);
310                 }
311         }
312
313         /*
314          * mbr_extended() abuses ssp->dss_nslices for the number of slices
315          * that would be found if there were no limit on the number of slices
316          * in *ssp.  Cut it back now.
317          */
318         if (ssp->dss_nslices > MAX_SLICES)
319                 ssp->dss_nslices = MAX_SLICES;
320
321 done:
322         bp->b_flags |= B_INVAL | B_AGE;
323         brelse(bp);
324         if (error == EINVAL)
325                 error = 0;
326         return (error);
327 }
328
329 static int
330 check_part(char *sname, struct dos_partition *dp, u_int64_t offset,
331             int nsectors, int ntracks, u_int64_t mbr_offset)
332 {
333         int     chs_ecyl;
334         int     chs_esect;
335         int     chs_scyl;
336         int     chs_ssect;
337         int     error;
338         u_long  secpercyl;
339         u_int64_t esector;
340         u_int64_t esector1;
341         u_int64_t ssector;
342         u_int64_t ssector1;
343
344         secpercyl = (u_long)nsectors * ntracks;
345         chs_scyl = DPCYL(dp->dp_scyl, dp->dp_ssect);
346         chs_ssect = DPSECT(dp->dp_ssect);
347         ssector = chs_ssect - 1 + dp->dp_shd * nsectors + chs_scyl * secpercyl
348                   + mbr_offset;
349         ssector1 = offset + dp->dp_start;
350
351         /*
352          * If ssector1 is on a cylinder >= 1024, then ssector can't be right.
353          * Allow the C/H/S for it to be 1023/ntracks-1/nsectors, or correct
354          * apart from the cylinder being reduced modulo 1024.  Always allow
355          * 1023/255/63, because this is the official way to represent
356          * pure-LBA for the starting position.
357          */
358         if ((ssector < ssector1
359              && ((chs_ssect == nsectors && dp->dp_shd == ntracks - 1
360                   && chs_scyl == 1023)
361                  || (secpercyl != 0
362                      && (ssector1 - ssector) % (1024 * secpercyl) == 0)))
363             || (dp->dp_scyl == 255 && dp->dp_shd == 255
364                 && dp->dp_ssect == 255)) {
365                 TRACE(("%s: C/H/S start %d/%d/%d, start %llu: allow\n",
366                        sname, chs_scyl, dp->dp_shd, chs_ssect,
367                        (long long)ssector1));
368                 ssector = ssector1;
369         }
370
371         chs_ecyl = DPCYL(dp->dp_ecyl, dp->dp_esect);
372         chs_esect = DPSECT(dp->dp_esect);
373         esector = chs_esect - 1 + dp->dp_ehd * nsectors + chs_ecyl * secpercyl
374                   + mbr_offset;
375         esector1 = ssector1 + dp->dp_size - 1;
376
377         /*
378          * Allow certain bogus C/H/S values for esector, as above. However,
379          * heads == 255 isn't really legal and causes some BIOS crashes. The
380          * correct value to indicate a pure-LBA end is 1023/heads-1/sectors -
381          * usually 1023/254/63. "heads" is base 0, "sectors" is base 1.
382          */
383         if ((esector < esector1
384              && ((chs_esect == nsectors && dp->dp_ehd == ntracks - 1
385                   && chs_ecyl == 1023)
386                  || (secpercyl != 0
387                      && (esector1 - esector) % (1024 * secpercyl) == 0)))
388             || (dp->dp_ecyl == 255 && dp->dp_ehd == 255
389                 && dp->dp_esect == 255)) {
390                 TRACE(("%s: C/H/S end %d/%d/%d, end %llu: allow\n",
391                        sname, chs_ecyl, dp->dp_ehd, chs_esect,
392                        (long long)esector1));
393                 esector = esector1;
394         }
395
396         error = (ssector == ssector1 && esector == esector1) ? 0 : EINVAL;
397         if (bootverbose)
398                 kprintf("%s: type 0x%x, start %llu, end = %llu, size %u %s\n",
399                        sname, dp->dp_typ,
400                        (long long)ssector1, (long long)esector1,
401                        dp->dp_size, (error ? "" : ": OK"));
402         if (ssector != ssector1 && bootverbose)
403                 kprintf("%s: C/H/S start %d/%d/%d (%llu) != start %llu: invalid\n",
404                        sname, chs_scyl, dp->dp_shd, chs_ssect,
405                        (long long)ssector, (long long)ssector1);
406         if (esector != esector1 && bootverbose)
407                 kprintf("%s: C/H/S end %d/%d/%d (%llu) != end %llu: invalid\n",
408                        sname, chs_ecyl, dp->dp_ehd, chs_esect,
409                        (long long)esector, (long long)esector1);
410         return (error);
411 }
412
413 static
414 void
415 mbr_extended(cdev_t dev, struct disk_info *info, struct diskslices *ssp,
416             u_int64_t ext_offset, u_int64_t ext_size, u_int64_t base_ext_offset,
417             int nsectors, int ntracks, u_int64_t mbr_offset, int level)
418 {
419         struct buf *bp;
420         u_char  *cp;
421         int     dospart;
422         struct dos_partition *dp;
423         struct dos_partition dpcopy[NDOSPART];
424         u_int64_t ext_offsets[NDOSPART];
425         u_int64_t ext_sizes[NDOSPART];
426         char    partname[2];
427         int     slice;
428         char    *sname;
429         struct diskslice *sp;
430
431         if (level >= 16) {
432                 kprintf(
433         "%s: excessive recursion in search for slices; aborting search\n",
434                        devtoname(dev));
435                 return;
436         }
437
438         /* Read extended boot record. */
439         bp = geteblk((int)info->d_media_blksize);
440         bp->b_bio1.bio_offset = (off_t)ext_offset * info->d_media_blksize;
441         bp->b_bio1.bio_done = biodone_sync;
442         bp->b_bio1.bio_flags |= BIO_SYNC;
443         bp->b_bcount = info->d_media_blksize;
444         bp->b_cmd = BUF_CMD_READ;
445         dev_dstrategy(dev, &bp->b_bio1);
446         if (biowait(&bp->b_bio1, "mbrrd") != 0) {
447                 diskerr(&bp->b_bio1, dev,
448                         "reading extended partition table: error",
449                         LOG_PRINTF, 0);
450                 kprintf("\n");
451                 goto done;
452         }
453
454         /* Weakly verify it. */
455         cp = bp->b_data;
456         if (cp[0x1FE] != 0x55 || cp[0x1FF] != 0xAA) {
457                 sname = dsname(dev, dkunit(dev), WHOLE_DISK_SLICE, WHOLE_SLICE_PART,
458                                partname);
459                 if (bootverbose)
460                         kprintf("%s: invalid extended partition table: no magic\n",
461                                sname);
462                 goto done;
463         }
464
465         /* Make a copy of the partition table to avoid alignment problems. */
466         memcpy(&dpcopy[0], cp + DOSPARTOFF, sizeof(dpcopy));
467
468         slice = ssp->dss_nslices;
469         for (dospart = 0, dp = &dpcopy[0]; dospart < NDOSPART;
470             dospart++, dp++) {
471                 ext_sizes[dospart] = 0;
472                 if (dp->dp_scyl == 0 && dp->dp_shd == 0 && dp->dp_ssect == 0
473                     && dp->dp_start == 0 && dp->dp_size == 0)
474                         continue;
475                 if (dp->dp_typ == DOSPTYP_EXTENDED ||
476                     dp->dp_typ == DOSPTYP_EXTENDEDX) {
477                         static char buf[32];
478
479                         sname = dsname(dev, dkunit(dev), WHOLE_DISK_SLICE,
480                                        WHOLE_SLICE_PART, partname);
481                         ksnprintf(buf, sizeof(buf), "%s", sname);
482                         if (strlen(buf) < sizeof buf - 11)
483                                 strcat(buf, "<extended>");
484                         check_part(buf, dp, base_ext_offset, nsectors,
485                                    ntracks, mbr_offset);
486                         ext_offsets[dospart] = base_ext_offset + dp->dp_start;
487                         ext_sizes[dospart] = dp->dp_size;
488                 } else {
489                         sname = dsname(dev, dkunit(dev), slice, WHOLE_SLICE_PART,
490                                        partname);
491                         check_part(sname, dp, ext_offset, nsectors, ntracks,
492                                    mbr_offset);
493                         if (slice >= MAX_SLICES) {
494                                 kprintf("%s: too many slices\n", sname);
495                                 slice++;
496                                 continue;
497                         }
498                         sp = &ssp->dss_slices[slice];
499                         if (mbr_setslice(sname, info, sp, dp, ext_offset) != 0)
500                                 continue;
501                         slice++;
502                 }
503         }
504         ssp->dss_nslices = slice;
505
506         /* If we found any more slices, recursively find all the subslices. */
507         for (dospart = 0; dospart < NDOSPART; dospart++) {
508                 if (ext_sizes[dospart] != 0) {
509                         mbr_extended(dev, info, ssp, ext_offsets[dospart],
510                                      ext_sizes[dospart], base_ext_offset,
511                                      nsectors, ntracks, mbr_offset, ++level);
512                 }
513         }
514
515 done:
516         bp->b_flags |= B_INVAL | B_AGE;
517         brelse(bp);
518 }
519
520 static int
521 mbr_setslice(char *sname, struct disk_info *info, struct diskslice *sp,
522             struct dos_partition *dp, u_int64_t br_offset)
523 {
524         u_int64_t       offset;
525         u_int64_t       size;
526
527         offset = br_offset + dp->dp_start;
528         if (offset > info->d_media_blocks || offset < br_offset) {
529                 kprintf(
530                 "%s: slice starts beyond end of the disk: rejecting it\n",
531                        sname);
532                 return (1);
533         }
534         size = info->d_media_blocks - offset;
535         if (size >= dp->dp_size) {
536                 if (dp->dp_size == 0xFFFFFFFFU) {
537                         kprintf("%s: slice >2TB, using media size instead "
538                                 "of slice table size\n", sname);
539                 } else {
540                         size = dp->dp_size;
541                 }
542         } else {
543                 kprintf("%s: slice extends beyond end of disk: "
544                         "truncating from %u to %llu sectors\n",
545                         sname, dp->dp_size, (unsigned long long)size);
546         }
547         sp->ds_offset = offset;
548         sp->ds_size = size;
549         sp->ds_type = dp->dp_typ;
550         bzero(&sp->ds_type_uuid, sizeof(sp->ds_type_uuid));
551         bzero(&sp->ds_stor_uuid, sizeof(sp->ds_type_uuid));
552
553         /*
554          * Slices do not overlap with the parent (if any).
555          */
556         sp->ds_reserved = 0;
557         return (0);
558 }