Imported Upstream version 3.8
[debian/elilo] / util.c
1 /*
2  *  Copyright (C) 2001-2003 Hewlett-Packard Co.
3  *      Contributed by Stephane Eranian <eranian@hpl.hp.com>
4  *
5  *  Copyright (C) 2001 Silicon Graphics, Inc.
6  *      Contributed by Brent Casavant <bcasavan@sgi.com>
7  *
8  *  Copyright (C) 2006-2009 Intel Corporation
9  *      Contributed by Fenghua Yu <fenghua.yu@intel.com>
10  *      Contributed by Bibo Mao <bibo.mao@intel.com>
11  *      Contributed by Chandramouli Narayanan <mouli@linux.intel.com>
12  *
13  * This file is part of the ELILO, the EFI Linux boot loader.
14  *
15  *  ELILO is free software; you can redistribute it and/or modify
16  *  it under the terms of the GNU General Public License as published by
17  *  the Free Software Foundation; either version 2, or (at your option)
18  *  any later version.
19  *
20  *  ELILO is distributed in the hope that it will be useful,
21  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
22  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
23  *  GNU General Public License for more details.
24  *
25  *  You should have received a copy of the GNU General Public License
26  *  along with ELILO; see the file COPYING.  If not, write to the Free
27  *  Software Foundation, 59 Temple Place - Suite 330, Boston, MA
28  *  02111-1307, USA.
29  *
30  * Please check out the elilo.txt for complete documentation on how
31  * to use this program.
32  */
33
34 #include <efi.h>
35 #include <efilib.h>
36
37 #include "elilo.h"
38
39 #define TENTH_SEC               1000000         /* 1/10th second in 100ns unit */
40 #define READ_BLOCK_SIZE         (4*EFI_PAGE_SIZE) /* block size for read_file */
41
42 #define is_cr(k)                (((k)==CHAR_LINEFEED)||((k)==CHAR_CARRIAGE_RETURN))
43 #define CHAR_SPACE              L' '
44
45 static INTN
46 read_keypress(EFI_INPUT_KEY *key)
47 {
48         return uefi_call_wrapper(systab->ConIn->ReadKeyStroke,
49                                 2,
50                                 systab->ConIn,
51                                 key);
52 }
53
54
55 EFI_STATUS
56 check_abort(VOID)
57 {
58         EFI_INPUT_KEY key;
59
60         return read_keypress(&key);
61 }
62
63 inline VOID
64 reset_input(VOID)
65 {
66         uefi_call_wrapper(systab->ConIn->Reset,
67                         2,
68                         systab->ConIn,
69                         1);
70 }
71
72 #if 0
73 INTN
74 wait_keypress_abort(VOID)
75 {
76         SIMPLE_INPUT_INTERFACE *conin = systab->ConIn;
77         EFI_INPUT_KEY key;
78         EFI_STATUS status;
79
80         reset_input();
81
82         Print(L"Hit ENTER to continue or ANY other key to cancel");
83
84         /* cleanup buffer first */
85         while (uefi_call_wrapper(conin->ReadKeyStroke, 2, conin, &key) == EFI_SUCCESS);
86
87         while ((status=uefi_call_wrapper(conin->ReadKeyStroke,2, conin, &key)) == EFI_NOT_READY );
88
89         if (EFI_ERROR(status)) return ELILO_LOAD_ERROR;
90
91         Print(L"\n");
92
93         return is_cr(key.UnicodeChar) ? ELILO_LOAD_SUCCESS: ELILO_BOOT_ABORTED;
94 }
95 #endif
96
97 /*
98  * wait for timeout to expire or keypress
99  * Return:
100  *      0 : timeout expired
101  *      1 : a key was pressed (still input stream to process)
102  *      -1: an error occured
103  */
104 INTN
105 wait_timeout(UINTN timeout)
106 {
107         EFI_STATUS status;
108         EFI_EVENT timer;
109         EFI_EVENT list[2];
110         UINTN idx;
111
112
113         if (timeout == 0) return 0;
114
115         /* Create a timeout timer */
116         status = uefi_call_wrapper(BS->CreateEvent, 5, EVT_TIMER, 0, NULL, NULL, &timer);
117         if (EFI_ERROR(status)) {
118                 ERR_PRT((L" waitkey CreateEvent failed %r", status));
119                 return -1;
120         }
121         /* In 100ns increments */
122         status = uefi_call_wrapper(BS->SetTimer, 3, timer, TimerPeriodic, TENTH_SEC);
123         if (EFI_ERROR(status)) {
124                 ERR_PRT((L"waitkey SetTimer failed %r", status));
125                 return -1;
126         }
127
128         list[0] = timer;
129         list[1] = systab->ConIn->WaitForKey;
130
131         do {
132                 status = uefi_call_wrapper(BS->WaitForEvent, 3, 2, list, &idx);
133                 if (EFI_ERROR(status)) {
134                         ERR_PRT((L"waitkey WaitForEvent failed %r", status));
135                         return -1;
136                 }
137
138         } while (timeout-- && idx == 0);        
139
140         /*
141          * SetTimer(timer, TimerCancel, 0) is causing problems on IA-32 and gcc3
142          * I do not know why it dies with EFI12.35. So let's fake a key stroke.
143          */
144         status = uefi_call_wrapper(BS->SetTimer, 3, timer, TimerCancel, 0);
145         if (EFI_ERROR(status)) {
146                 ERR_PRT((L"waitkey SetTimer(TimerCancel) failed %r", status));
147                 return -1;
148         }
149
150         uefi_call_wrapper(BS->CloseEvent, 1, timer);
151
152         return idx ? 1 : 0;
153 }
154
155 INTN
156 argify(CHAR16 *buf, UINTN len, CHAR16 **argv)   
157 {
158
159         UINTN     i=0, j=0;
160         CHAR16   *p = buf;
161         
162         if (buf == 0) { 
163                 argv[0] = NULL;
164                 return 0;
165         }
166         /* len represents the number of bytes, not the number of 16 bytes chars */
167         len = len >> 1;
168
169         /*
170          * Here we use CHAR_NULL as the terminator rather than the length
171          * because it seems like the EFI shell return rather bogus values for it.
172          * Apparently, we are guaranteed to find the '\0' character in the buffer
173          * where the real input arguments stop, so we use it instead.
174          */
175         for(;;) {
176                 while (buf[i] == CHAR_SPACE && buf[i] != CHAR_NULL && i < len) i++;
177
178                 if (buf[i] == CHAR_NULL || i == len) goto end;
179
180                 p = buf+i;
181                 i++;
182
183                 while (buf[i] != CHAR_SPACE && buf[i] != CHAR_NULL && i < len) i++;
184
185                 argv[j++] = p;
186
187                 if (buf[i] == CHAR_NULL) goto end;
188
189                 buf[i]  = CHAR_NULL;
190
191                 if (i == len)  goto end;
192
193                 i++;
194
195                 if (j == MAX_ARGS-1) {
196                         ERR_PRT((L"too many arguments (%d) truncating", j));
197                         goto end;
198                 }
199         }
200 end:
201 #if 0
202         if (i != len) {
203                 ERR_PRT((L"ignoring trailing %d characters on command line", len-i));
204         }
205 #endif
206         argv[j] = NULL;
207         return j;
208 }
209
210 VOID
211 unargify(CHAR16 **argv, CHAR16 **args)
212 {
213         if ( *argv == 0 ) {
214                 *args = L"";
215                 return;
216         }
217         *args = *argv;
218         while ( argv[1] ) {
219                 (*argv)[StrLen(*argv)] = CHAR_SPACE;
220                 argv++;
221         }
222 }
223
224 VOID
225 split_args(CHAR16 *buffer, CHAR16 *kname, CHAR16 *args)
226 {
227         CHAR16 *tmp;
228
229         /* find beginning of kernel name */
230         while (*buffer && *buffer == CHAR_SPACE) buffer++;
231
232         tmp = buffer;
233         
234         /* scan through kernel name */  
235         while (*buffer && *buffer != CHAR_SPACE) buffer++;
236
237         if (*buffer) {
238                 *buffer++ = CHAR_NULL;
239                 StrCpy(kname, tmp);
240         }
241
242         /* skip space between kernel and args */        
243         while (*buffer && *buffer == CHAR_SPACE) buffer++;
244
245         StrCpy(args, buffer);
246 }
247
248 INTN
249 read_file(UINTN fd, UINTN total_size, CHAR8 *buffer)
250 {
251         INTN size, j=0;
252         EFI_STATUS status;
253         CHAR16 helicopter[4] = { L'|' , L'/' , L'-' , L'\\' };
254         INTN ret = ELILO_LOAD_SUCCESS;
255         UINTN sum = 0;
256         /*
257          * We load by chunks rather than a single big read because
258          * early versions of EFI had troubles loading files
259          * from floppies in a single big request.  Breaking
260          * the read down into chunks of 4KB fixed that
261          * problem. While this problem has been fixed, we still prefer
262          * this method because it tells us whether or not we're making
263          * forward progress.
264          */
265
266         while (total_size > 0) {
267                 size = total_size < READ_BLOCK_SIZE? total_size : READ_BLOCK_SIZE;
268
269                 status = fops_read(fd, buffer, &size);
270                 if (EFI_ERROR(status)) {
271                         ERR_PRT((L"read_file failed %r", status));
272                         return ELILO_LOAD_ERROR;
273                 }
274                 sum += size;
275
276                 Print(L"%c\b",helicopter[j++%4]);
277
278                 buffer     += size;
279                 total_size -= size; 
280
281                 if (check_abort() == EFI_SUCCESS) {
282                         ret = ELILO_LOAD_ABORTED;
283                         break;
284                 }
285         }
286         return ret;
287 }
288
289 INTN
290 get_memmap(mmap_desc_t *desc)
291 {
292 #define ELILO_MEMMAP_SIZE_DEFAULT       (EFI_PAGE_SIZE*2)
293 #define ELILO_MEMMAP_INC                (sizeof(EFI_MEMORY_DESCRIPTOR)<<1)
294
295         EFI_STATUS status;
296
297         desc->map_size = ELILO_MEMMAP_SIZE_DEFAULT;
298
299         for(;;) {
300                 desc->md = (EFI_MEMORY_DESCRIPTOR *)alloc(desc->map_size, EfiLoaderData);
301
302                 if (desc->md == NULL) {
303                         ERR_PRT((L"failed to allocate memory map buffer"));
304                         return -1;
305                 }
306                 status = uefi_call_wrapper(BS->GetMemoryMap, 5, &desc->map_size, desc->md, 
307                                         &desc->cookie, &desc->desc_size, &desc->desc_version);
308                 if (status == EFI_SUCCESS) break;
309
310                 free(desc->md);
311
312                 if (status != EFI_BUFFER_TOO_SMALL) {
313                         ERR_PRT((L"failed to obtain memory map %r"));
314                         return -1;
315                 }
316                 desc->map_size += ELILO_MEMMAP_INC;
317         }
318         DBG_PRT((L"final get_memmap map_size=%ld", desc->map_size));
319
320         return 0;
321 }
322
323 #if 0
324 INTN
325 get_memmap(mmap_desc_t *desc)
326 {
327         EFI_STATUS status;
328
329         /* will get the right size in return */
330         desc->map_size = 0;
331
332         status = BS->GetMemoryMap(&desc->map_size, desc->md, &desc->cookie, &desc->desc_size, &desc->desc_version);
333         if (status != EFI_BUFFER_TOO_SMALL) return -1;
334
335         desc->md = (EFI_MEMORY_DESCRIPTOR *)alloc(desc->map_size, EfiLoaderData);
336         if (desc->md == NULL) {
337                 ERR_PRT((L"failed to allocate memory map buffer"));
338                 return -1;
339         }
340
341
342         status = BS->GetMemoryMap(&desc->map_size, desc->md, &desc->cookie, &desc->desc_size, &desc->desc_version);
343         if (EFI_ERROR(status)) {
344                 ERR_PRT((L"failed to obtain memory map %d: %r", desc->map_size, status));
345                 free(desc->md);
346                 return -1;
347         }
348         DBG_PRT((L"final get_memmap map_size=%d", desc->map_size));
349
350         return 0;
351 }
352 #endif
353
354
355 VOID
356 free_memmap(mmap_desc_t *desc)
357 {
358         if (desc->md) {
359                 free(desc->md);
360                 desc->md = NULL;
361         }
362 }
363
364 VOID
365 print_memmap(mmap_desc_t *desc)
366 {
367         EFI_MEMORY_DESCRIPTOR *md;
368         UINTN desc_size;
369         VOID *p;
370         VOID *md_end;
371         INT8 printed;
372         UINTN ntypes;
373         CHAR16* str;
374
375         static CHAR16 *memtypes[]={
376                 L"ReservedMemoryType",
377                 L"LoaderCode",
378                 L"LoaderData",
379                 L"BootServicesCode",
380                 L"BootServicesData",
381                 L"RuntimeServicesCode",
382                 L"RuntimeServicesData",
383                 L"ConventionalMemory",
384                 L"UnusableMemory",
385                 L"ACPIReclaimMemory",
386                 L"ACPIMemoryNVS",
387                 L"MemoryMappedIO",
388                 L"MemoryMappedIOPortSpace",
389                 L"PalCode"
390         };
391
392
393         md_end = ((VOID *)desc->md)+desc->map_size;
394         desc_size = desc->desc_size;
395
396         ntypes = sizeof(memtypes)/sizeof(CHAR16 *);
397
398         for(p = desc->md; p < md_end; p += desc_size) {
399                 md = p;
400
401                 str = md->Type < ntypes ? memtypes[md->Type] : L"Unknown";
402
403                 Print(L"%24s %lx-%lx %8lx", str, md->PhysicalStart,
404                                 md->PhysicalStart+(md->NumberOfPages<<EFI_PAGE_SHIFT),
405                                 md->NumberOfPages);
406
407                 printed=0;
408 #define P_FLG(f)        { \
409         Print(L" %s %s", printed ? L"|":L"", f); \
410         printed=1; \
411 }
412
413                 if (md->Attribute & EFI_MEMORY_UC) {
414                         P_FLG(L"UC");
415                 }
416                 if (md->Attribute & EFI_MEMORY_WC) {
417                         P_FLG(L"WC");
418                 }
419                 if (md->Attribute & EFI_MEMORY_WT) {
420                         P_FLG(L"WT");
421                 }
422                 if (md->Attribute & EFI_MEMORY_WB) {
423                         P_FLG(L"WB");
424                 }
425                 if (md->Attribute & EFI_MEMORY_UCE) {
426                         P_FLG(L"UCE");
427                 }
428                 if (md->Attribute & EFI_MEMORY_WP) {
429                         P_FLG(L"WP");
430                 }
431                 if (md->Attribute & EFI_MEMORY_RP) {
432                         P_FLG(L"RP");
433                 }
434                 if (md->Attribute & EFI_MEMORY_XP) {
435                         P_FLG(L"XP");
436                 }
437                 if (md->Attribute & EFI_MEMORY_RUNTIME) {
438                         P_FLG(L"RT");
439                 }
440                 Print(L"\n");
441         }
442 }
443
444 INTN
445 find_kernel_memory(VOID* low_addr, VOID* max_addr, UINTN alignment, VOID** start)
446 {       
447 #define HIGHEST_ADDR (VOID*)(~0)
448         mmap_desc_t mdesc;
449         EFI_MEMORY_DESCRIPTOR *md;
450         UINT64 size;
451         VOID *p, *addr;
452         VOID *desc_end, *md_end, *best_addr = HIGHEST_ADDR;
453
454         /*
455          * first get up-to-date memory map
456          *
457          * XXX: is there a danger of not seeing the latest version if interrupted
458          * during our scan ?
459          *
460          */
461         if (get_memmap(&mdesc) == -1) {
462                 ERR_PRT((L"find_kernel_memory :GetMemoryMap() failed"));
463                 return -1;
464         }
465
466         desc_end = ((VOID *)mdesc.md) + mdesc.map_size;
467         size     = max_addr - low_addr;
468         /*
469          * Find memory which covers the desired range
470          */
471         for(p = mdesc.md; p < desc_end; p += mdesc.desc_size) {
472                 md = p;
473
474                 /*
475                  * restrict to decent memory types. 
476                  *
477                  * the EFI memory map report where memory is and how it is currently used
478                  * using types.
479                  *
480                  * EfiLoaderData which is used by the AllocatePages() cannot be used
481                  * here because it may hold some valid information. Same thing for most
482                  * of the memory types with the exception of EfiConventional which 
483                  * can be assumed as being free to use. 
484                  */
485                 if (md->Type != EfiConventionalMemory) continue;
486
487                 /* 
488                  * compute aligned address and upper boundary for range
489                  */
490                 md_end = (VOID*)(md->PhysicalStart + md->NumberOfPages * EFI_PAGE_SIZE);        
491                 addr   = (VOID*)ROUNDUP(md->PhysicalStart, alignment);
492
493                 /*
494                  * need to check if:
495                  * - aligned address still in the range
496                  * - the range [addr-addr+size) still fits into memory range
497                  * if so we have a match. We do not assume that the memory ranges
498                  * are sorted by EFI, therefore we must record the match and only
499                  * keep the lowest possible one.
500                  */
501                 if (addr < best_addr && addr < md_end && addr+size <= md_end) best_addr = addr;
502         }
503         if (best_addr == HIGHEST_ADDR) {
504                 free_memmap(&mdesc);
505                 ERR_PRT((L"Could not find memory suitable for loading image"));
506                 return -1;
507         }
508
509         *start = best_addr;
510
511         free_memmap(&mdesc);
512
513         return 0;
514 }
515