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