xref: /openbmc/qemu/pc-bios/s390-ccw/netmain.c (revision d481cec7)
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 
58 void set_timer(int val)
59 {
60     dest_timer = get_time_ms() + val;
61 }
62 
63 int get_timer(void)
64 {
65     return dest_timer - get_time_ms();
66 }
67 
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  */
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  */
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 
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 
156 static int net_init(filename_ip_t *fn_ip)
157 {
158     int rc;
159 
160     memset(fn_ip, 0, sizeof(filename_ip_t));
161 
162     rc = virtio_net_init(mac);
163     if (rc < 0) {
164         puts("Could not initialize network device");
165         return -101;
166     }
167     fn_ip->fd = rc;
168 
169     printf("  Using MAC address: %02x:%02x:%02x:%02x:%02x:%02x\n",
170            mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
171 
172     set_mac_address(mac);    /* init ethernet layer */
173     seed_rng(mac);
174 
175     rc = dhcp(fn_ip, DEFAULT_BOOT_RETRIES);
176     if (rc >= 0) {
177         if (fn_ip->ip_version == 4) {
178             set_ipv4_address(fn_ip->own_ip);
179         }
180     } else {
181         puts("Could not get IP address");
182         return -101;
183     }
184 
185     if (fn_ip->ip_version == 4) {
186         printf("  Using IPv4 address: %d.%d.%d.%d\n",
187               (fn_ip->own_ip >> 24) & 0xFF, (fn_ip->own_ip >> 16) & 0xFF,
188               (fn_ip->own_ip >>  8) & 0xFF, fn_ip->own_ip & 0xFF);
189     } else if (fn_ip->ip_version == 6) {
190         char ip6_str[40];
191         ipv6_to_str(fn_ip->own_ip6.addr, ip6_str);
192         printf("  Using IPv6 address: %s\n", ip6_str);
193     }
194 
195     if (rc == -2) {
196         printf("ARP request to TFTP server (%d.%d.%d.%d) failed\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         return -102;
200     }
201     if (rc == -4 || rc == -3) {
202         puts("Can't obtain TFTP server IP address");
203         return -107;
204     }
205 
206     printf("  Using TFTP server: ");
207     if (fn_ip->ip_version == 4) {
208         printf("%d.%d.%d.%d\n",
209                (fn_ip->server_ip >> 24) & 0xFF, (fn_ip->server_ip >> 16) & 0xFF,
210                (fn_ip->server_ip >>  8) & 0xFF, fn_ip->server_ip & 0xFF);
211     } else if (fn_ip->ip_version == 6) {
212         char ip6_str[40];
213         ipv6_to_str(fn_ip->server_ip6.addr, ip6_str);
214         printf("%s\n", ip6_str);
215     }
216 
217     if (strlen(fn_ip->filename) > 0) {
218         printf("  Bootfile name: '%s'\n", fn_ip->filename);
219     }
220 
221     return rc;
222 }
223 
224 static void net_release(filename_ip_t *fn_ip)
225 {
226     if (fn_ip->ip_version == 4) {
227         dhcp_send_release(fn_ip->fd);
228     }
229 }
230 
231 /**
232  * Retrieve the Universally Unique Identifier of the VM.
233  * @return UUID string, or NULL in case of errors
234  */
235 static const char *get_uuid(void)
236 {
237     register int r0 asm("0");
238     register int r1 asm("1");
239     uint8_t *mem, *buf, uuid[16];
240     int i, cc, chk = 0;
241     static char uuid_str[37];
242 
243     mem = malloc(2 * PAGE_SIZE);
244     if (!mem) {
245         puts("Out of memory ... can not get UUID.");
246         return NULL;
247     }
248     buf = (uint8_t *)(((uint64_t)mem + PAGE_SIZE - 1) & ~(PAGE_SIZE - 1));
249     memset(buf, 0, PAGE_SIZE);
250 
251     /* Get SYSIB 3.2.2 */
252     r0 = (3 << 28) | 2;
253     r1 = 2;
254     asm volatile(" stsi 0(%[addr])\n"
255                  " ipm  %[cc]\n"
256                  " srl  %[cc],28\n"
257                  : [cc] "=d" (cc)
258                  : "d" (r0), "d" (r1), [addr] "a" (buf)
259                  : "cc", "memory");
260     if (cc) {
261         free(mem);
262         return NULL;
263     }
264 
265     for (i = 0; i < 16; i++) {
266         uuid[i] = buf[STSI322_VMDB_UUID_OFFSET + i];
267         chk |= uuid[i];
268     }
269     free(mem);
270     if (!chk) {
271         return NULL;
272     }
273 
274     sprintf(uuid_str, "%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-"
275             "%02x%02x%02x%02x%02x%02x", uuid[0], uuid[1], uuid[2], uuid[3],
276             uuid[4], uuid[5], uuid[6], uuid[7], uuid[8], uuid[9], uuid[10],
277             uuid[11], uuid[12], uuid[13], uuid[14], uuid[15]);
278 
279     return uuid_str;
280 }
281 
282 /**
283  * Load a kernel with initrd (i.e. with the information that we've got from
284  * a pxelinux.cfg config file)
285  */
286 static int load_kernel_with_initrd(filename_ip_t *fn_ip,
287                                    struct pl_cfg_entry *entry)
288 {
289     int rc;
290 
291     printf("Loading pxelinux.cfg entry '%s'\n", entry->label);
292 
293     if (!entry->kernel) {
294         puts("Kernel entry is missing!\n");
295         return -1;
296     }
297 
298     strncpy(fn_ip->filename, entry->kernel, sizeof(fn_ip->filename));
299     rc = tftp_load(fn_ip, KERNEL_ADDR, KERNEL_MAX_SIZE);
300     if (rc < 0) {
301         return rc;
302     }
303 
304     if (entry->initrd) {
305         uint64_t iaddr = (rc + 0xfff) & ~0xfffUL;
306 
307         strncpy(fn_ip->filename, entry->initrd, sizeof(fn_ip->filename));
308         rc = tftp_load(fn_ip, (void *)iaddr, KERNEL_MAX_SIZE - iaddr);
309         if (rc < 0) {
310             return rc;
311         }
312         /* Patch location and size: */
313         *(uint64_t *)0x10408 = iaddr;
314         *(uint64_t *)0x10410 = rc;
315         rc += iaddr;
316     }
317 
318     if (entry->append) {
319         strncpy((char *)0x10480, entry->append, ARCH_COMMAND_LINE_SIZE);
320     }
321 
322     return rc;
323 }
324 
325 #define MAX_PXELINUX_ENTRIES 16
326 
327 static int net_try_pxelinux_cfg(filename_ip_t *fn_ip)
328 {
329     struct pl_cfg_entry entries[MAX_PXELINUX_ENTRIES];
330     int num_ent, def_ent = 0;
331 
332     num_ent = pxelinux_load_parse_cfg(fn_ip, mac, get_uuid(),
333                                       DEFAULT_TFTP_RETRIES,
334                                       cfgbuf, sizeof(cfgbuf),
335                                       entries, MAX_PXELINUX_ENTRIES, &def_ent);
336     if (num_ent > 0) {
337         return load_kernel_with_initrd(fn_ip, &entries[def_ent]);
338     }
339 
340     return -1;
341 }
342 
343 /**
344  * Load via information from a .INS file (which can be found on CD-ROMs
345  * for example)
346  */
347 static int handle_ins_cfg(filename_ip_t *fn_ip, char *cfg, int cfgsize)
348 {
349     char *ptr;
350     int rc = -1, llen;
351     void *destaddr;
352     char *insbuf = cfg;
353 
354     ptr = strchr(insbuf, '\n');
355     if (!ptr) {
356         puts("Does not seem to be a valid .INS file");
357         return -1;
358     }
359 
360     *ptr = 0;
361     printf("\nParsing .INS file:\n %s\n", &insbuf[2]);
362 
363     insbuf = ptr + 1;
364     while (*insbuf && insbuf < cfg + cfgsize) {
365         ptr = strchr(insbuf, '\n');
366         if (ptr) {
367             *ptr = 0;
368         }
369         llen = strlen(insbuf);
370         if (!llen) {
371             insbuf = ptr + 1;
372             continue;
373         }
374         ptr = strchr(insbuf, ' ');
375         if (!ptr) {
376             puts("Missing space separator in .INS file");
377             return -1;
378         }
379         *ptr = 0;
380         strncpy(fn_ip->filename, insbuf, sizeof(fn_ip->filename));
381         destaddr = (char *)atol(ptr + 1);
382         rc = tftp_load(fn_ip, destaddr, (long)_start - (long)destaddr);
383         if (rc <= 0) {
384             break;
385         }
386         insbuf += llen + 1;
387     }
388 
389     return rc;
390 }
391 
392 static int net_try_direct_tftp_load(filename_ip_t *fn_ip)
393 {
394     int rc;
395     void *loadaddr = (void *)0x2000;  /* Load right after the low-core */
396 
397     rc = tftp_load(fn_ip, loadaddr, KERNEL_MAX_SIZE - (long)loadaddr);
398     if (rc < 0) {
399         return rc;
400     } else if (rc < 8) {
401         printf("'%s' is too small (%i bytes only).\n", fn_ip->filename, rc);
402         return -1;
403     }
404 
405     /* Check whether it is a configuration file instead of a kernel */
406     if (rc < sizeof(cfgbuf) - 1) {
407         memcpy(cfgbuf, loadaddr, rc);
408         cfgbuf[rc] = 0;    /* Make sure that it is NUL-terminated */
409         if (!strncmp("* ", cfgbuf, 2)) {
410             return handle_ins_cfg(fn_ip, cfgbuf, rc);
411         }
412         /*
413          * pxelinux.cfg support via bootfile name is just here for developers'
414          * convenience (it eases testing with the built-in DHCP server of QEMU
415          * that does not support RFC 5071). The official way to configure a
416          * pxelinux.cfg file name is to use DHCP options 209 and 210 instead.
417          * So only use the pxelinux.cfg parser here for files that start with
418          * a magic comment string.
419          */
420         if (!strncasecmp("# pxelinux", cfgbuf, 10)) {
421             struct pl_cfg_entry entries[MAX_PXELINUX_ENTRIES];
422             int num_ent, def_ent = 0;
423 
424             num_ent = pxelinux_parse_cfg(cfgbuf, sizeof(cfgbuf), entries,
425                                          MAX_PXELINUX_ENTRIES, &def_ent);
426             if (num_ent <= 0) {
427                 return -1;
428             }
429             return load_kernel_with_initrd(fn_ip, &entries[def_ent]);
430         }
431     }
432 
433     /* Move kernel to right location */
434     memmove(KERNEL_ADDR, loadaddr, rc);
435 
436     return rc;
437 }
438 
439 static bool find_net_dev(Schib *schib, int dev_no)
440 {
441     int i, r;
442 
443     for (i = 0; i < 0x10000; i++) {
444         net_schid.sch_no = i;
445         r = stsch_err(net_schid, schib);
446         if (r == 3 || r == -EIO) {
447             break;
448         }
449         if (!schib->pmcw.dnv) {
450             continue;
451         }
452         enable_subchannel(net_schid);
453         if (!virtio_is_supported(net_schid)) {
454             continue;
455         }
456         if (virtio_get_device_type() != VIRTIO_ID_NET) {
457             continue;
458         }
459         if (dev_no < 0 || schib->pmcw.dev == dev_no) {
460             return true;
461         }
462     }
463 
464     return false;
465 }
466 
467 static bool virtio_setup(void)
468 {
469     Schib schib;
470     int ssid;
471     bool found = false;
472     uint16_t dev_no;
473 
474     /*
475      * We unconditionally enable mss support. In every sane configuration,
476      * this will succeed; and even if it doesn't, stsch_err() can deal
477      * with the consequences.
478      */
479     enable_mss_facility();
480 
481     if (have_iplb || store_iplb(&iplb)) {
482         IPL_assert(iplb.pbt == S390_IPL_TYPE_CCW, "IPL_TYPE_CCW expected");
483         dev_no = iplb.ccw.devno;
484         debug_print_int("device no. ", dev_no);
485         net_schid.ssid = iplb.ccw.ssid & 0x3;
486         debug_print_int("ssid ", net_schid.ssid);
487         found = find_net_dev(&schib, dev_no);
488     } else {
489         for (ssid = 0; ssid < 0x3; ssid++) {
490             net_schid.ssid = ssid;
491             found = find_net_dev(&schib, -1);
492             if (found) {
493                 break;
494             }
495         }
496     }
497 
498     return found;
499 }
500 
501 int netmain(void)
502 {
503     filename_ip_t fn_ip;
504     int rc, fnlen;
505 
506     sclp_setup();
507     puts("Network boot starting...");
508 
509     if (!virtio_setup()) {
510         puts("No virtio net device found.");
511         return -1;
512     }
513 
514     rc = net_init(&fn_ip);
515     if (rc) {
516         puts("Network initialization failed.");
517         return -1;
518     }
519 
520     fnlen = strlen(fn_ip.filename);
521     if (fnlen > 0 && fn_ip.filename[fnlen - 1] != '/') {
522         rc = net_try_direct_tftp_load(&fn_ip);
523     }
524     if (rc <= 0) {
525         rc = net_try_pxelinux_cfg(&fn_ip);
526     }
527 
528     net_release(&fn_ip);
529 
530     if (rc > 0) {
531         puts("Network loading done, starting kernel...");
532         jump_to_low_kernel();
533     }
534 
535     puts("Failed to load OS from network.");
536     return -1;
537 }
538