6c459f5cb5df3a068bbcd5639b69d8e5e709a280
[safe/jmp/linux-2.6] / drivers / net / wimax / i2400m / fw.c
1 /*
2  * Intel Wireless WiMAX Connection 2400m
3  * Firmware uploader
4  *
5  *
6  * Copyright (C) 2007-2008 Intel Corporation. All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  *
12  *   * Redistributions of source code must retain the above copyright
13  *     notice, this list of conditions and the following disclaimer.
14  *   * Redistributions in binary form must reproduce the above copyright
15  *     notice, this list of conditions and the following disclaimer in
16  *     the documentation and/or other materials provided with the
17  *     distribution.
18  *   * Neither the name of Intel Corporation nor the names of its
19  *     contributors may be used to endorse or promote products derived
20  *     from this software without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
23  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
24  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
25  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
26  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
27  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
28  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
29  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
30  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
31  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
32  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
33  *
34  *
35  * Intel Corporation <linux-wimax@intel.com>
36  * Yanir Lubetkin <yanirx.lubetkin@intel.com>
37  * Inaky Perez-Gonzalez <inaky.perez-gonzalez@intel.com>
38  *  - Initial implementation
39  *
40  *
41  * THE PROCEDURE
42  *
43  * The 2400m and derived devices work in two modes: boot-mode or
44  * normal mode. In boot mode we can execute only a handful of commands
45  * targeted at uploading the firmware and launching it.
46  *
47  * The 2400m enters boot mode when it is first connected to the
48  * system, when it crashes and when you ask it to reboot. There are
49  * two submodes of the boot mode: signed and non-signed. Signed takes
50  * firmwares signed with a certain private key, non-signed takes any
51  * firmware. Normal hardware takes only signed firmware.
52  *
53  * On boot mode, in USB, we write to the device using the bulk out
54  * endpoint and read from it in the notification endpoint. In SDIO we
55  * talk to it via the write address and read from the read address.
56  *
57  * Upon entrance to boot mode, the device sends (preceeded with a few
58  * zero length packets (ZLPs) on the notification endpoint in USB) a
59  * reboot barker (4 le32 words with the same value). We ack it by
60  * sending the same barker to the device. The device acks with a
61  * reboot ack barker (4 le32 words with value I2400M_ACK_BARKER) and
62  * then is fully booted. At this point we can upload the firmware.
63  *
64  * Note that different iterations of the device and EEPROM
65  * configurations will send different [re]boot barkers; these are
66  * collected in i2400m_barker_db along with the firmware
67  * characteristics they require.
68  *
69  * This process is accomplished by the i2400m_bootrom_init()
70  * function. All the device interaction happens through the
71  * i2400m_bm_cmd() [boot mode command]. Special return values will
72  * indicate if the device did reset during the process.
73  *
74  * After this, we read the MAC address and then (if needed)
75  * reinitialize the device. We need to read it ahead of time because
76  * in the future, we might not upload the firmware until userspace
77  * 'ifconfig up's the device.
78  *
79  * We can then upload the firmware file. The file is composed of a BCF
80  * header (basic data, keys and signatures) and a list of write
81  * commands and payloads. Optionally more BCF headers might follow the
82  * main payload. We first upload the header [i2400m_dnload_init()] and
83  * then pass the commands and payloads verbatim to the i2400m_bm_cmd()
84  * function [i2400m_dnload_bcf()]. Then we tell the device to jump to
85  * the new firmware [i2400m_dnload_finalize()].
86  *
87  * Once firmware is uploaded, we are good to go :)
88  *
89  * When we don't know in which mode we are, we first try by sending a
90  * warm reset request that will take us to boot-mode. If we time out
91  * waiting for a reboot barker, that means maybe we are already in
92  * boot mode, so we send a reboot barker.
93  *
94  * COMMAND EXECUTION
95  *
96  * This code (and process) is single threaded; for executing commands,
97  * we post a URB to the notification endpoint, post the command, wait
98  * for data on the notification buffer. We don't need to worry about
99  * others as we know we are the only ones in there.
100  *
101  * BACKEND IMPLEMENTATION
102  *
103  * This code is bus-generic; the bus-specific driver provides back end
104  * implementations to send a boot mode command to the device and to
105  * read an acknolwedgement from it (or an asynchronous notification)
106  * from it.
107  *
108  * FIRMWARE LOADING
109  *
110  * Note that in some cases, we can't just load a firmware file (for
111  * example, when resuming). For that, we might cache the firmware
112  * file. Thus, when doing the bootstrap, if there is a cache firmware
113  * file, it is used; if not, loading from disk is attempted.
114  *
115  * ROADMAP
116  *
117  * i2400m_barker_db_init              Called by i2400m_driver_init()
118  *   i2400m_barker_db_add
119  *
120  * i2400m_barker_db_exit              Called by i2400m_driver_exit()
121  *
122  * i2400m_dev_bootstrap               Called by __i2400m_dev_start()
123  *   request_firmware
124  *   i2400m_fw_bootstrap
125  *     i2400m_fw_check
126  *       i2400m_fw_hdr_check
127  *     i2400m_fw_dnload
128  *   release_firmware
129  *
130  * i2400m_fw_dnload
131  *   i2400m_bootrom_init
132  *     i2400m_bm_cmd
133  *     i2400m_reset
134  *   i2400m_dnload_init
135  *     i2400m_dnload_init_signed
136  *     i2400m_dnload_init_nonsigned
137  *       i2400m_download_chunk
138  *         i2400m_bm_cmd
139  *   i2400m_dnload_bcf
140  *     i2400m_bm_cmd
141  *   i2400m_dnload_finalize
142  *     i2400m_bm_cmd
143  *
144  * i2400m_bm_cmd
145  *   i2400m->bus_bm_cmd_send()
146  *   i2400m->bus_bm_wait_for_ack
147  *   __i2400m_bm_ack_verify
148  *     i2400m_is_boot_barker
149  *
150  * i2400m_bm_cmd_prepare              Used by bus-drivers to prep
151  *                                    commands before sending
152  *
153  * i2400m_pm_notifier                 Called on Power Management events
154  *   i2400m_fw_cache
155  *   i2400m_fw_uncache
156  */
157 #include <linux/firmware.h>
158 #include <linux/sched.h>
159 #include <linux/usb.h>
160 #include "i2400m.h"
161
162
163 #define D_SUBMODULE fw
164 #include "debug-levels.h"
165
166
167 static const __le32 i2400m_ACK_BARKER[4] = {
168         cpu_to_le32(I2400M_ACK_BARKER),
169         cpu_to_le32(I2400M_ACK_BARKER),
170         cpu_to_le32(I2400M_ACK_BARKER),
171         cpu_to_le32(I2400M_ACK_BARKER)
172 };
173
174
175 /**
176  * Prepare a boot-mode command for delivery
177  *
178  * @cmd: pointer to bootrom header to prepare
179  *
180  * Computes checksum if so needed. After calling this function, DO NOT
181  * modify the command or header as the checksum won't work anymore.
182  *
183  * We do it from here because some times we cannot do it in the
184  * original context the command was sent (it is a const), so when we
185  * copy it to our staging buffer, we add the checksum there.
186  */
187 void i2400m_bm_cmd_prepare(struct i2400m_bootrom_header *cmd)
188 {
189         if (i2400m_brh_get_use_checksum(cmd)) {
190                 int i;
191                 u32 checksum = 0;
192                 const u32 *checksum_ptr = (void *) cmd->payload;
193                 for (i = 0; i < cmd->data_size / 4; i++)
194                         checksum += cpu_to_le32(*checksum_ptr++);
195                 checksum += cmd->command + cmd->target_addr + cmd->data_size;
196                 cmd->block_checksum = cpu_to_le32(checksum);
197         }
198 }
199 EXPORT_SYMBOL_GPL(i2400m_bm_cmd_prepare);
200
201
202 /*
203  * Database of known barkers.
204  *
205  * A barker is what the device sends indicating he is ready to be
206  * bootloaded. Different versions of the device will send different
207  * barkers. Depending on the barker, it might mean the device wants
208  * some kind of firmware or the other.
209  */
210 static struct i2400m_barker_db {
211         __le32 data[4];
212 } *i2400m_barker_db;
213 static size_t i2400m_barker_db_used, i2400m_barker_db_size;
214
215
216 static
217 int i2400m_zrealloc_2x(void **ptr, size_t *_count, size_t el_size,
218                        gfp_t gfp_flags)
219 {
220         size_t old_count = *_count,
221                 new_count = old_count ? 2 * old_count : 2,
222                 old_size = el_size * old_count,
223                 new_size = el_size * new_count;
224         void *nptr = krealloc(*ptr, new_size, gfp_flags);
225         if (nptr) {
226                 /* zero the other half or the whole thing if old_count
227                  * was zero */
228                 if (old_size == 0)
229                         memset(nptr, 0, new_size);
230                 else
231                         memset(nptr + old_size, 0, old_size);
232                 *_count = new_count;
233                 *ptr = nptr;
234                 return 0;
235         } else
236                 return -ENOMEM;
237 }
238
239
240 /*
241  * Add a barker to the database
242  *
243  * This cannot used outside of this module and only at at module_init
244  * time. This is to avoid the need to do locking.
245  */
246 static
247 int i2400m_barker_db_add(u32 barker_id)
248 {
249         int result;
250
251         struct i2400m_barker_db *barker;
252         if (i2400m_barker_db_used >= i2400m_barker_db_size) {
253                 result = i2400m_zrealloc_2x(
254                         (void **) &i2400m_barker_db, &i2400m_barker_db_size,
255                         sizeof(i2400m_barker_db[0]), GFP_KERNEL);
256                 if (result < 0)
257                         return result;
258         }
259         barker = i2400m_barker_db + i2400m_barker_db_used++;
260         barker->data[0] = le32_to_cpu(barker_id);
261         barker->data[1] = le32_to_cpu(barker_id);
262         barker->data[2] = le32_to_cpu(barker_id);
263         barker->data[3] = le32_to_cpu(barker_id);
264         return 0;
265 }
266
267
268 void i2400m_barker_db_exit(void)
269 {
270         kfree(i2400m_barker_db);
271         i2400m_barker_db = NULL;
272         i2400m_barker_db_size = 0;
273         i2400m_barker_db_used = 0;
274 }
275
276
277 /*
278  * Helper function to add all the known stable barkers to the barker
279  * database.
280  */
281 static
282 int i2400m_barker_db_known_barkers(void)
283 {
284         int result;
285
286         result = i2400m_barker_db_add(I2400M_NBOOT_BARKER);
287         if (result < 0)
288                 goto error_add;
289         result = i2400m_barker_db_add(I2400M_SBOOT_BARKER);
290         if (result < 0)
291                 goto error_add;
292         result = i2400m_barker_db_add(I2400M_SBOOT_BARKER_6050);
293         if (result < 0)
294                 goto error_add;
295 error_add:
296        return result;
297 }
298
299
300 /*
301  * Initialize the barker database
302  *
303  * This can only be used from the module_init function for this
304  * module; this is to avoid the need to do locking.
305  *
306  * @options: command line argument with extra barkers to
307  *     recognize. This is a comma-separated list of 32-bit hex
308  *     numbers. They are appended to the existing list. Setting 0
309  *     cleans the existing list and starts a new one.
310  */
311 int i2400m_barker_db_init(const char *_options)
312 {
313         int result;
314         char *options = NULL, *options_orig, *token;
315
316         i2400m_barker_db = NULL;
317         i2400m_barker_db_size = 0;
318         i2400m_barker_db_used = 0;
319
320         result = i2400m_barker_db_known_barkers();
321         if (result < 0)
322                 goto error_add;
323         /* parse command line options from i2400m.barkers */
324         if (_options != NULL) {
325                 unsigned barker;
326
327                 options_orig = kstrdup(_options, GFP_KERNEL);
328                 if (options_orig == NULL)
329                         goto error_parse;
330                 options = options_orig;
331
332                 while ((token = strsep(&options, ",")) != NULL) {
333                         if (*token == '\0')     /* eat joint commas */
334                                 continue;
335                         if (sscanf(token, "%x", &barker) != 1
336                             || barker > 0xffffffff) {
337                                 printk(KERN_ERR "%s: can't recognize "
338                                        "i2400m.barkers value '%s' as "
339                                        "a 32-bit number\n",
340                                        __func__, token);
341                                 result = -EINVAL;
342                                 goto error_parse;
343                         }
344                         if (barker == 0) {
345                                 /* clean list and start new */
346                                 i2400m_barker_db_exit();
347                                 continue;
348                         }
349                         result = i2400m_barker_db_add(barker);
350                         if (result < 0)
351                                 goto error_add;
352                 }
353                 kfree(options_orig);
354         }
355         return 0;
356
357 error_parse:
358 error_add:
359         kfree(i2400m_barker_db);
360         return result;
361 }
362
363
364 /*
365  * Recognize a boot barker
366  *
367  * @buf: buffer where the boot barker.
368  * @buf_size: size of the buffer (has to be 16 bytes). It is passed
369  *     here so the function can check it for the caller.
370  *
371  * Note that as a side effect, upon identifying the obtained boot
372  * barker, this function will set i2400m->barker to point to the right
373  * barker database entry. Subsequent calls to the function will result
374  * in verifying that the same type of boot barker is returned when the
375  * device [re]boots (as long as the same device instance is used).
376  *
377  * Return: 0 if @buf matches a known boot barker. -ENOENT if the
378  *     buffer in @buf doesn't match any boot barker in the database or
379  *     -EILSEQ if the buffer doesn't have the right size.
380  */
381 int i2400m_is_boot_barker(struct i2400m *i2400m,
382                           const void *buf, size_t buf_size)
383 {
384         int result;
385         struct device *dev = i2400m_dev(i2400m);
386         struct i2400m_barker_db *barker;
387         int i;
388
389         result = -ENOENT;
390         if (buf_size != sizeof(i2400m_barker_db[i].data))
391                 return result;
392
393         /* Short circuit if we have already discovered the barker
394          * associated with the device. */
395         if (i2400m->barker
396             && !memcmp(buf, i2400m->barker, sizeof(i2400m->barker->data))) {
397                 unsigned index = (i2400m->barker - i2400m_barker_db)
398                         / sizeof(*i2400m->barker);
399                 d_printf(2, dev, "boot barker cache-confirmed #%u/%08x\n",
400                          index, le32_to_cpu(i2400m->barker->data[0]));
401                 return 0;
402         }
403
404         for (i = 0; i < i2400m_barker_db_used; i++) {
405                 barker = &i2400m_barker_db[i];
406                 BUILD_BUG_ON(sizeof(barker->data) != 16);
407                 if (memcmp(buf, barker->data, sizeof(barker->data)))
408                         continue;
409
410                 if (i2400m->barker == NULL) {
411                         i2400m->barker = barker;
412                         d_printf(1, dev, "boot barker set to #%u/%08x\n",
413                                  i, le32_to_cpu(barker->data[0]));
414                         if (barker->data[0] == le32_to_cpu(I2400M_NBOOT_BARKER))
415                                 i2400m->sboot = 0;
416                         else
417                                 i2400m->sboot = 1;
418                 } else if (i2400m->barker != barker) {
419                         dev_err(dev, "HW inconsistency: device "
420                                 "reports a different boot barker "
421                                 "than set (from %08x to %08x)\n",
422                                 le32_to_cpu(i2400m->barker->data[0]),
423                                 le32_to_cpu(barker->data[0]));
424                         result = -EIO;
425                 } else
426                         d_printf(2, dev, "boot barker confirmed #%u/%08x\n",
427                                  i, le32_to_cpu(barker->data[0]));
428                 result = 0;
429                 break;
430         }
431         return result;
432 }
433 EXPORT_SYMBOL_GPL(i2400m_is_boot_barker);
434
435
436 /*
437  * Verify the ack data received
438  *
439  * Given a reply to a boot mode command, chew it and verify everything
440  * is ok.
441  *
442  * @opcode: opcode which generated this ack. For error messages.
443  * @ack: pointer to ack data we received
444  * @ack_size: size of that data buffer
445  * @flags: I2400M_BM_CMD_* flags we called the command with.
446  *
447  * Way too long function -- maybe it should be further split
448  */
449 static
450 ssize_t __i2400m_bm_ack_verify(struct i2400m *i2400m, int opcode,
451                                struct i2400m_bootrom_header *ack,
452                                size_t ack_size, int flags)
453 {
454         ssize_t result = -ENOMEM;
455         struct device *dev = i2400m_dev(i2400m);
456
457         d_fnstart(8, dev, "(i2400m %p opcode %d ack %p size %zu)\n",
458                   i2400m, opcode, ack, ack_size);
459         if (ack_size < sizeof(*ack)) {
460                 result = -EIO;
461                 dev_err(dev, "boot-mode cmd %d: HW BUG? notification didn't "
462                         "return enough data (%zu bytes vs %zu expected)\n",
463                         opcode, ack_size, sizeof(*ack));
464                 goto error_ack_short;
465         }
466         result = i2400m_is_boot_barker(i2400m, ack, ack_size);
467         if (result >= 0) {
468                 result = -ERESTARTSYS;
469                 d_printf(6, dev, "boot-mode cmd %d: HW boot barker\n", opcode);
470                 goto error_reboot;
471         }
472         if (ack_size == sizeof(i2400m_ACK_BARKER)
473                  && memcmp(ack, i2400m_ACK_BARKER, sizeof(*ack)) == 0) {
474                 result = -EISCONN;
475                 d_printf(3, dev, "boot-mode cmd %d: HW reboot ack barker\n",
476                          opcode);
477                 goto error_reboot_ack;
478         }
479         result = 0;
480         if (flags & I2400M_BM_CMD_RAW)
481                 goto out_raw;
482         ack->data_size = le32_to_cpu(ack->data_size);
483         ack->target_addr = le32_to_cpu(ack->target_addr);
484         ack->block_checksum = le32_to_cpu(ack->block_checksum);
485         d_printf(5, dev, "boot-mode cmd %d: notification for opcode %u "
486                  "response %u csum %u rr %u da %u\n",
487                  opcode, i2400m_brh_get_opcode(ack),
488                  i2400m_brh_get_response(ack),
489                  i2400m_brh_get_use_checksum(ack),
490                  i2400m_brh_get_response_required(ack),
491                  i2400m_brh_get_direct_access(ack));
492         result = -EIO;
493         if (i2400m_brh_get_signature(ack) != 0xcbbc) {
494                 dev_err(dev, "boot-mode cmd %d: HW BUG? wrong signature "
495                         "0x%04x\n", opcode, i2400m_brh_get_signature(ack));
496                 goto error_ack_signature;
497         }
498         if (opcode != -1 && opcode != i2400m_brh_get_opcode(ack)) {
499                 dev_err(dev, "boot-mode cmd %d: HW BUG? "
500                         "received response for opcode %u, expected %u\n",
501                         opcode, i2400m_brh_get_opcode(ack), opcode);
502                 goto error_ack_opcode;
503         }
504         if (i2400m_brh_get_response(ack) != 0) {        /* failed? */
505                 dev_err(dev, "boot-mode cmd %d: error; hw response %u\n",
506                         opcode, i2400m_brh_get_response(ack));
507                 goto error_ack_failed;
508         }
509         if (ack_size < ack->data_size + sizeof(*ack)) {
510                 dev_err(dev, "boot-mode cmd %d: SW BUG "
511                         "driver provided only %zu bytes for %zu bytes "
512                         "of data\n", opcode, ack_size,
513                         (size_t) le32_to_cpu(ack->data_size) + sizeof(*ack));
514                 goto error_ack_short_buffer;
515         }
516         result = ack_size;
517         /* Don't you love this stack of empty targets? Well, I don't
518          * either, but it helps track exactly who comes in here and
519          * why :) */
520 error_ack_short_buffer:
521 error_ack_failed:
522 error_ack_opcode:
523 error_ack_signature:
524 out_raw:
525 error_reboot_ack:
526 error_reboot:
527 error_ack_short:
528         d_fnend(8, dev, "(i2400m %p opcode %d ack %p size %zu) = %d\n",
529                 i2400m, opcode, ack, ack_size, (int) result);
530         return result;
531 }
532
533
534 /**
535  * i2400m_bm_cmd - Execute a boot mode command
536  *
537  * @cmd: buffer containing the command data (pointing at the header).
538  *     This data can be ANYWHERE (for USB, we will copy it to an
539  *     specific buffer). Make sure everything is in proper little
540  *     endian.
541  *
542  *     A raw buffer can be also sent, just cast it and set flags to
543  *     I2400M_BM_CMD_RAW.
544  *
545  *     This function will generate a checksum for you if the
546  *     checksum bit in the command is set (unless I2400M_BM_CMD_RAW
547  *     is set).
548  *
549  *     You can use the i2400m->bm_cmd_buf to stage your commands and
550  *     send them.
551  *
552  *     If NULL, no command is sent (we just wait for an ack).
553  *
554  * @cmd_size: size of the command. Will be auto padded to the
555  *     bus-specific drivers padding requirements.
556  *
557  * @ack: buffer where to place the acknowledgement. If it is a regular
558  *     command response, all fields will be returned with the right,
559  *     native endianess.
560  *
561  *     You *cannot* use i2400m->bm_ack_buf for this buffer.
562  *
563  * @ack_size: size of @ack, 16 aligned; you need to provide at least
564  *     sizeof(*ack) bytes and then enough to contain the return data
565  *     from the command
566  *
567  * @flags: see I2400M_BM_CMD_* above.
568  *
569  * @returns: bytes received by the notification; if < 0, an errno code
570  *     denoting an error or:
571  *
572  *     -ERESTARTSYS  The device has rebooted
573  *
574  * Executes a boot-mode command and waits for a response, doing basic
575  * validation on it; if a zero length response is received, it retries
576  * waiting for a response until a non-zero one is received (timing out
577  * after %I2400M_BOOT_RETRIES retries).
578  */
579 static
580 ssize_t i2400m_bm_cmd(struct i2400m *i2400m,
581                       const struct i2400m_bootrom_header *cmd, size_t cmd_size,
582                       struct i2400m_bootrom_header *ack, size_t ack_size,
583                       int flags)
584 {
585         ssize_t result = -ENOMEM, rx_bytes;
586         struct device *dev = i2400m_dev(i2400m);
587         int opcode = cmd == NULL ? -1 : i2400m_brh_get_opcode(cmd);
588
589         d_fnstart(6, dev, "(i2400m %p cmd %p size %zu ack %p size %zu)\n",
590                   i2400m, cmd, cmd_size, ack, ack_size);
591         BUG_ON(ack_size < sizeof(*ack));
592         BUG_ON(i2400m->boot_mode == 0);
593
594         if (cmd != NULL) {              /* send the command */
595                 result = i2400m->bus_bm_cmd_send(i2400m, cmd, cmd_size, flags);
596                 if (result < 0)
597                         goto error_cmd_send;
598                 if ((flags & I2400M_BM_CMD_RAW) == 0)
599                         d_printf(5, dev,
600                                  "boot-mode cmd %d csum %u rr %u da %u: "
601                                  "addr 0x%04x size %u block csum 0x%04x\n",
602                                  opcode, i2400m_brh_get_use_checksum(cmd),
603                                  i2400m_brh_get_response_required(cmd),
604                                  i2400m_brh_get_direct_access(cmd),
605                                  cmd->target_addr, cmd->data_size,
606                                  cmd->block_checksum);
607         }
608         result = i2400m->bus_bm_wait_for_ack(i2400m, ack, ack_size);
609         if (result < 0) {
610                 dev_err(dev, "boot-mode cmd %d: error waiting for an ack: %d\n",
611                         opcode, (int) result);  /* bah, %zd doesn't work */
612                 goto error_wait_for_ack;
613         }
614         rx_bytes = result;
615         /* verify the ack and read more if necessary [result is the
616          * final amount of bytes we get in the ack]  */
617         result = __i2400m_bm_ack_verify(i2400m, opcode, ack, ack_size, flags);
618         if (result < 0)
619                 goto error_bad_ack;
620         /* Don't you love this stack of empty targets? Well, I don't
621          * either, but it helps track exactly who comes in here and
622          * why :) */
623         result = rx_bytes;
624 error_bad_ack:
625 error_wait_for_ack:
626 error_cmd_send:
627         d_fnend(6, dev, "(i2400m %p cmd %p size %zu ack %p size %zu) = %d\n",
628                 i2400m, cmd, cmd_size, ack, ack_size, (int) result);
629         return result;
630 }
631
632
633 /**
634  * i2400m_download_chunk - write a single chunk of data to the device's memory
635  *
636  * @i2400m: device descriptor
637  * @buf: the buffer to write
638  * @buf_len: length of the buffer to write
639  * @addr: address in the device memory space
640  * @direct: bootrom write mode
641  * @do_csum: should a checksum validation be performed
642  */
643 static int i2400m_download_chunk(struct i2400m *i2400m, const void *chunk,
644                                  size_t __chunk_len, unsigned long addr,
645                                  unsigned int direct, unsigned int do_csum)
646 {
647         int ret;
648         size_t chunk_len = ALIGN(__chunk_len, I2400M_PL_ALIGN);
649         struct device *dev = i2400m_dev(i2400m);
650         struct {
651                 struct i2400m_bootrom_header cmd;
652                 u8 cmd_payload[chunk_len];
653         } __attribute__((packed)) *buf;
654         struct i2400m_bootrom_header ack;
655
656         d_fnstart(5, dev, "(i2400m %p chunk %p __chunk_len %zu addr 0x%08lx "
657                   "direct %u do_csum %u)\n", i2400m, chunk, __chunk_len,
658                   addr, direct, do_csum);
659         buf = i2400m->bm_cmd_buf;
660         memcpy(buf->cmd_payload, chunk, __chunk_len);
661         memset(buf->cmd_payload + __chunk_len, 0xad, chunk_len - __chunk_len);
662
663         buf->cmd.command = i2400m_brh_command(I2400M_BRH_WRITE,
664                                               __chunk_len & 0x3 ? 0 : do_csum,
665                                               __chunk_len & 0xf ? 0 : direct);
666         buf->cmd.target_addr = cpu_to_le32(addr);
667         buf->cmd.data_size = cpu_to_le32(__chunk_len);
668         ret = i2400m_bm_cmd(i2400m, &buf->cmd, sizeof(buf->cmd) + chunk_len,
669                             &ack, sizeof(ack), 0);
670         if (ret >= 0)
671                 ret = 0;
672         d_fnend(5, dev, "(i2400m %p chunk %p __chunk_len %zu addr 0x%08lx "
673                 "direct %u do_csum %u) = %d\n", i2400m, chunk, __chunk_len,
674                 addr, direct, do_csum, ret);
675         return ret;
676 }
677
678
679 /*
680  * Download a BCF file's sections to the device
681  *
682  * @i2400m: device descriptor
683  * @bcf: pointer to firmware data (first header followed by the
684  *     payloads). Assumed verified and consistent.
685  * @bcf_len: length (in bytes) of the @bcf buffer.
686  *
687  * Returns: < 0 errno code on error or the offset to the jump instruction.
688  *
689  * Given a BCF file, downloads each section (a command and a payload)
690  * to the device's address space. Actually, it just executes each
691  * command i the BCF file.
692  *
693  * The section size has to be aligned to 4 bytes AND the padding has
694  * to be taken from the firmware file, as the signature takes it into
695  * account.
696  */
697 static
698 ssize_t i2400m_dnload_bcf(struct i2400m *i2400m,
699                           const struct i2400m_bcf_hdr *bcf, size_t bcf_len)
700 {
701         ssize_t ret;
702         struct device *dev = i2400m_dev(i2400m);
703         size_t offset,          /* iterator offset */
704                 data_size,      /* Size of the data payload */
705                 section_size,   /* Size of the whole section (cmd + payload) */
706                 section = 1;
707         const struct i2400m_bootrom_header *bh;
708         struct i2400m_bootrom_header ack;
709
710         d_fnstart(3, dev, "(i2400m %p bcf %p bcf_len %zu)\n",
711                   i2400m, bcf, bcf_len);
712         /* Iterate over the command blocks in the BCF file that start
713          * after the header */
714         offset = le32_to_cpu(bcf->header_len) * sizeof(u32);
715         while (1) {     /* start sending the file */
716                 bh = (void *) bcf + offset;
717                 data_size = le32_to_cpu(bh->data_size);
718                 section_size = ALIGN(sizeof(*bh) + data_size, 4);
719                 d_printf(7, dev,
720                          "downloading section #%zu (@%zu %zu B) to 0x%08x\n",
721                          section, offset, sizeof(*bh) + data_size,
722                          le32_to_cpu(bh->target_addr));
723                 /*
724                  * We look for JUMP cmd from the bootmode header,
725                  * either I2400M_BRH_SIGNED_JUMP for secure boot
726                  * or I2400M_BRH_JUMP for unsecure boot, the last chunk
727                  * should be the bootmode header with JUMP cmd.
728                  */
729                 if (i2400m_brh_get_opcode(bh) == I2400M_BRH_SIGNED_JUMP ||
730                         i2400m_brh_get_opcode(bh) == I2400M_BRH_JUMP) {
731                         d_printf(5, dev,  "jump found @%zu\n", offset);
732                         break;
733                 }
734                 if (offset + section_size > bcf_len) {
735                         dev_err(dev, "fw %s: bad section #%zu, "
736                                 "end (@%zu) beyond EOF (@%zu)\n",
737                                 i2400m->fw_name, section,
738                                 offset + section_size,  bcf_len);
739                         ret = -EINVAL;
740                         goto error_section_beyond_eof;
741                 }
742                 __i2400m_msleep(20);
743                 ret = i2400m_bm_cmd(i2400m, bh, section_size,
744                                     &ack, sizeof(ack), I2400M_BM_CMD_RAW);
745                 if (ret < 0) {
746                         dev_err(dev, "fw %s: section #%zu (@%zu %zu B) "
747                                 "failed %d\n", i2400m->fw_name, section,
748                                 offset, sizeof(*bh) + data_size, (int) ret);
749                         goto error_send;
750                 }
751                 offset += section_size;
752                 section++;
753         }
754         ret = offset;
755 error_section_beyond_eof:
756 error_send:
757         d_fnend(3, dev, "(i2400m %p bcf %p bcf_len %zu) = %d\n",
758                 i2400m, bcf, bcf_len, (int) ret);
759         return ret;
760 }
761
762
763 /*
764  * Indicate if the device emitted a reboot barker that indicates
765  * "signed boot"
766  */
767 static
768 unsigned i2400m_boot_is_signed(struct i2400m *i2400m)
769 {
770         return likely(i2400m->sboot);
771 }
772
773
774 /*
775  * Do the final steps of uploading firmware
776  *
777  * @bcf_hdr: BCF header we are actually using
778  * @bcf: pointer to the firmware image (which matches the first header
779  *     that is followed by the actual payloads).
780  * @offset: [byte] offset into @bcf for the command we need to send.
781  *
782  * Depending on the boot mode (signed vs non-signed), different
783  * actions need to be taken.
784  */
785 static
786 int i2400m_dnload_finalize(struct i2400m *i2400m,
787                            const struct i2400m_bcf_hdr *bcf_hdr,
788                            const struct i2400m_bcf_hdr *bcf, size_t offset)
789 {
790         int ret = 0;
791         struct device *dev = i2400m_dev(i2400m);
792         struct i2400m_bootrom_header *cmd, ack;
793         struct {
794                 struct i2400m_bootrom_header cmd;
795                 u8 cmd_pl[0];
796         } __attribute__((packed)) *cmd_buf;
797         size_t signature_block_offset, signature_block_size;
798
799         d_fnstart(3, dev, "offset %zu\n", offset);
800         cmd = (void *) bcf + offset;
801         if (i2400m_boot_is_signed(i2400m) == 0) {
802                 struct i2400m_bootrom_header jump_ack;
803                 d_printf(1, dev, "unsecure boot, jumping to 0x%08x\n",
804                         le32_to_cpu(cmd->target_addr));
805                 cmd_buf = i2400m->bm_cmd_buf;
806                 memcpy(&cmd_buf->cmd, cmd, sizeof(*cmd));
807                 cmd = &cmd_buf->cmd;
808                 /* now cmd points to the actual bootrom_header in cmd_buf */
809                 i2400m_brh_set_opcode(cmd, I2400M_BRH_JUMP);
810                 cmd->data_size = 0;
811                 ret = i2400m_bm_cmd(i2400m, cmd, sizeof(*cmd),
812                                     &jump_ack, sizeof(jump_ack), 0);
813         } else {
814                 d_printf(1, dev, "secure boot, jumping to 0x%08x\n",
815                          le32_to_cpu(cmd->target_addr));
816                 cmd_buf = i2400m->bm_cmd_buf;
817                 memcpy(&cmd_buf->cmd, cmd, sizeof(*cmd));
818                 signature_block_offset =
819                         sizeof(*bcf_hdr)
820                         + le32_to_cpu(bcf_hdr->key_size) * sizeof(u32)
821                         + le32_to_cpu(bcf_hdr->exponent_size) * sizeof(u32);
822                 signature_block_size =
823                         le32_to_cpu(bcf_hdr->modulus_size) * sizeof(u32);
824                 memcpy(cmd_buf->cmd_pl,
825                        (void *) bcf_hdr + signature_block_offset,
826                        signature_block_size);
827                 ret = i2400m_bm_cmd(i2400m, &cmd_buf->cmd,
828                                     sizeof(cmd_buf->cmd) + signature_block_size,
829                                     &ack, sizeof(ack), I2400M_BM_CMD_RAW);
830         }
831         d_fnend(3, dev, "returning %d\n", ret);
832         return ret;
833 }
834
835
836 /**
837  * i2400m_bootrom_init - Reboots a powered device into boot mode
838  *
839  * @i2400m: device descriptor
840  * @flags:
841  *      I2400M_BRI_SOFT: a reboot barker has been seen
842  *          already, so don't wait for it.
843  *
844  *      I2400M_BRI_NO_REBOOT: Don't send a reboot command, but wait
845  *          for a reboot barker notification. This is a one shot; if
846  *          the state machine needs to send a reboot command it will.
847  *
848  * Returns:
849  *
850  *     < 0 errno code on error, 0 if ok.
851  *
852  * Description:
853  *
854  * Tries hard enough to put the device in boot-mode. There are two
855  * main phases to this:
856  *
857  * a. (1) send a reboot command and (2) get a reboot barker
858  *
859  * b. (1) echo/ack the reboot sending the reboot barker back and (2)
860  *        getting an ack barker in return
861  *
862  * We want to skip (a) in some cases [soft]. The state machine is
863  * horrible, but it is basically: on each phase, send what has to be
864  * sent (if any), wait for the answer and act on the answer. We might
865  * have to backtrack and retry, so we keep a max tries counter for
866  * that.
867  *
868  * It sucks because we don't know ahead of time which is going to be
869  * the reboot barker (the device might send different ones depending
870  * on its EEPROM config) and once the device reboots and waits for the
871  * echo/ack reboot barker being sent back, it doesn't understand
872  * anything else. So we can be left at the point where we don't know
873  * what to send to it -- cold reset and bus reset seem to have little
874  * effect. So the function iterates (in this case) through all the
875  * known barkers and tries them all until an ACK is
876  * received. Otherwise, it gives up.
877  *
878  * If we get a timeout after sending a warm reset, we do it again.
879  */
880 int i2400m_bootrom_init(struct i2400m *i2400m, enum i2400m_bri flags)
881 {
882         int result;
883         struct device *dev = i2400m_dev(i2400m);
884         struct i2400m_bootrom_header *cmd;
885         struct i2400m_bootrom_header ack;
886         int count = i2400m->bus_bm_retries;
887         int ack_timeout_cnt = 1;
888         unsigned i;
889
890         BUILD_BUG_ON(sizeof(*cmd) != sizeof(i2400m_barker_db[0].data));
891         BUILD_BUG_ON(sizeof(ack) != sizeof(i2400m_ACK_BARKER));
892
893         d_fnstart(4, dev, "(i2400m %p flags 0x%08x)\n", i2400m, flags);
894         result = -ENOMEM;
895         cmd = i2400m->bm_cmd_buf;
896         if (flags & I2400M_BRI_SOFT)
897                 goto do_reboot_ack;
898 do_reboot:
899         ack_timeout_cnt = 1;
900         if (--count < 0)
901                 goto error_timeout;
902         d_printf(4, dev, "device reboot: reboot command [%d # left]\n",
903                  count);
904         if ((flags & I2400M_BRI_NO_REBOOT) == 0)
905                 i2400m_reset(i2400m, I2400M_RT_WARM);
906         result = i2400m_bm_cmd(i2400m, NULL, 0, &ack, sizeof(ack),
907                                I2400M_BM_CMD_RAW);
908         flags &= ~I2400M_BRI_NO_REBOOT;
909         switch (result) {
910         case -ERESTARTSYS:
911                 /*
912                  * at this point, i2400m_bm_cmd(), through
913                  * __i2400m_bm_ack_process(), has updated
914                  * i2400m->barker and we are good to go.
915                  */
916                 d_printf(4, dev, "device reboot: got reboot barker\n");
917                 break;
918         case -EISCONN:  /* we don't know how it got here...but we follow it */
919                 d_printf(4, dev, "device reboot: got ack barker - whatever\n");
920                 goto do_reboot;
921         case -ETIMEDOUT:
922                 /*
923                  * Device has timed out, we might be in boot mode
924                  * already and expecting an ack; if we don't know what
925                  * the barker is, we just send them all. Cold reset
926                  * and bus reset don't work. Beats me.
927                  */
928                 if (i2400m->barker != NULL) {
929                         dev_err(dev, "device boot: reboot barker timed out, "
930                                 "trying (set) %08x echo/ack\n",
931                                 le32_to_cpu(i2400m->barker->data[0]));
932                         goto do_reboot_ack;
933                 }
934                 for (i = 0; i < i2400m_barker_db_used; i++) {
935                         struct i2400m_barker_db *barker = &i2400m_barker_db[i];
936                         memcpy(cmd, barker->data, sizeof(barker->data));
937                         result = i2400m_bm_cmd(i2400m, cmd, sizeof(*cmd),
938                                                &ack, sizeof(ack),
939                                                I2400M_BM_CMD_RAW);
940                         if (result == -EISCONN) {
941                                 dev_warn(dev, "device boot: got ack barker "
942                                          "after sending echo/ack barker "
943                                          "#%d/%08x; rebooting j.i.c.\n",
944                                          i, le32_to_cpu(barker->data[0]));
945                                 flags &= ~I2400M_BRI_NO_REBOOT;
946                                 goto do_reboot;
947                         }
948                 }
949                 dev_err(dev, "device boot: tried all the echo/acks, could "
950                         "not get device to respond; giving up");
951                 result = -ESHUTDOWN;
952         case -EPROTO:
953         case -ESHUTDOWN:        /* dev is gone */
954         case -EINTR:            /* user cancelled */
955                 goto error_dev_gone;
956         default:
957                 dev_err(dev, "device reboot: error %d while waiting "
958                         "for reboot barker - rebooting\n", result);
959                 d_dump(1, dev, &ack, result);
960                 goto do_reboot;
961         }
962         /* At this point we ack back with 4 REBOOT barkers and expect
963          * 4 ACK barkers. This is ugly, as we send a raw command --
964          * hence the cast. _bm_cmd() will catch the reboot ack
965          * notification and report it as -EISCONN. */
966 do_reboot_ack:
967         d_printf(4, dev, "device reboot ack: sending ack [%d # left]\n", count);
968         memcpy(cmd, i2400m->barker->data, sizeof(i2400m->barker->data));
969         result = i2400m_bm_cmd(i2400m, cmd, sizeof(*cmd),
970                                &ack, sizeof(ack), I2400M_BM_CMD_RAW);
971         switch (result) {
972         case -ERESTARTSYS:
973                 d_printf(4, dev, "reboot ack: got reboot barker - retrying\n");
974                 if (--count < 0)
975                         goto error_timeout;
976                 goto do_reboot_ack;
977         case -EISCONN:
978                 d_printf(4, dev, "reboot ack: got ack barker - good\n");
979                 break;
980         case -ETIMEDOUT:        /* no response, maybe it is the other type? */
981                 if (ack_timeout_cnt-- < 0) {
982                         d_printf(4, dev, "reboot ack timedout: retrying\n");
983                         goto do_reboot_ack;
984                 } else {
985                         dev_err(dev, "reboot ack timedout too long: "
986                                 "trying reboot\n");
987                         goto do_reboot;
988                 }
989                 break;
990         case -EPROTO:
991         case -ESHUTDOWN:        /* dev is gone */
992                 goto error_dev_gone;
993         default:
994                 dev_err(dev, "device reboot ack: error %d while waiting for "
995                         "reboot ack barker - rebooting\n", result);
996                 goto do_reboot;
997         }
998         d_printf(2, dev, "device reboot ack: got ack barker - boot done\n");
999         result = 0;
1000 exit_timeout:
1001 error_dev_gone:
1002         d_fnend(4, dev, "(i2400m %p flags 0x%08x) = %d\n",
1003                 i2400m, flags, result);
1004         return result;
1005
1006 error_timeout:
1007         dev_err(dev, "Timed out waiting for reboot ack\n");
1008         result = -ETIMEDOUT;
1009         goto exit_timeout;
1010 }
1011
1012
1013 /*
1014  * Read the MAC addr
1015  *
1016  * The position this function reads is fixed in device memory and
1017  * always available, even without firmware.
1018  *
1019  * Note we specify we want to read only six bytes, but provide space
1020  * for 16, as we always get it rounded up.
1021  */
1022 int i2400m_read_mac_addr(struct i2400m *i2400m)
1023 {
1024         int result;
1025         struct device *dev = i2400m_dev(i2400m);
1026         struct net_device *net_dev = i2400m->wimax_dev.net_dev;
1027         struct i2400m_bootrom_header *cmd;
1028         struct {
1029                 struct i2400m_bootrom_header ack;
1030                 u8 ack_pl[16];
1031         } __attribute__((packed)) ack_buf;
1032
1033         d_fnstart(5, dev, "(i2400m %p)\n", i2400m);
1034         cmd = i2400m->bm_cmd_buf;
1035         cmd->command = i2400m_brh_command(I2400M_BRH_READ, 0, 1);
1036         cmd->target_addr = cpu_to_le32(0x00203fe8);
1037         cmd->data_size = cpu_to_le32(6);
1038         result = i2400m_bm_cmd(i2400m, cmd, sizeof(*cmd),
1039                                &ack_buf.ack, sizeof(ack_buf), 0);
1040         if (result < 0) {
1041                 dev_err(dev, "BM: read mac addr failed: %d\n", result);
1042                 goto error_read_mac;
1043         }
1044         d_printf(2, dev,
1045                  "mac addr is %02x:%02x:%02x:%02x:%02x:%02x\n",
1046                  ack_buf.ack_pl[0], ack_buf.ack_pl[1],
1047                  ack_buf.ack_pl[2], ack_buf.ack_pl[3],
1048                  ack_buf.ack_pl[4], ack_buf.ack_pl[5]);
1049         if (i2400m->bus_bm_mac_addr_impaired == 1) {
1050                 ack_buf.ack_pl[0] = 0x00;
1051                 ack_buf.ack_pl[1] = 0x16;
1052                 ack_buf.ack_pl[2] = 0xd3;
1053                 get_random_bytes(&ack_buf.ack_pl[3], 3);
1054                 dev_err(dev, "BM is MAC addr impaired, faking MAC addr to "
1055                         "mac addr is %02x:%02x:%02x:%02x:%02x:%02x\n",
1056                         ack_buf.ack_pl[0], ack_buf.ack_pl[1],
1057                         ack_buf.ack_pl[2], ack_buf.ack_pl[3],
1058                         ack_buf.ack_pl[4], ack_buf.ack_pl[5]);
1059                 result = 0;
1060         }
1061         net_dev->addr_len = ETH_ALEN;
1062         memcpy(net_dev->perm_addr, ack_buf.ack_pl, ETH_ALEN);
1063         memcpy(net_dev->dev_addr, ack_buf.ack_pl, ETH_ALEN);
1064 error_read_mac:
1065         d_fnend(5, dev, "(i2400m %p) = %d\n", i2400m, result);
1066         return result;
1067 }
1068
1069
1070 /*
1071  * Initialize a non signed boot
1072  *
1073  * This implies sending some magic values to the device's memory. Note
1074  * we convert the values to little endian in the same array
1075  * declaration.
1076  */
1077 static
1078 int i2400m_dnload_init_nonsigned(struct i2400m *i2400m)
1079 {
1080         unsigned i = 0;
1081         int ret = 0;
1082         struct device *dev = i2400m_dev(i2400m);
1083         d_fnstart(5, dev, "(i2400m %p)\n", i2400m);
1084         if (i2400m->bus_bm_pokes_table) {
1085                 while (i2400m->bus_bm_pokes_table[i].address) {
1086                         ret = i2400m_download_chunk(
1087                                 i2400m,
1088                                 &i2400m->bus_bm_pokes_table[i].data,
1089                                 sizeof(i2400m->bus_bm_pokes_table[i].data),
1090                                 i2400m->bus_bm_pokes_table[i].address, 1, 1);
1091                         if (ret < 0)
1092                                 break;
1093                         i++;
1094                 }
1095         }
1096         d_fnend(5, dev, "(i2400m %p) = %d\n", i2400m, ret);
1097         return ret;
1098 }
1099
1100
1101 /*
1102  * Initialize the signed boot process
1103  *
1104  * @i2400m: device descriptor
1105  *
1106  * @bcf_hdr: pointer to the firmware header; assumes it is fully in
1107  *     memory (it has gone through basic validation).
1108  *
1109  * Returns: 0 if ok, < 0 errno code on error, -ERESTARTSYS if the hw
1110  *     rebooted.
1111  *
1112  * This writes the firmware BCF header to the device using the
1113  * HASH_PAYLOAD_ONLY command.
1114  */
1115 static
1116 int i2400m_dnload_init_signed(struct i2400m *i2400m,
1117                               const struct i2400m_bcf_hdr *bcf_hdr)
1118 {
1119         int ret;
1120         struct device *dev = i2400m_dev(i2400m);
1121         struct {
1122                 struct i2400m_bootrom_header cmd;
1123                 struct i2400m_bcf_hdr cmd_pl;
1124         } __attribute__((packed)) *cmd_buf;
1125         struct i2400m_bootrom_header ack;
1126
1127         d_fnstart(5, dev, "(i2400m %p bcf_hdr %p)\n", i2400m, bcf_hdr);
1128         cmd_buf = i2400m->bm_cmd_buf;
1129         cmd_buf->cmd.command =
1130                 i2400m_brh_command(I2400M_BRH_HASH_PAYLOAD_ONLY, 0, 0);
1131         cmd_buf->cmd.target_addr = 0;
1132         cmd_buf->cmd.data_size = cpu_to_le32(sizeof(cmd_buf->cmd_pl));
1133         memcpy(&cmd_buf->cmd_pl, bcf_hdr, sizeof(*bcf_hdr));
1134         ret = i2400m_bm_cmd(i2400m, &cmd_buf->cmd, sizeof(*cmd_buf),
1135                             &ack, sizeof(ack), 0);
1136         if (ret >= 0)
1137                 ret = 0;
1138         d_fnend(5, dev, "(i2400m %p bcf_hdr %p) = %d\n", i2400m, bcf_hdr, ret);
1139         return ret;
1140 }
1141
1142
1143 /*
1144  * Initialize the firmware download at the device size
1145  *
1146  * Multiplex to the one that matters based on the device's mode
1147  * (signed or non-signed).
1148  */
1149 static
1150 int i2400m_dnload_init(struct i2400m *i2400m,
1151                        const struct i2400m_bcf_hdr *bcf_hdr)
1152 {
1153         int result;
1154         struct device *dev = i2400m_dev(i2400m);
1155
1156         if (i2400m_boot_is_signed(i2400m)) {
1157                 d_printf(1, dev, "signed boot\n");
1158                 result = i2400m_dnload_init_signed(i2400m, bcf_hdr);
1159                 if (result == -ERESTARTSYS)
1160                         return result;
1161                 if (result < 0)
1162                         dev_err(dev, "firmware %s: signed boot download "
1163                                 "initialization failed: %d\n",
1164                                 i2400m->fw_name, result);
1165         } else {
1166                 /* non-signed boot process without pokes */
1167                 d_printf(1, dev, "non-signed boot\n");
1168                 result = i2400m_dnload_init_nonsigned(i2400m);
1169                 if (result == -ERESTARTSYS)
1170                         return result;
1171                 if (result < 0)
1172                         dev_err(dev, "firmware %s: non-signed download "
1173                                 "initialization failed: %d\n",
1174                                 i2400m->fw_name, result);
1175         }
1176         return result;
1177 }
1178
1179
1180 /*
1181  * Run consistency tests on the firmware file and load up headers
1182  *
1183  * Check for the firmware being made for the i2400m device,
1184  * etc...These checks are mostly informative, as the device will make
1185  * them too; but the driver's response is more informative on what
1186  * went wrong.
1187  *
1188  * This will also look at all the headers present on the firmware
1189  * file, and update i2400m->fw_bcf_hdr to point to them.
1190  */
1191 static
1192 int i2400m_fw_hdr_check(struct i2400m *i2400m,
1193                         const struct i2400m_bcf_hdr *bcf_hdr,
1194                         size_t index, size_t offset)
1195 {
1196         struct device *dev = i2400m_dev(i2400m);
1197
1198         unsigned module_type, header_len, major_version, minor_version,
1199                 module_id, module_vendor, date, size;
1200
1201         module_type = bcf_hdr->module_type;
1202         header_len = sizeof(u32) * le32_to_cpu(bcf_hdr->header_len);
1203         major_version = (le32_to_cpu(bcf_hdr->header_version) & 0xffff0000)
1204                 >> 16;
1205         minor_version = le32_to_cpu(bcf_hdr->header_version) & 0x0000ffff;
1206         module_id = le32_to_cpu(bcf_hdr->module_id);
1207         module_vendor = le32_to_cpu(bcf_hdr->module_vendor);
1208         date = le32_to_cpu(bcf_hdr->date);
1209         size = sizeof(u32) * le32_to_cpu(bcf_hdr->size);
1210
1211         d_printf(1, dev, "firmware %s #%zd@%08zx: BCF header "
1212                  "type:vendor:id 0x%x:%x:%x v%u.%u (%u/%u B) built %08x\n",
1213                  i2400m->fw_name, index, offset,
1214                  module_type, module_vendor, module_id,
1215                  major_version, minor_version, header_len, size, date);
1216
1217         /* Hard errors */
1218         if (major_version != 1) {
1219                 dev_err(dev, "firmware %s #%zd@%08zx: major header version "
1220                         "v%u.%u not supported\n",
1221                         i2400m->fw_name, index, offset,
1222                         major_version, minor_version);
1223                 return -EBADF;
1224         }
1225
1226         if (module_type != 6) {         /* built for the right hardware? */
1227                 dev_err(dev, "firmware %s #%zd@%08zx: unexpected module "
1228                         "type 0x%x; aborting\n",
1229                         i2400m->fw_name, index, offset,
1230                         module_type);
1231                 return -EBADF;
1232         }
1233
1234         if (module_vendor != 0x8086) {
1235                 dev_err(dev, "firmware %s #%zd@%08zx: unexpected module "
1236                         "vendor 0x%x; aborting\n",
1237                         i2400m->fw_name, index, offset, module_vendor);
1238                 return -EBADF;
1239         }
1240
1241         if (date < 0x20080300)
1242                 dev_warn(dev, "firmware %s #%zd@%08zx: build date %08x "
1243                          "too old; unsupported\n",
1244                          i2400m->fw_name, index, offset, date);
1245         return 0;
1246 }
1247
1248
1249 /*
1250  * Run consistency tests on the firmware file and load up headers
1251  *
1252  * Check for the firmware being made for the i2400m device,
1253  * etc...These checks are mostly informative, as the device will make
1254  * them too; but the driver's response is more informative on what
1255  * went wrong.
1256  *
1257  * This will also look at all the headers present on the firmware
1258  * file, and update i2400m->fw_hdrs to point to them.
1259  */
1260 static
1261 int i2400m_fw_check(struct i2400m *i2400m, const void *bcf, size_t bcf_size)
1262 {
1263         int result;
1264         struct device *dev = i2400m_dev(i2400m);
1265         size_t headers = 0;
1266         const struct i2400m_bcf_hdr *bcf_hdr;
1267         const void *itr, *next, *top;
1268         size_t slots = 0, used_slots = 0;
1269
1270         for (itr = bcf, top = itr + bcf_size;
1271              itr < top;
1272              headers++, itr = next) {
1273                 size_t leftover, offset, header_len, size;
1274
1275                 leftover = top - itr;
1276                 offset = itr - (const void *) bcf;
1277                 if (leftover <= sizeof(*bcf_hdr)) {
1278                         dev_err(dev, "firmware %s: %zu B left at @%zx, "
1279                                 "not enough for BCF header\n",
1280                                 i2400m->fw_name, leftover, offset);
1281                         break;
1282                 }
1283                 bcf_hdr = itr;
1284                 /* Only the first header is supposed to be followed by
1285                  * payload */
1286                 header_len = sizeof(u32) * le32_to_cpu(bcf_hdr->header_len);
1287                 size = sizeof(u32) * le32_to_cpu(bcf_hdr->size);
1288                 if (headers == 0)
1289                         next = itr + size;
1290                 else
1291                         next = itr + header_len;
1292
1293                 result = i2400m_fw_hdr_check(i2400m, bcf_hdr, headers, offset);
1294                 if (result < 0)
1295                         continue;
1296                 if (used_slots + 1 >= slots) {
1297                         /* +1 -> we need to account for the one we'll
1298                          * occupy and at least an extra one for
1299                          * always being NULL */
1300                         result = i2400m_zrealloc_2x(
1301                                 (void **) &i2400m->fw_hdrs, &slots,
1302                                 sizeof(i2400m->fw_hdrs[0]),
1303                                 GFP_KERNEL);
1304                         if (result < 0)
1305                                 goto error_zrealloc;
1306                 }
1307                 i2400m->fw_hdrs[used_slots] = bcf_hdr;
1308                 used_slots++;
1309         }
1310         if (headers == 0) {
1311                 dev_err(dev, "firmware %s: no usable headers found\n",
1312                         i2400m->fw_name);
1313                 result = -EBADF;
1314         } else
1315                 result = 0;
1316 error_zrealloc:
1317         return result;
1318 }
1319
1320
1321 /*
1322  * Match a barker to a BCF header module ID
1323  *
1324  * The device sends a barker which tells the firmware loader which
1325  * header in the BCF file has to be used. This does the matching.
1326  */
1327 static
1328 unsigned i2400m_bcf_hdr_match(struct i2400m *i2400m,
1329                               const struct i2400m_bcf_hdr *bcf_hdr)
1330 {
1331         u32 barker = le32_to_cpu(i2400m->barker->data[0])
1332                 & 0x7fffffff;
1333         u32 module_id = le32_to_cpu(bcf_hdr->module_id)
1334                 & 0x7fffffff;   /* high bit used for something else */
1335
1336         /* special case for 5x50 */
1337         if (barker == I2400M_SBOOT_BARKER && module_id == 0)
1338                 return 1;
1339         if (module_id == barker)
1340                 return 1;
1341         return 0;
1342 }
1343
1344 static
1345 const struct i2400m_bcf_hdr *i2400m_bcf_hdr_find(struct i2400m *i2400m)
1346 {
1347         struct device *dev = i2400m_dev(i2400m);
1348         const struct i2400m_bcf_hdr **bcf_itr, *bcf_hdr;
1349         unsigned i = 0;
1350         u32 barker = le32_to_cpu(i2400m->barker->data[0]);
1351
1352         d_printf(2, dev, "finding BCF header for barker %08x\n", barker);
1353         if (barker == I2400M_NBOOT_BARKER) {
1354                 bcf_hdr = i2400m->fw_hdrs[0];
1355                 d_printf(1, dev, "using BCF header #%u/%08x for non-signed "
1356                          "barker\n", 0, le32_to_cpu(bcf_hdr->module_id));
1357                 return bcf_hdr;
1358         }
1359         for (bcf_itr = i2400m->fw_hdrs; *bcf_itr != NULL; bcf_itr++, i++) {
1360                 bcf_hdr = *bcf_itr;
1361                 if (i2400m_bcf_hdr_match(i2400m, bcf_hdr)) {
1362                         d_printf(1, dev, "hit on BCF hdr #%u/%08x\n",
1363                                  i, le32_to_cpu(bcf_hdr->module_id));
1364                         return bcf_hdr;
1365                 } else
1366                         d_printf(1, dev, "miss on BCF hdr #%u/%08x\n",
1367                                  i, le32_to_cpu(bcf_hdr->module_id));
1368         }
1369         dev_err(dev, "cannot find a matching BCF header for barker %08x\n",
1370                 barker);
1371         return NULL;
1372 }
1373
1374
1375 /*
1376  * Download the firmware to the device
1377  *
1378  * @i2400m: device descriptor
1379  * @bcf: pointer to loaded (and minimally verified for consistency)
1380  *    firmware
1381  * @bcf_size: size of the @bcf buffer (header plus payloads)
1382  *
1383  * The process for doing this is described in this file's header.
1384  *
1385  * Note we only reinitialize boot-mode if the flags say so. Some hw
1386  * iterations need it, some don't. In any case, if we loop, we always
1387  * need to reinitialize the boot room, hence the flags modification.
1388  */
1389 static
1390 int i2400m_fw_dnload(struct i2400m *i2400m, const struct i2400m_bcf_hdr *bcf,
1391                      size_t fw_size, enum i2400m_bri flags)
1392 {
1393         int ret = 0;
1394         struct device *dev = i2400m_dev(i2400m);
1395         int count = i2400m->bus_bm_retries;
1396         const struct i2400m_bcf_hdr *bcf_hdr;
1397         size_t bcf_size;
1398
1399         d_fnstart(5, dev, "(i2400m %p bcf %p fw size %zu)\n",
1400                   i2400m, bcf, fw_size);
1401         i2400m->boot_mode = 1;
1402         wmb();          /* Make sure other readers see it */
1403 hw_reboot:
1404         if (count-- == 0) {
1405                 ret = -ERESTARTSYS;
1406                 dev_err(dev, "device rebooted too many times, aborting\n");
1407                 goto error_too_many_reboots;
1408         }
1409         if (flags & I2400M_BRI_MAC_REINIT) {
1410                 ret = i2400m_bootrom_init(i2400m, flags);
1411                 if (ret < 0) {
1412                         dev_err(dev, "bootrom init failed: %d\n", ret);
1413                         goto error_bootrom_init;
1414                 }
1415         }
1416         flags |= I2400M_BRI_MAC_REINIT;
1417
1418         /*
1419          * Initialize the download, push the bytes to the device and
1420          * then jump to the new firmware. Note @ret is passed with the
1421          * offset of the jump instruction to _dnload_finalize()
1422          *
1423          * Note we need to use the BCF header in the firmware image
1424          * that matches the barker that the device sent when it
1425          * rebooted, so it has to be passed along.
1426          */
1427         ret = -EBADF;
1428         bcf_hdr = i2400m_bcf_hdr_find(i2400m);
1429         if (bcf_hdr == NULL)
1430                 goto error_bcf_hdr_find;
1431
1432         ret = i2400m_dnload_init(i2400m, bcf_hdr);
1433         if (ret == -ERESTARTSYS)
1434                 goto error_dev_rebooted;
1435         if (ret < 0)
1436                 goto error_dnload_init;
1437
1438         /*
1439          * bcf_size refers to one header size plus the fw sections size
1440          * indicated by the header,ie. if there are other extended headers
1441          * at the tail, they are not counted
1442          */
1443         bcf_size = sizeof(u32) * le32_to_cpu(bcf_hdr->size);
1444         ret = i2400m_dnload_bcf(i2400m, bcf, bcf_size);
1445         if (ret == -ERESTARTSYS)
1446                 goto error_dev_rebooted;
1447         if (ret < 0) {
1448                 dev_err(dev, "fw %s: download failed: %d\n",
1449                         i2400m->fw_name, ret);
1450                 goto error_dnload_bcf;
1451         }
1452
1453         ret = i2400m_dnload_finalize(i2400m, bcf_hdr, bcf, ret);
1454         if (ret == -ERESTARTSYS)
1455                 goto error_dev_rebooted;
1456         if (ret < 0) {
1457                 dev_err(dev, "fw %s: "
1458                         "download finalization failed: %d\n",
1459                         i2400m->fw_name, ret);
1460                 goto error_dnload_finalize;
1461         }
1462
1463         d_printf(2, dev, "fw %s successfully uploaded\n",
1464                  i2400m->fw_name);
1465         i2400m->boot_mode = 0;
1466         wmb();          /* Make sure i2400m_msg_to_dev() sees boot_mode */
1467 error_dnload_finalize:
1468 error_dnload_bcf:
1469 error_dnload_init:
1470 error_bcf_hdr_find:
1471 error_bootrom_init:
1472 error_too_many_reboots:
1473         d_fnend(5, dev, "(i2400m %p bcf %p size %zu) = %d\n",
1474                 i2400m, bcf, fw_size, ret);
1475         return ret;
1476
1477 error_dev_rebooted:
1478         dev_err(dev, "device rebooted, %d tries left\n", count);
1479         /* we got the notification already, no need to wait for it again */
1480         flags |= I2400M_BRI_SOFT;
1481         goto hw_reboot;
1482 }
1483
1484 static
1485 int i2400m_fw_bootstrap(struct i2400m *i2400m, const struct firmware *fw,
1486                         enum i2400m_bri flags)
1487 {
1488         int ret;
1489         struct device *dev = i2400m_dev(i2400m);
1490         const struct i2400m_bcf_hdr *bcf;       /* Firmware data */
1491
1492         d_fnstart(5, dev, "(i2400m %p)\n", i2400m);
1493         bcf = (void *) fw->data;
1494         ret = i2400m_fw_check(i2400m, bcf, fw->size);
1495         if (ret >= 0)
1496                 ret = i2400m_fw_dnload(i2400m, bcf, fw->size, flags);
1497         if (ret < 0)
1498                 dev_err(dev, "%s: cannot use: %d, skipping\n",
1499                         i2400m->fw_name, ret);
1500         kfree(i2400m->fw_hdrs);
1501         i2400m->fw_hdrs = NULL;
1502         d_fnend(5, dev, "(i2400m %p) = %d\n", i2400m, ret);
1503         return ret;
1504 }
1505
1506
1507 /* Refcounted container for firmware data */
1508 struct i2400m_fw {
1509         struct kref kref;
1510         const struct firmware *fw;
1511 };
1512
1513
1514 static
1515 void i2400m_fw_destroy(struct kref *kref)
1516 {
1517         struct i2400m_fw *i2400m_fw =
1518                 container_of(kref, struct i2400m_fw, kref);
1519         release_firmware(i2400m_fw->fw);
1520         kfree(i2400m_fw);
1521 }
1522
1523
1524 static
1525 struct i2400m_fw *i2400m_fw_get(struct i2400m_fw *i2400m_fw)
1526 {
1527         if (i2400m_fw != NULL && i2400m_fw != (void *) ~0)
1528                 kref_get(&i2400m_fw->kref);
1529         return i2400m_fw;
1530 }
1531
1532
1533 static
1534 void i2400m_fw_put(struct i2400m_fw *i2400m_fw)
1535 {
1536         kref_put(&i2400m_fw->kref, i2400m_fw_destroy);
1537 }
1538
1539
1540 /**
1541  * i2400m_dev_bootstrap - Bring the device to a known state and upload firmware
1542  *
1543  * @i2400m: device descriptor
1544  *
1545  * Returns: >= 0 if ok, < 0 errno code on error.
1546  *
1547  * This sets up the firmware upload environment, loads the firmware
1548  * file from disk, verifies and then calls the firmware upload process
1549  * per se.
1550  *
1551  * Can be called either from probe, or after a warm reset.  Can not be
1552  * called from within an interrupt.  All the flow in this code is
1553  * single-threade; all I/Os are synchronous.
1554  */
1555 int i2400m_dev_bootstrap(struct i2400m *i2400m, enum i2400m_bri flags)
1556 {
1557         int ret, itr;
1558         struct device *dev = i2400m_dev(i2400m);
1559         struct i2400m_fw *i2400m_fw;
1560         const struct i2400m_bcf_hdr *bcf;       /* Firmware data */
1561         const struct firmware *fw;
1562         const char *fw_name;
1563
1564         d_fnstart(5, dev, "(i2400m %p)\n", i2400m);
1565
1566         ret = -ENODEV;
1567         spin_lock(&i2400m->rx_lock);
1568         i2400m_fw = i2400m_fw_get(i2400m->fw_cached);
1569         spin_unlock(&i2400m->rx_lock);
1570         if (i2400m_fw == (void *) ~0) {
1571                 dev_err(dev, "can't load firmware now!");
1572                 goto out;
1573         } else if (i2400m_fw != NULL) {
1574                 dev_info(dev, "firmware %s: loading from cache\n",
1575                          i2400m->fw_name);
1576                 ret = i2400m_fw_bootstrap(i2400m, i2400m_fw->fw, flags);
1577                 i2400m_fw_put(i2400m_fw);
1578                 goto out;
1579         }
1580
1581         /* Load firmware files to memory. */
1582         for (itr = 0, bcf = NULL, ret = -ENOENT; ; itr++) {
1583                 fw_name = i2400m->bus_fw_names[itr];
1584                 if (fw_name == NULL) {
1585                         dev_err(dev, "Could not find a usable firmware image\n");
1586                         break;
1587                 }
1588                 d_printf(1, dev, "trying firmware %s (%d)\n", fw_name, itr);
1589                 ret = request_firmware(&fw, fw_name, dev);
1590                 if (ret < 0) {
1591                         dev_err(dev, "fw %s: cannot load file: %d\n",
1592                                 fw_name, ret);
1593                         continue;
1594                 }
1595                 i2400m->fw_name = fw_name;
1596                 ret = i2400m_fw_bootstrap(i2400m, fw, flags);
1597                 release_firmware(fw);
1598                 if (ret >= 0)   /* firmware loaded succesfully */
1599                         break;
1600                 i2400m->fw_name = NULL;
1601         }
1602 out:
1603         d_fnend(5, dev, "(i2400m %p) = %d\n", i2400m, ret);
1604         return ret;
1605 }
1606 EXPORT_SYMBOL_GPL(i2400m_dev_bootstrap);
1607
1608
1609 void i2400m_fw_cache(struct i2400m *i2400m)
1610 {
1611         int result;
1612         struct i2400m_fw *i2400m_fw;
1613         struct device *dev = i2400m_dev(i2400m);
1614
1615         /* if there is anything there, free it -- now, this'd be weird */
1616         spin_lock(&i2400m->rx_lock);
1617         i2400m_fw = i2400m->fw_cached;
1618         spin_unlock(&i2400m->rx_lock);
1619         if (i2400m_fw != NULL && i2400m_fw != (void *) ~0) {
1620                 i2400m_fw_put(i2400m_fw);
1621                 WARN(1, "%s:%u: still cached fw still present?\n",
1622                      __func__, __LINE__);
1623         }
1624
1625         if (i2400m->fw_name == NULL) {
1626                 dev_err(dev, "firmware n/a: can't cache\n");
1627                 i2400m_fw = (void *) ~0;
1628                 goto out;
1629         }
1630
1631         i2400m_fw = kzalloc(sizeof(*i2400m_fw), GFP_ATOMIC);
1632         if (i2400m_fw == NULL)
1633                 goto out;
1634         kref_init(&i2400m_fw->kref);
1635         result = request_firmware(&i2400m_fw->fw, i2400m->fw_name, dev);
1636         if (result < 0) {
1637                 dev_err(dev, "firmware %s: failed to cache: %d\n",
1638                         i2400m->fw_name, result);
1639                 kfree(i2400m_fw);
1640                 i2400m_fw = (void *) ~0;
1641         } else
1642                 dev_info(dev, "firmware %s: cached\n", i2400m->fw_name);
1643 out:
1644         spin_lock(&i2400m->rx_lock);
1645         i2400m->fw_cached = i2400m_fw;
1646         spin_unlock(&i2400m->rx_lock);
1647 }
1648
1649
1650 void i2400m_fw_uncache(struct i2400m *i2400m)
1651 {
1652         struct i2400m_fw *i2400m_fw;
1653
1654         spin_lock(&i2400m->rx_lock);
1655         i2400m_fw = i2400m->fw_cached;
1656         i2400m->fw_cached = NULL;
1657         spin_unlock(&i2400m->rx_lock);
1658
1659         if (i2400m_fw != NULL && i2400m_fw != (void *) ~0)
1660                 i2400m_fw_put(i2400m_fw);
1661 }
1662