summaryrefslogtreecommitdiffstats
path: root/README.hardware
blob: d48c9533e7442cbf9b369fa6389ca7d5bdb033d7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
                          Poky Hardware README
                          ====================

This file gives details about using Poky with different hardware reference
boards and consumer devices. A full list of target machines can be found by
looking in the meta/conf/machine/ directory. If in doubt about using Poky with
your hardware, consult the documentation for your board/device.

Support for additional devices is normally added by creating BSP layers - for
more information please see the Yocto Board Support Package (BSP) Developer's
Guide - documentation source is in documentation/bspguide or download the PDF
from:

   http://yoctoproject.org/community/documentation

Support for machines other than QEMU may be moved out to separate BSP layers in
future versions.


QEMU Emulation Targets
======================

To simplify development Poky supports building images to work with the QEMU
emulator in system emulation mode. Several architectures are currently
supported:

  * ARM (qemuarm)
  * x86 (qemux86)
  * x86-64 (qemux86-64)
  * PowerPC (qemuppc)
  * MIPS (qemumips)

Use of the QEMU images is covered in the Poky Reference Manual. The Poky
MACHINE setting corresponding to the target is given in brackets.


Hardware Reference Boards
=========================

The following boards are supported by Poky's core layer:

  * Texas Instruments Beagleboard (beagleboard)
  * Freescale MPC8315E-RDB (mpc8315e-rdb)
  * Ubiquiti Networks RouterStation Pro (routerstationpro)

For more information see the board's section below. The Poky MACHINE setting
corresponding to the board is given in brackets.


Consumer Devices
================

The following consumer devices are supported by Poky's core layer:

  * Intel Atom based PCs and devices (atom-pc)

For more information see the device's section below. The Poky MACHINE setting
corresponding to the device is given in brackets.



                      Specific Hardware Documentation
                      ===============================


Intel Atom based PCs and devices (atom-pc)
==========================================

The atom-pc MACHINE is tested on the following platforms:

  o Asus EeePC 901
  o Acer Aspire One
  o Toshiba NB305
  o Intel Embedded Development Board 1-N450 (Black Sand)

and is likely to work on many unlisted Atom based devices. The MACHINE type
supports ethernet, wifi, sound, and i915 graphics by default in addition to
common PC input devices, busses, and so on.

Depending on the device, it can boot from a traditional hard-disk, a USB device,
or over the network. Writing poky generated images to physical media is
straightforward with a caveat for USB devices. The following examples assume the
target boot device is /dev/sdb, be sure to verify this and use the correct
device as the following commands are run as root and are not reversable.

USB Device:
  1. Build a live image. This image type consists of a simple filesystem
     without a partition table, which is suitable for USB keys, and with the
     default setup for the atom-pc machine, this image type is built
     automatically for any image you build. For example:

     $ bitbake core-image-minimal

  2. Use the "dd" utility to write the image to the raw block device. For
     example:

     # dd if=core-image-minimal-atom-pc.hddimg of=/dev/sdb

  If the device fails to boot with "Boot error" displayed, or apparently
  stops just after the SYSLINUX version banner, it is likely the BIOS cannot
  understand the physical layout of the disk (or rather it expects a
  particular layout and cannot handle anything else). There are two possible
  solutions to this problem:

  1. Change the BIOS USB Device setting to HDD mode. The label will vary by
     device, but the idea is to force BIOS to read the Cylinder/Head/Sector
     geometry from the device.

  2. Without such an option, the BIOS generally boots the device in USB-ZIP
     mode. To write an image to a USB device that will be bootable in
     USB-ZIP mode, carry out the following actions:

     a. Determine the geometry of your USB device using fdisk:

     # fdisk /dev/sdb
     Command (m for help): p

     Disk /dev/sdb: 4011 MB, 4011491328 bytes
     124 heads, 62 sectors/track, 1019 cylinders, total 7834944 sectors
     ...

     Command (m for help): q

     b. Configure the USB device for USB-ZIP mode:
     
     # mkdiskimage -4 /dev/sdb 1019 124 62

     Where 1019, 124 and 62 are the cylinder, head and sectors/track counts
     as reported by fdisk (substitute the values reported for your device).
     When the operation has finished and the access LED (if any) on the
     device stops flashing, remove and reinsert the device to allow the
     kernel to detect the new partition layout.

     c. Copy the contents of the poky image to the USB-ZIP mode device:

     # mkdir /tmp/image
     # mkdir /tmp/usbkey
     # mount -o loop core-image-minimal-atom-pc.hddimg  /tmp/image
     # mount /dev/sdb4 /tmp/usbkey
     # cp -rf /tmp/image/* /tmp/usbkey

     d. Install the syslinux boot loader:

     # syslinux /dev/sdb4

     e. Unmount everything:

     # umount /tmp/image
     # umount /tmp/usbkey

  Install the boot device in the target board and configure the BIOS to boot
  from it.

  For more details on the USB-ZIP scenario, see the syslinux documentation:
  http://git.kernel.org/?p=boot/syslinux/syslinux.git;a=blob_plain;f=doc/usbkey.txt;hb=HEAD


Texas Instruments Beagleboard (beagleboard)
===========================================

The Beagleboard is an ARM Cortex-A8 development board with USB, DVI-D, S-Video,
2D/3D accelerated graphics, audio, serial, JTAG, and SD/MMC. The xM adds a
faster CPU, more RAM, an ethernet port, more USB ports, microSD, and removes
the NAND flash. The beagleboard MACHINE is tested on the following platforms:

  o Beagleboard C4
  o Beagleboard xM rev A & B

The Beagleboard C4 has NAND, while the xM does not. For the sake of simplicity,
these instructions assume you have erased the NAND on the C4 so its boot
behavior matches that of the xM. To do this, issue the following commands from
the u-boot prompt (note that the unlock may be unecessary depending on the
version of u-boot installed on your board and only one of the erase commands
will succeed):

    # nand unlock
    # nand erase
    # nand erase.chip

To further tailor these instructions for your board, please refer to the
documentation at http://www.beagleboard.org.

From a Linux system with access to the image files perform the following steps
as root, replacing mmcblk0* with the SD card device on your machine (such as sdc
if used via a usb card reader):

  1. Partition and format an SD card:
     # fdisk -lu /dev/mmcblk0
     
     Disk /dev/mmcblk0: 3951 MB, 3951034368 bytes
     255 heads, 63 sectors/track, 480 cylinders, total 7716864 sectors
     Units = sectors of 1 * 512 = 512 bytes
     
             Device Boot      Start         End      Blocks  Id System
     /dev/mmcblk0p1   *          63      144584       72261   c Win95 FAT32 (LBA)
     /dev/mmcblk0p2          144585      465884      160650  83 Linux

     # mkfs.vfat -F 16 -n "boot" /dev/mmcblk0p1
     # mke2fs -j -L "root" /dev/mmcblk0p2

  The following assumes the SD card partition 1 and 2 are mounted at
  /media/boot and /media/root respectively. Removing the card and reinserting
  it will do just that on most modern Linux desktop environments.
  
  The files referenced below are made available after the build in
  build/tmp/deploy/images.

  2. Install the boot loaders
     # cp MLO-beagleboard /media/boot/MLO
     # cp u-boot-beagleboard.bin /media/boot/u-boot.bin

  3. Install the root filesystem
     # tar x -C /media/root -f core-image-$IMAGE_TYPE-beagleboard.tar.bz2
     # tar x -C /media/root -f modules-$KERNEL_VERSION-beagleboard.tgz

  4. Install the kernel uImage
     # cp uImage-beagleboard.bin /media/boot/uImage

  5. Prepare a u-boot script to simplify the boot process
     The Beagleboard can be made to boot at this point from the u-boot command
     shell. To automate this process, generate a user.scr script as follows.

     Install uboot-mkimage (from uboot-mkimage on Ubuntu or uboot-tools on Fedora).

     Prepare a script config:

     # (cat << EOF
     setenv bootcmd 'mmc init; fatload mmc 0:1 0x80300000 uImage; bootm 0x80300000'
     setenv bootargs 'console=tty0 console=ttyO2,115200n8 root=/dev/mmcblk0p2 rootwait rootfstype=ext3 ro'
     boot
     EOF
     ) > serial-boot.cmd
     # mkimage -A arm -O linux -T script -C none -a 0 -e 0 -n "Core Minimal" -d ./serial-boot.cmd ./boot.scr
     # cp boot.scr /media/boot

   6. Unmount the SD partitions, insert the SD card into the Beagleboard, and
      boot the Beagleboard

Note: As of the 2.6.37 linux-yocto kernel recipe, the Beagleboard uses the
      OMAP_SERIAL device (ttyO2). If you are using an older kernel, such as the
      2.6.34 linux-yocto-stable, be sure to replace ttyO2 with ttyS2 above. You
      should also override the machine SERIAL_CONSOLE in your local.conf in
      order to setup the getty on the serial line:

      SERIAL_CONSOLE_beagleboard = "115200 ttyS2"


Freescale MPC8315E-RDB (mpc8315e-rdb)
=====================================

The MPC8315 PowerPC reference platform (MPC8315E-RDB) is aimed at hardware and
software development of network attached storage (NAS) and digital media server
applications. The MPC8315E-RDB features the PowerQUICC II Pro processor, which
includes a built-in security accelerator.

(Note: you may find it easier to order MPC8315E-RDBA; this appears to be the
same board in an enclosure with accessories. In any case it is fully
compatible with the instructions given here.)

Setup instructions
------------------

You will need the following:
* NFS root setup on your workstation
* TFTP server installed on your workstation
* Straight-thru 9-conductor serial cable (DB9, M/F) connected from your 
  PC to UART1
* Ethernet connected to the first ethernet port on the board

--- Preparation ---

Note: if you have altered your board's ethernet MAC address(es) from the
defaults, or you need to do so because you want multiple boards on the same
network, then you will need to change the values in the dts file (patch
linux/arch/powerpc/boot/dts/mpc8315erdb.dts within the kernel source). If
you have left them at the factory default then you shouldn't need to do
anything here.

--- Booting from NFS root ---

Load the kernel and dtb (device tree blob), and boot the system as follows:

 1. Get the kernel (uImage-mpc8315e-rdb.bin) and dtb (uImage-mpc8315e-rdb.dtb)
    files from the Poky build tmp/deploy directory, and make them available on
    your TFTP server.

 2. Connect the board's first serial port to your workstation and then start up
    your favourite serial terminal so that you will be able to interact with
    the serial console. If you don't have a favourite, picocom is suggested:

  $ picocom /dev/ttyUSB0 -b 115200

 3. Power up or reset the board and press a key on the terminal when prompted
    to get to the U-Boot command line

 4. Set up the environment in U-Boot:

 => setenv ipaddr <board ip>
 => setenv serverip <tftp server ip>
 => setenv bootargs root=/dev/nfs rw nfsroot=<nfsroot ip>:<rootfs path> ip=<board ip>:<server ip>:<gateway ip>:255.255.255.0:mpc8315e:eth0:off console=ttyS0,115200

 5. Download the kernel and dtb, and boot:

 => tftp 800000 uImage-mpc8315e-rdb.bin
 => tftp 780000 uImage-mpc8315e-rdb.dtb
 => bootm 800000 - 780000


Ubiquiti Networks RouterStation Pro (routerstationpro)
======================================================

The RouterStation Pro is an Atheros AR7161 MIPS-based board. Geared towards
networking applications, it has all of the usual features as well as three
type IIIA mini-PCI slots and an on-board 3-port 10/100/1000 Ethernet switch,
in addition to the 10/100/1000 Ethernet WAN port which supports
Power-over-Ethernet.

Setup instructions
------------------

You will need the following:
* A serial cable - female to female (or female to male + gender changer)
  NOTE: cable must be straight through, *not* a null modem cable.
* USB flash drive or hard disk that is able to be powered from the
  board's USB port.
* tftp server installed on your workstation

NOTE: in the following instructions it is assumed that /dev/sdb corresponds
to the USB disk when it is plugged into your workstation. If this is not the
case in your setup then please be careful to substitute the correct device
name in all commands where appropriate.

--- Preparation ---

1) Build an image (e.g. core-image-minimal) using "routerstationpro" as the
MACHINE

2) Partition the USB drive so that primary partition 1 is type Linux (83).
Minimum size depends on your root image size - core-image-minimal probably
only needs 8-16MB, other images will need more.

  # fdisk /dev/sdb
  Command (m for help): p

  Disk /dev/sdb: 4011 MB, 4011491328 bytes
  124 heads, 62 sectors/track, 1019 cylinders, total 7834944 sectors
  Units = sectors of 1 * 512 = 512 bytes
  Sector size (logical/physical): 512 bytes / 512 bytes
  I/O size (minimum/optimal): 512 bytes / 512 bytes
  Disk identifier: 0x0009e87d

     Device Boot      Start         End      Blocks   Id  System
  /dev/sdb1              62     1952751      976345   83  Linux

3) Format partition 1 on the USB as ext3

  # mke2fs -j /dev/sdb1

4) Mount partition 1 and then extract the contents of
tmp/deploy/images/core-image-XXXX.tar.bz2 into it (preserving permissions).

  # mount /dev/sdb1 /media/sdb1
  # cd /media/sdb1
  # tar -xvjpf tmp/deploy/images/core-image-XXXX.tar.bz2

5) Unmount the USB drive and then plug it into the board's USB port

6) Connect the board's serial port to your workstation and then start up
your favourite serial terminal so that you will be able to interact with
the serial console. If you don't have a favourite, picocom is suggested:

  $ picocom /dev/ttyUSB0 -b 115200

7) Connect the network into eth0 (the one that is NOT the 3 port switch). If
you are using power-over-ethernet then the board will power up at this point.

8) Start up the board, watch the serial console. Hit Ctrl+C to abort the
autostart if the board is configured that way (it is by default). The
bootloader's fconfig command can be used to disable autostart and configure
the IP settings if you need to change them (default IP is 192.168.1.20).

9) Make the kernel (tmp/deploy/images/vmlinux-routerstationpro.bin) available
on the tftp server.

10) If you are going to write the kernel to flash (optional - see "Booting a
kernel directly" below for the alternative), remove the current kernel and
rootfs flash partitions. You can list the partitions using the following
bootloader command:

  RedBoot> fis list

You can delete the existing kernel and rootfs with these commands:

  RedBoot> fis delete kernel
  RedBoot> fis delete rootfs

--- Booting a kernel directly ---

1) Load the kernel using the following bootloader command:

  RedBoot> load -m tftp -h <ip of tftp server> vmlinux-routerstationpro.bin

You should see a message on it being successfully loaded.

2) Execute the kernel:

  RedBoot> exec -c "console=ttyS0,115200 root=/dev/sda1 rw rootdelay=2 board=UBNT-RSPRO"

Note that specifying the command line with -c is important as linux-yocto does
not provide a default command line.

--- Writing a kernel to flash ---

1) Go to your tftp server and gzip the kernel you want in flash. It should
halve the size.

2) Load the kernel using the following bootloader command:

  RedBoot> load -r -b 0x80600000 -m tftp -h <ip of tftp server> vmlinux-routerstationpro.bin.gz

This should output something similar to the following:

  Raw file loaded 0x80600000-0x8087c537, assumed entry at 0x80600000

Calculate the length by subtracting the first number from the second number
and then rounding the result up to the nearest 0x1000.

3) Using the length calculated above, create a flash partition for the kernel:

  RedBoot> fis create -b 0x80600000 -l 0x240000 kernel

(change 0x240000 to your rounded length -- change "kernel" to whatever
you want to name your kernel)

--- Booting a kernel from flash ---

To boot the flashed kernel perform the following steps.

1) At the bootloader prompt, load the kernel:

  RedBoot> fis load -d -e kernel

(Change the name "kernel" above if you chose something different earlier)

(-e means 'elf', -d 'decompress')

2) Execute the kernel using the exec command as above.

--- Automating the boot process ---

After writing the kernel to flash and testing the load and exec commands
manually, you can automate the boot process with a boot script.

1) RedBoot> fconfig
   (Answer the questions not specified here as they pertain to your environment)
2) Run script at boot: true
  Boot script: 
  .. fis load -d -e kernel
  .. exec
  Enter script, terminate with empty line
  >> fis load -d -e kernel
  >> exec -c "console=ttyS0,115200 root=/dev/sda1 rw rootdelay=2 board=UBNT-RSPRO"
  >> 
3) Answer the remaining questions and write the changes to flash:
  Update RedBoot non-volatile configuration - continue (y/n)? y
  ... Erase from 0xbfff0000-0xc0000000: .
  ... Program from 0x87ff0000-0x88000000 at 0xbfff0000: .
4) Power cycle the board.
='#n87'>87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781
/*
 *  c 2001 PPC 64 Team, IBM Corp
 *
 *      This program is free software; you can redistribute it and/or
 *      modify it under the terms of the GNU General Public License
 *      as published by the Free Software Foundation; either version
 *      2 of the License, or (at your option) any later version.
 *
 * /proc/powerpc/rtas/firmware_flash interface
 *
 * This file implements a firmware_flash interface to pump a firmware
 * image into the kernel.  At reboot time rtas_restart() will see the
 * firmware image and flash it as it reboots (see rtas.c).
 */

#include <linux/module.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/proc_fs.h>
#include <linux/reboot.h>
#include <asm/delay.h>
#include <linux/uaccess.h>
#include <asm/rtas.h>

#define MODULE_VERS "1.0"
#define MODULE_NAME "rtas_flash"

#define FIRMWARE_FLASH_NAME "firmware_flash"   
#define FIRMWARE_UPDATE_NAME "firmware_update"
#define MANAGE_FLASH_NAME "manage_flash"
#define VALIDATE_FLASH_NAME "validate_flash"

/* General RTAS Status Codes */
#define RTAS_RC_SUCCESS  0
#define RTAS_RC_HW_ERR	-1
#define RTAS_RC_BUSY	-2

/* Flash image status values */
#define FLASH_AUTH           -9002 /* RTAS Not Service Authority Partition */
#define FLASH_NO_OP          -1099 /* No operation initiated by user */	
#define FLASH_IMG_SHORT	     -1005 /* Flash image shorter than expected */
#define FLASH_IMG_BAD_LEN    -1004 /* Bad length value in flash list block */
#define FLASH_IMG_NULL_DATA  -1003 /* Bad data value in flash list block */
#define FLASH_IMG_READY      0     /* Firmware img ready for flash on reboot */

/* Manage image status values */
#define MANAGE_AUTH          -9002 /* RTAS Not Service Authority Partition */
#define MANAGE_ACTIVE_ERR    -9001 /* RTAS Cannot Overwrite Active Img */
#define MANAGE_NO_OP         -1099 /* No operation initiated by user */
#define MANAGE_PARAM_ERR     -3    /* RTAS Parameter Error */
#define MANAGE_HW_ERR        -1    /* RTAS Hardware Error */

/* Validate image status values */
#define VALIDATE_AUTH          -9002 /* RTAS Not Service Authority Partition */
#define VALIDATE_NO_OP         -1099 /* No operation initiated by the user */
#define VALIDATE_INCOMPLETE    -1002 /* User copied < VALIDATE_BUF_SIZE */
#define VALIDATE_READY	       -1001 /* Firmware image ready for validation */
#define VALIDATE_PARAM_ERR     -3    /* RTAS Parameter Error */
#define VALIDATE_HW_ERR        -1    /* RTAS Hardware Error */

/* ibm,validate-flash-image update result tokens */
#define VALIDATE_TMP_UPDATE    0     /* T side will be updated */
#define VALIDATE_FLASH_AUTH    1     /* Partition does not have authority */
#define VALIDATE_INVALID_IMG   2     /* Candidate image is not valid */
#define VALIDATE_CUR_UNKNOWN   3     /* Current fixpack level is unknown */
/*
 * Current T side will be committed to P side before being replace with new
 * image, and the new image is downlevel from current image
 */
#define VALIDATE_TMP_COMMIT_DL 4
/*
 * Current T side will be committed to P side before being replaced with new
 * image
 */
#define VALIDATE_TMP_COMMIT    5
/*
 * T side will be updated with a downlevel image
 */
#define VALIDATE_TMP_UPDATE_DL 6
/*
 * The candidate image's release date is later than the system's firmware
 * service entitlement date - service warranty period has expired
 */
#define VALIDATE_OUT_OF_WRNTY  7

/* ibm,manage-flash-image operation tokens */
#define RTAS_REJECT_TMP_IMG   0
#define RTAS_COMMIT_TMP_IMG   1

/* Array sizes */
#define VALIDATE_BUF_SIZE 4096    
#define VALIDATE_MSG_LEN  256
#define RTAS_MSG_MAXLEN   64

/* Quirk - RTAS requires 4k list length and block size */
#define RTAS_BLKLIST_LENGTH 4096
#define RTAS_BLK_SIZE 4096

struct flash_block {
	char *data;
	unsigned long length;
};

/* This struct is very similar but not identical to
 * that needed by the rtas flash update.
 * All we need to do for rtas is rewrite num_blocks
 * into a version/length and translate the pointers
 * to absolute.
 */
#define FLASH_BLOCKS_PER_NODE ((RTAS_BLKLIST_LENGTH - 16) / sizeof(struct flash_block))
struct flash_block_list {
	unsigned long num_blocks;
	struct flash_block_list *next;
	struct flash_block blocks[FLASH_BLOCKS_PER_NODE];
};

static struct flash_block_list *rtas_firmware_flash_list;

/* Use slab cache to guarantee 4k alignment */
static struct kmem_cache *flash_block_cache = NULL;

#define FLASH_BLOCK_LIST_VERSION (1UL)

/*
 * Local copy of the flash block list.
 *
 * The rtas_firmware_flash_list varable will be
 * set once the data is fully read.
 *
 * For convenience as we build the list we use virtual addrs,
 * we do not fill in the version number, and the length field
 * is treated as the number of entries currently in the block
 * (i.e. not a byte count).  This is all fixed when calling 
 * the flash routine.
 */

/* Status int must be first member of struct */
struct rtas_update_flash_t
{
	int status;			/* Flash update status */
	struct flash_block_list *flist; /* Local copy of flash block list */
};

/* Status int must be first member of struct */
struct rtas_manage_flash_t
{
	int status;			/* Returned status */
};

/* Status int must be first member of struct */
struct rtas_validate_flash_t
{
	int status;		 	/* Returned status */	
	char *buf;			/* Candidate image buffer */
	unsigned int buf_size;		/* Size of image buf */
	unsigned int update_results;	/* Update results token */
};

static struct rtas_update_flash_t rtas_update_flash_data;
static struct rtas_manage_flash_t rtas_manage_flash_data;
static struct rtas_validate_flash_t rtas_validate_flash_data;
static DEFINE_MUTEX(rtas_update_flash_mutex);
static DEFINE_MUTEX(rtas_manage_flash_mutex);
static DEFINE_MUTEX(rtas_validate_flash_mutex);

/* Do simple sanity checks on the flash image. */
static int flash_list_valid(struct flash_block_list *flist)
{
	struct flash_block_list *f;
	int i;
	unsigned long block_size, image_size;

	/* Paranoid self test here.  We also collect the image size. */
	image_size = 0;
	for (f = flist; f; f = f->next) {
		for (i = 0; i < f->num_blocks; i++) {
			if (f->blocks[i].data == NULL) {
				return FLASH_IMG_NULL_DATA;
			}
			block_size = f->blocks[i].length;
			if (block_size <= 0 || block_size > RTAS_BLK_SIZE) {
				return FLASH_IMG_BAD_LEN;
			}
			image_size += block_size;
		}
	}

	if (image_size < (256 << 10)) {
		if (image_size < 2) 
			return FLASH_NO_OP;
	}

	printk(KERN_INFO "FLASH: flash image with %ld bytes stored for hardware flash on reboot\n", image_size);

	return FLASH_IMG_READY;
}

static void free_flash_list(struct flash_block_list *f)
{
	struct flash_block_list *next;
	int i;

	while (f) {
		for (i = 0; i < f->num_blocks; i++)
			kmem_cache_free(flash_block_cache, f->blocks[i].data);
		next = f->next;
		kmem_cache_free(flash_block_cache, f);
		f = next;
	}
}

static int rtas_flash_release(struct inode *inode, struct file *file)
{
	struct rtas_update_flash_t *const uf = &rtas_update_flash_data;

	mutex_lock(&rtas_update_flash_mutex);

	if (uf->flist) {    
		/* File was opened in write mode for a new flash attempt */
		/* Clear saved list */
		if (rtas_firmware_flash_list) {
			free_flash_list(rtas_firmware_flash_list);
			rtas_firmware_flash_list = NULL;
		}

		if (uf->status != FLASH_AUTH)  
			uf->status = flash_list_valid(uf->flist);

		if (uf->status == FLASH_IMG_READY) 
			rtas_firmware_flash_list = uf->flist;
		else
			free_flash_list(uf->flist);

		uf->flist = NULL;
	}

	mutex_unlock(&rtas_update_flash_mutex);
	return 0;
}

static size_t get_flash_status_msg(int status, char *buf)
{
	const char *msg;
	size_t len;

	switch (status) {
	case FLASH_AUTH:
		msg = "error: this partition does not have service authority\n";
		break;
	case FLASH_NO_OP:
		msg = "info: no firmware image for flash\n";
		break;
	case FLASH_IMG_SHORT:
		msg = "error: flash image short\n";
		break;
	case FLASH_IMG_BAD_LEN:
		msg = "error: internal error bad length\n";
		break;
	case FLASH_IMG_NULL_DATA:
		msg = "error: internal error null data\n";
		break;
	case FLASH_IMG_READY:
		msg = "ready: firmware image ready for flash on reboot\n";
		break;
	default:
		return sprintf(buf, "error: unexpected status value %d\n",
			       status);
	}

	len = strlen(msg);
	memcpy(buf, msg, len + 1);
	return len;
}

/* Reading the proc file will show status (not the firmware contents) */
static ssize_t rtas_flash_read_msg(struct file *file, char __user *buf,
				   size_t count, loff_t *ppos)
{
	struct rtas_update_flash_t *const uf = &rtas_update_flash_data;
	char msg[RTAS_MSG_MAXLEN];
	size_t len;
	int status;

	mutex_lock(&rtas_update_flash_mutex);
	status = uf->status;
	mutex_unlock(&rtas_update_flash_mutex);

	/* Read as text message */
	len = get_flash_status_msg(status, msg);
	return simple_read_from_buffer(buf, count, ppos, msg, len);
}

static ssize_t rtas_flash_read_num(struct file *file, char __user *buf,
				   size_t count, loff_t *ppos)
{
	struct rtas_update_flash_t *const uf = &rtas_update_flash_data;
	char msg[RTAS_MSG_MAXLEN];
	int status;

	mutex_lock(&rtas_update_flash_mutex);
	status = uf->status;
	mutex_unlock(&rtas_update_flash_mutex);

	/* Read as number */
	sprintf(msg, "%d\n", status);
	return simple_read_from_buffer(buf, count, ppos, msg, strlen(msg));
}

/* We could be much more efficient here.  But to keep this function
 * simple we allocate a page to the block list no matter how small the
 * count is.  If the system is low on memory it will be just as well
 * that we fail....
 */
static ssize_t rtas_flash_write(struct file *file, const char __user *buffer,
				size_t count, loff_t *off)
{
	struct rtas_update_flash_t *const uf = &rtas_update_flash_data;
	char *p;
	int next_free, rc;
	struct flash_block_list *fl;

	mutex_lock(&rtas_update_flash_mutex);

	if (uf->status == FLASH_AUTH || count == 0)
		goto out;	/* discard data */

	/* In the case that the image is not ready for flashing, the memory
	 * allocated for the block list will be freed upon the release of the 
	 * proc file
	 */
	if (uf->flist == NULL) {
		uf->flist = kmem_cache_zalloc(flash_block_cache, GFP_KERNEL);
		if (!uf->flist)
			goto nomem;
	}

	fl = uf->flist;
	while (fl->next)
		fl = fl->next; /* seek to last block_list for append */
	next_free = fl->num_blocks;
	if (next_free == FLASH_BLOCKS_PER_NODE) {
		/* Need to allocate another block_list */
		fl->next = kmem_cache_zalloc(flash_block_cache, GFP_KERNEL);
		if (!fl->next)
			goto nomem;
		fl = fl->next;
		next_free = 0;
	}

	if (count > RTAS_BLK_SIZE)
		count = RTAS_BLK_SIZE;
	p = kmem_cache_zalloc(flash_block_cache, GFP_KERNEL);
	if (!p)
		goto nomem;
	
	if(copy_from_user(p, buffer, count)) {
		kmem_cache_free(flash_block_cache, p);
		rc = -EFAULT;
		goto error;
	}
	fl->blocks[next_free].data = p;
	fl->blocks[next_free].length = count;
	fl->num_blocks++;
out:
	mutex_unlock(&rtas_update_flash_mutex);
	return count;

nomem:
	rc = -ENOMEM;
error:
	mutex_unlock(&rtas_update_flash_mutex);
	return rc;
}

/*
 * Flash management routines.
 */
static void manage_flash(struct rtas_manage_flash_t *args_buf, unsigned int op)
{
	s32 rc;

	do {
		rc = rtas_call(rtas_token("ibm,manage-flash-image"), 1, 1,
			       NULL, op);
	} while (rtas_busy_delay(rc));

	args_buf->status = rc;
}

static ssize_t manage_flash_read(struct file *file, char __user *buf,
			       size_t count, loff_t *ppos)
{
	struct rtas_manage_flash_t *const args_buf = &rtas_manage_flash_data;
	char msg[RTAS_MSG_MAXLEN];
	int msglen, status;

	mutex_lock(&rtas_manage_flash_mutex);
	status = args_buf->status;
	mutex_unlock(&rtas_manage_flash_mutex);

	msglen = sprintf(msg, "%d\n", status);
	return simple_read_from_buffer(buf, count, ppos, msg, msglen);
}

static ssize_t manage_flash_write(struct file *file, const char __user *buf,
				size_t count, loff_t *off)
{
	struct rtas_manage_flash_t *const args_buf = &rtas_manage_flash_data;
	static const char reject_str[] = "0";
	static const char commit_str[] = "1";
	char stkbuf[10];
	int op, rc;

	mutex_lock(&rtas_manage_flash_mutex);

	if ((args_buf->status == MANAGE_AUTH) || (count == 0))
		goto out;
		
	op = -1;
	if (buf) {
		if (count > 9) count = 9;
		rc = -EFAULT;
		if (copy_from_user (stkbuf, buf, count))
			goto error;
		if (strncmp(stkbuf, reject_str, strlen(reject_str)) == 0) 
			op = RTAS_REJECT_TMP_IMG;
		else if (strncmp(stkbuf, commit_str, strlen(commit_str)) == 0) 
			op = RTAS_COMMIT_TMP_IMG;
	}
	
	if (op == -1) {   /* buf is empty, or contains invalid string */
		rc = -EINVAL;
		goto error;
	}

	manage_flash(args_buf, op);
out:
	mutex_unlock(&rtas_manage_flash_mutex);
	return count;

error:
	mutex_unlock(&rtas_manage_flash_mutex);
	return rc;
}

/*
 * Validation routines.
 */
static void validate_flash(struct rtas_validate_flash_t *args_buf)
{
	int token = rtas_token("ibm,validate-flash-image");
	int update_results;
	s32 rc;	

	rc = 0;
	do {
		spin_lock(&rtas_data_buf_lock);
		memcpy(rtas_data_buf, args_buf->buf, VALIDATE_BUF_SIZE);
		rc = rtas_call(token, 2, 2, &update_results, 
			       (u32) __pa(rtas_data_buf), args_buf->buf_size);
		memcpy(args_buf->buf, rtas_data_buf, VALIDATE_BUF_SIZE);
		spin_unlock(&rtas_data_buf_lock);
	} while (rtas_busy_delay(rc));

	args_buf->status = rc;
	args_buf->update_results = update_results;
}

static int get_validate_flash_msg(struct rtas_validate_flash_t *args_buf, 
		                   char *msg, int msglen)
{
	int n;

	if (args_buf->status >= VALIDATE_TMP_UPDATE) { 
		n = sprintf(msg, "%d\n", args_buf->update_results);
		if ((args_buf->update_results >= VALIDATE_CUR_UNKNOWN) ||
		    (args_buf->update_results == VALIDATE_TMP_UPDATE))
			n += snprintf(msg + n, msglen - n, "%s\n",
					args_buf->buf);
	} else {
		n = sprintf(msg, "%d\n", args_buf->status);
	}
	return n;
}

static ssize_t validate_flash_read(struct file *file, char __user *buf,
			       size_t count, loff_t *ppos)
{
	struct rtas_validate_flash_t *const args_buf =
		&rtas_validate_flash_data;
	char msg[VALIDATE_MSG_LEN];
	int msglen;

	mutex_lock(&rtas_validate_flash_mutex);
	msglen = get_validate_flash_msg(args_buf, msg, VALIDATE_MSG_LEN);
	mutex_unlock(&rtas_validate_flash_mutex);

	return simple_read_from_buffer(buf, count, ppos, msg, msglen);
}

static ssize_t validate_flash_write(struct file *file, const char __user *buf,
				    size_t count, loff_t *off)
{
	struct rtas_validate_flash_t *const args_buf =
		&rtas_validate_flash_data;
	int rc;

	mutex_lock(&rtas_validate_flash_mutex);

	/* We are only interested in the first 4K of the
	 * candidate image */
	if ((*off >= VALIDATE_BUF_SIZE) || 
		(args_buf->status == VALIDATE_AUTH)) {
		*off += count;
		mutex_unlock(&rtas_validate_flash_mutex);
		return count;
	}

	if (*off + count >= VALIDATE_BUF_SIZE)  {
		count = VALIDATE_BUF_SIZE - *off;
		args_buf->status = VALIDATE_READY;	
	} else {
		args_buf->status = VALIDATE_INCOMPLETE;
	}

	if (!access_ok(VERIFY_READ, buf, count)) {
		rc = -EFAULT;
		goto done;
	}
	if (copy_from_user(args_buf->buf + *off, buf, count)) {
		rc = -EFAULT;
		goto done;
	}

	*off += count;
	rc = count;
done:
	mutex_unlock(&rtas_validate_flash_mutex);
	return rc;
}

static int validate_flash_release(struct inode *inode, struct file *file)
{
	struct rtas_validate_flash_t *const args_buf =
		&rtas_validate_flash_data;

	mutex_lock(&rtas_validate_flash_mutex);

	if (args_buf->status == VALIDATE_READY) {
		args_buf->buf_size = VALIDATE_BUF_SIZE;
		validate_flash(args_buf);
	}

	mutex_unlock(&rtas_validate_flash_mutex);
	return 0;
}

/*
 * On-reboot flash update applicator.
 */
static void rtas_flash_firmware(int reboot_type)
{
	unsigned long image_size;
	struct flash_block_list *f, *next, *flist;
	unsigned long rtas_block_list;
	int i, status, update_token;

	if (rtas_firmware_flash_list == NULL)
		return;		/* nothing to do */

	if (reboot_type != SYS_RESTART) {
		printk(KERN_ALERT "FLASH: firmware flash requires a reboot\n");
		printk(KERN_ALERT "FLASH: the firmware image will NOT be flashed\n");
		return;
	}

	update_token = rtas_token("ibm,update-flash-64-and-reboot");
	if (update_token == RTAS_UNKNOWN_SERVICE) {
		printk(KERN_ALERT "FLASH: ibm,update-flash-64-and-reboot "
		       "is not available -- not a service partition?\n");
		printk(KERN_ALERT "FLASH: firmware will not be flashed\n");
		return;
	}

	/*
	 * Just before starting the firmware flash, cancel the event scan work
	 * to avoid any soft lockup issues.
	 */
	rtas_cancel_event_scan();

	/*
	 * NOTE: the "first" block must be under 4GB, so we create
	 * an entry with no data blocks in the reserved buffer in
	 * the kernel data segment.
	 */
	spin_lock(&rtas_data_buf_lock);
	flist = (struct flash_block_list *)&rtas_data_buf[0];
	flist->num_blocks = 0;
	flist->next = rtas_firmware_flash_list;
	rtas_block_list = __pa(flist);
	if (rtas_block_list >= 4UL*1024*1024*1024) {
		printk(KERN_ALERT "FLASH: kernel bug...flash list header addr above 4GB\n");
		spin_unlock(&rtas_data_buf_lock);
		return;
	}

	printk(KERN_ALERT "FLASH: preparing saved firmware image for flash\n");
	/* Update the block_list in place. */
	rtas_firmware_flash_list = NULL; /* too hard to backout on error */
	image_size = 0;
	for (f = flist; f; f = next) {
		/* Translate data addrs to absolute */
		for (i = 0; i < f->num_blocks; i++) {
			f->blocks[i].data = (char *)cpu_to_be64(__pa(f->blocks[i].data));
			image_size += f->blocks[i].length;
			f->blocks[i].length = cpu_to_be64(f->blocks[i].length);
		}
		next = f->next;
		/* Don't translate NULL pointer for last entry */
		if (f->next)
			f->next = (struct flash_block_list *)cpu_to_be64(__pa(f->next));
		else
			f->next = NULL;
		/* make num_blocks into the version/length field */
		f->num_blocks = (FLASH_BLOCK_LIST_VERSION << 56) | ((f->num_blocks+1)*16);
		f->num_blocks = cpu_to_be64(f->num_blocks);
	}

	printk(KERN_ALERT "FLASH: flash image is %ld bytes\n", image_size);
	printk(KERN_ALERT "FLASH: performing flash and reboot\n");
	rtas_progress("Flashing        \n", 0x0);
	rtas_progress("Please Wait...  ", 0x0);
	printk(KERN_ALERT "FLASH: this will take several minutes.  Do not power off!\n");
	status = rtas_call(update_token, 1, 1, NULL, rtas_block_list);
	switch (status) {	/* should only get "bad" status */
	    case 0:
		printk(KERN_ALERT "FLASH: success\n");
		break;
	    case -1:
		printk(KERN_ALERT "FLASH: hardware error.  Firmware may not be not flashed\n");
		break;
	    case -3:
		printk(KERN_ALERT "FLASH: image is corrupt or not correct for this platform.  Firmware not flashed\n");
		break;
	    case -4:
		printk(KERN_ALERT "FLASH: flash failed when partially complete.  System may not reboot\n");
		break;
	    default:
		printk(KERN_ALERT "FLASH: unknown flash return code %d\n", status);
		break;
	}
	spin_unlock(&rtas_data_buf_lock);
}

/*
 * Manifest of proc files to create
 */
struct rtas_flash_file {
	const char *filename;
	const char *rtas_call_name;
	int *status;
	const struct file_operations fops;
};

static const struct rtas_flash_file rtas_flash_files[] = {
	{
		.filename	= "powerpc/rtas/" FIRMWARE_FLASH_NAME,
		.rtas_call_name	= "ibm,update-flash-64-and-reboot",
		.status		= &rtas_update_flash_data.status,
		.fops.read	= rtas_flash_read_msg,
		.fops.write	= rtas_flash_write,
		.fops.release	= rtas_flash_release,
		.fops.llseek	= default_llseek,
	},
	{
		.filename	= "powerpc/rtas/" FIRMWARE_UPDATE_NAME,
		.rtas_call_name	= "ibm,update-flash-64-and-reboot",
		.status		= &rtas_update_flash_data.status,
		.fops.read	= rtas_flash_read_num,
		.fops.write	= rtas_flash_write,
		.fops.release	= rtas_flash_release,
		.fops.llseek	= default_llseek,
	},
	{
		.filename	= "powerpc/rtas/" VALIDATE_FLASH_NAME,
		.rtas_call_name	= "ibm,validate-flash-image",
		.status		= &rtas_validate_flash_data.status,
		.fops.read	= validate_flash_read,
		.fops.write	= validate_flash_write,
		.fops.release	= validate_flash_release,
		.fops.llseek	= default_llseek,
	},
	{
		.filename	= "powerpc/rtas/" MANAGE_FLASH_NAME,
		.rtas_call_name	= "ibm,manage-flash-image",
		.status		= &rtas_manage_flash_data.status,
		.fops.read	= manage_flash_read,
		.fops.write	= manage_flash_write,
		.fops.llseek	= default_llseek,
	}
};

static int __init rtas_flash_init(void)
{
	int i;

	if (rtas_token("ibm,update-flash-64-and-reboot") ==
		       RTAS_UNKNOWN_SERVICE) {
		pr_info("rtas_flash: no firmware flash support\n");
		return -EINVAL;
	}

	rtas_validate_flash_data.buf = kzalloc(VALIDATE_BUF_SIZE, GFP_KERNEL);
	if (!rtas_validate_flash_data.buf)
		return -ENOMEM;

	flash_block_cache = kmem_cache_create_usercopy("rtas_flash_cache",
						       RTAS_BLK_SIZE, RTAS_BLK_SIZE,
						       0, 0, RTAS_BLK_SIZE, NULL);
	if (!flash_block_cache) {
		printk(KERN_ERR "%s: failed to create block cache\n",
				__func__);
		goto enomem_buf;
	}

	for (i = 0; i < ARRAY_SIZE(rtas_flash_files); i++) {
		const struct rtas_flash_file *f = &rtas_flash_files[i];
		int token;

		if (!proc_create(f->filename, 0600, NULL, &f->fops))
			goto enomem;

		/*
		 * This code assumes that the status int is the first member of the
		 * struct
		 */
		token = rtas_token(f->rtas_call_name);
		if (token == RTAS_UNKNOWN_SERVICE)
			*f->status = FLASH_AUTH;
		else
			*f->status = FLASH_NO_OP;
	}

	rtas_flash_term_hook = rtas_flash_firmware;
	return 0;

enomem:
	while (--i >= 0) {
		const struct rtas_flash_file *f = &rtas_flash_files[i];
		remove_proc_entry(f->filename, NULL);
	}

	kmem_cache_destroy(flash_block_cache);
enomem_buf:
	kfree(rtas_validate_flash_data.buf);
	return -ENOMEM;
}

static void __exit rtas_flash_cleanup(void)
{
	int i;

	rtas_flash_term_hook = NULL;

	if (rtas_firmware_flash_list) {
		free_flash_list(rtas_firmware_flash_list);
		rtas_firmware_flash_list = NULL;
	}

	for (i = 0; i < ARRAY_SIZE(rtas_flash_files); i++) {
		const struct rtas_flash_file *f = &rtas_flash_files[i];
		remove_proc_entry(f->filename, NULL);
	}

	kmem_cache_destroy(flash_block_cache);
	kfree(rtas_validate_flash_data.buf);
}

module_init(rtas_flash_init);
module_exit(rtas_flash_cleanup);
MODULE_LICENSE("GPL");