File: asmstub.c

package info (click to toggle)
grub 0.97-77
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 7,176 kB
  • sloc: ansic: 40,100; sh: 5,391; asm: 2,227; makefile: 507; perl: 338
file content (1343 lines) | stat: -rw-r--r-- 28,498 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
/* asmstub.c - a version of shared_src/asm.S that works under Unix */
/*
 *  GRUB  --  GRand Unified Bootloader
 *  Copyright (C) 1999,2000,2001,2002,2004  Free Software Foundation, Inc.
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */

/* Try to use glibc's transparant LFS support. */
#define _LARGEFILE_SOURCE	1
/* lseek becomes synonymous with lseek64.  */
#define _FILE_OFFSET_BITS	64

/* Simulator entry point. */
int grub_stage2 (void);

#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <assert.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <time.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
#include <setjmp.h>
#include <sys/time.h>
#include <termios.h>
#include <signal.h>
#include <sys/mman.h>

#include <limits.h>
#ifndef PAGESIZE
#define PAGESIZE 4096
#endif

#ifdef __linux__
# include <sys/ioctl.h>		/* ioctl */
# if !defined(__GLIBC__) || \
	((__GLIBC__ < 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ < 1)))
/* Maybe libc doesn't have large file support.  */
#  include <linux/unistd.h>	/* _llseek */
# endif /* (GLIBC < 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR < 1)) */
# ifndef BLKFLSBUF
#  define BLKFLSBUF	_IO (0x12,97)	/* flush buffer cache */
# endif /* ! BLKFLSBUF */
#endif /* __linux__ */

#if defined(__FreeBSD_kernel__) || defined(__FreeBSD__)
# include <sys/sysctl.h>
#endif

/* We want to prevent any circularararity in our stubs, as well as
   libc name clashes. */
#define WITHOUT_LIBC_STUBS 1
#include <shared.h>
#include <device.h>
#include <serial.h>
#include <term.h>

/* Simulated memory sizes. */
#define EXTENDED_MEMSIZE (3 * 1024 * 1024)	/* 3MB */
#define CONVENTIONAL_MEMSIZE (640 * 1024)	/* 640kB */

unsigned long install_partition = 0x20000;
unsigned long boot_drive = 0;
int saved_entryno = 0;
char version_string[] = VERSION;
char config_file[128] = "/boot/grub/menu.lst"; /* FIXME: arbitrary */
unsigned long linux_text_len = 0;
char *linux_data_tmp_addr = 0;
char *linux_data_real_addr = 0;
unsigned short io_map[IO_MAP_SIZE];
struct apm_info apm_bios_info;

/* Emulation requirements. */
char *grub_scratch_mem = 0;

struct geometry *disks = 0;

/* The map between BIOS drives and UNIX device file names.  */
char **device_map = 0;

/* The jump buffer for exiting correctly.  */
static jmp_buf env_for_exit;

/* The current color for console.  */
int console_current_color = A_NORMAL;

/* The file descriptor for a serial device.  */
static int serial_fd = -1;

/* The file name of a serial device.  */
static char *serial_device = 0;

#ifdef SIMULATE_SLOWNESS_OF_SERIAL
/* The speed of a serial device.  */
static unsigned int serial_speed;
#endif /* SIMULATE_SLOWNESS_OF_SERIAL */

/* The main entry point into this mess. */
int
grub_stage2 (void)
{
  /* These need to be static, because they survive our stack transitions. */
  static int status = 0;
  static char *realstack;
  char *scratch, *simstack;
  int i;

  auto void doit_wrapper (void);
  auto void doit (jmp_buf *p_env_for_exit, int *p_status);
  
  void doit_wrapper (void)
    {
      asm volatile ("movl %%esp, %0\n\t"
                    "movl %2, %%esp\n\t"    /* Make sure our stack lives in the simulated memory area. */
                    "pushl %1\n\t"          /* Put realstack on the new stack */
                    "pushl %3\n\t"          /* Put &status on the new stack */
                    "pushl %4\n\t"          /* Put &env_for_exit on the new stack */
                    "call *%5\n\t"          /* Call doit */
                    "popl %0\n\t"           /* Remove &env_for_exit from the stack */
                    "popl %0\n\t"           /* Remove &status from the stack */
                    "popl %0\n\t"           /* Retrieve realstack from the new stack */
                    "movl %1, %%esp\n"      /* Switch back to the original stack */
                    : "=&r" (realstack)
                    : "0" (realstack), "r" (simstack), "r" (&status), "r" (&env_for_exit), "r" (doit));
    }

  /* We need a nested function so that we get a clean stack frame,
     regardless of how the code is optimized. */
  void doit (jmp_buf *p_env_for_exit, int *p_status)
    {
      /* Do a setjmp here for the stop command.  */
      if (! setjmp (*p_env_for_exit))
	{
	  /* Actually enter the generic stage2 code.  */
	  *p_status = 0;
	  init_bios_info ();
	}
      else
	{
	  /* If ERRNUM is non-zero, then set STATUS to non-zero.  */
	  if (errnum)
	    *p_status = 1;
	}
    }

  assert (grub_scratch_mem == 0);
  scratch = malloc (0x100000 + EXTENDED_MEMSIZE + 15);
  assert (scratch);

  {
    char *p;
    int ret;

    /* Align to a multiple of PAGESIZE, assumed to be a power of two. */
    p = (char *) (((long) scratch) & ~(PAGESIZE - 1));

    /* The simulated stack needs to be executable, since GCC uses stack
     * trampolines to implement nested functions.
     */
    ret = mprotect (p, 0x100000 + EXTENDED_MEMSIZE + 15,
		    PROT_READ | PROT_WRITE | PROT_EXEC);
    assert (ret == 0);
  }

  grub_scratch_mem = (char *) ((((int) scratch) >> 4) << 4);

  /* FIXME: simulate the memory holes using mprot, if available. */

  assert (disks == 0);
  disks = malloc (NUM_DISKS * sizeof (*disks));
  assert (disks);
  /* Initialize DISKS.  */
  for (i = 0; i < NUM_DISKS; i++)
    disks[i].flags = -1;

  if (! init_device_map (&device_map, device_map_file, floppy_disks))
    return 1;
  
  /* Check some invariants. */
  assert ((SCRATCHSEG << 4) == SCRATCHADDR);
  assert ((BUFFERSEG << 4) == BUFFERADDR);
  assert (BUFFERADDR + BUFFERLEN == SCRATCHADDR);
  assert (FSYS_BUF % 16 == 0);
  assert (FSYS_BUF + FSYS_BUFLEN == BUFFERADDR);

#ifdef HAVE_LIBCURSES
  /* Get into char-at-a-time mode. */
  if (use_curses)
    {
      initscr ();
      cbreak ();
      noecho ();
      nonl ();
      scrollok (stdscr, TRUE);
      keypad (stdscr, TRUE);
      wtimeout (stdscr, 100);
      signal (SIGWINCH, SIG_IGN);
    }
#endif

  /* Make sure that actual writing is done.  */
  sync ();

  /* Set our stack, and go for it. */
  simstack = (char *) PROTSTACKINIT;
  doit_wrapper ();

  /* I don't know if this is necessary really.  */
  sync ();

#ifdef HAVE_LIBCURSES
  if (use_curses)
    endwin ();
#endif

  /* Close off the file descriptors we used. */
  for (i = 0; i < NUM_DISKS; i ++)
    if (disks[i].flags != -1)
      {
#ifdef __linux__
	/* In Linux, invalidate the buffer cache. In other OSes, reboot
	   is one of the solutions...  */
	ioctl (disks[i].flags, BLKFLSBUF, 0);
#else
# warning "In your operating system, the buffer cache will not be flushed."
#endif
	close (disks[i].flags);
      }

  if (serial_fd >= 0)
    close (serial_fd);
  
  /* Release memory. */
  restore_device_map (device_map);
  device_map = 0;
  free (disks);
  disks = 0;
  free (scratch);
  grub_scratch_mem = 0;

  if (serial_device)
    free (serial_device);
  serial_device = 0;
  
  /* Ahh... at last we're ready to return to caller. */
  return status;
}

/* Assign DRIVE to a device name DEVICE.  */
void
assign_device_name (int drive, const char *device)
{
  /* If DRIVE is already assigned, free it.  */
  if (device_map[drive])
    free (device_map[drive]);

  /* If the old one is already opened, close it.  */
  if (disks[drive].flags != -1)
    {
      close (disks[drive].flags);
      disks[drive].flags = -1;
    }

  /* Assign DRIVE to DEVICE.  */
  if (! device)
    device_map[drive] = 0;
  else
    device_map[drive] = strdup (device);
}

void
stop (void)
{
#ifdef HAVE_LIBCURSES
  if (use_curses)
    endwin ();
#endif

  /* Jump to doit.  */
  longjmp (env_for_exit, 1);
}

void
grub_reboot (void)
{
  stop ();
}

void
grub_halt (int no_apm)
{
  stop ();
}

/* calls for direct boot-loader chaining */
void
chain_stage1 (unsigned long segment, unsigned long offset,
	      unsigned long part_table_addr)
{
  stop ();
}


void
chain_stage2 (unsigned long segment, unsigned long offset, int second_sector)
{
  stop ();
}


/* do some funky stuff, then boot linux */
void
linux_boot (void)
{
  stop ();
}


/* For bzImage kernels. */
void
big_linux_boot (void)
{
  stop ();
}


/* booting a multiboot executable */
void
multi_boot (int start, int mb_info)
{
  stop ();
}

/* sets it to linear or wired A20 operation */
void
gateA20 (int linear)
{
  /* Nothing to do in the simulator. */
}

/* Set up the int15 handler.  */
void
set_int15_handler (void)
{
  /* Nothing to do in the simulator.  */
}

/* Restore the original int15 handler.  */
void
unset_int15_handler (void)
{
  /* Nothing to do in the simulator.  */
}

/* The key map.  */
unsigned short bios_key_map[KEY_MAP_SIZE + 1];
unsigned short ascii_key_map[KEY_MAP_SIZE + 1];

/* Copy MAP to the drive map and set up the int13 handler.  */
void
set_int13_handler (unsigned short *map)
{
  /* Nothing to do in the simulator.  */
}

int
get_code_end (void)
{
  /* Just return a little area for simulation. */
  return BOOTSEC_LOCATION + (60 * 1024);
}


/* memory probe routines */
int
get_memsize (int type)
{
  if (! type)
    return CONVENTIONAL_MEMSIZE >> 10;
  else
    return EXTENDED_MEMSIZE >> 10;
}


/* get_eisamemsize() :  return packed EISA memory map, lower 16 bits is
 *		memory between 1M and 16M in 1K parts, upper 16 bits is
 *		memory above 16M in 64K parts.  If error, return -1.
 */
int
get_eisamemsize (void)
{
  return (EXTENDED_MEMSIZE >> 10);
}


#define MMAR_DESC_TYPE_AVAILABLE 1 /* available to OS */
#define MMAR_DESC_TYPE_RESERVED 2 /* not available */
#define MMAR_DESC_TYPE_ACPI_RECLAIM 3 /* usable by OS after reading ACPI */
#define MMAR_DESC_TYPE_ACPI_NVS 4 /* required to save between NVS sessions */

#define MMAR_DESC_LENGTH	20

/* Fetch the next entry in the memory map and return the continuation
   value.  DESC is a pointer to the descriptor buffer, and CONT is the
   previous continuation value (0 to get the first entry in the
   map).  */
int
get_mmap_entry (struct mmar_desc *desc, int cont)
{
  /* Record the memory map statically.  */
  static struct mmar_desc desc_table[] =
  {
    /* The conventional memory.  */
    {
      MMAR_DESC_LENGTH,
      0,
      CONVENTIONAL_MEMSIZE,
      MMAR_DESC_TYPE_AVAILABLE
    },
    /* BIOS RAM and ROM (such as video memory).  */
    {
      MMAR_DESC_LENGTH,
      CONVENTIONAL_MEMSIZE,
      0x100000 - CONVENTIONAL_MEMSIZE,
      MMAR_DESC_TYPE_RESERVED
    },
    /* The extended memory.  */
    {
      MMAR_DESC_LENGTH,
      0x100000,
      EXTENDED_MEMSIZE,
      MMAR_DESC_TYPE_AVAILABLE
    }
  };
  
  int num = sizeof (desc_table) / sizeof (*desc_table);

  if (cont < 0 || cont >= num)
    {
      /* Should not happen.  */
      desc->desc_len = 0;
    }
  else
    {
      /* Copy the entry.  */
      *desc = desc_table[cont++];

      /* If the next entry exists, return the index.  */
      if (cont < num)
	return cont;
    }
  
  return 0;
}

/* Track the int13 handler.  */
void
track_int13 (int drive)
{
  /* Nothing to do in the simulator.  */
}

/* Get the ROM configuration table.  */
unsigned long
get_rom_config_table (void)
{
  return 0;
}

/* Get APM BIOS information.  */
void
get_apm_info (void)
{
  /* Nothing to do in the simulator.  */
}

/* Get VBE controller information.  */
int
get_vbe_controller_info (struct vbe_controller *controller)
{
  /* Always fails.  */
  return 0;
}

/* Get VBE mode information.  */
int
get_vbe_mode_info (int mode_number, struct vbe_mode *mode)
{
  /* Always fails.  */
  return 0;
}

/* Set VBE mode.  */
int
set_vbe_mode (int mode_number)
{
  /* Always fails.  */
  return 0;
}

/* low-level timing info */
int
getrtsecs (void)
{
  /* FIXME: exact value is not important, so just return time_t for now. */
  return time (0);
}

int
currticks (void)
{
  struct timeval tv;
  long csecs;
  int ticks_per_csec, ticks_per_usec;

  /* Note: 18.2 ticks/sec.  */

  /* Get current time.  */
  gettimeofday (&tv, 0);

  /* Compute centiseconds.  */
  csecs = tv.tv_sec / 10;

  /* Ticks per centisecond.  */
  ticks_per_csec = csecs * 182;

  /* Ticks per microsecond.  */
  ticks_per_usec = (((tv.tv_sec - csecs * 10) * 1000000 + tv.tv_usec)
		    * 182 / 10000000);

  /* Sum them.  */
  return ticks_per_csec + ticks_per_usec;
}

/* displays an ASCII character.  IBM displays will translate some
   characters to special graphical ones */
void
console_putchar (int c)
{
  /* Curses doesn't have VGA fonts.  */
  switch (c)
    {
    case DISP_UL:
      c = ACS_ULCORNER;
      break;
    case DISP_UR:
      c = ACS_URCORNER;
      break;
    case DISP_LL:
      c = ACS_LLCORNER;
      break;
    case DISP_LR:
      c = ACS_LRCORNER;
      break;
    case DISP_HORIZ:
      c = ACS_HLINE;
      break;
    case DISP_VERT:
      c = ACS_VLINE;
      break;
    case DISP_LEFT:
      c = ACS_LARROW;
      break;
    case DISP_RIGHT:
      c = ACS_RARROW;
      break;
    case DISP_UP:
      c = ACS_UARROW;
      break;
    case DISP_DOWN:
      c = ACS_DARROW;
      break;
    default:
      break;
    }

#ifdef HAVE_LIBCURSES
  if (use_curses)
    {
      /* In ncurses, a newline is treated badly, so we emulate it in our
	 own way.  */
      if (c == '\n')
	{
	  int x, y;

	  getyx (stdscr, y, x);
	  if (y + 1 == LINES)
	    scroll (stdscr);
	  else
	    move (y + 1, x);
	}
      else if (isprint (c))
	{
	  int x, y;

	  getyx (stdscr, y, x);
	  if (x + 1 == COLS)
	    {
	      console_putchar ('\r');
	      console_putchar ('\n');
	    }
	  addch (c | console_current_color);
	}
      else
	{
	  addch (c);
	}
      
#ifdef REFRESH_IMMEDIATELY
      refresh ();
#endif
    }
  else
#endif
    {
      /* CR is not used in Unix.  */
      if (c != '\r')
	putchar (c);
    }
}

/* The store for ungetch simulation. This is necessary, because
   ncurses-1.9.9g is still used in the world and its ungetch is
   completely broken.  */
#ifdef HAVE_LIBCURSES
static int save_char = ERR;
#endif

static int
console_translate_key (int c)
{
  switch (c)
    {
    case KEY_LEFT:
      return 2;
    case KEY_RIGHT:
      return 6;
    case KEY_UP:
      return 16;
    case KEY_DOWN:
      return 14;
    case KEY_DC:
      return 4;
    case KEY_BACKSPACE:
      return 8;
    case KEY_HOME:
      return 1;
    case KEY_END:
      return 5;
    case KEY_PPAGE:
      return 7;
    case KEY_NPAGE:
      return 3;
    default:
      break;
    }

  return c;
}

/* like 'getkey', but doesn't wait, returns -1 if nothing available */
int
console_checkkey (void)
{
#ifdef HAVE_LIBCURSES
  if (use_curses)
    {
      int c;

      /* Check for SAVE_CHAR. This should not be true, because this
	 means checkkey is called twice continuously.  */
      if (save_char != ERR)
	return save_char;

      c = getch ();
      /* If C is not ERR, then put it back in the input queue.  */
      if (c != ERR)
	save_char = c;
      return console_translate_key (c);
    }
#endif

  /* Just pretend they hit the space bar, then read the real key when
     they call getkey. */
  return ' ';
}

/* returns packed BIOS/ASCII code */
int
console_getkey (void)
{
  int c;

#ifdef HAVE_LIBCURSES
  if (use_curses)
    {
      /* If checkkey has already got a character, then return it.  */
      if (save_char != ERR)
	{
	  c = save_char;
	  save_char = ERR;
	  return console_translate_key (c);
	}

      wtimeout (stdscr, -1);
      c = getch ();
      wtimeout (stdscr, 100);
    }
  else
#endif
    c = getchar ();

  /* Quit if we get EOF. */
  if (c == -1)
    stop ();
  
  return console_translate_key (c);
}

/* returns packed values, LSB+1 is x, LSB is y */
int
console_getxy (void)
{
  int y, x;
#ifdef HAVE_LIBCURSES
  if (use_curses)
    getyx (stdscr, y, x);
  else
#endif
  y = x = 0;
  return (x << 8) | (y & 0xff);
}

void
console_gotoxy (int x, int y)
{
#ifdef HAVE_LIBCURSES
  if (use_curses)
    move (y, x);
#endif
}

/* low-level character I/O */
void
console_cls (void)
{
#ifdef HAVE_LIBCURSES
  if (use_curses)
    clear ();
#endif
}

void
console_setcolorstate (color_state state)
{
  console_current_color = 
    (state == COLOR_STATE_HIGHLIGHT) ? A_REVERSE : A_NORMAL;
}

void
console_setcolor (int normal_color, int highlight_color)
{
  /* Nothing to do.  */
}

int
console_setcursor (int on)
{
  return 1;
}

/* Low-level disk I/O.  Our stubbed version just returns a file
   descriptor, not the actual geometry. */
int
get_diskinfo (int drive, struct geometry *geometry)
{
  /* FIXME: this function is truly horrid.  We try opening the device,
     then severely abuse the GEOMETRY->flags field to pass a file
     descriptor to biosdisk.  Thank God nobody's looking at this comment,
     or my reputation would be ruined. --Gord */

  /* See if we have a cached device. */
  if (disks[drive].flags == -1)
    {
      /* The unpartitioned device name: /dev/XdX */
      char *devname = device_map[drive];
      char buf[512];

      if (! devname)
	return -1;

      if (verbose)
	grub_printf ("Attempt to open drive 0x%x (%s)\n",
		     drive, devname);

      /* Open read/write, or read-only if that failed. */
      if (! read_only)
	{
/* By default, kernel of FreeBSD does not allow overwriting MBR */
#if defined(__FreeBSD_kernel__) || defined(__FreeBSD__)
#define GEOM_SYSCTL	"kern.geom.debugflags"
	  int old_flags, flags;
	  size_t sizeof_int = sizeof (int);

	  if (sysctlbyname (GEOM_SYSCTL, &old_flags, &sizeof_int, NULL, 0) != 0)
	    grub_printf ("failed to get " GEOM_SYSCTL "sysctl: %s\n", strerror (errno));

	  if ((old_flags & 0x10) == 0)
	    {
	      /* "allow foot shooting", see geom(4) */
	      flags = old_flags | 0x10;

	      if (sysctlbyname (GEOM_SYSCTL, NULL, NULL, &flags, sizeof (int)) != 0)
		{
		  flags = old_flags;
		  grub_printf ("failed to set " GEOM_SYSCTL "sysctl: %s\n", strerror (errno));
		}
	    }
	  else
	    flags = old_flags;
#endif
	  disks[drive].flags = open (devname, O_RDWR);
#if defined(__FreeBSD_kernel__) || defined(__FreeBSD__)
	  if (flags != old_flags)
	    {
	      if (sysctlbyname (GEOM_SYSCTL, NULL, NULL, &old_flags, sizeof (int)) != 0)
	        grub_printf ("failed to set " GEOM_SYSCTL "sysctl: %s\n", strerror (errno));
	    }
#endif
	}

      if (disks[drive].flags == -1)
	{
	  if (read_only || errno == EACCES || errno == EROFS || errno == EPERM)
	    {
	      disks[drive].flags = open (devname, O_RDONLY);
	      if (disks[drive].flags == -1)
		{
		  assign_device_name (drive, 0);
		  return -1;
		}
	    }
	  else
	    {
	      assign_device_name (drive, 0);
	      return -1;
	    }
	}

      /* Attempt to read the first sector.  */
      if (read (disks[drive].flags, buf, 512) != 512)
	{
	  close (disks[drive].flags);
	  disks[drive].flags = -1;
	  assign_device_name (drive, 0);
	  return -1;
	}

      if (disks[drive].flags != -1)
	get_drive_geometry (&disks[drive], device_map, drive);
    }

  if (disks[drive].flags == -1)
    return -1;

#ifdef __linux__
  /* In Linux, invalidate the buffer cache, so that left overs
     from other program in the cache are flushed and seen by us */
  ioctl (disks[drive].flags, BLKFLSBUF, 0);
#endif

  *geometry = disks[drive];
  return 0;
}

/* Read LEN bytes from FD in BUF. Return less than or equal to zero if an
   error occurs, otherwise return LEN.  */
static int
nread (int fd, char *buf, size_t len)
{
  int size = len;

  while (len)
    {
      int ret = read (fd, buf, len);

      if (ret <= 0)
	{
	  if (errno == EINTR)
	    continue;
	  else
	    return ret;
	}

      len -= ret;
      buf += ret;
    }

  return size;
}

/* Write LEN bytes from BUF to FD. Return less than or equal to zero if an
   error occurs, otherwise return LEN.  */
static int
nwrite (int fd, char *buf, size_t len)
{
  int size = len;

  while (len)
    {
      int ret = write (fd, buf, len);

      if (ret <= 0)
	{
	  if (errno == EINTR)
	    continue;
	  else
	    return ret;
	}

      len -= ret;
      buf += ret;
    }

  return size;
}

/* Dump BUF in the format of hexadecimal numbers.  */
static void
hex_dump (void *buf, size_t size)
{
  /* FIXME: How to determine which length is readable?  */
#define MAX_COLUMN	70

  /* use unsigned char for numerical computations */
  unsigned char *ptr = buf;
  /* count the width of the line */
  int column = 0;
  /* how many bytes written */
  int count = 0;

  while (size > 0)
    {
      /* high 4 bits */
      int hi = *ptr >> 4;
      /* low 4 bits */
      int low = *ptr & 0xf;

      /* grub_printf does not handle prefix number, such as %2x, so
	 format the number by hand...  */
      grub_printf ("%x%x", hi, low);
      column += 2;
      count++;
      ptr++;
      size--;

      /* Insert space or newline with the interval 4 bytes.  */
      if (size != 0 && (count % 4) == 0)
	{
	  if (column < MAX_COLUMN)
	    {
	      grub_printf (" ");
	      column++;
	    }
	  else
	    {
	      grub_printf ("\n");
	      column = 0;
	    }
	}
    }

  /* Add a newline at the end for readability.  */
  grub_printf ("\n");
}

int
biosdisk (int subfunc, int drive, struct geometry *geometry,
	  unsigned int sector, int nsec, int segment)
{
  char *buf;
  int fd = geometry->flags;

  /* Get the file pointer from the geometry, and make sure it matches. */
  if (fd == -1 || fd != disks[drive].flags)
    return BIOSDISK_ERROR_GEOMETRY;

  /* Seek to the specified location. */
#if defined(__linux__) && (!defined(__GLIBC__) || \
	((__GLIBC__ < 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ < 1))))
  /* Maybe libc doesn't have large file support.  */
  {
    loff_t offset, result;
    static int _llseek (uint filedes, ulong hi, ulong lo,
			loff_t *res, uint wh);
    _syscall5 (int, _llseek, uint, filedes, ulong, hi, ulong, lo,
	       loff_t *, res, uint, wh);

    offset = (loff_t) sector * (loff_t) SECTOR_SIZE;
    if (_llseek (fd, offset >> 32, offset & 0xffffffff, &result, SEEK_SET))
      return -1;
  }
#else
  {
    off_t offset = (off_t) sector * (off_t) SECTOR_SIZE;

    if (lseek (fd, offset, SEEK_SET) != offset)
      return -1;
  }
#endif

  buf = (char *) (segment << 4);

  switch (subfunc)
    {
    case BIOSDISK_READ:
#ifdef __linux__
      if (sector == 0 && nsec > 1)
	{
	  /* Work around a bug in linux's ez remapping.  Linux remaps all
	     sectors that are read together with the MBR in one read.  It
	     should only remap the MBR, so we split the read in two 
	     parts. -jochen  */
	  if (nread (fd, buf, SECTOR_SIZE) != SECTOR_SIZE)
	    return -1;
	  buf += SECTOR_SIZE;
	  nsec--;
	}
#endif
      if (nread (fd, buf, nsec * SECTOR_SIZE) != nsec * SECTOR_SIZE)
	return -1;
      break;

    case BIOSDISK_WRITE:
      if (verbose)
	{
	  grub_printf ("Write %d sectors starting from %d sector"
		       " to drive 0x%x (%s)\n",
		       nsec, sector, drive, device_map[drive]);
	  hex_dump (buf, nsec * SECTOR_SIZE);
	}
      if (! read_only)
	if (nwrite (fd, buf, nsec * SECTOR_SIZE) != nsec * SECTOR_SIZE)
	  return -1;
      break;

    default:
      grub_printf ("unknown subfunc %d\n", subfunc);
      break;
    }

  return 0;
}


void
stop_floppy (void)
{
  /* NOTUSED */
}

/* Fetch a key from a serial device.  */
int
serial_hw_fetch (void)
{
  fd_set fds;
  struct timeval to;
  char c;

  /* Wait only for the serial device.  */
  FD_ZERO (&fds);
  FD_SET (serial_fd, &fds);

  to.tv_sec = 0;
  to.tv_usec = 0;
  
  if (select (serial_fd + 1, &fds, 0, 0, &to) > 0)
    {
      if (nread (serial_fd, &c, 1) != 1)
	stop ();

      return c;
    }
  
  return -1;
}

/* Put a character to a serial device.  */
void
serial_hw_put (int c)
{
  char ch = (char) c;
  
  if (nwrite (serial_fd, &ch, 1) != 1)
    stop ();
}

void
serial_hw_delay (void)
{
#ifdef SIMULATE_SLOWNESS_OF_SERIAL
  struct timeval otv, tv;

  gettimeofday (&otv, 0);

  while (1)
    {
      long delta;
      
      gettimeofday (&tv, 0);
      delta = tv.tv_usec - otv.tv_usec;
      if (delta < 0)
	delta += 1000000;
      
      if (delta >= 1000000 / (serial_speed >> 3))
	break;
    }
#endif /* SIMULATE_SLOWNESS_OF_SERIAL */
}

static speed_t
get_termios_speed (int speed)
{
  switch (speed)
    {
    case 2400: return B2400;
    case 4800: return B4800;
    case 9600: return B9600;
    case 19200: return B19200;
    case 38400: return B38400;
#ifdef B57600
    case 57600: return B57600;
#endif
#ifdef B115200      
    case 115200: return B115200;
#endif
    }

  return B0;
}

/* Get the port number of the unit UNIT. In the grub shell, this doesn't
   make sense.  */
unsigned short
serial_hw_get_port (int unit)
{
  return 0;
}

/* Initialize a serial device. In the grub shell, PORT is unused.  */
int
serial_hw_init (unsigned short port, unsigned int speed,
		int word_len, int parity, int stop_bit_len)
{
  struct termios termios;
  speed_t termios_speed;
  int i;
  
  /* Check if the file name is specified.  */
  if (! serial_device)
    return 0;

  /* If a serial device is already opened, close it first.  */
  if (serial_fd >= 0)
    close (serial_fd);
  
  /* Open the device file.  */
  serial_fd = open (serial_device,
		    O_RDWR | O_NOCTTY
#if defined(O_SYNC)
		    /* O_SYNC is used in Linux (and some others?).  */
		    | O_SYNC
#elif defined(O_FSYNC)
		    /* O_FSYNC is used in FreeBSD.  */
		    | O_FSYNC
#endif
		    );
  if (serial_fd < 0)
    return 0;

  /* Get the termios parameters.  */
  if (tcgetattr (serial_fd, &termios))
    goto fail;

  /* Raw mode.  */
  cfmakeraw (&termios);

  /* Set the speed.  */
  termios_speed = get_termios_speed (speed);
  if (termios_speed == B0)
    goto fail;
  
  cfsetispeed (&termios, termios_speed);
  cfsetospeed (&termios, termios_speed);

  /* Set the word length.  */
  termios.c_cflag &= ~CSIZE;
  switch (word_len)
    {
    case UART_5BITS_WORD:
      termios.c_cflag |= CS5;
      break;
    case UART_6BITS_WORD:
      termios.c_cflag |= CS6;
      break;
    case UART_7BITS_WORD:
      termios.c_cflag |= CS7;
      break;
    case UART_8BITS_WORD:
      termios.c_cflag |= CS8;
      break;
    default:
      goto fail;
    }

  /* Set the parity.  */
  switch (parity)
    {
    case UART_NO_PARITY:
      termios.c_cflag &= ~PARENB;
      break;
    case UART_ODD_PARITY:
      termios.c_cflag |= PARENB;
      termios.c_cflag |= PARODD;
      break;
    case UART_EVEN_PARITY:
      termios.c_cflag |= PARENB;
      termios.c_cflag &= ~PARODD;
      break;
    default:
      goto fail;
    }

  /* Set the length of stop bit.  */
  switch (stop_bit_len)
    {
    case UART_1_STOP_BIT:
      termios.c_cflag &= ~CSTOPB;
      break;
    case UART_2_STOP_BITS:
      termios.c_cflag |= CSTOPB;
      break;
    default:
      goto fail;
    }

  /* Set the parameters.  */
  if (tcsetattr (serial_fd, TCSANOW, &termios))
    goto fail;

#ifdef SIMULATE_SLOWNESS_OF_SERIAL
  serial_speed = speed;
#endif /* SIMUATE_SLOWNESS_OF_SERIAL */

  /* Get rid of the flag TERM_NEED_INIT from the serial terminal.  */
  for (i = 0; term_table[i].name; i++)
    {
      if (strcmp (term_table[i].name, "serial") == 0)
	{
	  term_table[i].flags &= ~(TERM_NEED_INIT);
	  break;
	}
    }
  
  return 1;

 fail:
  close (serial_fd);
  serial_fd = -1;
  return 0;
}

/* Set the file name of a serial device (or a pty device). This is a
   function specific to the grub shell.  */
void
serial_set_device (const char *device)
{
  if (serial_device)
    free (serial_device);
  
  serial_device = strdup (device);
}

/* There is no difference between console and hercules in the grub shell.  */
void
hercules_putchar (int c)
{
  console_putchar (c);
}

int
hercules_getxy (void)
{
  return console_getxy ();
}

void
hercules_gotoxy (int x, int y)
{
  console_gotoxy (x, y);
}

void
hercules_cls (void)
{
  console_cls ();
}

void
hercules_setcolorstate (color_state state)
{
  console_setcolorstate (state);
}

void
hercules_setcolor (int normal_color, int highlight_color)
{
  console_setcolor (normal_color, highlight_color);
}

int
hercules_setcursor (int on)
{
  return 1;
}