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