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