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