Merge branch 'softres'
[profile/ivi/syslinux.git] / dos / syslinux.c
1 /* ----------------------------------------------------------------------- *
2  *
3  *   Copyright 1998-2008 H. Peter Anvin - All Rights Reserved
4  *   Copyright 2009 Intel Corporation; author: H. Peter Anvin
5  *
6  *   This program is free software; you can redistribute it and/or modify
7  *   it under the terms of the GNU General Public License as published by
8  *   the Free Software Foundation, Inc., 53 Temple Place Ste 330,
9  *   Boston MA 02111-1307, USA; either version 2 of the License, or
10  *   (at your option) any later version; incorporated herein by reference.
11  *
12  * ----------------------------------------------------------------------- */
13
14 /*
15  * syslinux.c - Linux installer program for SYSLINUX
16  *
17  * Hacked up for DOS.
18  */
19
20 #include <errno.h>
21 #include <stdio.h>
22 #include <string.h>
23 #include <stdlib.h>
24 #include <stdarg.h>
25 #include "mystuff.h"
26
27 #include "syslinux.h"
28 #include "libfat.h"
29
30 const char *program = "syslinux";       /* Name of program */
31 uint16_t dos_version;
32
33 #ifdef DEBUG
34 # define dprintf printf
35 void pause(void)
36 {
37     uint16_t ax;
38     
39     asm volatile("int $0x16" : "=a" (ax) : "a" (0));
40 }
41 #else
42 # define dprintf(...) ((void)0)
43 # define pause() ((void)0)
44 #endif
45
46 void __attribute__ ((noreturn)) usage(void)
47 {
48     puts("Usage: syslinux [-sfmar][-d directory] <drive>: [bootsecfile]\n");
49     exit(1);
50 }
51
52 void unlock_device(int);
53
54 void __attribute__ ((noreturn)) die(const char *msg)
55 {
56     unlock_device(0);
57     puts("syslinux: ");
58     puts(msg);
59     putchar('\n');
60     exit(1);
61 }
62
63 void warning(const char *msg)
64 {
65     puts("syslinux: warning: ");
66     puts(msg);
67     putchar('\n');
68 }
69
70 /*
71  * read/write wrapper functions
72  */
73 int creat(const char *filename, int mode)
74 {
75     uint16_t rv;
76     uint8_t err;
77
78     dprintf("creat(\"%s\", 0x%x)\n", filename, mode);
79
80     rv = 0x3C00;
81     asm volatile ("int $0x21 ; setc %0"
82                   : "=bcdm" (err), "+a" (rv)
83                   : "c" (mode), "d" (filename));
84     if (err) {
85         dprintf("rv = %d\n", rv);
86         die("cannot open ldlinux.sys");
87     }
88
89     return rv;
90 }
91
92 void close(int fd)
93 {
94     uint16_t rv = 0x3E00;
95
96     dprintf("close(%d)\n", fd);
97
98     asm volatile ("int $0x21":"+a" (rv)
99                   :"b"(fd));
100
101     /* The only error MS-DOS returns for close is EBADF,
102        and we really don't care... */
103 }
104
105 int rename(const char *oldname, const char *newname)
106 {
107     uint16_t rv = 0x5600;       /* Also support 43FFh? */
108     uint8_t err;
109
110     dprintf("rename(\"%s\", \"%s\")\n", oldname, newname);
111
112     asm volatile ("int $0x21 ; setc %0":"=bcdm" (err), "+a"(rv)
113                   :"d"(oldname), "D"(newname));
114
115     if (err) {
116         dprintf("rv = %d\n", rv);
117         warning("cannot move ldlinux.sys");
118         return rv;
119     }
120
121     return 0;
122 }
123
124 ssize_t write_file(int fd, const void *buf, size_t count)
125 {
126     uint16_t rv;
127     ssize_t done = 0;
128     uint8_t err;
129
130     dprintf("write_file(%d,%p,%u)\n", fd, buf, count);
131
132     while (count) {
133         rv = 0x4000;
134         asm volatile ("int $0x21 ; setc %0":"=abcdm" (err), "+a"(rv)
135                       :"b"(fd), "c"(count), "d"(buf));
136         if (err || rv == 0)
137             die("file write error");
138
139         done += rv;
140         count -= rv;
141     }
142
143     return done;
144 }
145
146 static inline __attribute__ ((const))
147 uint16_t data_segment(void)
148 {
149     uint16_t ds;
150
151     asm("movw %%ds,%0" : "=rm"(ds));
152     return ds;
153 }
154
155 void write_device(int drive, const void *buf, size_t nsecs, unsigned int sector)
156 {
157     uint16_t errnum;
158     struct diskio dio;
159
160     dprintf("write_device(%d,%p,%u,%u)\n", drive, buf, nsecs, sector);
161
162     dio.startsector = sector;
163     dio.sectors = nsecs;
164     dio.bufoffs = (uintptr_t) buf;
165     dio.bufseg = data_segment();
166
167     /* Try FAT32-aware system call first */
168     asm volatile("int $0x21 ; jc 1f ; xorw %0,%0\n"
169                  "1:"
170                  : "=a" (errnum)
171                  : "a" (0x7305), "b" (&dio), "c" (-1), "d" (drive),
172                    "S" (1), "m" (dio)
173                  : "memory");
174
175     /* If not supported, try the legacy system call (int2526.S) */
176     if (errnum == 0x0001)
177         errnum = int26_write_sector(drive, &dio);
178
179     if (errnum) {
180         dprintf("rv = %04x\n", errnum);
181         die("sector write error");
182     }
183 }
184
185 void read_device(int drive, const void *buf, size_t nsecs, unsigned int sector)
186 {
187     uint16_t errnum;
188     struct diskio dio;
189
190     dprintf("read_device(%d,%p,%u,%u)\n", drive, buf, nsecs, sector);
191
192     dio.startsector = sector;
193     dio.sectors = nsecs;
194     dio.bufoffs = (uintptr_t) buf;
195     dio.bufseg = data_segment();
196
197     /* Try FAT32-aware system call first */
198     asm volatile("int $0x21 ; jc 1f ; xorw %0,%0\n"
199                  "1:"
200                  : "=a" (errnum)
201                  : "a" (0x7305), "b" (&dio), "c" (-1), "d" (drive),
202                    "S" (0), "m" (dio));
203
204     /* If not supported, try the legacy system call (int2526.S) */
205     if (errnum == 0x0001)
206         errnum = int25_read_sector(drive, &dio);
207
208     if (errnum) {
209         dprintf("rv = %04x\n", errnum);
210         die("sector read error");
211     }
212 }
213
214 /* Both traditional DOS and FAT32 DOS return this structure, but
215    FAT32 return a lot more data, so make sure we have plenty of space */
216 struct deviceparams {
217     uint8_t specfunc;
218     uint8_t devtype;
219     uint16_t devattr;
220     uint16_t cylinders;
221     uint8_t mediatype;
222     uint16_t bytespersec;
223     uint8_t secperclust;
224     uint16_t ressectors;
225     uint8_t fats;
226     uint16_t rootdirents;
227     uint16_t sectors;
228     uint8_t media;
229     uint16_t fatsecs;
230     uint16_t secpertrack;
231     uint16_t heads;
232     uint32_t hiddensecs;
233     uint32_t hugesectors;
234     uint8_t lotsofpadding[224];
235 } __attribute__ ((packed));
236
237 uint32_t get_partition_offset(int drive)
238 {
239     uint8_t err;
240     uint16_t rv;
241     struct deviceparams dp;
242
243     dp.specfunc = 1;            /* Get current information */
244
245     rv = 0x440d;
246     asm volatile ("int $0x21 ; setc %0"
247                   :"=abcdm" (err), "+a"(rv), "=m"(dp)
248                   :"b" (drive), "c" (0x0860), "d" (&dp));
249
250     if (!err)
251         return dp.hiddensecs;
252
253     rv = 0x440d;
254     asm volatile ("int $0x21 ; setc %0"
255                   : "=abcdm" (err), "+a" (rv), "=m" (dp)
256                   : "b" (drive), "c" (0x4860), "d" (&dp));
257
258     if (!err)
259         return dp.hiddensecs;
260
261     die("could not find partition start offset");
262 }
263
264 struct rwblock {
265     uint8_t special;
266     uint16_t head;
267     uint16_t cylinder;
268     uint16_t firstsector;
269     uint16_t sectors;
270     uint16_t bufferoffset;
271     uint16_t bufferseg;
272 } __attribute__ ((packed));
273
274 static struct rwblock mbr = {
275     .special = 0,
276     .head = 0,
277     .cylinder = 0,
278     .firstsector = 0,           /* MS-DOS, unlike the BIOS, zero-base sectors */
279     .sectors = 1,
280     .bufferoffset = 0,
281     .bufferseg = 0
282 };
283
284 void write_mbr(int drive, const void *buf)
285 {
286     uint16_t rv;
287     uint8_t err;
288
289     dprintf("write_mbr(%d,%p)", drive, buf);
290
291     mbr.bufferoffset = (uintptr_t) buf;
292     mbr.bufferseg = data_segment();
293
294     rv = 0x440d;
295     asm volatile ("int $0x21 ; setc %0" : "=bcdm" (err), "+a"(rv)
296                   :"c"(0x0841), "d"(&mbr), "b"(drive), "m"(mbr));
297
298     dprintf(" rv(0841) = %04x", rv);
299     if (!err) {
300         dprintf("\n");
301         return;
302     }
303
304     rv = 0x440d;
305     asm volatile ("int $0x21 ; setc %0" : "=bcdm" (err), "+a"(rv)
306                   :"c"(0x4841), "d"(&mbr), "b"(drive), "m"(mbr));
307
308     dprintf(" rv(4841) = %04x\n", rv);
309     if (err)
310         die("mbr write error");
311 }
312
313 void read_mbr(int drive, const void *buf)
314 {
315     uint16_t rv;
316     uint8_t err;
317
318     dprintf("read_mbr(%d,%p)", drive, buf);
319
320     mbr.bufferoffset = (uintptr_t) buf;
321     mbr.bufferseg = data_segment();
322
323     rv = 0x440d;
324     asm volatile ("int $0x21 ; setc %0":"=abcdm" (err), "+a"(rv)
325                   :"c"(0x0861), "d"(&mbr), "b"(drive), "m"(mbr));
326
327     dprintf(" rv(0861) = %04x", rv);
328     if (!err) {
329         dprintf("\n");
330         return;
331     }
332
333     rv = 0x440d;
334     asm volatile ("int $0x21 ; setc %0":"=abcdm" (err), "+a"(rv)
335                   :"c"(0x4861), "d"(&mbr), "b"(drive), "m"(mbr));
336
337     dprintf(" rv(4841) = %04x\n", rv);
338     if (err)
339         die("mbr read error");
340
341     dprintf("Bytes: %02x %02x %02x %02x %02x %02x %02x %02x\n",
342             ((const uint8_t *)buf)[0],
343             ((const uint8_t *)buf)[1],
344             ((const uint8_t *)buf)[2],
345             ((const uint8_t *)buf)[3],
346             ((const uint8_t *)buf)[4],
347             ((const uint8_t *)buf)[5],
348             ((const uint8_t *)buf)[6],
349             ((const uint8_t *)buf)[7]);
350 }
351
352 /* This call can legitimately fail, and we don't care, so ignore error return */
353 void set_attributes(const char *file, int attributes)
354 {
355     uint16_t rv = 0x4301;
356
357     dprintf("set_attributes(\"%s\", 0x%02x)\n", file, attributes);
358
359     asm volatile ("int $0x21":"+a" (rv)
360                   :"c"(attributes), "d"(file));
361 }
362
363 /*
364  * Version of the read_device function suitable for libfat
365  */
366 int libfat_xpread(intptr_t pp, void *buf, size_t secsize,
367                   libfat_sector_t sector)
368 {
369     read_device(pp, buf, 1, sector);
370     return secsize;
371 }
372
373 static inline void get_dos_version(void)
374 {
375     uint16_t ver;
376
377     asm("int $0x21 ; xchgb %%ah,%%al"
378         : "=a" (ver) 
379         : "a" (0x3001)
380         : "ebx", "ecx");
381     dos_version = ver;
382
383     dprintf("DOS version %d.%d\n", (dos_version >> 8), dos_version & 0xff);
384 }
385
386 /* The locking interface relies on static variables.  A massive hack :( */
387 static uint8_t lock_level, lock_drive;
388
389 static inline void set_lock_device(uint8_t device)
390 {
391     lock_level  = 0;
392     lock_drive = device;
393 }
394
395 static int do_lock(uint8_t level)
396 {
397     uint16_t level_arg = lock_drive + (level << 8);
398     uint16_t rv;
399     uint8_t err;
400 #if 0
401     /* DOS 7.10 = Win95 OSR2 = first version with FAT32 */
402     uint16_t lock_call = (dos_version >= 0x070a) ? 0x484A : 0x084A;
403 #else
404     uint16_t lock_call = 0x084A; /* MSDN says this is OK for all filesystems */
405 #endif
406
407     dprintf("Trying lock %04x... ", level_arg);
408     asm volatile ("int $0x21 ; setc %0"
409                   : "=bcdm" (err), "=a" (rv)
410                   : "a" (0x440d), "b" (level_arg),
411                     "c" (lock_call), "d" (0x0001));
412     dprintf("%s %04x\n", err ? "err" : "ok", rv);
413
414     return err ? rv : 0;
415 }
416
417 void lock_device(int level)
418 {
419     static int hard_lock = 0;
420     int err;
421
422     if (dos_version < 0x0700)
423         return;                 /* Win9x/NT only */
424
425     if (!hard_lock) {
426         /* Assume hierarchial "soft" locking supported */
427
428         while (lock_level < level) {
429             int new_level = lock_level + 1;
430             err = do_lock(new_level);
431             if (err) {
432                 if (err == 0x0001) {
433                     /* Try hard locking next */
434                     hard_lock = 1;
435                 }
436                 goto soft_fail;
437             }
438
439             lock_level = new_level;
440         }
441         return;
442     }
443
444 soft_fail:
445     if (hard_lock) {
446         /* Hard locking, only level 4 supported */
447         /* This is needed for Win9x in DOS mode */
448         
449         err = do_lock(4);
450         if (err) {
451             if (err == 0x0001) {
452                 /* Assume locking is not needed */
453                 return;
454             }
455             goto hard_fail;
456         }
457
458         lock_level = 4;
459         return;
460     }
461
462 hard_fail:
463     die("could not lock device");
464 }
465
466 void unlock_device(int level)
467 {
468     uint16_t rv;
469     uint8_t err;
470     uint16_t unlock_call;
471
472     if (dos_version < 0x0700)
473         return;                 /* Win9x/NT only */
474
475 #if 0
476     /* DOS 7.10 = Win95 OSR2 = first version with FAT32 */
477     unlock_call = (dos_version >= 0x070a) ? 0x486A : 0x086A;
478 #else
479     unlock_call = 0x086A;       /* MSDN says this is OK for all filesystems */
480 #endif
481
482     if (lock_level == 4 && level > 0)
483         return;                 /* Only drop the hard lock at the end */
484
485     while (lock_level > level) {
486         uint8_t new_level = (lock_level == 4) ? 0 : lock_level - 1;
487         uint16_t level_arg = (new_level << 8) + lock_drive;
488         rv = 0x440d;
489         dprintf("Trying unlock %04x... ", new_level);
490         asm volatile ("int $0x21 ; setc %0"
491                       : "=bcdm" (err), "+a" (rv)
492                       : "b" (level_arg), "c" (unlock_call));
493         dprintf("%s %04x\n", err ? "err" : "ok", rv);
494         lock_level = new_level;
495     }
496 }
497
498 /*
499  * This function does any desired MBR manipulation; called with the device lock held.
500  */
501 struct mbr_entry {
502     uint8_t active;             /* Active flag */
503     uint8_t bhead;              /* Begin head */
504     uint8_t bsector;            /* Begin sector */
505     uint8_t bcylinder;          /* Begin cylinder */
506     uint8_t filesystem;         /* Filesystem value */
507     uint8_t ehead;              /* End head */
508     uint8_t esector;            /* End sector */
509     uint8_t ecylinder;          /* End cylinder */
510     uint32_t startlba;          /* Start sector LBA */
511     uint32_t sectors;           /* Length in sectors */
512 } __attribute__ ((packed));
513
514 static void adjust_mbr(int device, int writembr, int set_active)
515 {
516     static unsigned char sectbuf[512];
517     int i;
518
519     if (!writembr && !set_active)
520         return;                 /* Nothing to do */
521
522     read_mbr(device, sectbuf);
523
524     if (writembr) {
525         memcpy(sectbuf, syslinux_mbr, syslinux_mbr_len);
526         *(uint16_t *) (sectbuf + 510) = 0xaa55;
527     }
528
529     if (set_active) {
530         uint32_t offset = get_partition_offset(device);
531         struct mbr_entry *me = (struct mbr_entry *)(sectbuf + 446);
532         int found = 0;
533
534         dprintf("Searching for partition offset: %08x\n", offset);
535
536         for (i = 0; i < 4; i++) {
537             if (me->startlba == offset) {
538                 me->active = 0x80;
539                 found++;
540             } else {
541                 me->active = 0;
542             }
543             me++;
544         }
545
546         if (found < 1) {
547             die("partition not found (-a is not implemented for logical partitions)");
548         } else if (found > 1) {
549             die("multiple aliased partitions found");
550         }
551     }
552
553     write_mbr(device, sectbuf);
554 }
555
556 int main(int argc, char *argv[])
557 {
558     static unsigned char sectbuf[512];
559     int dev_fd, fd;
560     static char ldlinux_name[] = "@:\\ldlinux.sys";
561     char **argp, *opt;
562     int force = 0;              /* -f (force) option */
563     struct libfat_filesystem *fs;
564     libfat_sector_t s, *secp, sectors[65];      /* 65 is maximum possible */
565     int32_t ldlinux_cluster;
566     int nsectors;
567     const char *device = NULL, *bootsecfile = NULL;
568     const char *errmsg;
569     int i;
570     int writembr = 0;           /* -m (write MBR) option */
571     int set_active = 0;         /* -a (set partition active) option */
572     const char *subdir = NULL;
573     int stupid = 0;
574     int raid_mode = 0;
575
576     dprintf("argv = %p\n", argv);
577     for (i = 0; i <= argc; i++)
578         dprintf("argv[%d] = %p = \"%s\"\n", i, argv[i], argv[i]);
579
580     (void)argc;                 /* Unused */
581
582     get_dos_version();
583
584     for (argp = argv + 1; *argp; argp++) {
585         if (**argp == '-') {
586             opt = *argp + 1;
587             if (!*opt)
588                 usage();
589
590             while (*opt) {
591                 switch (*opt) {
592                 case 's':       /* Use "safe, slow and stupid" code */
593                     stupid = 1;
594                     break;
595                 case 'r':       /* RAID mode */
596                     raid_mode = 1;
597                     break;
598                 case 'f':       /* Force install */
599                     force = 1;
600                     break;
601                 case 'm':       /* Write MBR */
602                     writembr = 1;
603                     break;
604                 case 'a':       /* Set partition active */
605                     set_active = 1;
606                     break;
607                 case 'd':
608                     if (argp[1])
609                         subdir = *++argp;
610                     break;
611                 default:
612                     usage();
613                 }
614                 opt++;
615             }
616         } else {
617             if (bootsecfile)
618                 usage();
619             else if (device)
620                 bootsecfile = *argp;
621             else
622                 device = *argp;
623         }
624     }
625
626     if (!device)
627         usage();
628
629     /*
630      * Figure out which drive we're talking to
631      */
632     dev_fd = (device[0] & ~0x20) - 0x40;
633     if (dev_fd < 1 || dev_fd > 26 || device[1] != ':' || device[2])
634         usage();
635
636     set_lock_device(dev_fd);
637
638     lock_device(2);             /* Make sure we can lock the device */
639     read_device(dev_fd, sectbuf, 1, 0);
640     unlock_device(1);
641
642     /*
643      * Check to see that what we got was indeed an MS-DOS boot sector/superblock
644      */
645     if ((errmsg = syslinux_check_bootsect(sectbuf))) {
646         unlock_device(0);
647         puts(errmsg);
648         putchar('\n');
649         exit(1);
650     }
651
652     ldlinux_name[0] = dev_fd | 0x40;
653
654     set_attributes(ldlinux_name, 0x00);
655     fd = creat(ldlinux_name, 0);
656     write_file(fd, syslinux_ldlinux, syslinux_ldlinux_len);
657     close(fd);
658     set_attributes(ldlinux_name, 0x07); /* SYSTEM HIDDEN READONLY */
659
660     /*
661      * Now, use libfat to create a block map.  This probably
662      * should be changed to use ioctl(...,FIBMAP,...) since
663      * this is supposed to be a simple, privileged version
664      * of the installer.
665      */
666     lock_device(2);
667     fs = libfat_open(libfat_xpread, dev_fd);
668     ldlinux_cluster = libfat_searchdir(fs, 0, "LDLINUX SYS", NULL);
669     secp = sectors;
670     nsectors = 0;
671     s = libfat_clustertosector(fs, ldlinux_cluster);
672     while (s && nsectors < 65) {
673         *secp++ = s;
674         nsectors++;
675         s = libfat_nextsector(fs, s);
676     }
677     libfat_close(fs);
678
679     /*
680      * If requested, move ldlinux.sys
681      */
682     if (subdir) {
683         char new_ldlinux_name[160];
684         char *cp = new_ldlinux_name + 3;
685         const char *sd;
686         int slash = 1;
687
688         new_ldlinux_name[0] = dev_fd | 0x40;
689         new_ldlinux_name[1] = ':';
690         new_ldlinux_name[2] = '\\';
691
692         for (sd = subdir; *sd; sd++) {
693             char c = *sd;
694
695             if (c == '/' || c == '\\') {
696                 if (slash)
697                     continue;
698                 c = '\\';
699                 slash = 1;
700             } else {
701                 slash = 0;
702             }
703
704             *cp++ = c;
705         }
706
707         /* Skip if subdirectory == root */
708         if (cp > new_ldlinux_name + 3) {
709             if (!slash)
710                 *cp++ = '\\';
711
712             memcpy(cp, "ldlinux.sys", 12);
713
714             set_attributes(ldlinux_name, 0);
715             if (rename(ldlinux_name, new_ldlinux_name))
716                 set_attributes(ldlinux_name, 0x07);
717             else
718                 set_attributes(new_ldlinux_name, 0x07);
719         }
720     }
721
722     /*
723      * Patch ldlinux.sys and the boot sector
724      */
725     syslinux_patch(sectors, nsectors, stupid, raid_mode);
726
727     /*
728      * Write the now-patched first sector of ldlinux.sys
729      */
730     /* lock_device(3); -- doesn't seem to be needed */
731     write_device(dev_fd, syslinux_ldlinux, 1, sectors[0]);
732
733     /*
734      * Muck with the MBR, if desired, while we hold the lock
735      */
736     adjust_mbr(dev_fd, writembr, set_active);
737
738     /*
739      * To finish up, write the boot sector
740      */
741
742     /* Read the superblock again since it might have changed while mounted */
743     read_device(dev_fd, sectbuf, 1, 0);
744
745     /* Copy the syslinux code into the boot sector */
746     syslinux_make_bootsect(sectbuf);
747
748     /* Write new boot sector */
749     if (bootsecfile) {
750         unlock_device(0);
751         fd = creat(bootsecfile, 0x20);  /* ARCHIVE */
752         write_file(fd, sectbuf, 512);
753         close(fd);
754     } else {
755         write_device(dev_fd, sectbuf, 1, 0);
756         unlock_device(0);
757     }
758
759     /* Done! */
760
761     return 0;
762 }