dos: fix the soft-locking loop
[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 struct diskio {
156     uint32_t startsector;
157     uint16_t sectors;
158     uint16_t bufoffs, bufseg;
159 } __attribute__ ((packed));
160
161 void write_device(int drive, const void *buf, size_t nsecs, unsigned int sector)
162 {
163     uint8_t err;
164     uint16_t errnum;
165     struct diskio dio;
166
167     dprintf("write_device(%d,%p,%u,%u)\n", drive, buf, nsecs, sector);
168
169     dio.startsector = sector;
170     dio.sectors = nsecs;
171     dio.bufoffs = (uintptr_t) buf;
172     dio.bufseg = data_segment();
173
174     if (dos_version >= 0x0710) {
175         asm volatile("int $0x21 ; setc %0"
176                      : "=bcdm" (err), "=a" (errnum)
177                      : "a" (0x7305), "b" (&dio), "c" (-1), "d" (drive),
178                        "S" (1), "m" (dio)
179                      : "memory");
180     } else {
181         asm volatile("int $0x26 ; setc %0 ; popfw"
182                      : "=bcdm" (err), "=a" (errnum)
183                      : "a" (drive-1), "b" (&dio), "c" (-1), "d" (buf),
184                        "m" (dio)
185                      : "esi", "memory");
186     }
187
188     if (err) {
189         dprintf("rv = %04x\n", errnum);
190         die("sector write error");
191     }
192 }
193
194 void read_device(int drive, const void *buf, size_t nsecs, unsigned int sector)
195 {
196     uint8_t err;
197     uint16_t errnum;
198     struct diskio dio;
199
200     dprintf("read_device(%d,%p,%u,%u)\n", drive, buf, nsecs, sector);
201
202     dio.startsector = sector;
203     dio.sectors = nsecs;
204     dio.bufoffs = (uintptr_t) buf;
205     dio.bufseg = data_segment();
206
207     if (dos_version >= 0x0710) {
208         asm volatile("int $0x21 ; setc %0"
209                      : "=bcdm" (err), "=a" (errnum)
210                      : "a" (0x7305), "b" (&dio), "c" (-1), "d" (drive),
211                      "S" (0), "m" (dio));
212     } else {
213         asm volatile("int $0x25 ; setc %0 ; popfw"
214                      : "=bcdm" (err), "=a" (errnum)
215                      : "a" (drive-1), "b" (&dio), "c" (-1), "d" (buf),
216                        "m" (dio)
217                      : "esi");
218     }
219
220     if (err) {
221         dprintf("rv = %04x\n", errnum);
222         die("sector read error");
223     }
224 }
225
226 /* Both traditional DOS and FAT32 DOS return this structure, but
227    FAT32 return a lot more data, so make sure we have plenty of space */
228 struct deviceparams {
229     uint8_t specfunc;
230     uint8_t devtype;
231     uint16_t devattr;
232     uint16_t cylinders;
233     uint8_t mediatype;
234     uint16_t bytespersec;
235     uint8_t secperclust;
236     uint16_t ressectors;
237     uint8_t fats;
238     uint16_t rootdirents;
239     uint16_t sectors;
240     uint8_t media;
241     uint16_t fatsecs;
242     uint16_t secpertrack;
243     uint16_t heads;
244     uint32_t hiddensecs;
245     uint32_t hugesectors;
246     uint8_t lotsofpadding[224];
247 } __attribute__ ((packed));
248
249 uint32_t get_partition_offset(int drive)
250 {
251     uint8_t err;
252     uint16_t rv;
253     struct deviceparams dp;
254
255     dp.specfunc = 1;            /* Get current information */
256
257     rv = 0x440d;
258     asm volatile ("int $0x21 ; setc %0"
259                   :"=abcdm" (err), "+a"(rv), "=m"(dp)
260                   :"b" (drive), "c" (0x0860), "d" (&dp));
261
262     if (!err)
263         return dp.hiddensecs;
264
265     rv = 0x440d;
266     asm volatile ("int $0x21 ; setc %0"
267                   : "=abcdm" (err), "+a" (rv), "=m" (dp)
268                   : "b" (drive), "c" (0x4860), "d" (&dp));
269
270     if (!err)
271         return dp.hiddensecs;
272
273     die("could not find partition start offset");
274 }
275
276 struct rwblock {
277     uint8_t special;
278     uint16_t head;
279     uint16_t cylinder;
280     uint16_t firstsector;
281     uint16_t sectors;
282     uint16_t bufferoffset;
283     uint16_t bufferseg;
284 } __attribute__ ((packed));
285
286 static struct rwblock mbr = {
287     .special = 0,
288     .head = 0,
289     .cylinder = 0,
290     .firstsector = 0,           /* MS-DOS, unlike the BIOS, zero-base sectors */
291     .sectors = 1,
292     .bufferoffset = 0,
293     .bufferseg = 0
294 };
295
296 void write_mbr(int drive, const void *buf)
297 {
298     uint16_t rv;
299     uint8_t err;
300
301     dprintf("write_mbr(%d,%p)", drive, buf);
302
303     mbr.bufferoffset = (uintptr_t) buf;
304     mbr.bufferseg = data_segment();
305
306     rv = 0x440d;
307     asm volatile ("int $0x21 ; setc %0" : "=bcdm" (err), "+a"(rv)
308                   :"c"(0x0841), "d"(&mbr), "b"(drive), "m"(mbr));
309
310     dprintf(" rv(0841) = %04x", rv);
311     if (!err) {
312         dprintf("\n");
313         return;
314     }
315
316     rv = 0x440d;
317     asm volatile ("int $0x21 ; setc %0" : "=bcdm" (err), "+a"(rv)
318                   :"c"(0x4841), "d"(&mbr), "b"(drive), "m"(mbr));
319
320     dprintf(" rv(4841) = %04x\n", rv);
321     if (err)
322         die("mbr write error");
323 }
324
325 void read_mbr(int drive, const void *buf)
326 {
327     uint16_t rv;
328     uint8_t err;
329
330     dprintf("read_mbr(%d,%p)", drive, buf);
331
332     mbr.bufferoffset = (uintptr_t) buf;
333     mbr.bufferseg = data_segment();
334
335     rv = 0x440d;
336     asm volatile ("int $0x21 ; setc %0":"=abcdm" (err), "+a"(rv)
337                   :"c"(0x0861), "d"(&mbr), "b"(drive), "m"(mbr));
338
339     dprintf(" rv(0861) = %04x", rv);
340     if (!err) {
341         dprintf("\n");
342         return;
343     }
344
345     rv = 0x440d;
346     asm volatile ("int $0x21 ; setc %0":"=abcdm" (err), "+a"(rv)
347                   :"c"(0x4861), "d"(&mbr), "b"(drive), "m"(mbr));
348
349     dprintf(" rv(4841) = %04x\n", rv);
350     if (err)
351         die("mbr read error");
352
353     dprintf("Bytes: %02x %02x %02x %02x %02x %02x %02x %02x\n",
354             ((const uint8_t *)buf)[0],
355             ((const uint8_t *)buf)[1],
356             ((const uint8_t *)buf)[2],
357             ((const uint8_t *)buf)[3],
358             ((const uint8_t *)buf)[4],
359             ((const uint8_t *)buf)[5],
360             ((const uint8_t *)buf)[6],
361             ((const uint8_t *)buf)[7]);
362 }
363
364 /* This call can legitimately fail, and we don't care, so ignore error return */
365 void set_attributes(const char *file, int attributes)
366 {
367     uint16_t rv = 0x4301;
368
369     dprintf("set_attributes(\"%s\", 0x%02x)\n", file, attributes);
370
371     asm volatile ("int $0x21":"+a" (rv)
372                   :"c"(attributes), "d"(file));
373 }
374
375 /*
376  * Version of the read_device function suitable for libfat
377  */
378 int libfat_xpread(intptr_t pp, void *buf, size_t secsize,
379                   libfat_sector_t sector)
380 {
381     read_device(pp, buf, 1, sector);
382     return secsize;
383 }
384
385 static inline void get_dos_version(void)
386 {
387     uint16_t ver;
388
389     asm("int $0x21 ; xchgb %%ah,%%al"
390         : "=a" (ver) 
391         : "a" (0x3001)
392         : "ebx", "ecx");
393     dos_version = ver;
394
395     dprintf("DOS version %d.%d\n", (dos_version >> 8), dos_version & 0xff);
396 }
397
398 /* The locking interface relies on static variables.  A massive hack :( */
399 static uint8_t lock_level, lock_drive;
400
401 static inline void set_lock_device(uint8_t device)
402 {
403     lock_level  = 0;
404     lock_drive = device;
405 }
406
407 static int do_lock(uint8_t level)
408 {
409     uint16_t level_arg = lock_drive + (level << 8);
410     uint16_t rv;
411     uint8_t err;
412 #if 0
413     /* DOS 7.10 = Win95 OSR2 = first version with FAT32 */
414     uint16_t lock_call = (dos_version >= 0x0710) ? 0x484A : 0x084A;
415 #else
416     uint16_t lock_call = 0x084A; /* MSDN says this is OK for all filesystems */
417 #endif
418
419     dprintf("Trying lock %04x... ", level_arg);
420     asm volatile ("int $0x21 ; setc %0"
421                   : "=bcdm" (err), "=a" (rv)
422                   : "a" (0x440d), "b" (level_arg),
423                     "c" (lock_call), "d" (0x0001));
424     dprintf("%s %04x\n", err ? "err" : "ok", rv);
425
426     return err ? rv : 0;
427 }
428
429 void lock_device(int level)
430 {
431     static int hard_lock = 0;
432     int err;
433
434     if (dos_version < 0x0700)
435         return;                 /* Win9x/NT only */
436
437     if (!hard_lock) {
438         /* Assume hierarchial "soft" locking supported */
439
440         while (lock_level < level) {
441             int new_level = lock_level + 1;
442             err = do_lock(new_level);
443             if (err) {
444                 if (err == 0x0001) {
445                     /* Try hard locking next */
446                     hard_lock = 1;
447                 }
448                 goto soft_fail;
449             }
450
451             lock_level = new_level;
452         }
453         return;
454     }
455
456 soft_fail:
457     if (hard_lock) {
458         /* Hard locking, only level 4 supported */
459         /* This is needed for Win9x in DOS mode */
460         
461         err = do_lock(4);
462         if (err) {
463             if (err == 0x0001) {
464                 /* Assume locking is not needed */
465                 return;
466             }
467             goto hard_fail;
468         }
469
470         lock_level = 4;
471         return;
472     }
473
474 hard_fail:
475     die("could not lock device");
476 }
477
478 void unlock_device(int level)
479 {
480     uint16_t rv;
481     uint8_t err;
482     uint16_t unlock_call;
483
484     if (dos_version < 0x0700)
485         return;                 /* Win9x/NT only */
486
487 #if 0
488     /* DOS 7.10 = Win95 OSR2 = first version with FAT32 */
489     unlock_call = (dos_version >= 0x0710) ? 0x486A : 0x086A;
490 #else
491     unlock_call = 0x086A;       /* MSDN says this is OK for all filesystems */
492 #endif
493
494     if (lock_level == 4 && level > 0)
495         return;                 /* Only drop the hard lock at the end */
496
497     while (lock_level > level) {
498         uint8_t new_level = (lock_level == 4) ? 0 : lock_level - 1;
499         uint16_t level_arg = (new_level << 8) + lock_drive;
500         rv = 0x440d;
501         dprintf("Trying unlock %04x... ", new_level);
502         asm volatile ("int $0x21 ; setc %0"
503                       : "=bcdm" (err), "+a" (rv)
504                       : "b" (level_arg), "c" (unlock_call));
505         dprintf("%s %04x\n", err ? "err" : "ok", rv);
506         lock_level = new_level;
507     }
508 }
509
510 /*
511  * This function does any desired MBR manipulation; called with the device lock held.
512  */
513 struct mbr_entry {
514     uint8_t active;             /* Active flag */
515     uint8_t bhead;              /* Begin head */
516     uint8_t bsector;            /* Begin sector */
517     uint8_t bcylinder;          /* Begin cylinder */
518     uint8_t filesystem;         /* Filesystem value */
519     uint8_t ehead;              /* End head */
520     uint8_t esector;            /* End sector */
521     uint8_t ecylinder;          /* End cylinder */
522     uint32_t startlba;          /* Start sector LBA */
523     uint32_t sectors;           /* Length in sectors */
524 } __attribute__ ((packed));
525
526 static void adjust_mbr(int device, int writembr, int set_active)
527 {
528     static unsigned char sectbuf[512];
529     int i;
530
531     if (!writembr && !set_active)
532         return;                 /* Nothing to do */
533
534     read_mbr(device, sectbuf);
535
536     if (writembr) {
537         memcpy(sectbuf, syslinux_mbr, syslinux_mbr_len);
538         *(uint16_t *) (sectbuf + 510) = 0xaa55;
539     }
540
541     if (set_active) {
542         uint32_t offset = get_partition_offset(device);
543         struct mbr_entry *me = (struct mbr_entry *)(sectbuf + 446);
544         int found = 0;
545
546         dprintf("Searching for partition offset: %08x\n", offset);
547
548         for (i = 0; i < 4; i++) {
549             if (me->startlba == offset) {
550                 me->active = 0x80;
551                 found++;
552             } else {
553                 me->active = 0;
554             }
555             me++;
556         }
557
558         if (found < 1) {
559             die("partition not found (-a is not implemented for logical partitions)");
560         } else if (found > 1) {
561             die("multiple aliased partitions found");
562         }
563     }
564
565     write_mbr(device, sectbuf);
566 }
567
568 int main(int argc, char *argv[])
569 {
570     static unsigned char sectbuf[512];
571     int dev_fd, fd;
572     static char ldlinux_name[] = "@:\\ldlinux.sys";
573     char **argp, *opt;
574     int force = 0;              /* -f (force) option */
575     struct libfat_filesystem *fs;
576     libfat_sector_t s, *secp, sectors[65];      /* 65 is maximum possible */
577     int32_t ldlinux_cluster;
578     int nsectors;
579     const char *device = NULL, *bootsecfile = NULL;
580     const char *errmsg;
581     int i;
582     int writembr = 0;           /* -m (write MBR) option */
583     int set_active = 0;         /* -a (set partition active) option */
584     const char *subdir = NULL;
585     int stupid = 0;
586     int raid_mode = 0;
587
588     dprintf("argv = %p\n", argv);
589     for (i = 0; i <= argc; i++)
590         dprintf("argv[%d] = %p = \"%s\"\n", i, argv[i], argv[i]);
591
592     (void)argc;                 /* Unused */
593
594     get_dos_version();
595
596     for (argp = argv + 1; *argp; argp++) {
597         if (**argp == '-') {
598             opt = *argp + 1;
599             if (!*opt)
600                 usage();
601
602             while (*opt) {
603                 switch (*opt) {
604                 case 's':       /* Use "safe, slow and stupid" code */
605                     stupid = 1;
606                     break;
607                 case 'r':       /* RAID mode */
608                     raid_mode = 1;
609                     break;
610                 case 'f':       /* Force install */
611                     force = 1;
612                     break;
613                 case 'm':       /* Write MBR */
614                     writembr = 1;
615                     break;
616                 case 'a':       /* Set partition active */
617                     set_active = 1;
618                     break;
619                 case 'd':
620                     if (argp[1])
621                         subdir = *++argp;
622                     break;
623                 default:
624                     usage();
625                 }
626                 opt++;
627             }
628         } else {
629             if (bootsecfile)
630                 usage();
631             else if (device)
632                 bootsecfile = *argp;
633             else
634                 device = *argp;
635         }
636     }
637
638     if (!device)
639         usage();
640
641     /*
642      * Figure out which drive we're talking to
643      */
644     dev_fd = (device[0] & ~0x20) - 0x40;
645     if (dev_fd < 1 || dev_fd > 26 || device[1] != ':' || device[2])
646         usage();
647
648     set_lock_device(dev_fd);
649
650     lock_device(2);             /* Make sure we can lock the device */
651     read_device(dev_fd, sectbuf, 1, 0);
652     unlock_device(1);
653
654     /*
655      * Check to see that what we got was indeed an MS-DOS boot sector/superblock
656      */
657     if ((errmsg = syslinux_check_bootsect(sectbuf))) {
658         unlock_device(0);
659         puts(errmsg);
660         putchar('\n');
661         exit(1);
662     }
663
664     ldlinux_name[0] = dev_fd | 0x40;
665
666     set_attributes(ldlinux_name, 0x00);
667     fd = creat(ldlinux_name, 0);
668     write_file(fd, syslinux_ldlinux, syslinux_ldlinux_len);
669     close(fd);
670     set_attributes(ldlinux_name, 0x07); /* SYSTEM HIDDEN READONLY */
671
672     /*
673      * Now, use libfat to create a block map.  This probably
674      * should be changed to use ioctl(...,FIBMAP,...) since
675      * this is supposed to be a simple, privileged version
676      * of the installer.
677      */
678     lock_device(2);
679     fs = libfat_open(libfat_xpread, dev_fd);
680     ldlinux_cluster = libfat_searchdir(fs, 0, "LDLINUX SYS", NULL);
681     secp = sectors;
682     nsectors = 0;
683     s = libfat_clustertosector(fs, ldlinux_cluster);
684     while (s && nsectors < 65) {
685         *secp++ = s;
686         nsectors++;
687         s = libfat_nextsector(fs, s);
688     }
689     libfat_close(fs);
690
691     /*
692      * If requested, move ldlinux.sys
693      */
694     if (subdir) {
695         char new_ldlinux_name[160];
696         char *cp = new_ldlinux_name + 3;
697         const char *sd;
698         int slash = 1;
699
700         new_ldlinux_name[0] = dev_fd | 0x40;
701         new_ldlinux_name[1] = ':';
702         new_ldlinux_name[2] = '\\';
703
704         for (sd = subdir; *sd; sd++) {
705             char c = *sd;
706
707             if (c == '/' || c == '\\') {
708                 if (slash)
709                     continue;
710                 c = '\\';
711                 slash = 1;
712             } else {
713                 slash = 0;
714             }
715
716             *cp++ = c;
717         }
718
719         /* Skip if subdirectory == root */
720         if (cp > new_ldlinux_name + 3) {
721             if (!slash)
722                 *cp++ = '\\';
723
724             memcpy(cp, "ldlinux.sys", 12);
725
726             set_attributes(ldlinux_name, 0);
727             if (rename(ldlinux_name, new_ldlinux_name))
728                 set_attributes(ldlinux_name, 0x07);
729             else
730                 set_attributes(new_ldlinux_name, 0x07);
731         }
732     }
733
734     /*
735      * Patch ldlinux.sys and the boot sector
736      */
737     syslinux_patch(sectors, nsectors, stupid, raid_mode);
738
739     /*
740      * Write the now-patched first sector of ldlinux.sys
741      */
742     /* lock_device(3); -- doesn't seem to be needed */
743     write_device(dev_fd, syslinux_ldlinux, 1, sectors[0]);
744
745     /*
746      * Muck with the MBR, if desired, while we hold the lock
747      */
748     adjust_mbr(dev_fd, writembr, set_active);
749
750     /*
751      * To finish up, write the boot sector
752      */
753
754     /* Read the superblock again since it might have changed while mounted */
755     read_device(dev_fd, sectbuf, 1, 0);
756
757     /* Copy the syslinux code into the boot sector */
758     syslinux_make_bootsect(sectbuf);
759
760     /* Write new boot sector */
761     if (bootsecfile) {
762         unlock_device(0);
763         fd = creat(bootsecfile, 0x20);  /* ARCHIVE */
764         write_file(fd, sectbuf, 512);
765         close(fd);
766     } else {
767         write_device(dev_fd, sectbuf, 1, 0);
768         unlock_device(0);
769     }
770
771     /* Done! */
772
773     return 0;
774 }