1
2
3
4
5
6
7#define _LARGEFILE64_SOURCE
8#define _GNU_SOURCE
9#include <stdio.h>
10#include <string.h>
11#include <unistd.h>
12#include <err.h>
13#include <stdint.h>
14#include <stdlib.h>
15#include <elf.h>
16#include <sys/mman.h>
17#include <sys/param.h>
18#include <sys/types.h>
19#include <sys/stat.h>
20#include <sys/wait.h>
21#include <sys/eventfd.h>
22#include <fcntl.h>
23#include <stdbool.h>
24#include <errno.h>
25#include <ctype.h>
26#include <sys/socket.h>
27#include <sys/ioctl.h>
28#include <sys/time.h>
29#include <time.h>
30#include <netinet/in.h>
31#include <net/if.h>
32#include <linux/sockios.h>
33#include <linux/if_tun.h>
34#include <sys/uio.h>
35#include <termios.h>
36#include <getopt.h>
37#include <assert.h>
38#include <sched.h>
39#include <limits.h>
40#include <stddef.h>
41#include <signal.h>
42#include <pwd.h>
43#include <grp.h>
44
45#include <linux/virtio_config.h>
46#include <linux/virtio_net.h>
47#include <linux/virtio_blk.h>
48#include <linux/virtio_console.h>
49#include <linux/virtio_rng.h>
50#include <linux/virtio_ring.h>
51#include <asm/bootparam.h>
52#include "../../include/linux/lguest_launcher.h"
53
54
55
56
57
58
59
60
61
62typedef unsigned long long u64;
63typedef uint32_t u32;
64typedef uint16_t u16;
65typedef uint8_t u8;
66
67
68#define BRIDGE_PFX "bridge:"
69#ifndef SIOCBRADDIF
70#define SIOCBRADDIF 0x89a2
71#endif
72
73#define DEVICE_PAGES 256
74
75#define VIRTQUEUE_NUM 256
76
77
78
79
80
81static bool verbose;
82#define verbose(args...) \
83 do { if (verbose) printf(args); } while(0)
84
85
86
87static void *guest_base;
88
89static unsigned long guest_limit, guest_max;
90
91static int lguest_fd;
92
93
94static unsigned int __thread cpu_id;
95
96
97struct device_list {
98
99 unsigned int next_irq;
100
101
102 unsigned int device_num;
103
104
105 u8 *descpage;
106
107
108 struct device *dev;
109
110 struct device *lastdev;
111};
112
113
114static struct device_list devices;
115
116
117struct device {
118
119 struct device *next;
120
121
122 struct lguest_device_desc *desc;
123
124
125 unsigned int feature_len;
126 unsigned int num_vq;
127
128
129 const char *name;
130
131
132 struct virtqueue *vq;
133
134
135 bool running;
136
137
138 void *priv;
139};
140
141
142struct virtqueue {
143 struct virtqueue *next;
144
145
146 struct device *dev;
147
148
149 struct lguest_vqconfig config;
150
151
152 struct vring vring;
153
154
155 u16 last_avail_idx;
156
157
158 unsigned int pending_used;
159
160
161 int eventfd;
162
163
164 void (*service)(struct virtqueue *vq);
165 pid_t thread;
166};
167
168
169static char **main_args;
170
171
172static struct termios orig_term;
173
174
175
176
177
178
179#define wmb() __asm__ __volatile__("" : : : "memory")
180#define mb() __asm__ __volatile__("" : : : "memory")
181
182
183#define lg_last_avail(vq) ((vq)->last_avail_idx)
184
185
186
187
188
189#define cpu_to_le16(v16) (v16)
190#define cpu_to_le32(v32) (v32)
191#define cpu_to_le64(v64) (v64)
192#define le16_to_cpu(v16) (v16)
193#define le32_to_cpu(v32) (v32)
194#define le64_to_cpu(v64) (v64)
195
196
197static bool iov_empty(const struct iovec iov[], unsigned int num_iov)
198{
199 unsigned int i;
200
201 for (i = 0; i < num_iov; i++)
202 if (iov[i].iov_len)
203 return false;
204 return true;
205}
206
207
208static void iov_consume(struct iovec iov[], unsigned num_iov,
209 void *dest, unsigned len)
210{
211 unsigned int i;
212
213 for (i = 0; i < num_iov; i++) {
214 unsigned int used;
215
216 used = iov[i].iov_len < len ? iov[i].iov_len : len;
217 if (dest) {
218 memcpy(dest, iov[i].iov_base, used);
219 dest += used;
220 }
221 iov[i].iov_base += used;
222 iov[i].iov_len -= used;
223 len -= used;
224 }
225 if (len != 0)
226 errx(1, "iovec too short!");
227}
228
229
230static u8 *get_feature_bits(struct device *dev)
231{
232 return (u8 *)(dev->desc + 1)
233 + dev->num_vq * sizeof(struct lguest_vqconfig);
234}
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251static void *from_guest_phys(unsigned long addr)
252{
253 return guest_base + addr;
254}
255
256static unsigned long to_guest_phys(const void *addr)
257{
258 return (addr - guest_base);
259}
260
261
262
263
264
265
266
267static int open_or_die(const char *name, int flags)
268{
269 int fd = open(name, flags);
270 if (fd < 0)
271 err(1, "Failed to open %s", name);
272 return fd;
273}
274
275
276static void *map_zeroed_pages(unsigned int num)
277{
278 int fd = open_or_die("/dev/zero", O_RDONLY);
279 void *addr;
280
281
282
283
284
285
286 addr = mmap(NULL, getpagesize() * (num+2),
287 PROT_NONE, MAP_PRIVATE, fd, 0);
288
289 if (addr == MAP_FAILED)
290 err(1, "Mmapping %u pages of /dev/zero", num);
291
292 if (mprotect(addr + getpagesize(), getpagesize() * num,
293 PROT_READ|PROT_WRITE) == -1)
294 err(1, "mprotect rw %u pages failed", num);
295
296
297
298
299
300 close(fd);
301
302
303 return addr + getpagesize();
304}
305
306
307static void *get_pages(unsigned int num)
308{
309 void *addr = from_guest_phys(guest_limit);
310
311 guest_limit += num * getpagesize();
312 if (guest_limit > guest_max)
313 errx(1, "Not enough memory for devices");
314 return addr;
315}
316
317
318
319
320
321
322static void map_at(int fd, void *addr, unsigned long offset, unsigned long len)
323{
324 ssize_t r;
325
326
327
328
329
330
331
332
333
334
335 if (mmap(addr, len, PROT_READ|PROT_WRITE,
336 MAP_FIXED|MAP_PRIVATE, fd, offset) != MAP_FAILED)
337 return;
338
339
340 r = pread(fd, addr, len, offset);
341 if (r != len)
342 err(1, "Reading offset %lu len %lu gave %zi", offset, len, r);
343}
344
345
346
347
348
349
350
351
352
353
354
355
356static unsigned long map_elf(int elf_fd, const Elf32_Ehdr *ehdr)
357{
358 Elf32_Phdr phdr[ehdr->e_phnum];
359 unsigned int i;
360
361
362
363
364
365 if (ehdr->e_type != ET_EXEC
366 || ehdr->e_machine != EM_386
367 || ehdr->e_phentsize != sizeof(Elf32_Phdr)
368 || ehdr->e_phnum < 1 || ehdr->e_phnum > 65536U/sizeof(Elf32_Phdr))
369 errx(1, "Malformed elf header");
370
371
372
373
374
375
376
377
378 if (lseek(elf_fd, ehdr->e_phoff, SEEK_SET) < 0)
379 err(1, "Seeking to program headers");
380 if (read(elf_fd, phdr, sizeof(phdr)) != sizeof(phdr))
381 err(1, "Reading program headers");
382
383
384
385
386
387 for (i = 0; i < ehdr->e_phnum; i++) {
388
389 if (phdr[i].p_type != PT_LOAD)
390 continue;
391
392 verbose("Section %i: size %i addr %p\n",
393 i, phdr[i].p_memsz, (void *)phdr[i].p_paddr);
394
395
396 map_at(elf_fd, from_guest_phys(phdr[i].p_paddr),
397 phdr[i].p_offset, phdr[i].p_filesz);
398 }
399
400
401 return ehdr->e_entry;
402}
403
404
405
406
407
408
409
410
411
412
413static unsigned long load_bzimage(int fd)
414{
415 struct boot_params boot;
416 int r;
417
418 void *p = from_guest_phys(0x100000);
419
420
421
422
423
424 lseek(fd, 0, SEEK_SET);
425 read(fd, &boot, sizeof(boot));
426
427
428 if (memcmp(&boot.hdr.header, "HdrS", 4) != 0)
429 errx(1, "This doesn't look like a bzImage to me");
430
431
432 lseek(fd, (boot.hdr.setup_sects+1) * 512, SEEK_SET);
433
434
435 while ((r = read(fd, p, 65536)) > 0)
436 p += r;
437
438
439 return boot.hdr.code32_start;
440}
441
442
443
444
445
446
447static unsigned long load_kernel(int fd)
448{
449 Elf32_Ehdr hdr;
450
451
452 if (read(fd, &hdr, sizeof(hdr)) != sizeof(hdr))
453 err(1, "Reading kernel");
454
455
456 if (memcmp(hdr.e_ident, ELFMAG, SELFMAG) == 0)
457 return map_elf(fd, &hdr);
458
459
460 return load_bzimage(fd);
461}
462
463
464
465
466
467
468
469
470static inline unsigned long page_align(unsigned long addr)
471{
472
473 return ((addr + getpagesize()-1) & ~(getpagesize()-1));
474}
475
476
477
478
479
480
481
482
483
484
485static unsigned long load_initrd(const char *name, unsigned long mem)
486{
487 int ifd;
488 struct stat st;
489 unsigned long len;
490
491 ifd = open_or_die(name, O_RDONLY);
492
493 if (fstat(ifd, &st) < 0)
494 err(1, "fstat() on initrd '%s'", name);
495
496
497
498
499
500 len = page_align(st.st_size);
501 map_at(ifd, from_guest_phys(mem - len), 0, st.st_size);
502
503
504
505
506 close(ifd);
507 verbose("mapped initrd %s size=%lu @ %p\n", name, len, (void*)mem-len);
508
509
510 return len;
511}
512
513
514
515
516
517
518static void concat(char *dst, char *args[])
519{
520 unsigned int i, len = 0;
521
522 for (i = 0; args[i]; i++) {
523 if (i) {
524 strcat(dst+len, " ");
525 len++;
526 }
527 strcpy(dst+len, args[i]);
528 len += strlen(args[i]);
529 }
530
531 dst[len] = '\0';
532}
533
534
535
536
537
538
539
540static void tell_kernel(unsigned long start)
541{
542 unsigned long args[] = { LHREQ_INITIALIZE,
543 (unsigned long)guest_base,
544 guest_limit / getpagesize(), start };
545 verbose("Guest: %p - %p (%#lx)\n",
546 guest_base, guest_base + guest_limit, guest_limit);
547 lguest_fd = open_or_die("/dev/lguest", O_RDWR);
548 if (write(lguest_fd, args, sizeof(args)) < 0)
549 err(1, "Writing to /dev/lguest");
550}
551
552
553
554
555
556
557
558
559
560
561static void *_check_pointer(unsigned long addr, unsigned int size,
562 unsigned int line)
563{
564
565
566
567
568 if ((addr + size) > guest_limit || (addr + size) < addr)
569 errx(1, "%s:%i: Invalid address %#lx", __FILE__, line, addr);
570
571
572
573
574 return from_guest_phys(addr);
575}
576
577#define check_pointer(addr,size) _check_pointer(addr, size, __LINE__)
578
579
580
581
582
583
584static unsigned next_desc(struct vring_desc *desc,
585 unsigned int i, unsigned int max)
586{
587 unsigned int next;
588
589
590 if (!(desc[i].flags & VRING_DESC_F_NEXT))
591 return max;
592
593
594 next = desc[i].next;
595
596 wmb();
597
598 if (next >= max)
599 errx(1, "Desc next is %u", next);
600
601 return next;
602}
603
604
605
606
607
608static void trigger_irq(struct virtqueue *vq)
609{
610 unsigned long buf[] = { LHREQ_IRQ, vq->config.irq };
611
612
613 if (!vq->pending_used)
614 return;
615 vq->pending_used = 0;
616
617
618 if (vq->vring.avail->flags & VRING_AVAIL_F_NO_INTERRUPT) {
619 return;
620 }
621
622
623 if (write(lguest_fd, buf, sizeof(buf)) != 0)
624 err(1, "Triggering irq %i", vq->config.irq);
625}
626
627
628
629
630
631
632
633
634
635static unsigned wait_for_vq_desc(struct virtqueue *vq,
636 struct iovec iov[],
637 unsigned int *out_num, unsigned int *in_num)
638{
639 unsigned int i, head, max;
640 struct vring_desc *desc;
641 u16 last_avail = lg_last_avail(vq);
642
643
644 while (last_avail == vq->vring.avail->idx) {
645 u64 event;
646
647
648
649
650
651 trigger_irq(vq);
652
653
654 vq->vring.used->flags &= ~VRING_USED_F_NO_NOTIFY;
655
656
657
658
659
660 mb();
661 if (last_avail != vq->vring.avail->idx) {
662 vq->vring.used->flags |= VRING_USED_F_NO_NOTIFY;
663 break;
664 }
665
666
667 if (read(vq->eventfd, &event, sizeof(event)) != sizeof(event))
668 errx(1, "Event read failed?");
669
670
671 vq->vring.used->flags |= VRING_USED_F_NO_NOTIFY;
672 }
673
674
675 if ((u16)(vq->vring.avail->idx - last_avail) > vq->vring.num)
676 errx(1, "Guest moved used index from %u to %u",
677 last_avail, vq->vring.avail->idx);
678
679
680
681
682
683 head = vq->vring.avail->ring[last_avail % vq->vring.num];
684 lg_last_avail(vq)++;
685
686
687 if (head >= vq->vring.num)
688 errx(1, "Guest says index %u is available", head);
689
690
691 *out_num = *in_num = 0;
692
693 max = vq->vring.num;
694 desc = vq->vring.desc;
695 i = head;
696
697
698
699
700
701 if (desc[i].flags & VRING_DESC_F_INDIRECT) {
702 if (desc[i].len % sizeof(struct vring_desc))
703 errx(1, "Invalid size for indirect buffer table");
704
705 max = desc[i].len / sizeof(struct vring_desc);
706 desc = check_pointer(desc[i].addr, desc[i].len);
707 i = 0;
708 }
709
710 do {
711
712 iov[*out_num + *in_num].iov_len = desc[i].len;
713 iov[*out_num + *in_num].iov_base
714 = check_pointer(desc[i].addr, desc[i].len);
715
716 if (desc[i].flags & VRING_DESC_F_WRITE)
717 (*in_num)++;
718 else {
719
720
721
722
723 if (*in_num)
724 errx(1, "Descriptor has out after in");
725 (*out_num)++;
726 }
727
728
729 if (*out_num + *in_num > max)
730 errx(1, "Looped descriptor");
731 } while ((i = next_desc(desc, i, max)) != max);
732
733 return head;
734}
735
736
737
738
739
740
741static void add_used(struct virtqueue *vq, unsigned int head, int len)
742{
743 struct vring_used_elem *used;
744
745
746
747
748
749 used = &vq->vring.used->ring[vq->vring.used->idx % vq->vring.num];
750 used->id = head;
751 used->len = len;
752
753 wmb();
754 vq->vring.used->idx++;
755 vq->pending_used++;
756}
757
758
759static void add_used_and_trigger(struct virtqueue *vq, unsigned head, int len)
760{
761 add_used(vq, head, len);
762 trigger_irq(vq);
763}
764
765
766
767
768
769
770struct console_abort {
771
772 int count;
773
774 struct timeval start;
775};
776
777
778static void console_input(struct virtqueue *vq)
779{
780 int len;
781 unsigned int head, in_num, out_num;
782 struct console_abort *abort = vq->dev->priv;
783 struct iovec iov[vq->vring.num];
784
785
786 head = wait_for_vq_desc(vq, iov, &out_num, &in_num);
787 if (out_num)
788 errx(1, "Output buffers in console in queue?");
789
790
791 len = readv(STDIN_FILENO, iov, in_num);
792 if (len <= 0) {
793
794 warnx("Failed to get console input, ignoring console.");
795
796
797
798
799 for (;;)
800 pause();
801 }
802
803
804 add_used_and_trigger(vq, head, len);
805
806
807
808
809
810
811
812
813
814 if (len != 1 || ((char *)iov[0].iov_base)[0] != 3) {
815 abort->count = 0;
816 return;
817 }
818
819 abort->count++;
820 if (abort->count == 1)
821 gettimeofday(&abort->start, NULL);
822 else if (abort->count == 3) {
823 struct timeval now;
824 gettimeofday(&now, NULL);
825
826 if (now.tv_sec <= abort->start.tv_sec+1)
827 kill(0, SIGINT);
828 abort->count = 0;
829 }
830}
831
832
833static void console_output(struct virtqueue *vq)
834{
835 unsigned int head, out, in;
836 struct iovec iov[vq->vring.num];
837
838
839 head = wait_for_vq_desc(vq, iov, &out, &in);
840 if (in)
841 errx(1, "Input buffers in console output queue?");
842
843
844 while (!iov_empty(iov, out)) {
845 int len = writev(STDOUT_FILENO, iov, out);
846 if (len <= 0) {
847 warn("Write to stdout gave %i (%d)", len, errno);
848 break;
849 }
850 iov_consume(iov, out, NULL, len);
851 }
852
853
854
855
856
857 add_used(vq, head, 0);
858}
859
860
861
862
863
864
865
866struct net_info {
867 int tunfd;
868};
869
870static void net_output(struct virtqueue *vq)
871{
872 struct net_info *net_info = vq->dev->priv;
873 unsigned int head, out, in;
874 struct iovec iov[vq->vring.num];
875
876
877 head = wait_for_vq_desc(vq, iov, &out, &in);
878 if (in)
879 errx(1, "Input buffers in net output queue?");
880
881
882
883
884 if (writev(net_info->tunfd, iov, out) < 0)
885 warnx("Write to tun failed (%d)?", errno);
886
887
888
889
890
891 add_used(vq, head, 0);
892}
893
894
895
896
897
898
899
900static bool will_block(int fd)
901{
902 fd_set fdset;
903 struct timeval zero = { 0, 0 };
904 FD_ZERO(&fdset);
905 FD_SET(fd, &fdset);
906 return select(fd+1, &fdset, NULL, NULL, &zero) != 1;
907}
908
909
910
911
912
913
914static void net_input(struct virtqueue *vq)
915{
916 int len;
917 unsigned int head, out, in;
918 struct iovec iov[vq->vring.num];
919 struct net_info *net_info = vq->dev->priv;
920
921
922
923
924
925 head = wait_for_vq_desc(vq, iov, &out, &in);
926 if (out)
927 errx(1, "Output buffers in net input queue?");
928
929
930
931
932
933 if (vq->pending_used && will_block(net_info->tunfd))
934 trigger_irq(vq);
935
936
937
938
939
940 len = readv(net_info->tunfd, iov, in);
941 if (len <= 0)
942 warn("Failed to read from tun (%d).", errno);
943
944
945
946
947
948 add_used(vq, head, len);
949}
950
951
952
953static int do_thread(void *_vq)
954{
955 struct virtqueue *vq = _vq;
956
957 for (;;)
958 vq->service(vq);
959 return 0;
960}
961
962
963
964
965
966static void kill_launcher(int signal)
967{
968 kill(0, SIGTERM);
969}
970
971static void reset_device(struct device *dev)
972{
973 struct virtqueue *vq;
974
975 verbose("Resetting device %s\n", dev->name);
976
977
978 memset(get_feature_bits(dev) + dev->feature_len, 0, dev->feature_len);
979
980
981 signal(SIGCHLD, SIG_IGN);
982
983
984 for (vq = dev->vq; vq; vq = vq->next) {
985 if (vq->thread != (pid_t)-1) {
986 kill(vq->thread, SIGTERM);
987 waitpid(vq->thread, NULL, 0);
988 vq->thread = (pid_t)-1;
989 }
990 memset(vq->vring.desc, 0,
991 vring_size(vq->config.num, LGUEST_VRING_ALIGN));
992 lg_last_avail(vq) = 0;
993 }
994 dev->running = false;
995
996
997 signal(SIGCHLD, (void *)kill_launcher);
998}
999
1000
1001
1002
1003static void create_thread(struct virtqueue *vq)
1004{
1005
1006
1007
1008
1009 char *stack = malloc(32768);
1010 unsigned long args[] = { LHREQ_EVENTFD,
1011 vq->config.pfn*getpagesize(), 0 };
1012
1013
1014 vq->eventfd = eventfd(0, 0);
1015 if (vq->eventfd < 0)
1016 err(1, "Creating eventfd");
1017 args[2] = vq->eventfd;
1018
1019
1020
1021
1022
1023 if (write(lguest_fd, &args, sizeof(args)) != 0)
1024 err(1, "Attaching eventfd");
1025
1026
1027
1028
1029
1030 vq->thread = clone(do_thread, stack + 32768, CLONE_VM | SIGCHLD, vq);
1031 if (vq->thread == (pid_t)-1)
1032 err(1, "Creating clone");
1033
1034
1035 close(vq->eventfd);
1036}
1037
1038static void start_device(struct device *dev)
1039{
1040 unsigned int i;
1041 struct virtqueue *vq;
1042
1043 verbose("Device %s OK: offered", dev->name);
1044 for (i = 0; i < dev->feature_len; i++)
1045 verbose(" %02x", get_feature_bits(dev)[i]);
1046 verbose(", accepted");
1047 for (i = 0; i < dev->feature_len; i++)
1048 verbose(" %02x", get_feature_bits(dev)
1049 [dev->feature_len+i]);
1050
1051 for (vq = dev->vq; vq; vq = vq->next) {
1052 if (vq->service)
1053 create_thread(vq);
1054 }
1055 dev->running = true;
1056}
1057
1058static void cleanup_devices(void)
1059{
1060 struct device *dev;
1061
1062 for (dev = devices.dev; dev; dev = dev->next)
1063 reset_device(dev);
1064
1065
1066 if (orig_term.c_lflag & (ISIG|ICANON|ECHO))
1067 tcsetattr(STDIN_FILENO, TCSANOW, &orig_term);
1068}
1069
1070
1071static void update_device_status(struct device *dev)
1072{
1073
1074 if (dev->desc->status == 0)
1075 reset_device(dev);
1076 else if (dev->desc->status & VIRTIO_CONFIG_S_FAILED) {
1077 warnx("Device %s configuration FAILED", dev->name);
1078 if (dev->running)
1079 reset_device(dev);
1080 } else {
1081 if (dev->running)
1082 err(1, "Device %s features finalized twice", dev->name);
1083 start_device(dev);
1084 }
1085}
1086
1087
1088
1089
1090
1091static void handle_output(unsigned long addr)
1092{
1093 struct device *i;
1094
1095
1096 for (i = devices.dev; i; i = i->next) {
1097 struct virtqueue *vq;
1098
1099
1100
1101
1102
1103 if (from_guest_phys(addr) == i->desc) {
1104 update_device_status(i);
1105 return;
1106 }
1107
1108
1109 for (vq = i->vq; vq; vq = vq->next) {
1110 if (addr != vq->config.pfn*getpagesize())
1111 continue;
1112 errx(1, "Notification on %s before setup!", i->name);
1113 }
1114 }
1115
1116
1117
1118
1119
1120
1121 if (addr >= guest_limit)
1122 errx(1, "Bad NOTIFY %#lx", addr);
1123
1124 write(STDOUT_FILENO, from_guest_phys(addr),
1125 strnlen(from_guest_phys(addr), guest_limit - addr));
1126}
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142static u8 *device_config(const struct device *dev)
1143{
1144 return (void *)(dev->desc + 1)
1145 + dev->num_vq * sizeof(struct lguest_vqconfig)
1146 + dev->feature_len * 2;
1147}
1148
1149
1150
1151
1152
1153
1154static struct lguest_device_desc *new_dev_desc(u16 type)
1155{
1156 struct lguest_device_desc d = { .type = type };
1157 void *p;
1158
1159
1160 if (devices.lastdev)
1161 p = device_config(devices.lastdev)
1162 + devices.lastdev->desc->config_len;
1163 else
1164 p = devices.descpage;
1165
1166
1167 if (p + sizeof(d) > (void *)devices.descpage + getpagesize())
1168 errx(1, "Too many devices");
1169
1170
1171 return memcpy(p, &d, sizeof(d));
1172}
1173
1174
1175
1176
1177
1178static void add_virtqueue(struct device *dev, unsigned int num_descs,
1179 void (*service)(struct virtqueue *))
1180{
1181 unsigned int pages;
1182 struct virtqueue **i, *vq = malloc(sizeof(*vq));
1183 void *p;
1184
1185
1186 pages = (vring_size(num_descs, LGUEST_VRING_ALIGN) + getpagesize() - 1)
1187 / getpagesize();
1188 p = get_pages(pages);
1189
1190
1191 vq->next = NULL;
1192 vq->last_avail_idx = 0;
1193 vq->dev = dev;
1194
1195
1196
1197
1198
1199 vq->service = service;
1200 vq->thread = (pid_t)-1;
1201
1202
1203 vq->config.num = num_descs;
1204 vq->config.irq = devices.next_irq++;
1205 vq->config.pfn = to_guest_phys(p) / getpagesize();
1206
1207
1208 vring_init(&vq->vring, num_descs, p, LGUEST_VRING_ALIGN);
1209
1210
1211
1212
1213
1214
1215
1216 assert(dev->desc->config_len == 0 && dev->desc->feature_len == 0);
1217 memcpy(device_config(dev), &vq->config, sizeof(vq->config));
1218 dev->num_vq++;
1219 dev->desc->num_vq++;
1220
1221 verbose("Virtqueue page %#lx\n", to_guest_phys(p));
1222
1223
1224
1225
1226
1227 for (i = &dev->vq; *i; i = &(*i)->next);
1228 *i = vq;
1229}
1230
1231
1232
1233
1234
1235static void add_feature(struct device *dev, unsigned bit)
1236{
1237 u8 *features = get_feature_bits(dev);
1238
1239
1240 if (dev->desc->feature_len <= bit / CHAR_BIT) {
1241 assert(dev->desc->config_len == 0);
1242 dev->feature_len = dev->desc->feature_len = (bit/CHAR_BIT) + 1;
1243 }
1244
1245 features[bit / CHAR_BIT] |= (1 << (bit % CHAR_BIT));
1246}
1247
1248
1249
1250
1251
1252
1253static void set_config(struct device *dev, unsigned len, const void *conf)
1254{
1255
1256 if (device_config(dev) + len > devices.descpage + getpagesize())
1257 errx(1, "Too many devices");
1258
1259
1260 memcpy(device_config(dev), conf, len);
1261 dev->desc->config_len = len;
1262
1263
1264 assert(dev->desc->config_len == len);
1265}
1266
1267
1268
1269
1270
1271
1272
1273
1274static struct device *new_device(const char *name, u16 type)
1275{
1276 struct device *dev = malloc(sizeof(*dev));
1277
1278
1279 dev->desc = new_dev_desc(type);
1280 dev->name = name;
1281 dev->vq = NULL;
1282 dev->feature_len = 0;
1283 dev->num_vq = 0;
1284 dev->running = false;
1285 dev->next = NULL;
1286
1287
1288
1289
1290
1291
1292
1293 if (devices.lastdev)
1294 devices.lastdev->next = dev;
1295 else
1296 devices.dev = dev;
1297 devices.lastdev = dev;
1298
1299 return dev;
1300}
1301
1302
1303
1304
1305
1306static void setup_console(void)
1307{
1308 struct device *dev;
1309
1310
1311 if (tcgetattr(STDIN_FILENO, &orig_term) == 0) {
1312 struct termios term = orig_term;
1313
1314
1315
1316
1317 term.c_lflag &= ~(ISIG|ICANON|ECHO);
1318 tcsetattr(STDIN_FILENO, TCSANOW, &term);
1319 }
1320
1321 dev = new_device("console", VIRTIO_ID_CONSOLE);
1322
1323
1324 dev->priv = malloc(sizeof(struct console_abort));
1325 ((struct console_abort *)dev->priv)->count = 0;
1326
1327
1328
1329
1330
1331
1332
1333 add_virtqueue(dev, VIRTQUEUE_NUM, console_input);
1334 add_virtqueue(dev, VIRTQUEUE_NUM, console_output);
1335
1336 verbose("device %u: console\n", ++devices.device_num);
1337}
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358static u32 str2ip(const char *ipaddr)
1359{
1360 unsigned int b[4];
1361
1362 if (sscanf(ipaddr, "%u.%u.%u.%u", &b[0], &b[1], &b[2], &b[3]) != 4)
1363 errx(1, "Failed to parse IP address '%s'", ipaddr);
1364 return (b[0] << 24) | (b[1] << 16) | (b[2] << 8) | b[3];
1365}
1366
1367static void str2mac(const char *macaddr, unsigned char mac[6])
1368{
1369 unsigned int m[6];
1370 if (sscanf(macaddr, "%02x:%02x:%02x:%02x:%02x:%02x",
1371 &m[0], &m[1], &m[2], &m[3], &m[4], &m[5]) != 6)
1372 errx(1, "Failed to parse mac address '%s'", macaddr);
1373 mac[0] = m[0];
1374 mac[1] = m[1];
1375 mac[2] = m[2];
1376 mac[3] = m[3];
1377 mac[4] = m[4];
1378 mac[5] = m[5];
1379}
1380
1381
1382
1383
1384
1385
1386
1387
1388static void add_to_bridge(int fd, const char *if_name, const char *br_name)
1389{
1390 int ifidx;
1391 struct ifreq ifr;
1392
1393 if (!*br_name)
1394 errx(1, "must specify bridge name");
1395
1396 ifidx = if_nametoindex(if_name);
1397 if (!ifidx)
1398 errx(1, "interface %s does not exist!", if_name);
1399
1400 strncpy(ifr.ifr_name, br_name, IFNAMSIZ);
1401 ifr.ifr_name[IFNAMSIZ-1] = '\0';
1402 ifr.ifr_ifindex = ifidx;
1403 if (ioctl(fd, SIOCBRADDIF, &ifr) < 0)
1404 err(1, "can't add %s to bridge %s", if_name, br_name);
1405}
1406
1407
1408
1409
1410
1411
1412static void configure_device(int fd, const char *tapif, u32 ipaddr)
1413{
1414 struct ifreq ifr;
1415 struct sockaddr_in sin;
1416
1417 memset(&ifr, 0, sizeof(ifr));
1418 strcpy(ifr.ifr_name, tapif);
1419
1420
1421 sin.sin_family = AF_INET;
1422 sin.sin_addr.s_addr = htonl(ipaddr);
1423 memcpy(&ifr.ifr_addr, &sin, sizeof(sin));
1424 if (ioctl(fd, SIOCSIFADDR, &ifr) != 0)
1425 err(1, "Setting %s interface address", tapif);
1426 ifr.ifr_flags = IFF_UP;
1427 if (ioctl(fd, SIOCSIFFLAGS, &ifr) != 0)
1428 err(1, "Bringing interface %s up", tapif);
1429}
1430
1431static int get_tun_device(char tapif[IFNAMSIZ])
1432{
1433 struct ifreq ifr;
1434 int netfd;
1435
1436
1437 memset(&ifr, 0, sizeof(ifr));
1438
1439
1440
1441
1442
1443
1444
1445 netfd = open_or_die("/dev/net/tun", O_RDWR);
1446 ifr.ifr_flags = IFF_TAP | IFF_NO_PI | IFF_VNET_HDR;
1447 strcpy(ifr.ifr_name, "tap%d");
1448 if (ioctl(netfd, TUNSETIFF, &ifr) != 0)
1449 err(1, "configuring /dev/net/tun");
1450
1451 if (ioctl(netfd, TUNSETOFFLOAD,
1452 TUN_F_CSUM|TUN_F_TSO4|TUN_F_TSO6|TUN_F_TSO_ECN) != 0)
1453 err(1, "Could not set features for tun device");
1454
1455
1456
1457
1458
1459 ioctl(netfd, TUNSETNOCSUM, 1);
1460
1461 memcpy(tapif, ifr.ifr_name, IFNAMSIZ);
1462 return netfd;
1463}
1464
1465
1466
1467
1468
1469
1470
1471static void setup_tun_net(char *arg)
1472{
1473 struct device *dev;
1474 struct net_info *net_info = malloc(sizeof(*net_info));
1475 int ipfd;
1476 u32 ip = INADDR_ANY;
1477 bool bridging = false;
1478 char tapif[IFNAMSIZ], *p;
1479 struct virtio_net_config conf;
1480
1481 net_info->tunfd = get_tun_device(tapif);
1482
1483
1484 dev = new_device("net", VIRTIO_ID_NET);
1485 dev->priv = net_info;
1486
1487
1488 add_virtqueue(dev, VIRTQUEUE_NUM, net_input);
1489 add_virtqueue(dev, VIRTQUEUE_NUM, net_output);
1490
1491
1492
1493
1494
1495 ipfd = socket(PF_INET, SOCK_DGRAM, IPPROTO_IP);
1496 if (ipfd < 0)
1497 err(1, "opening IP socket");
1498
1499
1500 if (!strncmp(BRIDGE_PFX, arg, strlen(BRIDGE_PFX))) {
1501 arg += strlen(BRIDGE_PFX);
1502 bridging = true;
1503 }
1504
1505
1506 p = strchr(arg, ':');
1507 if (p) {
1508 str2mac(p+1, conf.mac);
1509 add_feature(dev, VIRTIO_NET_F_MAC);
1510 *p = '\0';
1511 }
1512
1513
1514 if (bridging)
1515 add_to_bridge(ipfd, tapif, arg);
1516 else
1517 ip = str2ip(arg);
1518
1519
1520 configure_device(ipfd, tapif, ip);
1521
1522
1523 add_feature(dev, VIRTIO_NET_F_CSUM);
1524 add_feature(dev, VIRTIO_NET_F_GUEST_CSUM);
1525 add_feature(dev, VIRTIO_NET_F_GUEST_TSO4);
1526 add_feature(dev, VIRTIO_NET_F_GUEST_TSO6);
1527 add_feature(dev, VIRTIO_NET_F_GUEST_ECN);
1528 add_feature(dev, VIRTIO_NET_F_HOST_TSO4);
1529 add_feature(dev, VIRTIO_NET_F_HOST_TSO6);
1530 add_feature(dev, VIRTIO_NET_F_HOST_ECN);
1531
1532 add_feature(dev, VIRTIO_RING_F_INDIRECT_DESC);
1533 set_config(dev, sizeof(conf), &conf);
1534
1535
1536 close(ipfd);
1537
1538 devices.device_num++;
1539
1540 if (bridging)
1541 verbose("device %u: tun %s attached to bridge: %s\n",
1542 devices.device_num, tapif, arg);
1543 else
1544 verbose("device %u: tun %s: %s\n",
1545 devices.device_num, tapif, arg);
1546}
1547
1548
1549
1550struct vblk_info {
1551
1552 off64_t len;
1553
1554
1555 int fd;
1556
1557};
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573static void blk_request(struct virtqueue *vq)
1574{
1575 struct vblk_info *vblk = vq->dev->priv;
1576 unsigned int head, out_num, in_num, wlen;
1577 int ret, i;
1578 u8 *in;
1579 struct virtio_blk_outhdr out;
1580 struct iovec iov[vq->vring.num];
1581 off64_t off;
1582
1583
1584
1585
1586
1587 head = wait_for_vq_desc(vq, iov, &out_num, &in_num);
1588
1589
1590 iov_consume(iov, out_num, &out, sizeof(out));
1591
1592
1593 in = NULL;
1594 for (i = out_num + in_num - 1; i >= out_num; i--) {
1595 if (iov[i].iov_len > 0) {
1596 in = iov[i].iov_base + iov[i].iov_len - 1;
1597 iov[i].iov_len--;
1598 break;
1599 }
1600 }
1601 if (!in)
1602 errx(1, "Bad virtblk cmd with no room for status");
1603
1604
1605
1606
1607
1608 off = out.sector * 512;
1609
1610
1611
1612
1613
1614 if (out.type & VIRTIO_BLK_T_SCSI_CMD) {
1615 fprintf(stderr, "Scsi commands unsupported\n");
1616 *in = VIRTIO_BLK_S_UNSUPP;
1617 wlen = sizeof(*in);
1618 } else if (out.type & VIRTIO_BLK_T_OUT) {
1619
1620
1621
1622
1623
1624
1625 if (lseek64(vblk->fd, off, SEEK_SET) != off)
1626 err(1, "Bad seek to sector %llu", out.sector);
1627
1628 ret = writev(vblk->fd, iov, out_num);
1629 verbose("WRITE to sector %llu: %i\n", out.sector, ret);
1630
1631
1632
1633
1634
1635
1636 if (ret > 0 && off + ret > vblk->len) {
1637
1638 ftruncate64(vblk->fd, vblk->len);
1639
1640 errx(1, "Write past end %llu+%u", off, ret);
1641 }
1642
1643 wlen = sizeof(*in);
1644 *in = (ret >= 0 ? VIRTIO_BLK_S_OK : VIRTIO_BLK_S_IOERR);
1645 } else if (out.type & VIRTIO_BLK_T_FLUSH) {
1646
1647 ret = fdatasync(vblk->fd);
1648 verbose("FLUSH fdatasync: %i\n", ret);
1649 wlen = sizeof(*in);
1650 *in = (ret >= 0 ? VIRTIO_BLK_S_OK : VIRTIO_BLK_S_IOERR);
1651 } else {
1652
1653
1654
1655
1656
1657
1658 if (lseek64(vblk->fd, off, SEEK_SET) != off)
1659 err(1, "Bad seek to sector %llu", out.sector);
1660
1661 ret = readv(vblk->fd, iov + out_num, in_num);
1662 if (ret >= 0) {
1663 wlen = sizeof(*in) + ret;
1664 *in = VIRTIO_BLK_S_OK;
1665 } else {
1666 wlen = sizeof(*in);
1667 *in = VIRTIO_BLK_S_IOERR;
1668 }
1669 }
1670
1671
1672 add_used(vq, head, wlen);
1673}
1674
1675
1676static void setup_block_file(const char *filename)
1677{
1678 struct device *dev;
1679 struct vblk_info *vblk;
1680 struct virtio_blk_config conf;
1681
1682
1683 dev = new_device("block", VIRTIO_ID_BLOCK);
1684
1685
1686 add_virtqueue(dev, VIRTQUEUE_NUM, blk_request);
1687
1688
1689 vblk = dev->priv = malloc(sizeof(*vblk));
1690
1691
1692 vblk->fd = open_or_die(filename, O_RDWR|O_LARGEFILE);
1693 vblk->len = lseek64(vblk->fd, 0, SEEK_END);
1694
1695
1696 add_feature(dev, VIRTIO_BLK_F_FLUSH);
1697
1698
1699 conf.capacity = cpu_to_le64(vblk->len / 512);
1700
1701
1702
1703
1704
1705 add_feature(dev, VIRTIO_BLK_F_SEG_MAX);
1706 conf.seg_max = cpu_to_le32(VIRTQUEUE_NUM - 2);
1707
1708
1709 set_config(dev, offsetof(struct virtio_blk_config, geometry), &conf);
1710
1711 verbose("device %u: virtblock %llu sectors\n",
1712 ++devices.device_num, le64_to_cpu(conf.capacity));
1713}
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723struct rng_info {
1724 int rfd;
1725};
1726
1727static void rng_input(struct virtqueue *vq)
1728{
1729 int len;
1730 unsigned int head, in_num, out_num, totlen = 0;
1731 struct rng_info *rng_info = vq->dev->priv;
1732 struct iovec iov[vq->vring.num];
1733
1734
1735 head = wait_for_vq_desc(vq, iov, &out_num, &in_num);
1736 if (out_num)
1737 errx(1, "Output buffers in rng?");
1738
1739
1740
1741
1742
1743 while (!iov_empty(iov, in_num)) {
1744 len = readv(rng_info->rfd, iov, in_num);
1745 if (len <= 0)
1746 err(1, "Read from /dev/random gave %i", len);
1747 iov_consume(iov, in_num, NULL, len);
1748 totlen += len;
1749 }
1750
1751
1752 add_used(vq, head, totlen);
1753}
1754
1755
1756
1757
1758static void setup_rng(void)
1759{
1760 struct device *dev;
1761 struct rng_info *rng_info = malloc(sizeof(*rng_info));
1762
1763
1764 rng_info->rfd = open_or_die("/dev/random", O_RDONLY);
1765
1766
1767 dev = new_device("rng", VIRTIO_ID_RNG);
1768 dev->priv = rng_info;
1769
1770
1771 add_virtqueue(dev, VIRTQUEUE_NUM, rng_input);
1772
1773 verbose("device %u: rng\n", devices.device_num++);
1774}
1775
1776
1777
1778static void __attribute__((noreturn)) restart_guest(void)
1779{
1780 unsigned int i;
1781
1782
1783
1784
1785
1786 for (i = 3; i < FD_SETSIZE; i++)
1787 close(i);
1788
1789
1790 cleanup_devices();
1791
1792 execv(main_args[0], main_args);
1793 err(1, "Could not exec %s", main_args[0]);
1794}
1795
1796
1797
1798
1799
1800static void __attribute__((noreturn)) run_guest(void)
1801{
1802 for (;;) {
1803 unsigned long notify_addr;
1804 int readval;
1805
1806
1807 readval = pread(lguest_fd, ¬ify_addr,
1808 sizeof(notify_addr), cpu_id);
1809
1810
1811 if (readval == sizeof(notify_addr)) {
1812 verbose("Notify on address %#lx\n", notify_addr);
1813 handle_output(notify_addr);
1814
1815 } else if (errno == ENOENT) {
1816 char reason[1024] = { 0 };
1817 pread(lguest_fd, reason, sizeof(reason)-1, cpu_id);
1818 errx(1, "%s", reason);
1819
1820 } else if (errno == ERESTART) {
1821 restart_guest();
1822
1823 } else
1824 err(1, "Running guest failed");
1825 }
1826}
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836static struct option opts[] = {
1837 { "verbose", 0, NULL, 'v' },
1838 { "tunnet", 1, NULL, 't' },
1839 { "block", 1, NULL, 'b' },
1840 { "rng", 0, NULL, 'r' },
1841 { "initrd", 1, NULL, 'i' },
1842 { "username", 1, NULL, 'u' },
1843 { "chroot", 1, NULL, 'c' },
1844 { NULL },
1845};
1846static void usage(void)
1847{
1848 errx(1, "Usage: lguest [--verbose] "
1849 "[--tunnet=(<ipaddr>:<macaddr>|bridge:<bridgename>:<macaddr>)\n"
1850 "|--block=<filename>|--initrd=<filename>]...\n"
1851 "<mem-in-mb> vmlinux [args...]");
1852}
1853
1854
1855int main(int argc, char *argv[])
1856{
1857
1858 unsigned long mem = 0, start, initrd_size = 0;
1859
1860 int i, c;
1861
1862 struct boot_params *boot;
1863
1864 const char *initrd_name = NULL;
1865
1866
1867 struct passwd *user_details = NULL;
1868
1869
1870 char *chroot_path = NULL;
1871
1872
1873 main_args = argv;
1874
1875
1876
1877
1878
1879
1880 devices.lastdev = NULL;
1881 devices.next_irq = 1;
1882
1883
1884 cpu_id = 0;
1885
1886
1887
1888
1889
1890
1891
1892 for (i = 1; i < argc; i++) {
1893 if (argv[i][0] != '-') {
1894 mem = atoi(argv[i]) * 1024 * 1024;
1895
1896
1897
1898
1899
1900
1901 guest_base = map_zeroed_pages(mem / getpagesize()
1902 + DEVICE_PAGES);
1903 guest_limit = mem;
1904 guest_max = mem + DEVICE_PAGES*getpagesize();
1905 devices.descpage = get_pages(1);
1906 break;
1907 }
1908 }
1909
1910
1911 while ((c = getopt_long(argc, argv, "v", opts, NULL)) != EOF) {
1912 switch (c) {
1913 case 'v':
1914 verbose = true;
1915 break;
1916 case 't':
1917 setup_tun_net(optarg);
1918 break;
1919 case 'b':
1920 setup_block_file(optarg);
1921 break;
1922 case 'r':
1923 setup_rng();
1924 break;
1925 case 'i':
1926 initrd_name = optarg;
1927 break;
1928 case 'u':
1929 user_details = getpwnam(optarg);
1930 if (!user_details)
1931 err(1, "getpwnam failed, incorrect username?");
1932 break;
1933 case 'c':
1934 chroot_path = optarg;
1935 break;
1936 default:
1937 warnx("Unknown argument %s", argv[optind]);
1938 usage();
1939 }
1940 }
1941
1942
1943
1944
1945 if (optind + 2 > argc)
1946 usage();
1947
1948 verbose("Guest base is at %p\n", guest_base);
1949
1950
1951 setup_console();
1952
1953
1954 start = load_kernel(open_or_die(argv[optind+1], O_RDONLY));
1955
1956
1957 boot = from_guest_phys(0);
1958
1959
1960 if (initrd_name) {
1961 initrd_size = load_initrd(initrd_name, mem);
1962
1963
1964
1965
1966 boot->hdr.ramdisk_image = mem - initrd_size;
1967 boot->hdr.ramdisk_size = initrd_size;
1968
1969 boot->hdr.type_of_loader = 0xFF;
1970 }
1971
1972
1973
1974
1975
1976 boot->e820_entries = 1;
1977 boot->e820_map[0] = ((struct e820entry) { 0, mem, E820_RAM });
1978
1979
1980
1981
1982 boot->hdr.cmd_line_ptr = to_guest_phys(boot + 1);
1983
1984 concat((char *)(boot + 1), argv+optind+2);
1985
1986
1987 boot->hdr.kernel_alignment = 0x1000000;
1988
1989
1990 boot->hdr.version = 0x207;
1991
1992
1993 boot->hdr.hardware_subarch = 1;
1994
1995
1996 boot->hdr.loadflags |= KEEP_SEGMENTS;
1997
1998
1999 tell_kernel(start);
2000
2001
2002 signal(SIGCHLD, kill_launcher);
2003
2004
2005 atexit(cleanup_devices);
2006
2007
2008 if (chroot_path) {
2009 if (chroot(chroot_path) != 0)
2010 err(1, "chroot(\"%s\") failed", chroot_path);
2011
2012 if (chdir("/") != 0)
2013 err(1, "chdir(\"/\") failed");
2014
2015 verbose("chroot done\n");
2016 }
2017
2018
2019 if (user_details) {
2020 uid_t u;
2021 gid_t g;
2022
2023 u = user_details->pw_uid;
2024 g = user_details->pw_gid;
2025
2026 if (initgroups(user_details->pw_name, g) != 0)
2027 err(1, "initgroups failed");
2028
2029 if (setresgid(g, g, g) != 0)
2030 err(1, "setresgid failed");
2031
2032 if (setresuid(u, u, u) != 0)
2033 err(1, "setresuid failed");
2034
2035 verbose("Dropping privileges completed\n");
2036 }
2037
2038
2039 run_guest();
2040}
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053