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