summaryrefslogtreecommitdiff
path: root/boot/boot.c
blob: 2fe1688ea07c6bf06b560d4cf959b3fddf0b8d1c (plain)
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
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
/* Load a task using the single server, and then run it
   as if we were the kernel.
   Copyright (C) 1993,94,95,96,97,98,99,2000,01,02,2006,14,16
     Free Software Foundation, Inc.

   This file is part of the GNU Hurd.

   The GNU Hurd 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, or (at your option)
   any later version.

   The GNU Hurd 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 the GNU Hurd; see the file COPYING.  If not, write to
   the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.  */

/* Written by Michael I. Bushnell.  */

#include <mach.h>
#include <mach/notify.h>
#include <device/device.h>
#include <mach/message.h>
#include <mach/mig_errors.h>
#include <mach/task_notify.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <pthread.h>
#include <fcntl.h>
#include <mach/mig_support.h>
#include <mach/default_pager.h>
#include <argp.h>
#include <hurd/store.h>
#include <hurd/ihash.h>
#include <sys/reboot.h>
#include <sys/mman.h>
#include <version.h>

#include "notify_S.h"
#include "device_S.h"
#include "io_S.h"
#include "device_reply_U.h"
#include "io_reply_U.h"
#include "term_S.h"
#include "bootstrap_S.h"
/* #include "tioctl_S.h" */
#include "mach_S.h"
#include "mach_host_S.h"
#include "gnumach_S.h"
#include "task_notify_S.h"

#include "boot_script.h"

#include <hurd/auth.h>

#include <unistd.h>
#include <fcntl.h>
#include <signal.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <termios.h>
#include <error.h>
#include <hurd.h>
#include <assert.h>

/* We support two modes of operation.  Traditionally, Subhurds were
   privileged, i.e. they had the privileged kernel ports.  This has a
   few drawbacks.  Privileged subhurds can manipulate all tasks on the
   system and halt the system.  Nowadays we allow an unprivileged
   mode.  */
static int privileged;
static int want_privileged;

static struct termios orig_tty_state;
static int isig;
static char *kernel_command_line;

static void
init_termstate ()
{
  struct termios tty_state;

  if (tcgetattr (0, &tty_state) < 0)
    error (10, errno, "tcgetattr");

  orig_tty_state = tty_state;
  cfmakeraw (&tty_state);
  if (isig)
    tty_state.c_lflag |= ISIG;

  if (tcsetattr (0, 0, &tty_state) < 0)
    error (11, errno, "tcsetattr");
}

static void
restore_termstate ()
{
  tcsetattr (0, 0, &orig_tty_state);
}

#define host_fstat fstat
typedef struct stat host_stat_t;

void __attribute__ ((__noreturn__))
host_exit (int status)
{
  restore_termstate ();
  exit (status);
}

mach_port_t privileged_host_port, master_device_port;
mach_port_t pseudo_privileged_host_port;
mach_port_t pseudo_master_device_port;
mach_port_t receive_set;
mach_port_t pseudo_console, pseudo_root, pseudo_time;
mach_port_t pseudo_pset;
task_t pseudo_kernel;
mach_port_t task_notification_port;
mach_port_t dead_task_notification_port;
auth_t authserver;

struct store *root_store;

pthread_spinlock_t queuelock = PTHREAD_SPINLOCK_INITIALIZER;
pthread_spinlock_t readlock = PTHREAD_SPINLOCK_INITIALIZER;

mach_port_t php_child_name, psmdp_child_name, taskname;

task_t child_task;
mach_port_t bootport;

int console_mscount;

vm_address_t fs_stack_base;
vm_size_t fs_stack_size;

void init_termstate ();
void restore_termstate ();

char *fsname;

char bootstrap_args[100] = "-";
char *bootdevice = 0;
char *bootscript = 0;


void safe_gets (char *buf, int buf_len)
{
  fgets (buf, buf_len, stdin);
}

extern char *useropen_dir;

/* XXX: glibc should provide mig_reply_setup but does not.  */
/* Fill in default response.  */
void
mig_reply_setup (
	const mach_msg_header_t	*in,
	mach_msg_header_t	*out)
{
      static const mach_msg_type_t RetCodeType = {
		/* msgt_name = */		MACH_MSG_TYPE_INTEGER_32,
		/* msgt_size = */		32,
		/* msgt_number = */		1,
		/* msgt_inline = */		TRUE,
		/* msgt_longform = */		FALSE,
		/* msgt_deallocate = */		FALSE,
		/* msgt_unused = */		0
	};

#define	InP	(in)
#define	OutP	((mig_reply_header_t *) out)
      OutP->Head.msgh_bits =
	MACH_MSGH_BITS(MACH_MSGH_BITS_REMOTE(InP->msgh_bits), 0);
      OutP->Head.msgh_size = sizeof *OutP;
      OutP->Head.msgh_remote_port = InP->msgh_remote_port;
      OutP->Head.msgh_local_port = MACH_PORT_NULL;
      OutP->Head.msgh_seqno = 0;
      OutP->Head.msgh_id = InP->msgh_id + 100;
      OutP->RetCodeType = RetCodeType;
      OutP->RetCode = MIG_BAD_ID;
#undef InP
#undef OutP
}

int
boot_demuxer (mach_msg_header_t *inp,
	      mach_msg_header_t *outp)
{
  mig_routine_t routine;
  mig_reply_setup (inp, outp);
  if ((routine = io_server_routine (inp)) ||
      (routine = device_server_routine (inp)) ||
      (routine = notify_server_routine (inp)) ||
      (routine = term_server_routine (inp)) ||
      (routine = mach_server_routine (inp)) ||
      (routine = mach_host_server_routine (inp)) ||
      (routine = gnumach_server_routine (inp)) ||
      (routine = task_notify_server_routine (inp))
      /* (routine = tioctl_server_routine (inp)) */)
    {
      (*routine) (inp, outp);
      return TRUE;
    }
  else
    return FALSE;
}

void read_reply ();
void * msg_thread (void *);

const char *argp_program_version = STANDARD_HURD_VERSION (boot);

#define OPT_PRIVILEGED	-1
#define OPT_BOOT_SCRIPT	-2

static struct argp_option options[] =
{
  { NULL, 0, NULL, 0, "Boot options:" },
  { "boot-script", OPT_BOOT_SCRIPT, "BOOT-SCRIPT", 0,
    "boot script to execute" },
  { "boot-root",   'D', "DIR", 0,
    "Root of a directory tree in which to find files specified in BOOT-SCRIPT" },
  { "single-user", 's', 0, 0,
    "Boot in single user mode" },
  { "kernel-command-line", 'c', "COMMAND LINE", 0,
    "Simulated multiboot command line to supply" },
  { "pause" ,      'd', 0, 0,
    "Pause for user confirmation at various times during booting" },
  { "isig",      'I', 0, 0,
    "Do not disable terminal signals, so you can suspend and interrupt boot"},
  { "device",	   'f', "SUBHURD_NAME=DEVICE_FILE", 0,
    "Pass the given DEVICE_FILE to the Subhurd as device SUBHURD_NAME"},
  { "privileged", OPT_PRIVILEGED, NULL, 0,
    "Allow the subhurd to access privileged kernel ports"},
  { 0 }
};
static char doc[] = "Boot a second hurd";



/* Device pass through.  */

struct dev_map
{
  char *device_name;	/* The name of the device in the Subhurd.  */
  char *file_name;	/* The filename outside the Subhurd.  */
  struct dev_map *next;
};

static struct dev_map *dev_map_head;

static struct dev_map *
add_dev_map (const char *dev_name, const char *dev_file)
{
  file_t node;
  struct dev_map *map;

  /* See if we can open the file.  */
  node = file_name_lookup (dev_file, 0, 0);
  if (! MACH_PORT_VALID (node))
    error (1, errno, "%s", dev_file);
  mach_port_deallocate (mach_task_self (), node);

  map = malloc (sizeof *map);
  if (map == NULL)
    return NULL;

  map->device_name = strdup (dev_name);
  map->file_name = strdup (dev_file);
  map->next = dev_map_head;
  dev_map_head = map;
  return map;
}

static struct dev_map *lookup_dev (char *dev_name)
{
  struct dev_map *map;

  for (map = dev_map_head; map; map = map->next)
    {
      if (strcmp (map->device_name, dev_name) == 0)
	return map;
    }
  return NULL;
}

static error_t
parse_opt (int key, char *arg, struct argp_state *state)
{
  char *dev_file;

  switch (key)
    {
      size_t len;

    case 'c':  kernel_command_line = arg; break;

    case 'D':  useropen_dir = arg; break;

    case 'I':  isig = 1; break;

    case 's': case 'd':
      len = strlen (bootstrap_args);
      if (len >= sizeof bootstrap_args - 1)
	argp_error (state, "Too many bootstrap args");
      bootstrap_args[len++] = key;
      bootstrap_args[len] = '\0';
      break;

    case 'f':
      dev_file = strchr (arg, '=');
      if (dev_file == NULL)
	return ARGP_ERR_UNKNOWN;
      *dev_file = 0;
      add_dev_map (arg, dev_file+1);
      break;

    case OPT_PRIVILEGED:
      want_privileged = 1;
      break;

    case OPT_BOOT_SCRIPT:
      bootscript = arg;
      break;

    case ARGP_KEY_ARG:
      return ARGP_ERR_UNKNOWN;

    case ARGP_KEY_INIT:
      state->child_inputs[0] = state->input; break;

    default:
      return ARGP_ERR_UNKNOWN;
    }
  return 0;
}

static error_t
allocate_pseudo_ports (void)
{
  mach_port_t old;

  /* Allocate a port that we hand out as the privileged host port.  */
  mach_port_allocate (mach_task_self (), MACH_PORT_RIGHT_RECEIVE,
		      &pseudo_privileged_host_port);
  mach_port_insert_right (mach_task_self (),
			  pseudo_privileged_host_port,
			  pseudo_privileged_host_port,
			  MACH_MSG_TYPE_MAKE_SEND);
  mach_port_move_member (mach_task_self (), pseudo_privileged_host_port,
			 receive_set);
  mach_port_request_notification (mach_task_self (),
                                  pseudo_privileged_host_port,
				  MACH_NOTIFY_NO_SENDERS, 1,
				  pseudo_privileged_host_port,
				  MACH_MSG_TYPE_MAKE_SEND_ONCE, &old);
  assert (old == MACH_PORT_NULL);

  /* Allocate a port that we hand out as the privileged processor set
     port.  */
  mach_port_allocate (mach_task_self (), MACH_PORT_RIGHT_RECEIVE,
		      &pseudo_pset);
  mach_port_move_member (mach_task_self (), pseudo_pset,
			 receive_set);
  /* Make one send right that we copy when handing it out.  */
  mach_port_insert_right (mach_task_self (),
			  pseudo_pset,
			  pseudo_pset,
			  MACH_MSG_TYPE_MAKE_SEND);

  /* We will receive new task notifications on this port.  */
  mach_port_allocate (mach_task_self (), MACH_PORT_RIGHT_RECEIVE,
		      &task_notification_port);
  mach_port_move_member (mach_task_self (), task_notification_port,
			 receive_set);

  /* And information about dying tasks here.  */
  mach_port_allocate (mach_task_self (), MACH_PORT_RIGHT_RECEIVE,
		      &dead_task_notification_port);
  mach_port_move_member (mach_task_self (), dead_task_notification_port,
			 receive_set);

  return 0;
}

void
read_boot_script (char **buffer, size_t *length)
{
  char *p, *buf;
  static const char filemsg[] = "Can't open boot script\n";
  static const char memmsg[] = "Not enough memory\n";
  int i, fd;
  size_t amt, len;

  fd = open (bootscript, O_RDONLY, 0);
  if (fd < 0)
    {
      write (2, filemsg, sizeof (filemsg));
      host_exit (1);
    }
  p = buf = malloc (500);
  if (!buf)
    {
      write (2, memmsg, sizeof (memmsg));
      host_exit (1);
    }
  len = 500;
  amt = 0;
  while (1)
    {
      i = read (fd, p, len - (p - buf));
      if (i <= 0)
        break;
      p += i;
      amt += i;
      if (p == buf + len)
        {
          char *newbuf;

          len += 500;
          newbuf = realloc (buf, len);
          if (!newbuf)
            {
              write (2, memmsg, sizeof (memmsg));
              host_exit (1);
            }
          p = newbuf + (p - buf);
          buf = newbuf;
        }
    }

  close (fd);
  *buffer = buf;
  *length = amt;
}


/* Boot script file for booting contemporary GNU Hurd systems.  Each
   line specifies a file to be loaded by the boot loader (the first
   word), and actions to be done with it.  */
const char *default_boot_script =
  /* First, the bootstrap filesystem.  It needs several ports as
     arguments, as well as the user flags from the boot loader.  */
  "/hurd/ext2fs.static"
  " --readonly"
  " --multiboot-command-line=${kernel-command-line}"
  " --host-priv-port=${host-port}"
  " --device-master-port=${device-port}"
  " --exec-server-task=${exec-task}"
  " -T device ${root-device} $(task-create) $(task-resume)"
  "\n"

  /* Now the exec server; to load the dynamically-linked exec server
     program, we have the boot loader in fact load and run ld.so,
     which in turn loads and runs /hurd/exec.  This task is created,
     and its task port saved in ${exec-task} to be passed to the fs
     above, but it is left suspended; the fs will resume the exec task
     once it is ready.  */
  "/lib/ld.so /hurd/exec $(exec-task=task-create)"
  "\n";


int
main (int argc, char **argv, char **envp)
{
  error_t err;
  mach_port_t foo;
  char *buf = 0;
  pthread_t pthread_id;
  char *root_store_name;
  const struct argp_child kids[] = { { &store_argp, 0, "Store options:", -2 },
                                     { 0 }};
  struct argp argp = { options, parse_opt, NULL, doc, kids };
  struct store_argp_params store_argp_params = { 0 };

  argp_parse (&argp, argc, argv, 0, 0, &store_argp_params);
  err = store_parsed_name (store_argp_params.result, &root_store_name);
  if (err)
    error (2, err, "store_parsed_name");

  err = store_parsed_open (store_argp_params.result, 0, &root_store);
  if (err)
    error (4, err, "%s", root_store_name);

  if (want_privileged)
    {
      get_privileged_ports (&privileged_host_port, &master_device_port);
      privileged = MACH_PORT_VALID (master_device_port);

      if (! privileged)
        error (1, 0, "Must be run as root for privileged subhurds");
    }

  if (privileged)
    strcat (bootstrap_args, "f");

  mach_port_allocate (mach_task_self (), MACH_PORT_RIGHT_PORT_SET,
		      &receive_set);

  if (root_store->class == &store_device_class && root_store->name
      && (root_store->flags & STORE_ENFORCED)
      && root_store->num_runs == 1
      && root_store->runs[0].start == 0
      && privileged)
    /* Let known device nodes pass through directly.  */
    bootdevice = root_store->name;
  else
    /* Pass a magic value that we can use to do I/O to ROOT_STORE.  */
    {
      bootdevice = "pseudo-root";
      mach_port_allocate (mach_task_self (), MACH_PORT_RIGHT_RECEIVE,
			  &pseudo_root);
      mach_port_move_member (mach_task_self (), pseudo_root, receive_set);
    }

  mach_port_allocate (mach_task_self (), MACH_PORT_RIGHT_RECEIVE,
		      &pseudo_master_device_port);
  mach_port_insert_right (mach_task_self (),
			  pseudo_master_device_port,
			  pseudo_master_device_port,
			  MACH_MSG_TYPE_MAKE_SEND);
  mach_port_move_member (mach_task_self (), pseudo_master_device_port,
			 receive_set);
  mach_port_request_notification (mach_task_self (), pseudo_master_device_port,
				  MACH_NOTIFY_NO_SENDERS, 1,
				  pseudo_master_device_port,
				  MACH_MSG_TYPE_MAKE_SEND_ONCE, &foo);
  if (foo != MACH_PORT_NULL)
    mach_port_deallocate (mach_task_self (), foo);

  mach_port_allocate (mach_task_self (), MACH_PORT_RIGHT_RECEIVE,
		      &pseudo_console);
  mach_port_move_member (mach_task_self (), pseudo_console, receive_set);
  mach_port_request_notification (mach_task_self (), pseudo_console,
				  MACH_NOTIFY_NO_SENDERS, 1, pseudo_console,
				  MACH_MSG_TYPE_MAKE_SEND_ONCE, &foo);
  if (foo != MACH_PORT_NULL)
    mach_port_deallocate (mach_task_self (), foo);

  mach_port_allocate (mach_task_self (), MACH_PORT_RIGHT_RECEIVE,
		      &pseudo_time);
  mach_port_move_member (mach_task_self (), pseudo_time, receive_set);
  mach_port_request_notification (mach_task_self (), pseudo_time,
				  MACH_NOTIFY_NO_SENDERS, 1, pseudo_time,
				  MACH_MSG_TYPE_MAKE_SEND_ONCE, &foo);
  if (foo != MACH_PORT_NULL)
    mach_port_deallocate (mach_task_self (), foo);

  if (! privileged)
    {
      err = allocate_pseudo_ports ();
      if (err)
        error (1, err, "Allocating pseudo ports");

      /* Create a new task namespace for us.  */
      err = proc_make_task_namespace (getproc (), task_notification_port,
                                      MACH_MSG_TYPE_MAKE_SEND);
      if (err)
        error (1, err, "proc_make_task_namespace");

      /* Create an empty task that the subhurds can freely frobnicate.  */
      err = task_create (mach_task_self (), 0, &pseudo_kernel);
      if (err)
        error (1, err, "task_create");
    }

  if (kernel_command_line == 0)
    asprintf (&kernel_command_line, "%s %s root=%s",
	      argv[0], bootstrap_args, bootdevice);

  /* Initialize boot script variables.  */
  if (boot_script_set_variable ("host-port", VAL_PORT,
                                privileged
                                ? (int) privileged_host_port
				: (int) pseudo_privileged_host_port)
      || boot_script_set_variable ("device-port", VAL_PORT,
				   (integer_t) pseudo_master_device_port)
      || boot_script_set_variable ("kernel-command-line", VAL_STR,
				   (integer_t) kernel_command_line)
      || boot_script_set_variable ("root-device",
				   VAL_STR, (integer_t) bootdevice)
      || boot_script_set_variable ("boot-args",
				   VAL_STR, (integer_t) bootstrap_args))
    {
      static const char msg[] = "error setting variable";

      write (2, msg, strlen (msg));
      host_exit (1);
    }

  /* Turn each `FOO=BAR' word in the command line into a boot script
     variable ${FOO} with value BAR.  */
  {
    int len = strlen (kernel_command_line) + 1;
    char *s = memcpy (alloca (len), kernel_command_line, len);
    char *word;

    while ((word = strsep (&s, " \t")) != 0)
      {
       char *eq = strchr (word, '=');
       if (eq == 0)
         continue;
       *eq++ = '\0';
       err = boot_script_set_variable (word, VAL_STR, (integer_t) eq);
       if (err)
         {
           char *msg;
           asprintf (&msg, "cannot set boot-script variable %s: %s\n",
                     word, boot_script_error_string (err));
           assert (msg);
           write (2, msg, strlen (msg));
           free (msg);
           host_exit (1);
         }
      }
  }

  /* Parse the boot script.  */
  {
    char *p, *line;
    size_t amt;
    if (bootscript)
      read_boot_script (&buf, &amt);
    else
      buf = strdup (default_boot_script), amt = strlen (default_boot_script);

    line = p = buf;
    while (1)
      {
	while (p < buf + amt && *p != '\n')
	  p++;
	*p = '\0';
	err = boot_script_parse_line (0, line);
	if (err)
	  {
	    char *str;
	    int i;

	    str = boot_script_error_string (err);
	    i = strlen (str);
	    write (2, str, i);
	    write (2, " in `", 5);
	    write (2, line, strlen (line));
	    write (2, "'\n", 2);
	    host_exit (1);
	  }
	if (p == buf + amt)
	  break;
	line = ++p;
      }
  }

  if (index (bootstrap_args, 'd'))
    {
      static const char msg[] = "Pausing. . .";
      char c;
      write (2, msg, sizeof (msg) - 1);
      read (0, &c, 1);
    }

  init_termstate ();

  /* The boot script has now been parsed into internal data structures.
     Now execute its directives.  */
  {
    err = boot_script_exec ();
    if (err)
      {
	char *str = boot_script_error_string (err);
	int i = strlen (str);

	write (2, str, i);
	write (2, "\n",  1);
	host_exit (1);
      }
    free (buf);
  }

  mach_port_deallocate (mach_task_self (), pseudo_master_device_port);

  err = pthread_create (&pthread_id, NULL, msg_thread, NULL);
  if (!err)
    pthread_detach (pthread_id);
  else
    {
      errno = err;
      perror ("pthread_create");
    }

  for (;;)
    {
      fd_set rmask;
      FD_ZERO (&rmask);
      FD_SET (0, &rmask);
      if (select (1, &rmask, 0, 0, 0) == 1)
	read_reply ();
      else if (errno != EINTR)
        /* We hosed */
	error (5, errno, "select");
    }
}

void *
msg_thread (void *arg)
{
  while (1)
    mach_msg_server (boot_demuxer, 0, receive_set);
}


enum read_type
{
  DEV_READ,
  DEV_READI,
  IO_READ,
};
struct qr
{
  enum read_type type;
  mach_port_t reply_port;
  mach_msg_type_name_t reply_type;
  int amount;
  struct qr *next;
};
struct qr *qrhead, *qrtail;

/* Queue a read for later reply. */
kern_return_t
queue_read (enum read_type type,
	    mach_port_t reply_port,
	    mach_msg_type_name_t reply_type,
	    int amount)
{
  struct qr *qr;

  qr = malloc (sizeof (struct qr));
  if (!qr)
    return D_NO_MEMORY;

  pthread_spin_lock (&queuelock);

  qr->type = type;
  qr->reply_port = reply_port;
  qr->reply_type = reply_type;
  qr->amount = amount;
  qr->next = 0;
  if (qrtail)
    qrtail->next = qr;
  else
    qrhead = qrtail = qr;

  pthread_spin_unlock (&queuelock);
  return D_SUCCESS;
}

/* TRUE if there's data available on stdin, which should be used to satisfy
   console read requests.  */
static int should_read = 0;

/* Reply to a queued read. */
void
read_reply ()
{
  int avail;
  struct qr *qr;
  char * buf;
  int amtread;

  /* By forcing SHOULD_READ to true before trying the lock, we ensure that
     either we get the lock ourselves or that whoever currently holds the
     lock will service this read when he unlocks it.  */
  should_read = 1;
  if (pthread_spin_trylock (&readlock))
    return;

  /* Since we're committed to servicing the read, no one else need do so.  */
  should_read = 0;

  ioctl (0, FIONREAD, &avail);
  if (!avail)
    {
      pthread_spin_unlock (&readlock);
      return;
    }

  pthread_spin_lock (&queuelock);

  if (!qrhead)
    {
      pthread_spin_unlock (&queuelock);
      pthread_spin_unlock (&readlock);
      return;
    }

  qr = qrhead;
  qrhead = qr->next;
  if (qr == qrtail)
    qrtail = 0;

  pthread_spin_unlock (&queuelock);

  if (qr->type == DEV_READ)
    buf = mmap (0, qr->amount, PROT_READ|PROT_WRITE, MAP_ANON, 0, 0);
  else
    buf = alloca (qr->amount);
  amtread = read (0, buf, qr->amount);

  pthread_spin_unlock (&readlock);

  switch (qr->type)
    {
    case DEV_READ:
      if (amtread >= 0)
	ds_device_read_reply (qr->reply_port, qr->reply_type, 0,
			      (io_buf_ptr_t) buf, amtread);
      else
	ds_device_read_reply (qr->reply_port, qr->reply_type, errno, 0, 0);
      break;

    case DEV_READI:
      if (amtread >= 0)
	ds_device_read_reply_inband (qr->reply_port, qr->reply_type, 0,
				     buf, amtread);
      else
	ds_device_read_reply_inband (qr->reply_port, qr->reply_type, errno,
				     0, 0);
      break;

    case IO_READ:
      if (amtread >= 0)
	io_read_reply (qr->reply_port, qr->reply_type, 0,
		       buf, amtread);
      else
	io_read_reply (qr->reply_port, qr->reply_type, errno, 0, 0);
      break;
    }

  free (qr);
}

/* Unlock READLOCK, and also service any new read requests that it was
   blocking.  */
static void
unlock_readlock ()
{
  pthread_spin_unlock (&readlock);
  while (should_read)
    read_reply ();
}

/*
 *	Handle bootstrap requests.
 */
kern_return_t
do_bootstrap_privileged_ports(bootstrap, hostp, devicep)
	mach_port_t bootstrap;
	mach_port_t *hostp, *devicep;
{
	*hostp = privileged_host_port;
	*devicep = pseudo_master_device_port;
	return KERN_SUCCESS;
}

/* Implementation of device interface */

kern_return_t
ds_device_open (mach_port_t master_port,
		mach_port_t reply_port,
		mach_msg_type_name_t reply_type,
		dev_mode_t mode,
		dev_name_t name,
		mach_port_t *device,
		mach_msg_type_name_t *devicetype)
{
  struct dev_map *map;

  if (master_port != pseudo_master_device_port)
    return D_INVALID_OPERATION;

  if (!strcmp (name, "console"))
    {
#if 0
      mach_port_insert_right (mach_task_self (), pseudo_console,
			      pseudo_console, MACH_MSG_TYPE_MAKE_SEND);
      console_send_rights++;
#endif
      console_mscount++;
      *device = pseudo_console;
      *devicetype = MACH_MSG_TYPE_MAKE_SEND;
      return 0;
    }
  else if (!strcmp (name, "time"))
    {
      *device = pseudo_time;
      *devicetype = MACH_MSG_TYPE_MAKE_SEND;
      return 0;
    }
  else if (strcmp (name, "pseudo-root") == 0)
    /* Magic root device.  */
    {
      *device = pseudo_root;
      *devicetype = MACH_MSG_TYPE_MAKE_SEND;
      return 0;
    }

  map = lookup_dev (name);
  if (map)
    {
      error_t err;
      file_t node;

      node = file_name_lookup (map->file_name, 0, 0);
      if (! MACH_PORT_VALID (node))
        return D_NO_SUCH_DEVICE;

      *devicetype = MACH_MSG_TYPE_MOVE_SEND;
      err = device_open (node, mode, "", device);
      mach_port_deallocate (mach_task_self (), node);
      return err;
    }

  *devicetype = MACH_MSG_TYPE_MOVE_SEND;
  return device_open (master_device_port, mode, name, device);
}

kern_return_t
ds_device_close (device_t device)
{
  if (device != pseudo_console && device != pseudo_root)
    return D_NO_SUCH_DEVICE;
  return 0;
}

kern_return_t
ds_device_write (device_t device,
		 mach_port_t reply_port,
		 mach_msg_type_name_t reply_type,
		 dev_mode_t mode,
		 recnum_t recnum,
		 io_buf_ptr_t data,
		 size_t datalen,
		 int *bytes_written)
{
  if (device == pseudo_console)
    {
#if 0
      if (console_send_rights)
	{
	  mach_port_mod_refs (mach_task_self (), pseudo_console,
			      MACH_PORT_TYPE_SEND, -console_send_rights);
	  console_send_rights = 0;
	}
#endif

      *bytes_written = write (1, data, datalen);

      return (*bytes_written == -1 ? D_IO_ERROR : D_SUCCESS);
    }
  else if (device == pseudo_root)
    {
      size_t wrote;
      if (store_write (root_store, recnum, data, datalen, &wrote) != 0)
	return D_IO_ERROR;
      *bytes_written = wrote;
      return D_SUCCESS;
    }
  else
    return D_NO_SUCH_DEVICE;
}

kern_return_t
ds_device_write_inband (device_t device,
			mach_port_t reply_port,
			mach_msg_type_name_t reply_type,
			dev_mode_t mode,
			recnum_t recnum,
			io_buf_ptr_inband_t data,
			size_t datalen,
			int *bytes_written)
{
  if (device == pseudo_console)
    {
#if 0
      if (console_send_rights)
	{
	  mach_port_mod_refs (mach_task_self (), pseudo_console,
			      MACH_PORT_TYPE_SEND, -console_send_rights);
	  console_send_rights = 0;
	}
#endif

      *bytes_written = write (1, data, datalen);

      return (*bytes_written == -1 ? D_IO_ERROR : D_SUCCESS);
    }
  else if (device == pseudo_root)
    {
      size_t wrote;
      if (store_write (root_store, recnum, data, datalen, &wrote) != 0)
	return D_IO_ERROR;
      *bytes_written = wrote;
      return D_SUCCESS;
    }
  else
    return D_NO_SUCH_DEVICE;
}

kern_return_t
ds_device_read (device_t device,
		mach_port_t reply_port,
		mach_msg_type_name_t reply_type,
		dev_mode_t mode,
		recnum_t recnum,
		int bytes_wanted,
		io_buf_ptr_t *data,
		size_t *datalen)
{
  if (device == pseudo_console)
    {
      int avail;

#if 0
      if (console_send_rights)
	{
	  mach_port_mod_refs (mach_task_self (), pseudo_console,
			      MACH_PORT_TYPE_SEND, -console_send_rights);
	  console_send_rights = 0;
	}
#endif

      pthread_spin_lock (&readlock);
      ioctl (0, FIONREAD, &avail);
      if (avail)
	{
	  *data = mmap (0, bytes_wanted, PROT_READ|PROT_WRITE, MAP_ANON, 0, 0);
	  *datalen = read (0, *data, bytes_wanted);
	  unlock_readlock ();
	  return (*datalen == -1 ? D_IO_ERROR : D_SUCCESS);
	}
      else
	{
	  kern_return_t err;

	  unlock_readlock ();
	  err = queue_read (DEV_READ, reply_port, reply_type, bytes_wanted);
	  if (err)
	    return err;
	  return MIG_NO_REPLY;
	}
    }
  else if (device == pseudo_root)
    {
      *datalen = 0;
      return
	(store_read (root_store, recnum, bytes_wanted, (void **)data, datalen) == 0
	 ? D_SUCCESS
	 : D_IO_ERROR);
    }
  else
    return D_NO_SUCH_DEVICE;
}

kern_return_t
ds_device_read_inband (device_t device,
		       mach_port_t reply_port,
		       mach_msg_type_name_t reply_type,
		       dev_mode_t mode,
		       recnum_t recnum,
		       int bytes_wanted,
		       io_buf_ptr_inband_t data,
		       size_t *datalen)
{
  if (device == pseudo_console)
    {
      int avail;

#if 0
      if (console_send_rights)
	{
	  mach_port_mod_refs (mach_task_self (), pseudo_console,
			      MACH_PORT_TYPE_SEND, -console_send_rights);
	  console_send_rights = 0;
	}
#endif

      pthread_spin_lock (&readlock);
      ioctl (0, FIONREAD, &avail);
      if (avail)
	{
	  *datalen = read (0, data, bytes_wanted);
	  unlock_readlock ();
	  return (*datalen == -1 ? D_IO_ERROR : D_SUCCESS);
	}
      else
	{
	  kern_return_t err;

	  unlock_readlock ();
	  err = queue_read (DEV_READI, reply_port, reply_type, bytes_wanted);
	  if (err)
	    return err;
	  return MIG_NO_REPLY;
	}
    }
  else if (device == pseudo_root)
    {
      error_t err;
      void *returned = data;

      *datalen = bytes_wanted;
      err =
	store_read (root_store, recnum, bytes_wanted, (void **)&returned, datalen);

      if (! err)
	{
	  if (returned != data)
	    {
	      bcopy (returned, (void *)data, *datalen);
	      munmap ((caddr_t) returned, *datalen);
	    }
	  return D_SUCCESS;
	}
      else
	return D_IO_ERROR;
    }
  else
    return D_NO_SUCH_DEVICE;
}

kern_return_t
ds_device_map (device_t device,
	       vm_prot_t prot,
	       vm_offset_t offset,
	       vm_size_t size,
	       memory_object_t *pager,
	       int unmap)
{
  if (device == pseudo_console || device == pseudo_root)
    return D_INVALID_OPERATION;
  else if (device == pseudo_time)
    {
      error_t err;
      mach_port_t wr_memobj;
      file_t node = file_name_lookup ("/dev/time", O_RDONLY, 0);

      if (node == MACH_PORT_NULL)
	return D_IO_ERROR;

      err = io_map (node, pager, &wr_memobj);
      if (!err && MACH_PORT_VALID (wr_memobj))
	mach_port_deallocate (mach_task_self (), wr_memobj);

      mach_port_deallocate (mach_task_self (), node);
      return D_SUCCESS;
    }
  else
    return D_NO_SUCH_DEVICE;
}

kern_return_t
ds_device_set_status (device_t device,
		      dev_flavor_t flavor,
		      dev_status_t status,
		      size_t statuslen)
{
  if (device != pseudo_console && device != pseudo_root)
    return D_NO_SUCH_DEVICE;
  return D_INVALID_OPERATION;
}

kern_return_t
ds_device_get_status (device_t device,
		      dev_flavor_t flavor,
		      dev_status_t status,
		      size_t *statuslen)
{
  if (device == pseudo_console)
    return D_INVALID_OPERATION;
  else if (device == pseudo_root)
    switch (flavor)
      {
      case DEV_GET_SIZE:
        if (*statuslen < DEV_GET_SIZE_COUNT)
          return D_INVALID_SIZE;
        status[DEV_GET_SIZE_DEVICE_SIZE] = root_store->size;
        status[DEV_GET_SIZE_RECORD_SIZE] = root_store->block_size;
        *statuslen = DEV_GET_SIZE_COUNT;
        return D_SUCCESS;

      case DEV_GET_RECORDS:
        if (*statuslen < DEV_GET_RECORDS_COUNT)
          return D_INVALID_SIZE;
        status[DEV_GET_RECORDS_DEVICE_RECORDS] = root_store->blocks;
        status[DEV_GET_RECORDS_RECORD_SIZE] = root_store->block_size;
        *statuslen = DEV_GET_RECORDS_COUNT;
        return D_SUCCESS;

      default:
        return D_INVALID_OPERATION;
      }
  else
    return D_NO_SUCH_DEVICE;
}

kern_return_t
ds_device_set_filter (device_t device,
		      mach_port_t receive_port,
		      int priority,
		      filter_array_t filter,
		      size_t filterlen)
{
  if (device != pseudo_console && device != pseudo_root)
    return D_NO_SUCH_DEVICE;
  return D_INVALID_OPERATION;
}


/* Implementation of notify interface */
kern_return_t
do_mach_notify_port_deleted (mach_port_t notify,
			     mach_port_t name)
{
  return EOPNOTSUPP;
}

kern_return_t
do_mach_notify_msg_accepted (mach_port_t notify,
			     mach_port_t name)
{
  return EOPNOTSUPP;
}

kern_return_t
do_mach_notify_port_destroyed (mach_port_t notify,
			       mach_port_t port)
{
  return EOPNOTSUPP;
}

kern_return_t
do_mach_notify_no_senders (mach_port_t notify,
			   mach_port_mscount_t mscount)
{
  static int no_console;
  mach_port_t foo;
  if (notify == pseudo_master_device_port)
    {
      if (no_console)
	goto bye;
      pseudo_master_device_port = MACH_PORT_NULL;
      return 0;
    }
  if (notify == pseudo_console)
    {
      if (mscount == console_mscount &&
	  pseudo_master_device_port == MACH_PORT_NULL)
	{
	bye:
	  restore_termstate ();
	  write (2, "bye\n", 4);
	  host_exit (0);
	}
      else
	{
	  no_console = (mscount == console_mscount);

	  mach_port_request_notification (mach_task_self (), pseudo_console,
					  MACH_NOTIFY_NO_SENDERS,
					  console_mscount == mscount
					  ? mscount + 1
					  : console_mscount,
					  pseudo_console,
					  MACH_MSG_TYPE_MAKE_SEND_ONCE, &foo);
	  if (foo != MACH_PORT_NULL)
	    mach_port_deallocate (mach_task_self (), foo);
	}
    }

  return EOPNOTSUPP;
}

kern_return_t
do_mach_notify_send_once (mach_port_t notify)
{
  return EOPNOTSUPP;
}

static void task_died (mach_port_t name);

kern_return_t
do_mach_notify_dead_name (mach_port_t notify,
			  mach_port_t name)
{
#if 0
  if (name == child_task && notify == bootport)
    host_exit (0);
#endif
  if (notify != dead_task_notification_port)
    return EOPNOTSUPP;
  task_died (name);
  mach_port_deallocate (mach_task_self (), name);
  return 0;
}


/* Implementation of the Hurd I/O interface, which
   we support for the console port only. */

kern_return_t
S_io_write (mach_port_t object,
	    mach_port_t reply_port,
	    mach_msg_type_name_t reply_type,
	    char *data,
	    mach_msg_type_number_t datalen,
	    off_t offset,
	    mach_msg_type_number_t *amtwritten)
{
  if (object != pseudo_console)
    return EOPNOTSUPP;

#if 0
  if (console_send_rights)
    {
      mach_port_mod_refs (mach_task_self (), pseudo_console,
			  MACH_PORT_TYPE_SEND, -console_send_rights);
      console_send_rights = 0;
    }
#endif

  *amtwritten = write (1, data, datalen);
  return *amtwritten == -1 ? errno : 0;
}

kern_return_t
S_io_read (mach_port_t object,
	   mach_port_t reply_port,
	   mach_msg_type_name_t reply_type,
	   char **data,
	   mach_msg_type_number_t *datalen,
	   off_t offset,
	   mach_msg_type_number_t amount)
{
  mach_msg_type_number_t avail;

  if (object != pseudo_console)
    return EOPNOTSUPP;

#if 0
  if (console_send_rights)
    {
      mach_port_mod_refs (mach_task_self (), pseudo_console,
			  MACH_PORT_TYPE_SEND, -console_send_rights);
      console_send_rights = 0;
    }
#endif

  pthread_spin_lock (&readlock);
  ioctl (0, FIONREAD, &avail);
  if (avail)
    {
      if (amount > *datalen)
	*data = mmap (0, amount, PROT_READ|PROT_WRITE, MAP_ANON, 0, 0);
      *datalen = read (0, *data, amount);
      unlock_readlock ();
      return *datalen == -1 ? errno : 0;
    }
  else
    {
      kern_return_t err;
      unlock_readlock ();
      err = queue_read (IO_READ, reply_port, reply_type, amount);
      if (err)
	return err;
      return MIG_NO_REPLY;
    }
}

kern_return_t
S_io_seek (mach_port_t object,
	   mach_port_t reply_port,
	   mach_msg_type_name_t reply_type,
	   off_t offset,
	   int whence,
	   off_t *newp)
{
  return object == pseudo_console ? ESPIPE : EOPNOTSUPP;
}

kern_return_t
S_io_readable (mach_port_t object,
	       mach_port_t reply_port,
	       mach_msg_type_name_t reply_type,
	       mach_msg_type_number_t *amt)
{
  if (object != pseudo_console)
    return EOPNOTSUPP;
  ioctl (0, FIONREAD, amt);
  return 0;
}

kern_return_t
S_io_set_all_openmodes (mach_port_t object,
			mach_port_t reply_port,
			mach_msg_type_name_t reply_type,
			int bits)
{
  return EOPNOTSUPP;
}

kern_return_t
S_io_get_openmodes (mach_port_t object,
		    mach_port_t reply_port,
		    mach_msg_type_name_t reply_type,
		    int *modes)
{
  *modes = O_READ | O_WRITE;
  return object == pseudo_console ? 0 : EOPNOTSUPP;
}

kern_return_t
S_io_set_some_openmodes (mach_port_t object,
			 mach_port_t reply_port,
			 mach_msg_type_name_t reply_type,
			 int bits)
{
  return EOPNOTSUPP;
}

kern_return_t
S_io_clear_some_openmodes (mach_port_t object,
			   mach_port_t reply_port,
			   mach_msg_type_name_t reply_type,
			   int bits)
{
  return EOPNOTSUPP;
}

kern_return_t
S_io_async (mach_port_t object,
	    mach_port_t reply_port,
	    mach_msg_type_name_t reply_type,
	    mach_port_t notify,
	    mach_port_t *id,
	    mach_msg_type_name_t *idtype)
{
  return EOPNOTSUPP;
}

kern_return_t
S_io_mod_owner (mach_port_t object,
		mach_port_t reply_port,
		mach_msg_type_name_t reply_type,
		pid_t owner)
{
  return EOPNOTSUPP;
}

kern_return_t
S_io_get_owner (mach_port_t object,
		mach_port_t reply_port,
		mach_msg_type_name_t reply_type,
		pid_t *owner)
{
  return EOPNOTSUPP;
}

kern_return_t
S_io_get_icky_async_id (mach_port_t object,
			mach_port_t reply_port,
			mach_msg_type_name_t reply_type,
			mach_port_t *id,
			mach_msg_type_name_t *idtype)
{
  return EOPNOTSUPP;
}

static kern_return_t
io_select_common (mach_port_t object,
		  mach_port_t reply_port,
		  mach_msg_type_name_t reply_type,
		  struct timespec *tsp, int *type)
{
  struct timeval tv, *tvp;
  fd_set r, w, x;
  int n;

  if (object != pseudo_console)
    return EOPNOTSUPP;

  FD_ZERO (&r);
  FD_ZERO (&w);
  FD_ZERO (&x);
  FD_SET (0, &r);
  FD_SET (0, &w);
  FD_SET (0, &x);

  if (tsp == NULL)
    tvp = NULL;
  else
    {
      tv.tv_sec = tsp->tv_sec;
      tv.tv_usec = tsp->tv_nsec / 1000;
      tvp = &tv;
    }

  n = select (1,
	      (*type & SELECT_READ) ? &r : 0,
	      (*type & SELECT_WRITE) ? &w : 0,
	      (*type & SELECT_URG) ? &x : 0,
	      tvp);
  if (n < 0)
    return errno;

  if (! FD_ISSET (0, &r))
    *type &= ~SELECT_READ;
  if (! FD_ISSET (0, &w))
    *type &= ~SELECT_WRITE;
  if (! FD_ISSET (0, &x))
    *type &= ~SELECT_URG;

  return 0;
}

kern_return_t
S_io_select (mach_port_t object,
	     mach_port_t reply_port,
	     mach_msg_type_name_t reply_type,
	     int *type)
{
  return io_select_common (object, reply_port, reply_type, NULL, type);
}

kern_return_t
S_io_select_timeout (mach_port_t object,
		     mach_port_t reply_port,
		     mach_msg_type_name_t reply_type,
		     struct timespec ts,
		     int *type)
{
  return io_select_common (object, reply_port, reply_type, &ts, type);
}

kern_return_t
S_io_stat (mach_port_t object,
	   mach_port_t reply_port,
	   mach_msg_type_name_t reply_type,
	   struct stat *st)
{
  if (object != pseudo_console)
    return EOPNOTSUPP;

  memset (st, 0, sizeof(struct stat));
  st->st_blksize = 1024;
  return 0;
}

kern_return_t
S_io_reauthenticate (mach_port_t object,
		     mach_port_t reply_port,
		     mach_msg_type_name_t reply_type,
		     mach_port_t rend)
{
  uid_t *gu, *au;
  gid_t *gg, *ag;
  size_t gulen = 0, aulen = 0, gglen = 0, aglen = 0;
  error_t err;

  /* XXX: This cannot possibly work, authserver is 0.  */

  err = mach_port_insert_right (mach_task_self (), object, object,
				MACH_MSG_TYPE_MAKE_SEND);
  assert_perror (err);

  do
    err = auth_server_authenticate (authserver,
				  rend, MACH_MSG_TYPE_COPY_SEND,
				  object, MACH_MSG_TYPE_COPY_SEND,
				  &gu, &gulen,
				  &au, &aulen,
				  &gg, &gglen,
				  &ag, &aglen);
  while (err == EINTR);

  if (!err)
    {
      mig_deallocate ((vm_address_t) gu, gulen * sizeof *gu);
      mig_deallocate ((vm_address_t) au, aulen * sizeof *gu);
      mig_deallocate ((vm_address_t) gg, gglen * sizeof *gu);
      mig_deallocate ((vm_address_t) au, aulen * sizeof *gu);
    }
  mach_port_deallocate (mach_task_self (), rend);
  mach_port_deallocate (mach_task_self (), object);

  return 0;
}

kern_return_t
S_io_restrict_auth (mach_port_t object,
		    mach_port_t reply_port,
		    mach_msg_type_name_t reply_type,
		    mach_port_t *newobject,
		    mach_msg_type_name_t *newobjtype,
		    uid_t *uids,
		    size_t nuids,
		    uid_t *gids,
		    size_t ngids)
{
  if (object != pseudo_console)
    return EOPNOTSUPP;
  *newobject = pseudo_console;
  *newobjtype = MACH_MSG_TYPE_MAKE_SEND;
  console_mscount++;
  return 0;
}

kern_return_t
S_io_duplicate (mach_port_t object,
		mach_port_t reply_port,
		mach_msg_type_name_t reply_type,
		mach_port_t *newobj,
		mach_msg_type_name_t *newobjtype)
{
  if (object != pseudo_console)
    return EOPNOTSUPP;
  *newobj = pseudo_console;
  *newobjtype = MACH_MSG_TYPE_MAKE_SEND;
  console_mscount++;
  return 0;
}

kern_return_t
S_io_server_version (mach_port_t object,
		     mach_port_t reply_port,
		     mach_msg_type_name_t reply_type,
		     char *name,
		     int *maj,
		     int *min,
		     int *edit)
{
  return EOPNOTSUPP;
}

kern_return_t
S_io_map (mach_port_t obj,
	  mach_port_t reply_port,
	  mach_msg_type_name_t reply_type,
	  mach_port_t *rd,
	  mach_msg_type_name_t *rdtype,
	  mach_port_t *wr,
	  mach_msg_type_name_t *wrtype)
{
  return EOPNOTSUPP;
}

kern_return_t
S_io_map_cntl (mach_port_t obj,
	       mach_port_t reply_port,
	       mach_msg_type_name_t reply_type,
	       mach_port_t *mem,
	       mach_msg_type_name_t *memtype)
{
  return EOPNOTSUPP;
}

kern_return_t
S_io_get_conch (mach_port_t obj,
		mach_port_t reply_port,
		mach_msg_type_name_t reply_type)
{
  return EOPNOTSUPP;
}

kern_return_t
S_io_release_conch (mach_port_t obj,
		    mach_port_t reply_port,
		    mach_msg_type_name_t reply_type)
{
  return EOPNOTSUPP;
}

kern_return_t
S_io_eofnotify (mach_port_t obj,
		mach_port_t reply_port,
		mach_msg_type_name_t reply_type)

{
  return EOPNOTSUPP;
}

kern_return_t
S_io_prenotify (mach_port_t obj,
		mach_port_t reply_port,
		mach_msg_type_name_t reply_type,
		vm_offset_t start,
		vm_offset_t end)
{
  return EOPNOTSUPP;
}

kern_return_t
S_io_postnotify (mach_port_t obj,
		 mach_port_t reply_port,
		 mach_msg_type_name_t reply_type,
		 vm_offset_t start,
		 vm_offset_t end)
{
  return EOPNOTSUPP;
}

kern_return_t
S_io_readsleep (mach_port_t obj,
		mach_port_t reply_port,
		mach_msg_type_name_t reply_type)
{
  return EOPNOTSUPP;
}

kern_return_t
S_io_readnotify (mach_port_t obj,
		 mach_port_t reply_port,
		 mach_msg_type_name_t reply_type)
{
  return EOPNOTSUPP;
}


kern_return_t
S_io_sigio (mach_port_t obj,
	    mach_port_t reply_port,
	    mach_msg_type_name_t reply_type)
{
  return EOPNOTSUPP;
}


kern_return_t
S_io_pathconf (mach_port_t obj,
	       mach_port_t reply_port,
	       mach_msg_type_name_t reply_type,
	       int name, int *value)
{
  return EOPNOTSUPP;
}

kern_return_t
S_io_identity (mach_port_t obj,
	       mach_port_t reply,
	       mach_msg_type_name_t replytype,
	       mach_port_t *id,
	       mach_msg_type_name_t *idtype,
	       mach_port_t *fsid,
	       mach_msg_type_name_t *fsidtype,
	       ino_t *fileno)
{
  return EOPNOTSUPP;
}

kern_return_t
S_io_revoke (mach_port_t obj,
	     mach_port_t reply, mach_msg_type_name_t replyPoly)
{
  return EOPNOTSUPP;
}



/* Implementation of the Hurd terminal driver interface, which we only
   support on the console device.  */

kern_return_t
S_termctty_open_terminal (ctty_t object,
			  int flags,
			  mach_port_t *result,
			  mach_msg_type_name_t *restype)
{
  return EOPNOTSUPP;
}

kern_return_t
S_term_getctty (mach_port_t object,
		mach_port_t *cttyid, mach_msg_type_name_t *cttyPoly)
{
  static mach_port_t id = MACH_PORT_NULL;

  if (object != pseudo_console)
    return EOPNOTSUPP;

  if (id == MACH_PORT_NULL)
    mach_port_allocate (mach_task_self (), MACH_PORT_RIGHT_DEAD_NAME, &id);

  *cttyid = id;
  *cttyPoly = MACH_MSG_TYPE_COPY_SEND;
  return 0;
}


kern_return_t S_term_open_ctty
(
	io_t terminal,
	pid_t pid,
	pid_t pgrp,
	mach_port_t *newtty,
	mach_msg_type_name_t *newttytype
)
{ return EOPNOTSUPP; }

kern_return_t S_term_set_nodename
(
	io_t terminal,
	string_t name
)
{ return EOPNOTSUPP; }

kern_return_t S_term_get_nodename
(
	io_t terminal,
	string_t name
)
{ return EOPNOTSUPP; }

kern_return_t S_term_get_peername
(
	io_t terminal,
	string_t name
)
{ return EOPNOTSUPP; }

kern_return_t S_term_set_filenode
(
	io_t terminal,
	file_t filenode
)
{ return EOPNOTSUPP; }

kern_return_t S_term_get_bottom_type
(
	io_t terminal,
	int *ttype
)
{ return EOPNOTSUPP; }

kern_return_t S_term_on_machdev
(
	io_t terminal,
	mach_port_t machdev
)
{ return EOPNOTSUPP; }

kern_return_t S_term_on_hurddev
(
	io_t terminal,
	io_t hurddev
)
{ return EOPNOTSUPP; }

kern_return_t S_term_on_pty
(
	io_t terminal,
	io_t *ptymaster
)
{ return EOPNOTSUPP; }

/* Mach host emulation.  */

kern_return_t
S_vm_set_default_memory_manager (mach_port_t host_priv,
                                 mach_port_t *default_manager)
{
  if (host_priv != pseudo_privileged_host_port)
    return KERN_INVALID_HOST;

  if (*default_manager != MACH_PORT_NULL)
    return KERN_INVALID_ARGUMENT;

  *default_manager = MACH_PORT_NULL;
  return KERN_SUCCESS;
}

kern_return_t
S_host_reboot (mach_port_t host_priv,
               int flags)
{
  fprintf (stderr, "Would %s the system.  Bye.\n",
           flags & RB_HALT? "halt": "reboot");
  host_exit (0);
}


kern_return_t
S_host_processor_set_priv (mach_port_t host_priv,
			   mach_port_t set_name,
			   mach_port_t *set)
{
  if (host_priv != pseudo_privileged_host_port)
    return KERN_INVALID_HOST;

  *set = pseudo_pset;
  return KERN_SUCCESS;
}

mach_port_t new_task_notification;

kern_return_t
S_register_new_task_notification (mach_port_t host_priv,
				  mach_port_t notification)
{
  if (host_priv != pseudo_privileged_host_port)
    return KERN_INVALID_HOST;

  if (! MACH_PORT_VALID (notification))
    return KERN_INVALID_ARGUMENT;

  if (MACH_PORT_VALID (new_task_notification))
    return KERN_NO_ACCESS;

  new_task_notification = notification;
  return KERN_SUCCESS;
}


/* Managing tasks.  */

static void
task_ihash_cleanup (hurd_ihash_value_t value, void *cookie)
{
  (void) cookie;
  mach_port_deallocate (mach_task_self (), (mach_port_t) value);
}

static struct hurd_ihash task_ihash =
  HURD_IHASH_INITIALIZER_GKI (HURD_IHASH_NO_LOCP, task_ihash_cleanup, NULL,
                              NULL, NULL);

static void
task_died (mach_port_t name)
{
  hurd_ihash_remove (&task_ihash, (hurd_ihash_key_t) name);
}

/* Handle new task notifications from proc.  */
error_t
S_mach_notify_new_task (mach_port_t notify,
			mach_port_t task,
			mach_port_t parent)
{
  error_t err;
  mach_port_t previous;

  if (notify != task_notification_port)
    return EOPNOTSUPP;

  err = mach_port_request_notification (mach_task_self (), task,
                                        MACH_NOTIFY_DEAD_NAME, 0,
                                        dead_task_notification_port,
                                        MACH_MSG_TYPE_MAKE_SEND_ONCE,
                                        &previous);
  if (err)
    goto fail;
  assert (! MACH_PORT_VALID (previous));

  mach_port_mod_refs (mach_task_self (), task, MACH_PORT_RIGHT_SEND, +1);
  err = hurd_ihash_add (&task_ihash,
                        (hurd_ihash_key_t) task, (hurd_ihash_value_t) task);
  if (err)
    {
      mach_port_deallocate (mach_task_self (), task);
      goto fail;
    }

  if (MACH_PORT_VALID (new_task_notification))
    /* Relay the notification.  This consumes task and parent.  */
    return mach_notify_new_task (new_task_notification, task, parent);

  mach_port_deallocate (mach_task_self (), task);
  mach_port_deallocate (mach_task_self (), parent);
  return 0;

 fail:
  task_terminate (task);
  return err;
}

kern_return_t
S_processor_set_tasks(mach_port_t processor_set,
		      task_array_t *task_list,
		      mach_msg_type_number_t *task_listCnt)
{
  error_t err;
  size_t i;

  if (!task_ihash.nr_items)
    {
      *task_listCnt = 0;
      return 0;
    }

  err = vm_allocate (mach_task_self (), (vm_address_t *) task_list,
		     task_ihash.nr_items * sizeof **task_list, 1);
  if (err)
    return err;

  /* The first task has to be the kernel.  */
  (*task_list)[0] = pseudo_kernel;

  i = 1;
  HURD_IHASH_ITERATE (&task_ihash, value)
    {
      task_t task = (task_t) value;
      if (task == pseudo_kernel)
        continue;

      (*task_list)[i] = task;
      i += 1;
    }

  *task_listCnt = task_ihash.nr_items;
  return 0;
}