xref: /openbmc/qemu/pc-bios/s390-ccw/netmain.c (revision 3adbf0bb8a78f17a1e9390b59e51eb1a47d8ac98)
1 /*
2  * S390 virtio-ccw network boot loading program
3  *
4  * Copyright 2017 Thomas Huth, Red Hat Inc.
5  *
6  * Based on the S390 virtio-ccw loading program (main.c)
7  * Copyright (c) 2013 Alexander Graf <agraf@suse.de>
8  *
9  * And based on the network loading code from SLOF (netload.c)
10  * Copyright (c) 2004, 2008 IBM Corporation
11  *
12  * This code is free software; you can redistribute it and/or modify it
13  * under the terms of the GNU General Public License as published by the
14  * Free Software Foundation; either version 2 of the License, or (at your
15  * option) any later version.
16  */
17 
18 #include <stdint.h>
19 #include <stdbool.h>
20 #include <stdio.h>
21 #include <stdlib.h>
22 #include <string.h>
23 #include <unistd.h>
24 
25 #include <tftp.h>
26 #include <ethernet.h>
27 #include <dhcp.h>
28 #include <dhcpv6.h>
29 #include <ipv4.h>
30 #include <ipv6.h>
31 #include <dns.h>
32 #include <time.h>
33 #include <pxelinux.h>
34 
35 #include "s390-ccw.h"
36 #include "cio.h"
37 #include "virtio.h"
38 #include "s390-time.h"
39 
40 #define DEFAULT_BOOT_RETRIES 10
41 #define DEFAULT_TFTP_RETRIES 20
42 
43 extern char _start[];
44 
45 #define KERNEL_ADDR             ((void *)0L)
46 #define KERNEL_MAX_SIZE         ((long)_start)
47 #define ARCH_COMMAND_LINE_SIZE  896              /* Taken from Linux kernel */
48 
49 /* STSI 3.2.2 offset of first vmdb + offset of uuid inside vmdb */
50 #define STSI322_VMDB_UUID_OFFSET ((8 + 12) * 4)
51 
52 static char cfgbuf[2048];
53 
54 SubChannelId net_schid = { .one = 1 };
55 static uint8_t mac[6];
56 static uint64_t dest_timer;
57 
set_timer(int val)58 void set_timer(int val)
59 {
60     dest_timer = get_time_ms() + val;
61 }
62 
get_timer(void)63 int get_timer(void)
64 {
65     return dest_timer - get_time_ms();
66 }
67 
get_sec_ticks(void)68 int get_sec_ticks(void)
69 {
70     return 1000;    /* number of ticks in 1 second */
71 }
72 
73 /**
74  * Obtain IP and configuration info from DHCP server (either IPv4 or IPv6).
75  * @param  fn_ip     contains the following configuration information:
76  *                   client MAC, client IP, TFTP-server MAC, TFTP-server IP,
77  *                   boot file name
78  * @param  retries   Number of DHCP attempts
79  * @return           0 : IP and configuration info obtained;
80  *                   non-0 : error condition occurred.
81  */
dhcp(struct filename_ip * fn_ip,int retries)82 static int dhcp(struct filename_ip *fn_ip, int retries)
83 {
84     int i = retries + 1;
85     int rc = -1;
86 
87     printf("  Requesting information via DHCP:     ");
88 
89     dhcpv4_generate_transaction_id();
90     dhcpv6_generate_transaction_id();
91 
92     do {
93         printf("\b\b\b%03d", i - 1);
94         if (!--i) {
95             printf("\nGiving up after %d DHCP requests\n", retries);
96             return -1;
97         }
98         fn_ip->ip_version = 4;
99         rc = dhcpv4(NULL, fn_ip);
100         if (rc == -1) {
101             fn_ip->ip_version = 6;
102             set_ipv6_address(fn_ip->fd, 0);
103             rc = dhcpv6(NULL, fn_ip);
104             if (rc == 0) {
105                 memcpy(&fn_ip->own_ip6, get_ipv6_address(), 16);
106                 break;
107             }
108         }
109         if (rc != -1) {    /* either success or non-dhcp failure */
110             break;
111         }
112     } while (1);
113     printf("\b\b\b\bdone\n");
114 
115     return rc;
116 }
117 
118 /**
119  * Seed the random number generator with our mac and current timestamp
120  */
seed_rng(uint8_t mac[])121 static void seed_rng(uint8_t mac[])
122 {
123     uint64_t seed;
124 
125     asm volatile(" stck %0 " : : "Q"(seed) : "memory");
126     seed ^= (mac[2] << 24) | (mac[3] << 16) | (mac[4] << 8) | mac[5];
127     srand(seed);
128 }
129 
tftp_load(filename_ip_t * fnip,void * buffer,int len)130 static int tftp_load(filename_ip_t *fnip, void *buffer, int len)
131 {
132     tftp_err_t tftp_err;
133     int rc;
134 
135     rc = tftp(fnip, buffer, len, DEFAULT_TFTP_RETRIES, &tftp_err);
136 
137     if (rc < 0) {
138         /* Make sure that error messages are put into a new line */
139         printf("\n  ");
140     }
141 
142     if (rc > 1024) {
143         printf("  TFTP: Received %s (%d KBytes)\n", fnip->filename, rc / 1024);
144     } else if (rc > 0) {
145         printf("  TFTP: Received %s (%d Bytes)\n", fnip->filename, rc);
146     } else {
147         const char *errstr = NULL;
148         int ecode;
149         tftp_get_error_info(fnip, &tftp_err, rc, &errstr, &ecode);
150         printf("TFTP error: %s\n", errstr ? errstr : "unknown error");
151     }
152 
153     return rc;
154 }
155 
net_init_ip(filename_ip_t * fn_ip)156 static int net_init_ip(filename_ip_t *fn_ip)
157 {
158     int rc;
159 
160     printf("  Using MAC address: %02x:%02x:%02x:%02x:%02x:%02x\n",
161            mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
162 
163     set_mac_address(mac);    /* init ethernet layer */
164     seed_rng(mac);
165 
166     rc = dhcp(fn_ip, DEFAULT_BOOT_RETRIES);
167     if (rc >= 0) {
168         if (fn_ip->ip_version == 4) {
169             set_ipv4_address(fn_ip->own_ip);
170         }
171     } else if (rc == -2) {
172         printf("ARP request to TFTP server (%d.%d.%d.%d) failed\n",
173                (fn_ip->server_ip >> 24) & 0xFF, (fn_ip->server_ip >> 16) & 0xFF,
174                (fn_ip->server_ip >>  8) & 0xFF, fn_ip->server_ip & 0xFF);
175         return -102;
176     } else if (rc == -4 || rc == -3) {
177         puts("Can't obtain TFTP server IP address");
178         return -107;
179     } else {
180         puts("Could not get IP address");
181         return -101;
182     }
183 
184     if (fn_ip->ip_version == 4) {
185         printf("  Using IPv4 address: %d.%d.%d.%d\n",
186               (fn_ip->own_ip >> 24) & 0xFF, (fn_ip->own_ip >> 16) & 0xFF,
187               (fn_ip->own_ip >>  8) & 0xFF, fn_ip->own_ip & 0xFF);
188     } else if (fn_ip->ip_version == 6) {
189         char ip6_str[40];
190         ipv6_to_str(fn_ip->own_ip6.addr, ip6_str);
191         printf("  Using IPv6 address: %s\n", ip6_str);
192     }
193 
194     printf("  Using TFTP server: ");
195     if (fn_ip->ip_version == 4) {
196         printf("%d.%d.%d.%d\n",
197                (fn_ip->server_ip >> 24) & 0xFF, (fn_ip->server_ip >> 16) & 0xFF,
198                (fn_ip->server_ip >>  8) & 0xFF, fn_ip->server_ip & 0xFF);
199     } else if (fn_ip->ip_version == 6) {
200         char ip6_str[40];
201         ipv6_to_str(fn_ip->server_ip6.addr, ip6_str);
202         printf("%s\n", ip6_str);
203     }
204 
205     if (strlen(fn_ip->filename) > 0) {
206         printf("  Bootfile name: '%s'\n", fn_ip->filename);
207     }
208 
209     return rc;
210 }
211 
net_init(filename_ip_t * fn_ip)212 static int net_init(filename_ip_t *fn_ip)
213 {
214     int rc;
215 
216     memset(fn_ip, 0, sizeof(filename_ip_t));
217 
218     rc = virtio_net_init(mac);
219     if (rc < 0) {
220         puts("Could not initialize network device");
221         return -101;
222     }
223     fn_ip->fd = rc;
224 
225     rc = net_init_ip(fn_ip);
226     if (rc < 0) {
227         virtio_net_deinit();
228     }
229 
230     return rc;
231 }
232 
net_release(filename_ip_t * fn_ip)233 static void net_release(filename_ip_t *fn_ip)
234 {
235     if (fn_ip->ip_version == 4) {
236         dhcp_send_release(fn_ip->fd);
237     }
238     virtio_net_deinit();
239 }
240 
241 /**
242  * Retrieve the Universally Unique Identifier of the VM.
243  * @return UUID string, or NULL in case of errors
244  */
get_uuid(void)245 static const char *get_uuid(void)
246 {
247     register int r0 asm("0");
248     register int r1 asm("1");
249     uint8_t *mem, *buf, uuid[16];
250     int i, cc, chk = 0;
251     static char uuid_str[37];
252 
253     mem = malloc(2 * PAGE_SIZE);
254     if (!mem) {
255         puts("Out of memory ... can not get UUID.");
256         return NULL;
257     }
258     buf = (uint8_t *)(((uint64_t)mem + PAGE_SIZE - 1) & ~(PAGE_SIZE - 1));
259     memset(buf, 0, PAGE_SIZE);
260 
261     /* Get SYSIB 3.2.2 */
262     r0 = (3 << 28) | 2;
263     r1 = 2;
264     asm volatile(" stsi 0(%[addr])\n"
265                  " ipm  %[cc]\n"
266                  " srl  %[cc],28\n"
267                  : [cc] "=d" (cc)
268                  : "d" (r0), "d" (r1), [addr] "a" (buf)
269                  : "cc", "memory");
270     if (cc) {
271         free(mem);
272         return NULL;
273     }
274 
275     for (i = 0; i < 16; i++) {
276         uuid[i] = buf[STSI322_VMDB_UUID_OFFSET + i];
277         chk |= uuid[i];
278     }
279     free(mem);
280     if (!chk) {
281         return NULL;
282     }
283 
284     sprintf(uuid_str, "%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-"
285             "%02x%02x%02x%02x%02x%02x", uuid[0], uuid[1], uuid[2], uuid[3],
286             uuid[4], uuid[5], uuid[6], uuid[7], uuid[8], uuid[9], uuid[10],
287             uuid[11], uuid[12], uuid[13], uuid[14], uuid[15]);
288 
289     return uuid_str;
290 }
291 
292 /**
293  * Load a kernel with initrd (i.e. with the information that we've got from
294  * a pxelinux.cfg config file)
295  */
load_kernel_with_initrd(filename_ip_t * fn_ip,struct pl_cfg_entry * entry)296 static int load_kernel_with_initrd(filename_ip_t *fn_ip,
297                                    struct pl_cfg_entry *entry)
298 {
299     int rc;
300 
301     printf("Loading pxelinux.cfg entry '%s'\n", entry->label);
302 
303     if (!entry->kernel) {
304         puts("Kernel entry is missing!\n");
305         return -1;
306     }
307 
308     strncpy(fn_ip->filename, entry->kernel, sizeof(fn_ip->filename));
309     rc = tftp_load(fn_ip, KERNEL_ADDR, KERNEL_MAX_SIZE);
310     if (rc < 0) {
311         return rc;
312     }
313 
314     if (entry->initrd) {
315         uint64_t iaddr = (rc + 0xfff) & ~0xfffUL;
316 
317         strncpy(fn_ip->filename, entry->initrd, sizeof(fn_ip->filename));
318         rc = tftp_load(fn_ip, (void *)iaddr, KERNEL_MAX_SIZE - iaddr);
319         if (rc < 0) {
320             return rc;
321         }
322         /* Patch location and size: */
323         *(uint64_t *)0x10408 = iaddr;
324         *(uint64_t *)0x10410 = rc;
325         rc += iaddr;
326     }
327 
328     if (entry->append) {
329         strncpy((char *)0x10480, entry->append, ARCH_COMMAND_LINE_SIZE);
330     }
331 
332     return rc;
333 }
334 
net_boot_menu(int num_ent,int def_ent,struct pl_cfg_entry * entries)335 static int net_boot_menu(int num_ent, int def_ent,
336                          struct pl_cfg_entry *entries)
337 {
338     bool valid_entries[MAX_BOOT_ENTRIES] = { false };
339     int idx;
340 
341     puts("\ns390-ccw pxelinux.cfg boot menu:\n");
342     printf(" [0] default (%d)\n", def_ent + 1);
343     valid_entries[0] = true;
344 
345     for (idx = 1; idx <= num_ent; idx++) {
346         printf(" [%d] %s\n", idx, entries[idx - 1].label);
347         valid_entries[idx] = true;
348     }
349     putchar('\n');
350 
351     idx = menu_get_boot_index(valid_entries);
352     putchar('\n');
353 
354     return idx;
355 }
356 
net_select_and_load_kernel(filename_ip_t * fn_ip,int num_ent,int selected,struct pl_cfg_entry * entries)357 static int net_select_and_load_kernel(filename_ip_t *fn_ip,
358                                       int num_ent, int selected,
359                                       struct pl_cfg_entry *entries)
360 {
361     unsigned int loadparm = get_loadparm_index();
362 
363     if (num_ent <= 0) {
364         return -1;
365     }
366 
367     if (menu_is_enabled_enum() && num_ent > 1) {
368         loadparm = net_boot_menu(num_ent, selected, entries);
369     }
370 
371     IPL_assert(loadparm <= num_ent,
372                "loadparm is set to an entry that is not available in the "
373                "pxelinux.cfg file!");
374 
375     if (loadparm > 0) {
376         selected = loadparm - 1;
377     }
378 
379     return load_kernel_with_initrd(fn_ip, &entries[selected]);
380 }
381 
net_try_pxelinux_cfg(filename_ip_t * fn_ip)382 static int net_try_pxelinux_cfg(filename_ip_t *fn_ip)
383 {
384     struct pl_cfg_entry entries[MAX_BOOT_ENTRIES];
385     int num_ent, def_ent = 0;
386 
387     num_ent = pxelinux_load_parse_cfg(fn_ip, mac, get_uuid(),
388                                       DEFAULT_TFTP_RETRIES,
389                                       cfgbuf, sizeof(cfgbuf),
390                                       entries, MAX_BOOT_ENTRIES, &def_ent);
391 
392     return net_select_and_load_kernel(fn_ip, num_ent, def_ent, entries);
393 }
394 
395 /**
396  * Load via information from a .INS file (which can be found on CD-ROMs
397  * for example)
398  */
handle_ins_cfg(filename_ip_t * fn_ip,char * cfg,int cfgsize)399 static int handle_ins_cfg(filename_ip_t *fn_ip, char *cfg, int cfgsize)
400 {
401     char *ptr;
402     int rc = -1, llen;
403     void *destaddr;
404     char *insbuf = cfg;
405 
406     ptr = strchr(insbuf, '\n');
407     if (!ptr) {
408         puts("Does not seem to be a valid .INS file");
409         return -1;
410     }
411 
412     *ptr = 0;
413     printf("\nParsing .INS file:\n %s\n", &insbuf[2]);
414 
415     insbuf = ptr + 1;
416     while (*insbuf && insbuf < cfg + cfgsize) {
417         ptr = strchr(insbuf, '\n');
418         if (ptr) {
419             *ptr = 0;
420         }
421         llen = strlen(insbuf);
422         if (!llen) {
423             insbuf = ptr + 1;
424             continue;
425         }
426         ptr = strchr(insbuf, ' ');
427         if (!ptr) {
428             puts("Missing space separator in .INS file");
429             return -1;
430         }
431         *ptr = 0;
432         strncpy(fn_ip->filename, insbuf, sizeof(fn_ip->filename));
433         destaddr = (char *)atol(ptr + 1);
434         rc = tftp_load(fn_ip, destaddr, (long)_start - (long)destaddr);
435         if (rc <= 0) {
436             break;
437         }
438         insbuf += llen + 1;
439     }
440 
441     return rc;
442 }
443 
net_try_direct_tftp_load(filename_ip_t * fn_ip)444 static int net_try_direct_tftp_load(filename_ip_t *fn_ip)
445 {
446     int rc;
447     void *loadaddr = (void *)0x2000;  /* Load right after the low-core */
448 
449     rc = tftp_load(fn_ip, loadaddr, KERNEL_MAX_SIZE - (long)loadaddr);
450     if (rc < 0) {
451         return rc;
452     } else if (rc < 8) {
453         printf("'%s' is too small (%i bytes only).\n", fn_ip->filename, rc);
454         return -1;
455     }
456 
457     /* Check whether it is a configuration file instead of a kernel */
458     if (rc < sizeof(cfgbuf) - 1) {
459         memcpy(cfgbuf, loadaddr, rc);
460         cfgbuf[rc] = 0;    /* Make sure that it is NUL-terminated */
461         if (!strncmp("* ", cfgbuf, 2)) {
462             return handle_ins_cfg(fn_ip, cfgbuf, rc);
463         }
464         /*
465          * pxelinux.cfg support via bootfile name is just here for developers'
466          * convenience (it eases testing with the built-in DHCP server of QEMU
467          * that does not support RFC 5071). The official way to configure a
468          * pxelinux.cfg file name is to use DHCP options 209 and 210 instead.
469          * So only use the pxelinux.cfg parser here for files that start with
470          * a magic comment string.
471          */
472         if (!strncasecmp("# pxelinux", cfgbuf, 10)) {
473             struct pl_cfg_entry entries[MAX_BOOT_ENTRIES];
474             int num_ent, def_ent = 0;
475 
476             num_ent = pxelinux_parse_cfg(cfgbuf, sizeof(cfgbuf), entries,
477                                          MAX_BOOT_ENTRIES, &def_ent);
478             return net_select_and_load_kernel(fn_ip, num_ent, def_ent,
479                                               entries);
480         }
481     }
482 
483     /* Move kernel to right location */
484     memmove(KERNEL_ADDR, loadaddr, rc);
485 
486     return rc;
487 }
488 
find_net_dev(Schib * schib,int dev_no)489 static bool find_net_dev(Schib *schib, int dev_no)
490 {
491     int i, r;
492 
493     for (i = 0; i < 0x10000; i++) {
494         net_schid.sch_no = i;
495         r = stsch_err(net_schid, schib);
496         if (r == 3 || r == -EIO) {
497             break;
498         }
499         if (!schib->pmcw.dnv) {
500             continue;
501         }
502         enable_subchannel(net_schid);
503         if (!virtio_is_supported(net_schid)) {
504             continue;
505         }
506         if (virtio_get_device_type() != VIRTIO_ID_NET) {
507             continue;
508         }
509         if (dev_no < 0 || schib->pmcw.dev == dev_no) {
510             return true;
511         }
512     }
513 
514     return false;
515 }
516 
virtio_setup(void)517 static bool virtio_setup(void)
518 {
519     Schib schib;
520     int ssid;
521     bool found = false;
522     uint16_t dev_no;
523 
524     /*
525      * We unconditionally enable mss support. In every sane configuration,
526      * this will succeed; and even if it doesn't, stsch_err() can deal
527      * with the consequences.
528      */
529     enable_mss_facility();
530 
531     if (have_iplb || store_iplb(&iplb)) {
532         IPL_assert(iplb.pbt == S390_IPL_TYPE_CCW, "IPL_TYPE_CCW expected");
533         dev_no = iplb.ccw.devno;
534         debug_print_int("device no. ", dev_no);
535         net_schid.ssid = iplb.ccw.ssid & 0x3;
536         debug_print_int("ssid ", net_schid.ssid);
537         found = find_net_dev(&schib, dev_no);
538     } else {
539         for (ssid = 0; ssid < 0x3; ssid++) {
540             net_schid.ssid = ssid;
541             found = find_net_dev(&schib, -1);
542             if (found) {
543                 break;
544             }
545         }
546     }
547 
548     return found;
549 }
550 
netmain(void)551 int netmain(void)
552 {
553     filename_ip_t fn_ip;
554     int rc, fnlen;
555 
556     sclp_setup();
557     puts("Network boot starting...");
558 
559     if (!virtio_setup()) {
560         puts("No virtio net device found.");
561         return -1;
562     }
563 
564     rc = net_init(&fn_ip);
565     if (rc) {
566         puts("Network initialization failed.");
567         return -1;
568     }
569 
570     fnlen = strlen(fn_ip.filename);
571     if (fnlen > 0 && fn_ip.filename[fnlen - 1] != '/') {
572         rc = net_try_direct_tftp_load(&fn_ip);
573     }
574     if (rc <= 0) {
575         rc = net_try_pxelinux_cfg(&fn_ip);
576     }
577 
578     net_release(&fn_ip);
579 
580     if (rc > 0) {
581         puts("Network loading done, starting kernel...");
582         jump_to_low_kernel();
583     }
584 
585     puts("Failed to load OS from network.");
586     return -1;
587 }
588