421357831f3d41db935fe42de9ef8d190b5ad271
[linux-2.6-microblaze.git] / drivers / bluetooth / btintel.c
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  *
4  *  Bluetooth support for Intel devices
5  *
6  *  Copyright (C) 2015  Intel Corporation
7  */
8
9 #include <linux/module.h>
10 #include <linux/firmware.h>
11 #include <linux/regmap.h>
12 #include <asm/unaligned.h>
13
14 #include <net/bluetooth/bluetooth.h>
15 #include <net/bluetooth/hci_core.h>
16
17 #include "btintel.h"
18
19 #define VERSION "0.1"
20
21 #define BDADDR_INTEL            (&(bdaddr_t){{0x00, 0x8b, 0x9e, 0x19, 0x03, 0x00}})
22 #define RSA_HEADER_LEN          644
23 #define CSS_HEADER_OFFSET       8
24 #define ECDSA_OFFSET            644
25 #define ECDSA_HEADER_LEN        320
26
27 #define CMD_WRITE_BOOT_PARAMS   0xfc0e
28 struct cmd_write_boot_params {
29         u32 boot_addr;
30         u8  fw_build_num;
31         u8  fw_build_ww;
32         u8  fw_build_yy;
33 } __packed;
34
35 int btintel_check_bdaddr(struct hci_dev *hdev)
36 {
37         struct hci_rp_read_bd_addr *bda;
38         struct sk_buff *skb;
39
40         skb = __hci_cmd_sync(hdev, HCI_OP_READ_BD_ADDR, 0, NULL,
41                              HCI_INIT_TIMEOUT);
42         if (IS_ERR(skb)) {
43                 int err = PTR_ERR(skb);
44                 bt_dev_err(hdev, "Reading Intel device address failed (%d)",
45                            err);
46                 return err;
47         }
48
49         if (skb->len != sizeof(*bda)) {
50                 bt_dev_err(hdev, "Intel device address length mismatch");
51                 kfree_skb(skb);
52                 return -EIO;
53         }
54
55         bda = (struct hci_rp_read_bd_addr *)skb->data;
56
57         /* For some Intel based controllers, the default Bluetooth device
58          * address 00:03:19:9E:8B:00 can be found. These controllers are
59          * fully operational, but have the danger of duplicate addresses
60          * and that in turn can cause problems with Bluetooth operation.
61          */
62         if (!bacmp(&bda->bdaddr, BDADDR_INTEL)) {
63                 bt_dev_err(hdev, "Found Intel default device address (%pMR)",
64                            &bda->bdaddr);
65                 set_bit(HCI_QUIRK_INVALID_BDADDR, &hdev->quirks);
66         }
67
68         kfree_skb(skb);
69
70         return 0;
71 }
72 EXPORT_SYMBOL_GPL(btintel_check_bdaddr);
73
74 int btintel_enter_mfg(struct hci_dev *hdev)
75 {
76         static const u8 param[] = { 0x01, 0x00 };
77         struct sk_buff *skb;
78
79         skb = __hci_cmd_sync(hdev, 0xfc11, 2, param, HCI_CMD_TIMEOUT);
80         if (IS_ERR(skb)) {
81                 bt_dev_err(hdev, "Entering manufacturer mode failed (%ld)",
82                            PTR_ERR(skb));
83                 return PTR_ERR(skb);
84         }
85         kfree_skb(skb);
86
87         return 0;
88 }
89 EXPORT_SYMBOL_GPL(btintel_enter_mfg);
90
91 int btintel_exit_mfg(struct hci_dev *hdev, bool reset, bool patched)
92 {
93         u8 param[] = { 0x00, 0x00 };
94         struct sk_buff *skb;
95
96         /* The 2nd command parameter specifies the manufacturing exit method:
97          * 0x00: Just disable the manufacturing mode (0x00).
98          * 0x01: Disable manufacturing mode and reset with patches deactivated.
99          * 0x02: Disable manufacturing mode and reset with patches activated.
100          */
101         if (reset)
102                 param[1] |= patched ? 0x02 : 0x01;
103
104         skb = __hci_cmd_sync(hdev, 0xfc11, 2, param, HCI_CMD_TIMEOUT);
105         if (IS_ERR(skb)) {
106                 bt_dev_err(hdev, "Exiting manufacturer mode failed (%ld)",
107                            PTR_ERR(skb));
108                 return PTR_ERR(skb);
109         }
110         kfree_skb(skb);
111
112         return 0;
113 }
114 EXPORT_SYMBOL_GPL(btintel_exit_mfg);
115
116 int btintel_set_bdaddr(struct hci_dev *hdev, const bdaddr_t *bdaddr)
117 {
118         struct sk_buff *skb;
119         int err;
120
121         skb = __hci_cmd_sync(hdev, 0xfc31, 6, bdaddr, HCI_INIT_TIMEOUT);
122         if (IS_ERR(skb)) {
123                 err = PTR_ERR(skb);
124                 bt_dev_err(hdev, "Changing Intel device address failed (%d)",
125                            err);
126                 return err;
127         }
128         kfree_skb(skb);
129
130         return 0;
131 }
132 EXPORT_SYMBOL_GPL(btintel_set_bdaddr);
133
134 int btintel_set_diag(struct hci_dev *hdev, bool enable)
135 {
136         struct sk_buff *skb;
137         u8 param[3];
138         int err;
139
140         if (enable) {
141                 param[0] = 0x03;
142                 param[1] = 0x03;
143                 param[2] = 0x03;
144         } else {
145                 param[0] = 0x00;
146                 param[1] = 0x00;
147                 param[2] = 0x00;
148         }
149
150         skb = __hci_cmd_sync(hdev, 0xfc43, 3, param, HCI_INIT_TIMEOUT);
151         if (IS_ERR(skb)) {
152                 err = PTR_ERR(skb);
153                 if (err == -ENODATA)
154                         goto done;
155                 bt_dev_err(hdev, "Changing Intel diagnostic mode failed (%d)",
156                            err);
157                 return err;
158         }
159         kfree_skb(skb);
160
161 done:
162         btintel_set_event_mask(hdev, enable);
163         return 0;
164 }
165 EXPORT_SYMBOL_GPL(btintel_set_diag);
166
167 static int btintel_set_diag_mfg(struct hci_dev *hdev, bool enable)
168 {
169         int err, ret;
170
171         err = btintel_enter_mfg(hdev);
172         if (err)
173                 return err;
174
175         ret = btintel_set_diag(hdev, enable);
176
177         err = btintel_exit_mfg(hdev, false, false);
178         if (err)
179                 return err;
180
181         return ret;
182 }
183
184 static int btintel_set_diag_combined(struct hci_dev *hdev, bool enable)
185 {
186         int ret;
187
188         /* Legacy ROM device needs to be in the manufacturer mode to apply
189          * diagnostic setting
190          *
191          * This flag is set after reading the Intel version.
192          */
193         if (btintel_test_flag(hdev, INTEL_ROM_LEGACY))
194                 ret = btintel_set_diag_mfg(hdev, enable);
195         else
196                 ret = btintel_set_diag(hdev, enable);
197
198         return ret;
199 }
200
201 void btintel_hw_error(struct hci_dev *hdev, u8 code)
202 {
203         struct sk_buff *skb;
204         u8 type = 0x00;
205
206         bt_dev_err(hdev, "Hardware error 0x%2.2x", code);
207
208         skb = __hci_cmd_sync(hdev, HCI_OP_RESET, 0, NULL, HCI_INIT_TIMEOUT);
209         if (IS_ERR(skb)) {
210                 bt_dev_err(hdev, "Reset after hardware error failed (%ld)",
211                            PTR_ERR(skb));
212                 return;
213         }
214         kfree_skb(skb);
215
216         skb = __hci_cmd_sync(hdev, 0xfc22, 1, &type, HCI_INIT_TIMEOUT);
217         if (IS_ERR(skb)) {
218                 bt_dev_err(hdev, "Retrieving Intel exception info failed (%ld)",
219                            PTR_ERR(skb));
220                 return;
221         }
222
223         if (skb->len != 13) {
224                 bt_dev_err(hdev, "Exception info size mismatch");
225                 kfree_skb(skb);
226                 return;
227         }
228
229         bt_dev_err(hdev, "Exception info %s", (char *)(skb->data + 1));
230
231         kfree_skb(skb);
232 }
233 EXPORT_SYMBOL_GPL(btintel_hw_error);
234
235 int btintel_version_info(struct hci_dev *hdev, struct intel_version *ver)
236 {
237         const char *variant;
238
239         /* The hardware platform number has a fixed value of 0x37 and
240          * for now only accept this single value.
241          */
242         if (ver->hw_platform != 0x37) {
243                 bt_dev_err(hdev, "Unsupported Intel hardware platform (%u)",
244                            ver->hw_platform);
245                 return -EINVAL;
246         }
247
248         /* Check for supported iBT hardware variants of this firmware
249          * loading method.
250          *
251          * This check has been put in place to ensure correct forward
252          * compatibility options when newer hardware variants come along.
253          */
254         switch (ver->hw_variant) {
255         case 0x07:      /* WP - Legacy ROM */
256         case 0x08:      /* StP - Legacy ROM */
257         case 0x0b:      /* SfP */
258         case 0x0c:      /* WsP */
259         case 0x11:      /* JfP */
260         case 0x12:      /* ThP */
261         case 0x13:      /* HrP */
262         case 0x14:      /* CcP */
263                 break;
264         default:
265                 bt_dev_err(hdev, "Unsupported Intel hardware variant (%u)",
266                            ver->hw_variant);
267                 return -EINVAL;
268         }
269
270         switch (ver->fw_variant) {
271         case 0x01:
272                 variant = "Legacy ROM 2.5";
273                 break;
274         case 0x06:
275                 variant = "Bootloader";
276                 break;
277         case 0x22:
278                 variant = "Legacy ROM 2.x";
279                 break;
280         case 0x23:
281                 variant = "Firmware";
282                 break;
283         default:
284                 bt_dev_err(hdev, "Unsupported firmware variant(%02x)", ver->fw_variant);
285                 return -EINVAL;
286         }
287
288         bt_dev_info(hdev, "%s revision %u.%u build %u week %u %u",
289                     variant, ver->fw_revision >> 4, ver->fw_revision & 0x0f,
290                     ver->fw_build_num, ver->fw_build_ww,
291                     2000 + ver->fw_build_yy);
292
293         return 0;
294 }
295 EXPORT_SYMBOL_GPL(btintel_version_info);
296
297 int btintel_secure_send(struct hci_dev *hdev, u8 fragment_type, u32 plen,
298                         const void *param)
299 {
300         while (plen > 0) {
301                 struct sk_buff *skb;
302                 u8 cmd_param[253], fragment_len = (plen > 252) ? 252 : plen;
303
304                 cmd_param[0] = fragment_type;
305                 memcpy(cmd_param + 1, param, fragment_len);
306
307                 skb = __hci_cmd_sync(hdev, 0xfc09, fragment_len + 1,
308                                      cmd_param, HCI_INIT_TIMEOUT);
309                 if (IS_ERR(skb))
310                         return PTR_ERR(skb);
311
312                 kfree_skb(skb);
313
314                 plen -= fragment_len;
315                 param += fragment_len;
316         }
317
318         return 0;
319 }
320 EXPORT_SYMBOL_GPL(btintel_secure_send);
321
322 int btintel_load_ddc_config(struct hci_dev *hdev, const char *ddc_name)
323 {
324         const struct firmware *fw;
325         struct sk_buff *skb;
326         const u8 *fw_ptr;
327         int err;
328
329         err = request_firmware_direct(&fw, ddc_name, &hdev->dev);
330         if (err < 0) {
331                 bt_dev_err(hdev, "Failed to load Intel DDC file %s (%d)",
332                            ddc_name, err);
333                 return err;
334         }
335
336         bt_dev_info(hdev, "Found Intel DDC parameters: %s", ddc_name);
337
338         fw_ptr = fw->data;
339
340         /* DDC file contains one or more DDC structure which has
341          * Length (1 byte), DDC ID (2 bytes), and DDC value (Length - 2).
342          */
343         while (fw->size > fw_ptr - fw->data) {
344                 u8 cmd_plen = fw_ptr[0] + sizeof(u8);
345
346                 skb = __hci_cmd_sync(hdev, 0xfc8b, cmd_plen, fw_ptr,
347                                      HCI_INIT_TIMEOUT);
348                 if (IS_ERR(skb)) {
349                         bt_dev_err(hdev, "Failed to send Intel_Write_DDC (%ld)",
350                                    PTR_ERR(skb));
351                         release_firmware(fw);
352                         return PTR_ERR(skb);
353                 }
354
355                 fw_ptr += cmd_plen;
356                 kfree_skb(skb);
357         }
358
359         release_firmware(fw);
360
361         bt_dev_info(hdev, "Applying Intel DDC parameters completed");
362
363         return 0;
364 }
365 EXPORT_SYMBOL_GPL(btintel_load_ddc_config);
366
367 int btintel_set_event_mask(struct hci_dev *hdev, bool debug)
368 {
369         u8 mask[8] = { 0x87, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
370         struct sk_buff *skb;
371         int err;
372
373         if (debug)
374                 mask[1] |= 0x62;
375
376         skb = __hci_cmd_sync(hdev, 0xfc52, 8, mask, HCI_INIT_TIMEOUT);
377         if (IS_ERR(skb)) {
378                 err = PTR_ERR(skb);
379                 bt_dev_err(hdev, "Setting Intel event mask failed (%d)", err);
380                 return err;
381         }
382         kfree_skb(skb);
383
384         return 0;
385 }
386 EXPORT_SYMBOL_GPL(btintel_set_event_mask);
387
388 int btintel_set_event_mask_mfg(struct hci_dev *hdev, bool debug)
389 {
390         int err, ret;
391
392         err = btintel_enter_mfg(hdev);
393         if (err)
394                 return err;
395
396         ret = btintel_set_event_mask(hdev, debug);
397
398         err = btintel_exit_mfg(hdev, false, false);
399         if (err)
400                 return err;
401
402         return ret;
403 }
404 EXPORT_SYMBOL_GPL(btintel_set_event_mask_mfg);
405
406 int btintel_read_version(struct hci_dev *hdev, struct intel_version *ver)
407 {
408         struct sk_buff *skb;
409
410         skb = __hci_cmd_sync(hdev, 0xfc05, 0, NULL, HCI_CMD_TIMEOUT);
411         if (IS_ERR(skb)) {
412                 bt_dev_err(hdev, "Reading Intel version information failed (%ld)",
413                            PTR_ERR(skb));
414                 return PTR_ERR(skb);
415         }
416
417         if (skb->len != sizeof(*ver)) {
418                 bt_dev_err(hdev, "Intel version event size mismatch");
419                 kfree_skb(skb);
420                 return -EILSEQ;
421         }
422
423         memcpy(ver, skb->data, sizeof(*ver));
424
425         kfree_skb(skb);
426
427         return 0;
428 }
429 EXPORT_SYMBOL_GPL(btintel_read_version);
430
431 int btintel_version_info_tlv(struct hci_dev *hdev, struct intel_version_tlv *version)
432 {
433         const char *variant;
434
435         /* The hardware platform number has a fixed value of 0x37 and
436          * for now only accept this single value.
437          */
438         if (INTEL_HW_PLATFORM(version->cnvi_bt) != 0x37) {
439                 bt_dev_err(hdev, "Unsupported Intel hardware platform (0x%2x)",
440                            INTEL_HW_PLATFORM(version->cnvi_bt));
441                 return -EINVAL;
442         }
443
444         /* Check for supported iBT hardware variants of this firmware
445          * loading method.
446          *
447          * This check has been put in place to ensure correct forward
448          * compatibility options when newer hardware variants come along.
449          */
450         switch (INTEL_HW_VARIANT(version->cnvi_bt)) {
451         case 0x17:      /* TyP */
452         case 0x18:      /* Slr */
453         case 0x19:      /* Slr-F */
454                 break;
455         default:
456                 bt_dev_err(hdev, "Unsupported Intel hardware variant (0x%x)",
457                            INTEL_HW_VARIANT(version->cnvi_bt));
458                 return -EINVAL;
459         }
460
461         switch (version->img_type) {
462         case 0x01:
463                 variant = "Bootloader";
464                 /* It is required that every single firmware fragment is acknowledged
465                  * with a command complete event. If the boot parameters indicate
466                  * that this bootloader does not send them, then abort the setup.
467                  */
468                 if (version->limited_cce != 0x00) {
469                         bt_dev_err(hdev, "Unsupported Intel firmware loading method (0x%x)",
470                                    version->limited_cce);
471                         return -EINVAL;
472                 }
473
474                 /* Secure boot engine type should be either 1 (ECDSA) or 0 (RSA) */
475                 if (version->sbe_type > 0x01) {
476                         bt_dev_err(hdev, "Unsupported Intel secure boot engine type (0x%x)",
477                                    version->sbe_type);
478                         return -EINVAL;
479                 }
480
481                 bt_dev_info(hdev, "Device revision is %u", version->dev_rev_id);
482                 bt_dev_info(hdev, "Secure boot is %s",
483                             version->secure_boot ? "enabled" : "disabled");
484                 bt_dev_info(hdev, "OTP lock is %s",
485                             version->otp_lock ? "enabled" : "disabled");
486                 bt_dev_info(hdev, "API lock is %s",
487                             version->api_lock ? "enabled" : "disabled");
488                 bt_dev_info(hdev, "Debug lock is %s",
489                             version->debug_lock ? "enabled" : "disabled");
490                 bt_dev_info(hdev, "Minimum firmware build %u week %u %u",
491                             version->min_fw_build_nn, version->min_fw_build_cw,
492                             2000 + version->min_fw_build_yy);
493                 break;
494         case 0x03:
495                 variant = "Firmware";
496                 break;
497         default:
498                 bt_dev_err(hdev, "Unsupported image type(%02x)", version->img_type);
499                 return -EINVAL;
500         }
501
502         bt_dev_info(hdev, "%s timestamp %u.%u buildtype %u build %u", variant,
503                     2000 + (version->timestamp >> 8), version->timestamp & 0xff,
504                     version->build_type, version->build_num);
505
506         return 0;
507 }
508 EXPORT_SYMBOL_GPL(btintel_version_info_tlv);
509
510 static int btintel_parse_version_tlv(struct hci_dev *hdev,
511                                      struct intel_version_tlv *version,
512                                      struct sk_buff *skb)
513 {
514         /* Consume Command Complete Status field */
515         skb_pull(skb, 1);
516
517         /* Event parameters contatin multiple TLVs. Read each of them
518          * and only keep the required data. Also, it use existing legacy
519          * version field like hw_platform, hw_variant, and fw_variant
520          * to keep the existing setup flow
521          */
522         while (skb->len) {
523                 struct intel_tlv *tlv;
524
525                 /* Make sure skb has a minimum length of the header */
526                 if (skb->len < sizeof(*tlv))
527                         return -EINVAL;
528
529                 tlv = (struct intel_tlv *)skb->data;
530
531                 /* Make sure skb has a enough data */
532                 if (skb->len < tlv->len + sizeof(*tlv))
533                         return -EINVAL;
534
535                 switch (tlv->type) {
536                 case INTEL_TLV_CNVI_TOP:
537                         version->cnvi_top = get_unaligned_le32(tlv->val);
538                         break;
539                 case INTEL_TLV_CNVR_TOP:
540                         version->cnvr_top = get_unaligned_le32(tlv->val);
541                         break;
542                 case INTEL_TLV_CNVI_BT:
543                         version->cnvi_bt = get_unaligned_le32(tlv->val);
544                         break;
545                 case INTEL_TLV_CNVR_BT:
546                         version->cnvr_bt = get_unaligned_le32(tlv->val);
547                         break;
548                 case INTEL_TLV_DEV_REV_ID:
549                         version->dev_rev_id = get_unaligned_le16(tlv->val);
550                         break;
551                 case INTEL_TLV_IMAGE_TYPE:
552                         version->img_type = tlv->val[0];
553                         break;
554                 case INTEL_TLV_TIME_STAMP:
555                         /* If image type is Operational firmware (0x03), then
556                          * running FW Calendar Week and Year information can
557                          * be extracted from Timestamp information
558                          */
559                         version->min_fw_build_cw = tlv->val[0];
560                         version->min_fw_build_yy = tlv->val[1];
561                         version->timestamp = get_unaligned_le16(tlv->val);
562                         break;
563                 case INTEL_TLV_BUILD_TYPE:
564                         version->build_type = tlv->val[0];
565                         break;
566                 case INTEL_TLV_BUILD_NUM:
567                         /* If image type is Operational firmware (0x03), then
568                          * running FW build number can be extracted from the
569                          * Build information
570                          */
571                         version->min_fw_build_nn = tlv->val[0];
572                         version->build_num = get_unaligned_le32(tlv->val);
573                         break;
574                 case INTEL_TLV_SECURE_BOOT:
575                         version->secure_boot = tlv->val[0];
576                         break;
577                 case INTEL_TLV_OTP_LOCK:
578                         version->otp_lock = tlv->val[0];
579                         break;
580                 case INTEL_TLV_API_LOCK:
581                         version->api_lock = tlv->val[0];
582                         break;
583                 case INTEL_TLV_DEBUG_LOCK:
584                         version->debug_lock = tlv->val[0];
585                         break;
586                 case INTEL_TLV_MIN_FW:
587                         version->min_fw_build_nn = tlv->val[0];
588                         version->min_fw_build_cw = tlv->val[1];
589                         version->min_fw_build_yy = tlv->val[2];
590                         break;
591                 case INTEL_TLV_LIMITED_CCE:
592                         version->limited_cce = tlv->val[0];
593                         break;
594                 case INTEL_TLV_SBE_TYPE:
595                         version->sbe_type = tlv->val[0];
596                         break;
597                 case INTEL_TLV_OTP_BDADDR:
598                         memcpy(&version->otp_bd_addr, tlv->val,
599                                                         sizeof(bdaddr_t));
600                         break;
601                 default:
602                         /* Ignore rest of information */
603                         break;
604                 }
605                 /* consume the current tlv and move to next*/
606                 skb_pull(skb, tlv->len + sizeof(*tlv));
607         }
608
609         return 0;
610 }
611
612 int btintel_read_version_tlv(struct hci_dev *hdev, struct intel_version_tlv *version)
613 {
614         struct sk_buff *skb;
615         const u8 param[1] = { 0xFF };
616
617         if (!version)
618                 return -EINVAL;
619
620         skb = __hci_cmd_sync(hdev, 0xfc05, 1, param, HCI_CMD_TIMEOUT);
621         if (IS_ERR(skb)) {
622                 bt_dev_err(hdev, "Reading Intel version information failed (%ld)",
623                            PTR_ERR(skb));
624                 return PTR_ERR(skb);
625         }
626
627         if (skb->data[0]) {
628                 bt_dev_err(hdev, "Intel Read Version command failed (%02x)",
629                            skb->data[0]);
630                 kfree_skb(skb);
631                 return -EIO;
632         }
633
634         btintel_parse_version_tlv(hdev, version, skb);
635
636         kfree_skb(skb);
637         return 0;
638 }
639 EXPORT_SYMBOL_GPL(btintel_read_version_tlv);
640
641 /* ------- REGMAP IBT SUPPORT ------- */
642
643 #define IBT_REG_MODE_8BIT  0x00
644 #define IBT_REG_MODE_16BIT 0x01
645 #define IBT_REG_MODE_32BIT 0x02
646
647 struct regmap_ibt_context {
648         struct hci_dev *hdev;
649         __u16 op_write;
650         __u16 op_read;
651 };
652
653 struct ibt_cp_reg_access {
654         __le32  addr;
655         __u8    mode;
656         __u8    len;
657         __u8    data[];
658 } __packed;
659
660 struct ibt_rp_reg_access {
661         __u8    status;
662         __le32  addr;
663         __u8    data[];
664 } __packed;
665
666 static int regmap_ibt_read(void *context, const void *addr, size_t reg_size,
667                            void *val, size_t val_size)
668 {
669         struct regmap_ibt_context *ctx = context;
670         struct ibt_cp_reg_access cp;
671         struct ibt_rp_reg_access *rp;
672         struct sk_buff *skb;
673         int err = 0;
674
675         if (reg_size != sizeof(__le32))
676                 return -EINVAL;
677
678         switch (val_size) {
679         case 1:
680                 cp.mode = IBT_REG_MODE_8BIT;
681                 break;
682         case 2:
683                 cp.mode = IBT_REG_MODE_16BIT;
684                 break;
685         case 4:
686                 cp.mode = IBT_REG_MODE_32BIT;
687                 break;
688         default:
689                 return -EINVAL;
690         }
691
692         /* regmap provides a little-endian formatted addr */
693         cp.addr = *(__le32 *)addr;
694         cp.len = val_size;
695
696         bt_dev_dbg(ctx->hdev, "Register (0x%x) read", le32_to_cpu(cp.addr));
697
698         skb = hci_cmd_sync(ctx->hdev, ctx->op_read, sizeof(cp), &cp,
699                            HCI_CMD_TIMEOUT);
700         if (IS_ERR(skb)) {
701                 err = PTR_ERR(skb);
702                 bt_dev_err(ctx->hdev, "regmap: Register (0x%x) read error (%d)",
703                            le32_to_cpu(cp.addr), err);
704                 return err;
705         }
706
707         if (skb->len != sizeof(*rp) + val_size) {
708                 bt_dev_err(ctx->hdev, "regmap: Register (0x%x) read error, bad len",
709                            le32_to_cpu(cp.addr));
710                 err = -EINVAL;
711                 goto done;
712         }
713
714         rp = (struct ibt_rp_reg_access *)skb->data;
715
716         if (rp->addr != cp.addr) {
717                 bt_dev_err(ctx->hdev, "regmap: Register (0x%x) read error, bad addr",
718                            le32_to_cpu(rp->addr));
719                 err = -EINVAL;
720                 goto done;
721         }
722
723         memcpy(val, rp->data, val_size);
724
725 done:
726         kfree_skb(skb);
727         return err;
728 }
729
730 static int regmap_ibt_gather_write(void *context,
731                                    const void *addr, size_t reg_size,
732                                    const void *val, size_t val_size)
733 {
734         struct regmap_ibt_context *ctx = context;
735         struct ibt_cp_reg_access *cp;
736         struct sk_buff *skb;
737         int plen = sizeof(*cp) + val_size;
738         u8 mode;
739         int err = 0;
740
741         if (reg_size != sizeof(__le32))
742                 return -EINVAL;
743
744         switch (val_size) {
745         case 1:
746                 mode = IBT_REG_MODE_8BIT;
747                 break;
748         case 2:
749                 mode = IBT_REG_MODE_16BIT;
750                 break;
751         case 4:
752                 mode = IBT_REG_MODE_32BIT;
753                 break;
754         default:
755                 return -EINVAL;
756         }
757
758         cp = kmalloc(plen, GFP_KERNEL);
759         if (!cp)
760                 return -ENOMEM;
761
762         /* regmap provides a little-endian formatted addr/value */
763         cp->addr = *(__le32 *)addr;
764         cp->mode = mode;
765         cp->len = val_size;
766         memcpy(&cp->data, val, val_size);
767
768         bt_dev_dbg(ctx->hdev, "Register (0x%x) write", le32_to_cpu(cp->addr));
769
770         skb = hci_cmd_sync(ctx->hdev, ctx->op_write, plen, cp, HCI_CMD_TIMEOUT);
771         if (IS_ERR(skb)) {
772                 err = PTR_ERR(skb);
773                 bt_dev_err(ctx->hdev, "regmap: Register (0x%x) write error (%d)",
774                            le32_to_cpu(cp->addr), err);
775                 goto done;
776         }
777         kfree_skb(skb);
778
779 done:
780         kfree(cp);
781         return err;
782 }
783
784 static int regmap_ibt_write(void *context, const void *data, size_t count)
785 {
786         /* data contains register+value, since we only support 32bit addr,
787          * minimum data size is 4 bytes.
788          */
789         if (WARN_ONCE(count < 4, "Invalid register access"))
790                 return -EINVAL;
791
792         return regmap_ibt_gather_write(context, data, 4, data + 4, count - 4);
793 }
794
795 static void regmap_ibt_free_context(void *context)
796 {
797         kfree(context);
798 }
799
800 static struct regmap_bus regmap_ibt = {
801         .read = regmap_ibt_read,
802         .write = regmap_ibt_write,
803         .gather_write = regmap_ibt_gather_write,
804         .free_context = regmap_ibt_free_context,
805         .reg_format_endian_default = REGMAP_ENDIAN_LITTLE,
806         .val_format_endian_default = REGMAP_ENDIAN_LITTLE,
807 };
808
809 /* Config is the same for all register regions */
810 static const struct regmap_config regmap_ibt_cfg = {
811         .name      = "btintel_regmap",
812         .reg_bits  = 32,
813         .val_bits  = 32,
814 };
815
816 struct regmap *btintel_regmap_init(struct hci_dev *hdev, u16 opcode_read,
817                                    u16 opcode_write)
818 {
819         struct regmap_ibt_context *ctx;
820
821         bt_dev_info(hdev, "regmap: Init R%x-W%x region", opcode_read,
822                     opcode_write);
823
824         ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
825         if (!ctx)
826                 return ERR_PTR(-ENOMEM);
827
828         ctx->op_read = opcode_read;
829         ctx->op_write = opcode_write;
830         ctx->hdev = hdev;
831
832         return regmap_init(&hdev->dev, &regmap_ibt, ctx, &regmap_ibt_cfg);
833 }
834 EXPORT_SYMBOL_GPL(btintel_regmap_init);
835
836 int btintel_send_intel_reset(struct hci_dev *hdev, u32 boot_param)
837 {
838         struct intel_reset params = { 0x00, 0x01, 0x00, 0x01, 0x00000000 };
839         struct sk_buff *skb;
840
841         params.boot_param = cpu_to_le32(boot_param);
842
843         skb = __hci_cmd_sync(hdev, 0xfc01, sizeof(params), &params,
844                              HCI_INIT_TIMEOUT);
845         if (IS_ERR(skb)) {
846                 bt_dev_err(hdev, "Failed to send Intel Reset command");
847                 return PTR_ERR(skb);
848         }
849
850         kfree_skb(skb);
851
852         return 0;
853 }
854 EXPORT_SYMBOL_GPL(btintel_send_intel_reset);
855
856 int btintel_read_boot_params(struct hci_dev *hdev,
857                              struct intel_boot_params *params)
858 {
859         struct sk_buff *skb;
860
861         skb = __hci_cmd_sync(hdev, 0xfc0d, 0, NULL, HCI_INIT_TIMEOUT);
862         if (IS_ERR(skb)) {
863                 bt_dev_err(hdev, "Reading Intel boot parameters failed (%ld)",
864                            PTR_ERR(skb));
865                 return PTR_ERR(skb);
866         }
867
868         if (skb->len != sizeof(*params)) {
869                 bt_dev_err(hdev, "Intel boot parameters size mismatch");
870                 kfree_skb(skb);
871                 return -EILSEQ;
872         }
873
874         memcpy(params, skb->data, sizeof(*params));
875
876         kfree_skb(skb);
877
878         if (params->status) {
879                 bt_dev_err(hdev, "Intel boot parameters command failed (%02x)",
880                            params->status);
881                 return -bt_to_errno(params->status);
882         }
883
884         bt_dev_info(hdev, "Device revision is %u",
885                     le16_to_cpu(params->dev_revid));
886
887         bt_dev_info(hdev, "Secure boot is %s",
888                     params->secure_boot ? "enabled" : "disabled");
889
890         bt_dev_info(hdev, "OTP lock is %s",
891                     params->otp_lock ? "enabled" : "disabled");
892
893         bt_dev_info(hdev, "API lock is %s",
894                     params->api_lock ? "enabled" : "disabled");
895
896         bt_dev_info(hdev, "Debug lock is %s",
897                     params->debug_lock ? "enabled" : "disabled");
898
899         bt_dev_info(hdev, "Minimum firmware build %u week %u %u",
900                     params->min_fw_build_nn, params->min_fw_build_cw,
901                     2000 + params->min_fw_build_yy);
902
903         return 0;
904 }
905 EXPORT_SYMBOL_GPL(btintel_read_boot_params);
906
907 static int btintel_sfi_rsa_header_secure_send(struct hci_dev *hdev,
908                                               const struct firmware *fw)
909 {
910         int err;
911
912         /* Start the firmware download transaction with the Init fragment
913          * represented by the 128 bytes of CSS header.
914          */
915         err = btintel_secure_send(hdev, 0x00, 128, fw->data);
916         if (err < 0) {
917                 bt_dev_err(hdev, "Failed to send firmware header (%d)", err);
918                 goto done;
919         }
920
921         /* Send the 256 bytes of public key information from the firmware
922          * as the PKey fragment.
923          */
924         err = btintel_secure_send(hdev, 0x03, 256, fw->data + 128);
925         if (err < 0) {
926                 bt_dev_err(hdev, "Failed to send firmware pkey (%d)", err);
927                 goto done;
928         }
929
930         /* Send the 256 bytes of signature information from the firmware
931          * as the Sign fragment.
932          */
933         err = btintel_secure_send(hdev, 0x02, 256, fw->data + 388);
934         if (err < 0) {
935                 bt_dev_err(hdev, "Failed to send firmware signature (%d)", err);
936                 goto done;
937         }
938
939 done:
940         return err;
941 }
942
943 static int btintel_sfi_ecdsa_header_secure_send(struct hci_dev *hdev,
944                                                 const struct firmware *fw)
945 {
946         int err;
947
948         /* Start the firmware download transaction with the Init fragment
949          * represented by the 128 bytes of CSS header.
950          */
951         err = btintel_secure_send(hdev, 0x00, 128, fw->data + 644);
952         if (err < 0) {
953                 bt_dev_err(hdev, "Failed to send firmware header (%d)", err);
954                 return err;
955         }
956
957         /* Send the 96 bytes of public key information from the firmware
958          * as the PKey fragment.
959          */
960         err = btintel_secure_send(hdev, 0x03, 96, fw->data + 644 + 128);
961         if (err < 0) {
962                 bt_dev_err(hdev, "Failed to send firmware pkey (%d)", err);
963                 return err;
964         }
965
966         /* Send the 96 bytes of signature information from the firmware
967          * as the Sign fragment
968          */
969         err = btintel_secure_send(hdev, 0x02, 96, fw->data + 644 + 224);
970         if (err < 0) {
971                 bt_dev_err(hdev, "Failed to send firmware signature (%d)",
972                            err);
973                 return err;
974         }
975         return 0;
976 }
977
978 static int btintel_download_firmware_payload(struct hci_dev *hdev,
979                                              const struct firmware *fw,
980                                              size_t offset)
981 {
982         int err;
983         const u8 *fw_ptr;
984         u32 frag_len;
985
986         fw_ptr = fw->data + offset;
987         frag_len = 0;
988         err = -EINVAL;
989
990         while (fw_ptr - fw->data < fw->size) {
991                 struct hci_command_hdr *cmd = (void *)(fw_ptr + frag_len);
992
993                 frag_len += sizeof(*cmd) + cmd->plen;
994
995                 /* The parameter length of the secure send command requires
996                  * a 4 byte alignment. It happens so that the firmware file
997                  * contains proper Intel_NOP commands to align the fragments
998                  * as needed.
999                  *
1000                  * Send set of commands with 4 byte alignment from the
1001                  * firmware data buffer as a single Data fragement.
1002                  */
1003                 if (!(frag_len % 4)) {
1004                         err = btintel_secure_send(hdev, 0x01, frag_len, fw_ptr);
1005                         if (err < 0) {
1006                                 bt_dev_err(hdev,
1007                                            "Failed to send firmware data (%d)",
1008                                            err);
1009                                 goto done;
1010                         }
1011
1012                         fw_ptr += frag_len;
1013                         frag_len = 0;
1014                 }
1015         }
1016
1017 done:
1018         return err;
1019 }
1020
1021 static bool btintel_firmware_version(struct hci_dev *hdev,
1022                                      u8 num, u8 ww, u8 yy,
1023                                      const struct firmware *fw,
1024                                      u32 *boot_addr)
1025 {
1026         const u8 *fw_ptr;
1027
1028         fw_ptr = fw->data;
1029
1030         while (fw_ptr - fw->data < fw->size) {
1031                 struct hci_command_hdr *cmd = (void *)(fw_ptr);
1032
1033                 /* Each SKU has a different reset parameter to use in the
1034                  * HCI_Intel_Reset command and it is embedded in the firmware
1035                  * data. So, instead of using static value per SKU, check
1036                  * the firmware data and save it for later use.
1037                  */
1038                 if (le16_to_cpu(cmd->opcode) == CMD_WRITE_BOOT_PARAMS) {
1039                         struct cmd_write_boot_params *params;
1040
1041                         params = (void *)(fw_ptr + sizeof(*cmd));
1042
1043                         bt_dev_info(hdev, "Boot Address: 0x%x",
1044                                     le32_to_cpu(params->boot_addr));
1045
1046                         bt_dev_info(hdev, "Firmware Version: %u-%u.%u",
1047                                     params->fw_build_num, params->fw_build_ww,
1048                                     params->fw_build_yy);
1049
1050                         return (num == params->fw_build_num &&
1051                                 ww == params->fw_build_ww &&
1052                                 yy == params->fw_build_yy);
1053                 }
1054
1055                 fw_ptr += sizeof(*cmd) + cmd->plen;
1056         }
1057
1058         return false;
1059 }
1060
1061 int btintel_download_firmware(struct hci_dev *hdev,
1062                               struct intel_version *ver,
1063                               const struct firmware *fw,
1064                               u32 *boot_param)
1065 {
1066         int err;
1067
1068         /* SfP and WsP don't seem to update the firmware version on file
1069          * so version checking is currently not possible.
1070          */
1071         switch (ver->hw_variant) {
1072         case 0x0b:      /* SfP */
1073         case 0x0c:      /* WsP */
1074                 /* Skip version checking */
1075                 break;
1076         default:
1077                 /* Skip reading firmware file version in bootloader mode */
1078                 if (ver->fw_variant == 0x06)
1079                         break;
1080
1081                 /* Skip download if firmware has the same version */
1082                 if (btintel_firmware_version(hdev, ver->fw_build_num,
1083                                              ver->fw_build_ww, ver->fw_build_yy,
1084                                              fw, boot_param)) {
1085                         bt_dev_info(hdev, "Firmware already loaded");
1086                         /* Return -EALREADY to indicate that the firmware has
1087                          * already been loaded.
1088                          */
1089                         return -EALREADY;
1090                 }
1091         }
1092
1093         /* The firmware variant determines if the device is in bootloader
1094          * mode or is running operational firmware. The value 0x06 identifies
1095          * the bootloader and the value 0x23 identifies the operational
1096          * firmware.
1097          *
1098          * If the firmware version has changed that means it needs to be reset
1099          * to bootloader when operational so the new firmware can be loaded.
1100          */
1101         if (ver->fw_variant == 0x23)
1102                 return -EINVAL;
1103
1104         err = btintel_sfi_rsa_header_secure_send(hdev, fw);
1105         if (err)
1106                 return err;
1107
1108         return btintel_download_firmware_payload(hdev, fw, RSA_HEADER_LEN);
1109 }
1110 EXPORT_SYMBOL_GPL(btintel_download_firmware);
1111
1112 static int btintel_download_fw_tlv(struct hci_dev *hdev,
1113                                    struct intel_version_tlv *ver,
1114                                    const struct firmware *fw, u32 *boot_param,
1115                                    u8 hw_variant, u8 sbe_type)
1116 {
1117         int err;
1118         u32 css_header_ver;
1119
1120         /* Skip reading firmware file version in bootloader mode */
1121         if (ver->img_type != 0x01) {
1122                 /* Skip download if firmware has the same version */
1123                 if (btintel_firmware_version(hdev, ver->min_fw_build_nn,
1124                                              ver->min_fw_build_cw,
1125                                              ver->min_fw_build_yy,
1126                                              fw, boot_param)) {
1127                         bt_dev_info(hdev, "Firmware already loaded");
1128                         /* Return -EALREADY to indicate that firmware has
1129                          * already been loaded.
1130                          */
1131                         return -EALREADY;
1132                 }
1133         }
1134
1135         /* The firmware variant determines if the device is in bootloader
1136          * mode or is running operational firmware. The value 0x01 identifies
1137          * the bootloader and the value 0x03 identifies the operational
1138          * firmware.
1139          *
1140          * If the firmware version has changed that means it needs to be reset
1141          * to bootloader when operational so the new firmware can be loaded.
1142          */
1143         if (ver->img_type == 0x03)
1144                 return -EINVAL;
1145
1146         /* iBT hardware variants 0x0b, 0x0c, 0x11, 0x12, 0x13, 0x14 support
1147          * only RSA secure boot engine. Hence, the corresponding sfi file will
1148          * have RSA header of 644 bytes followed by Command Buffer.
1149          *
1150          * iBT hardware variants 0x17, 0x18 onwards support both RSA and ECDSA
1151          * secure boot engine. As a result, the corresponding sfi file will
1152          * have RSA header of 644, ECDSA header of 320 bytes followed by
1153          * Command Buffer.
1154          *
1155          * CSS Header byte positions 0x08 to 0x0B represent the CSS Header
1156          * version: RSA(0x00010000) , ECDSA (0x00020000)
1157          */
1158         css_header_ver = get_unaligned_le32(fw->data + CSS_HEADER_OFFSET);
1159         if (css_header_ver != 0x00010000) {
1160                 bt_dev_err(hdev, "Invalid CSS Header version");
1161                 return -EINVAL;
1162         }
1163
1164         if (hw_variant <= 0x14) {
1165                 if (sbe_type != 0x00) {
1166                         bt_dev_err(hdev, "Invalid SBE type for hardware variant (%d)",
1167                                    hw_variant);
1168                         return -EINVAL;
1169                 }
1170
1171                 err = btintel_sfi_rsa_header_secure_send(hdev, fw);
1172                 if (err)
1173                         return err;
1174
1175                 err = btintel_download_firmware_payload(hdev, fw, RSA_HEADER_LEN);
1176                 if (err)
1177                         return err;
1178         } else if (hw_variant >= 0x17) {
1179                 /* Check if CSS header for ECDSA follows the RSA header */
1180                 if (fw->data[ECDSA_OFFSET] != 0x06)
1181                         return -EINVAL;
1182
1183                 /* Check if the CSS Header version is ECDSA(0x00020000) */
1184                 css_header_ver = get_unaligned_le32(fw->data + ECDSA_OFFSET + CSS_HEADER_OFFSET);
1185                 if (css_header_ver != 0x00020000) {
1186                         bt_dev_err(hdev, "Invalid CSS Header version");
1187                         return -EINVAL;
1188                 }
1189
1190                 if (sbe_type == 0x00) {
1191                         err = btintel_sfi_rsa_header_secure_send(hdev, fw);
1192                         if (err)
1193                                 return err;
1194
1195                         err = btintel_download_firmware_payload(hdev, fw,
1196                                                                 RSA_HEADER_LEN + ECDSA_HEADER_LEN);
1197                         if (err)
1198                                 return err;
1199                 } else if (sbe_type == 0x01) {
1200                         err = btintel_sfi_ecdsa_header_secure_send(hdev, fw);
1201                         if (err)
1202                                 return err;
1203
1204                         err = btintel_download_firmware_payload(hdev, fw,
1205                                                                 RSA_HEADER_LEN + ECDSA_HEADER_LEN);
1206                         if (err)
1207                                 return err;
1208                 }
1209         }
1210         return 0;
1211 }
1212
1213 void btintel_reset_to_bootloader(struct hci_dev *hdev)
1214 {
1215         struct intel_reset params;
1216         struct sk_buff *skb;
1217
1218         /* Send Intel Reset command. This will result in
1219          * re-enumeration of BT controller.
1220          *
1221          * Intel Reset parameter description:
1222          * reset_type :   0x00 (Soft reset),
1223          *                0x01 (Hard reset)
1224          * patch_enable : 0x00 (Do not enable),
1225          *                0x01 (Enable)
1226          * ddc_reload :   0x00 (Do not reload),
1227          *                0x01 (Reload)
1228          * boot_option:   0x00 (Current image),
1229          *                0x01 (Specified boot address)
1230          * boot_param:    Boot address
1231          *
1232          */
1233         params.reset_type = 0x01;
1234         params.patch_enable = 0x01;
1235         params.ddc_reload = 0x01;
1236         params.boot_option = 0x00;
1237         params.boot_param = cpu_to_le32(0x00000000);
1238
1239         skb = __hci_cmd_sync(hdev, 0xfc01, sizeof(params),
1240                              &params, HCI_INIT_TIMEOUT);
1241         if (IS_ERR(skb)) {
1242                 bt_dev_err(hdev, "FW download error recovery failed (%ld)",
1243                            PTR_ERR(skb));
1244                 return;
1245         }
1246         bt_dev_info(hdev, "Intel reset sent to retry FW download");
1247         kfree_skb(skb);
1248
1249         /* Current Intel BT controllers(ThP/JfP) hold the USB reset
1250          * lines for 2ms when it receives Intel Reset in bootloader mode.
1251          * Whereas, the upcoming Intel BT controllers will hold USB reset
1252          * for 150ms. To keep the delay generic, 150ms is chosen here.
1253          */
1254         msleep(150);
1255 }
1256 EXPORT_SYMBOL_GPL(btintel_reset_to_bootloader);
1257
1258 int btintel_read_debug_features(struct hci_dev *hdev,
1259                                 struct intel_debug_features *features)
1260 {
1261         struct sk_buff *skb;
1262         u8 page_no = 1;
1263
1264         /* Intel controller supports two pages, each page is of 128-bit
1265          * feature bit mask. And each bit defines specific feature support
1266          */
1267         skb = __hci_cmd_sync(hdev, 0xfca6, sizeof(page_no), &page_no,
1268                              HCI_INIT_TIMEOUT);
1269         if (IS_ERR(skb)) {
1270                 bt_dev_err(hdev, "Reading supported features failed (%ld)",
1271                            PTR_ERR(skb));
1272                 return PTR_ERR(skb);
1273         }
1274
1275         if (skb->len != (sizeof(features->page1) + 3)) {
1276                 bt_dev_err(hdev, "Supported features event size mismatch");
1277                 kfree_skb(skb);
1278                 return -EILSEQ;
1279         }
1280
1281         memcpy(features->page1, skb->data + 3, sizeof(features->page1));
1282
1283         /* Read the supported features page2 if required in future.
1284          */
1285         kfree_skb(skb);
1286         return 0;
1287 }
1288 EXPORT_SYMBOL_GPL(btintel_read_debug_features);
1289
1290 int btintel_set_debug_features(struct hci_dev *hdev,
1291                                const struct intel_debug_features *features)
1292 {
1293         u8 mask[11] = { 0x0a, 0x92, 0x02, 0x07, 0x00, 0x00, 0x00, 0x00,
1294                         0x00, 0x00, 0x00 };
1295         struct sk_buff *skb;
1296
1297         if (!features)
1298                 return -EINVAL;
1299
1300         if (!(features->page1[0] & 0x3f)) {
1301                 bt_dev_info(hdev, "Telemetry exception format not supported");
1302                 return 0;
1303         }
1304
1305         skb = __hci_cmd_sync(hdev, 0xfc8b, 11, mask, HCI_INIT_TIMEOUT);
1306         if (IS_ERR(skb)) {
1307                 bt_dev_err(hdev, "Setting Intel telemetry ddc write event mask failed (%ld)",
1308                            PTR_ERR(skb));
1309                 return PTR_ERR(skb);
1310         }
1311
1312         kfree_skb(skb);
1313         return 0;
1314 }
1315 EXPORT_SYMBOL_GPL(btintel_set_debug_features);
1316
1317 static const struct firmware *btintel_legacy_rom_get_fw(struct hci_dev *hdev,
1318                                                struct intel_version *ver)
1319 {
1320         const struct firmware *fw;
1321         char fwname[64];
1322         int ret;
1323
1324         snprintf(fwname, sizeof(fwname),
1325                  "intel/ibt-hw-%x.%x.%x-fw-%x.%x.%x.%x.%x.bseq",
1326                  ver->hw_platform, ver->hw_variant, ver->hw_revision,
1327                  ver->fw_variant,  ver->fw_revision, ver->fw_build_num,
1328                  ver->fw_build_ww, ver->fw_build_yy);
1329
1330         ret = request_firmware(&fw, fwname, &hdev->dev);
1331         if (ret < 0) {
1332                 if (ret == -EINVAL) {
1333                         bt_dev_err(hdev, "Intel firmware file request failed (%d)",
1334                                    ret);
1335                         return NULL;
1336                 }
1337
1338                 bt_dev_err(hdev, "failed to open Intel firmware file: %s (%d)",
1339                            fwname, ret);
1340
1341                 /* If the correct firmware patch file is not found, use the
1342                  * default firmware patch file instead
1343                  */
1344                 snprintf(fwname, sizeof(fwname), "intel/ibt-hw-%x.%x.bseq",
1345                          ver->hw_platform, ver->hw_variant);
1346                 if (request_firmware(&fw, fwname, &hdev->dev) < 0) {
1347                         bt_dev_err(hdev, "failed to open default fw file: %s",
1348                                    fwname);
1349                         return NULL;
1350                 }
1351         }
1352
1353         bt_dev_info(hdev, "Intel Bluetooth firmware file: %s", fwname);
1354
1355         return fw;
1356 }
1357
1358 static int btintel_legacy_rom_patching(struct hci_dev *hdev,
1359                                       const struct firmware *fw,
1360                                       const u8 **fw_ptr, int *disable_patch)
1361 {
1362         struct sk_buff *skb;
1363         struct hci_command_hdr *cmd;
1364         const u8 *cmd_param;
1365         struct hci_event_hdr *evt = NULL;
1366         const u8 *evt_param = NULL;
1367         int remain = fw->size - (*fw_ptr - fw->data);
1368
1369         /* The first byte indicates the types of the patch command or event.
1370          * 0x01 means HCI command and 0x02 is HCI event. If the first bytes
1371          * in the current firmware buffer doesn't start with 0x01 or
1372          * the size of remain buffer is smaller than HCI command header,
1373          * the firmware file is corrupted and it should stop the patching
1374          * process.
1375          */
1376         if (remain > HCI_COMMAND_HDR_SIZE && *fw_ptr[0] != 0x01) {
1377                 bt_dev_err(hdev, "Intel fw corrupted: invalid cmd read");
1378                 return -EINVAL;
1379         }
1380         (*fw_ptr)++;
1381         remain--;
1382
1383         cmd = (struct hci_command_hdr *)(*fw_ptr);
1384         *fw_ptr += sizeof(*cmd);
1385         remain -= sizeof(*cmd);
1386
1387         /* Ensure that the remain firmware data is long enough than the length
1388          * of command parameter. If not, the firmware file is corrupted.
1389          */
1390         if (remain < cmd->plen) {
1391                 bt_dev_err(hdev, "Intel fw corrupted: invalid cmd len");
1392                 return -EFAULT;
1393         }
1394
1395         /* If there is a command that loads a patch in the firmware
1396          * file, then enable the patch upon success, otherwise just
1397          * disable the manufacturer mode, for example patch activation
1398          * is not required when the default firmware patch file is used
1399          * because there are no patch data to load.
1400          */
1401         if (*disable_patch && le16_to_cpu(cmd->opcode) == 0xfc8e)
1402                 *disable_patch = 0;
1403
1404         cmd_param = *fw_ptr;
1405         *fw_ptr += cmd->plen;
1406         remain -= cmd->plen;
1407
1408         /* This reads the expected events when the above command is sent to the
1409          * device. Some vendor commands expects more than one events, for
1410          * example command status event followed by vendor specific event.
1411          * For this case, it only keeps the last expected event. so the command
1412          * can be sent with __hci_cmd_sync_ev() which returns the sk_buff of
1413          * last expected event.
1414          */
1415         while (remain > HCI_EVENT_HDR_SIZE && *fw_ptr[0] == 0x02) {
1416                 (*fw_ptr)++;
1417                 remain--;
1418
1419                 evt = (struct hci_event_hdr *)(*fw_ptr);
1420                 *fw_ptr += sizeof(*evt);
1421                 remain -= sizeof(*evt);
1422
1423                 if (remain < evt->plen) {
1424                         bt_dev_err(hdev, "Intel fw corrupted: invalid evt len");
1425                         return -EFAULT;
1426                 }
1427
1428                 evt_param = *fw_ptr;
1429                 *fw_ptr += evt->plen;
1430                 remain -= evt->plen;
1431         }
1432
1433         /* Every HCI commands in the firmware file has its correspond event.
1434          * If event is not found or remain is smaller than zero, the firmware
1435          * file is corrupted.
1436          */
1437         if (!evt || !evt_param || remain < 0) {
1438                 bt_dev_err(hdev, "Intel fw corrupted: invalid evt read");
1439                 return -EFAULT;
1440         }
1441
1442         skb = __hci_cmd_sync_ev(hdev, le16_to_cpu(cmd->opcode), cmd->plen,
1443                                 cmd_param, evt->evt, HCI_INIT_TIMEOUT);
1444         if (IS_ERR(skb)) {
1445                 bt_dev_err(hdev, "sending Intel patch command (0x%4.4x) failed (%ld)",
1446                            cmd->opcode, PTR_ERR(skb));
1447                 return PTR_ERR(skb);
1448         }
1449
1450         /* It ensures that the returned event matches the event data read from
1451          * the firmware file. At fist, it checks the length and then
1452          * the contents of the event.
1453          */
1454         if (skb->len != evt->plen) {
1455                 bt_dev_err(hdev, "mismatch event length (opcode 0x%4.4x)",
1456                            le16_to_cpu(cmd->opcode));
1457                 kfree_skb(skb);
1458                 return -EFAULT;
1459         }
1460
1461         if (memcmp(skb->data, evt_param, evt->plen)) {
1462                 bt_dev_err(hdev, "mismatch event parameter (opcode 0x%4.4x)",
1463                            le16_to_cpu(cmd->opcode));
1464                 kfree_skb(skb);
1465                 return -EFAULT;
1466         }
1467         kfree_skb(skb);
1468
1469         return 0;
1470 }
1471
1472 static int btintel_legacy_rom_setup(struct hci_dev *hdev,
1473                                     struct intel_version *ver)
1474 {
1475         const struct firmware *fw;
1476         const u8 *fw_ptr;
1477         int disable_patch, err;
1478         struct intel_version new_ver;
1479
1480         BT_DBG("%s", hdev->name);
1481
1482         /* fw_patch_num indicates the version of patch the device currently
1483          * have. If there is no patch data in the device, it is always 0x00.
1484          * So, if it is other than 0x00, no need to patch the device again.
1485          */
1486         if (ver->fw_patch_num) {
1487                 bt_dev_info(hdev,
1488                             "Intel device is already patched. patch num: %02x",
1489                             ver->fw_patch_num);
1490                 goto complete;
1491         }
1492
1493         /* Opens the firmware patch file based on the firmware version read
1494          * from the controller. If it fails to open the matching firmware
1495          * patch file, it tries to open the default firmware patch file.
1496          * If no patch file is found, allow the device to operate without
1497          * a patch.
1498          */
1499         fw = btintel_legacy_rom_get_fw(hdev, ver);
1500         if (!fw)
1501                 goto complete;
1502         fw_ptr = fw->data;
1503
1504         /* Enable the manufacturer mode of the controller.
1505          * Only while this mode is enabled, the driver can download the
1506          * firmware patch data and configuration parameters.
1507          */
1508         err = btintel_enter_mfg(hdev);
1509         if (err) {
1510                 release_firmware(fw);
1511                 return err;
1512         }
1513
1514         disable_patch = 1;
1515
1516         /* The firmware data file consists of list of Intel specific HCI
1517          * commands and its expected events. The first byte indicates the
1518          * type of the message, either HCI command or HCI event.
1519          *
1520          * It reads the command and its expected event from the firmware file,
1521          * and send to the controller. Once __hci_cmd_sync_ev() returns,
1522          * the returned event is compared with the event read from the firmware
1523          * file and it will continue until all the messages are downloaded to
1524          * the controller.
1525          *
1526          * Once the firmware patching is completed successfully,
1527          * the manufacturer mode is disabled with reset and activating the
1528          * downloaded patch.
1529          *
1530          * If the firmware patching fails, the manufacturer mode is
1531          * disabled with reset and deactivating the patch.
1532          *
1533          * If the default patch file is used, no reset is done when disabling
1534          * the manufacturer.
1535          */
1536         while (fw->size > fw_ptr - fw->data) {
1537                 int ret;
1538
1539                 ret = btintel_legacy_rom_patching(hdev, fw, &fw_ptr,
1540                                                  &disable_patch);
1541                 if (ret < 0)
1542                         goto exit_mfg_deactivate;
1543         }
1544
1545         release_firmware(fw);
1546
1547         if (disable_patch)
1548                 goto exit_mfg_disable;
1549
1550         /* Patching completed successfully and disable the manufacturer mode
1551          * with reset and activate the downloaded firmware patches.
1552          */
1553         err = btintel_exit_mfg(hdev, true, true);
1554         if (err)
1555                 return err;
1556
1557         /* Need build number for downloaded fw patches in
1558          * every power-on boot
1559          */
1560         err = btintel_read_version(hdev, &new_ver);
1561         if (err)
1562                 return err;
1563
1564         bt_dev_info(hdev, "Intel BT fw patch 0x%02x completed & activated",
1565                     new_ver.fw_patch_num);
1566
1567         goto complete;
1568
1569 exit_mfg_disable:
1570         /* Disable the manufacturer mode without reset */
1571         err = btintel_exit_mfg(hdev, false, false);
1572         if (err)
1573                 return err;
1574
1575         bt_dev_info(hdev, "Intel firmware patch completed");
1576
1577         goto complete;
1578
1579 exit_mfg_deactivate:
1580         release_firmware(fw);
1581
1582         /* Patching failed. Disable the manufacturer mode with reset and
1583          * deactivate the downloaded firmware patches.
1584          */
1585         err = btintel_exit_mfg(hdev, true, false);
1586         if (err)
1587                 return err;
1588
1589         bt_dev_info(hdev, "Intel firmware patch completed and deactivated");
1590
1591 complete:
1592         /* Set the event mask for Intel specific vendor events. This enables
1593          * a few extra events that are useful during general operation.
1594          */
1595         btintel_set_event_mask_mfg(hdev, false);
1596
1597         btintel_check_bdaddr(hdev);
1598
1599         return 0;
1600 }
1601
1602 static int btintel_download_wait(struct hci_dev *hdev, ktime_t calltime, int msec)
1603 {
1604         ktime_t delta, rettime;
1605         unsigned long long duration;
1606         int err;
1607
1608         btintel_set_flag(hdev, INTEL_FIRMWARE_LOADED);
1609
1610         bt_dev_info(hdev, "Waiting for firmware download to complete");
1611
1612         err = btintel_wait_on_flag_timeout(hdev, INTEL_DOWNLOADING,
1613                                            TASK_INTERRUPTIBLE,
1614                                            msecs_to_jiffies(msec));
1615         if (err == -EINTR) {
1616                 bt_dev_err(hdev, "Firmware loading interrupted");
1617                 return err;
1618         }
1619
1620         if (err) {
1621                 bt_dev_err(hdev, "Firmware loading timeout");
1622                 return -ETIMEDOUT;
1623         }
1624
1625         if (btintel_test_flag(hdev, INTEL_FIRMWARE_FAILED)) {
1626                 bt_dev_err(hdev, "Firmware loading failed");
1627                 return -ENOEXEC;
1628         }
1629
1630         rettime = ktime_get();
1631         delta = ktime_sub(rettime, calltime);
1632         duration = (unsigned long long)ktime_to_ns(delta) >> 10;
1633
1634         bt_dev_info(hdev, "Firmware loaded in %llu usecs", duration);
1635
1636         return 0;
1637 }
1638
1639 static int btintel_boot_wait(struct hci_dev *hdev, ktime_t calltime, int msec)
1640 {
1641         ktime_t delta, rettime;
1642         unsigned long long duration;
1643         int err;
1644
1645         bt_dev_info(hdev, "Waiting for device to boot");
1646
1647         err = btintel_wait_on_flag_timeout(hdev, INTEL_BOOTING,
1648                                            TASK_INTERRUPTIBLE,
1649                                            msecs_to_jiffies(msec));
1650         if (err == -EINTR) {
1651                 bt_dev_err(hdev, "Device boot interrupted");
1652                 return -EINTR;
1653         }
1654
1655         if (err) {
1656                 bt_dev_err(hdev, "Device boot timeout");
1657                 return -ETIMEDOUT;
1658         }
1659
1660         rettime = ktime_get();
1661         delta = ktime_sub(rettime, calltime);
1662         duration = (unsigned long long) ktime_to_ns(delta) >> 10;
1663
1664         bt_dev_info(hdev, "Device booted in %llu usecs", duration);
1665
1666         return 0;
1667 }
1668
1669 static int btintel_boot(struct hci_dev *hdev, u32 boot_addr)
1670 {
1671         ktime_t calltime;
1672         int err;
1673
1674         calltime = ktime_get();
1675
1676         btintel_set_flag(hdev, INTEL_BOOTING);
1677
1678         err = btintel_send_intel_reset(hdev, boot_addr);
1679         if (err) {
1680                 bt_dev_err(hdev, "Intel Soft Reset failed (%d)", err);
1681                 btintel_reset_to_bootloader(hdev);
1682                 return err;
1683         }
1684
1685         /* The bootloader will not indicate when the device is ready. This
1686          * is done by the operational firmware sending bootup notification.
1687          *
1688          * Booting into operational firmware should not take longer than
1689          * 1 second. However if that happens, then just fail the setup
1690          * since something went wrong.
1691          */
1692         err = btintel_boot_wait(hdev, calltime, 1000);
1693         if (err == -ETIMEDOUT)
1694                 btintel_reset_to_bootloader(hdev);
1695
1696         return err;
1697 }
1698
1699 static int btintel_get_fw_name(struct intel_version *ver,
1700                                              struct intel_boot_params *params,
1701                                              char *fw_name, size_t len,
1702                                              const char *suffix)
1703 {
1704         switch (ver->hw_variant) {
1705         case 0x0b:      /* SfP */
1706         case 0x0c:      /* WsP */
1707                 snprintf(fw_name, len, "intel/ibt-%u-%u.%s",
1708                         le16_to_cpu(ver->hw_variant),
1709                         le16_to_cpu(params->dev_revid),
1710                         suffix);
1711                 break;
1712         case 0x11:      /* JfP */
1713         case 0x12:      /* ThP */
1714         case 0x13:      /* HrP */
1715         case 0x14:      /* CcP */
1716                 snprintf(fw_name, len, "intel/ibt-%u-%u-%u.%s",
1717                         le16_to_cpu(ver->hw_variant),
1718                         le16_to_cpu(ver->hw_revision),
1719                         le16_to_cpu(ver->fw_revision),
1720                         suffix);
1721                 break;
1722         default:
1723                 return -EINVAL;
1724         }
1725
1726         return 0;
1727 }
1728
1729 static int btintel_download_fw(struct hci_dev *hdev,
1730                                          struct intel_version *ver,
1731                                          struct intel_boot_params *params,
1732                                          u32 *boot_param)
1733 {
1734         const struct firmware *fw;
1735         char fwname[64];
1736         int err;
1737         ktime_t calltime;
1738
1739         if (!ver || !params)
1740                 return -EINVAL;
1741
1742         /* The firmware variant determines if the device is in bootloader
1743          * mode or is running operational firmware. The value 0x06 identifies
1744          * the bootloader and the value 0x23 identifies the operational
1745          * firmware.
1746          *
1747          * When the operational firmware is already present, then only
1748          * the check for valid Bluetooth device address is needed. This
1749          * determines if the device will be added as configured or
1750          * unconfigured controller.
1751          *
1752          * It is not possible to use the Secure Boot Parameters in this
1753          * case since that command is only available in bootloader mode.
1754          */
1755         if (ver->fw_variant == 0x23) {
1756                 btintel_clear_flag(hdev, INTEL_BOOTLOADER);
1757                 btintel_check_bdaddr(hdev);
1758
1759                 /* SfP and WsP don't seem to update the firmware version on file
1760                  * so version checking is currently possible.
1761                  */
1762                 switch (ver->hw_variant) {
1763                 case 0x0b:      /* SfP */
1764                 case 0x0c:      /* WsP */
1765                         return 0;
1766                 }
1767
1768                 /* Proceed to download to check if the version matches */
1769                 goto download;
1770         }
1771
1772         /* Read the secure boot parameters to identify the operating
1773          * details of the bootloader.
1774          */
1775         err = btintel_read_boot_params(hdev, params);
1776         if (err)
1777                 return err;
1778
1779         /* It is required that every single firmware fragment is acknowledged
1780          * with a command complete event. If the boot parameters indicate
1781          * that this bootloader does not send them, then abort the setup.
1782          */
1783         if (params->limited_cce != 0x00) {
1784                 bt_dev_err(hdev, "Unsupported Intel firmware loading method (%u)",
1785                            params->limited_cce);
1786                 return -EINVAL;
1787         }
1788
1789         /* If the OTP has no valid Bluetooth device address, then there will
1790          * also be no valid address for the operational firmware.
1791          */
1792         if (!bacmp(&params->otp_bdaddr, BDADDR_ANY)) {
1793                 bt_dev_info(hdev, "No device address configured");
1794                 set_bit(HCI_QUIRK_INVALID_BDADDR, &hdev->quirks);
1795         }
1796
1797 download:
1798         /* With this Intel bootloader only the hardware variant and device
1799          * revision information are used to select the right firmware for SfP
1800          * and WsP.
1801          *
1802          * The firmware filename is ibt-<hw_variant>-<dev_revid>.sfi.
1803          *
1804          * Currently the supported hardware variants are:
1805          *   11 (0x0b) for iBT3.0 (LnP/SfP)
1806          *   12 (0x0c) for iBT3.5 (WsP)
1807          *
1808          * For ThP/JfP and for future SKU's, the FW name varies based on HW
1809          * variant, HW revision and FW revision, as these are dependent on CNVi
1810          * and RF Combination.
1811          *
1812          *   17 (0x11) for iBT3.5 (JfP)
1813          *   18 (0x12) for iBT3.5 (ThP)
1814          *
1815          * The firmware file name for these will be
1816          * ibt-<hw_variant>-<hw_revision>-<fw_revision>.sfi.
1817          *
1818          */
1819         err = btintel_get_fw_name(ver, params, fwname, sizeof(fwname), "sfi");
1820         if (err < 0) {
1821                 if (!btintel_test_flag(hdev, INTEL_BOOTLOADER)) {
1822                         /* Firmware has already been loaded */
1823                         btintel_set_flag(hdev, INTEL_FIRMWARE_LOADED);
1824                         return 0;
1825                 }
1826
1827                 bt_dev_err(hdev, "Unsupported Intel firmware naming");
1828                 return -EINVAL;
1829         }
1830
1831         err = firmware_request_nowarn(&fw, fwname, &hdev->dev);
1832         if (err < 0) {
1833                 if (!btintel_test_flag(hdev, INTEL_BOOTLOADER)) {
1834                         /* Firmware has already been loaded */
1835                         btintel_set_flag(hdev, INTEL_FIRMWARE_LOADED);
1836                         return 0;
1837                 }
1838
1839                 bt_dev_err(hdev, "Failed to load Intel firmware file %s (%d)",
1840                            fwname, err);
1841                 return err;
1842         }
1843
1844         bt_dev_info(hdev, "Found device firmware: %s", fwname);
1845
1846         if (fw->size < 644) {
1847                 bt_dev_err(hdev, "Invalid size of firmware file (%zu)",
1848                            fw->size);
1849                 err = -EBADF;
1850                 goto done;
1851         }
1852
1853         calltime = ktime_get();
1854
1855         btintel_set_flag(hdev, INTEL_DOWNLOADING);
1856
1857         /* Start firmware downloading and get boot parameter */
1858         err = btintel_download_firmware(hdev, ver, fw, boot_param);
1859         if (err < 0) {
1860                 if (err == -EALREADY) {
1861                         /* Firmware has already been loaded */
1862                         btintel_set_flag(hdev, INTEL_FIRMWARE_LOADED);
1863                         err = 0;
1864                         goto done;
1865                 }
1866
1867                 /* When FW download fails, send Intel Reset to retry
1868                  * FW download.
1869                  */
1870                 btintel_reset_to_bootloader(hdev);
1871                 goto done;
1872         }
1873
1874         /* Before switching the device into operational mode and with that
1875          * booting the loaded firmware, wait for the bootloader notification
1876          * that all fragments have been successfully received.
1877          *
1878          * When the event processing receives the notification, then the
1879          * INTEL_DOWNLOADING flag will be cleared.
1880          *
1881          * The firmware loading should not take longer than 5 seconds
1882          * and thus just timeout if that happens and fail the setup
1883          * of this device.
1884          */
1885         err = btintel_download_wait(hdev, calltime, 5000);
1886         if (err == -ETIMEDOUT)
1887                 btintel_reset_to_bootloader(hdev);
1888
1889 done:
1890         release_firmware(fw);
1891         return err;
1892 }
1893
1894 static int btintel_bootloader_setup(struct hci_dev *hdev,
1895                                     struct intel_version *ver)
1896 {
1897         struct intel_version new_ver;
1898         struct intel_boot_params params;
1899         u32 boot_param;
1900         char ddcname[64];
1901         int err;
1902         struct intel_debug_features features;
1903
1904         BT_DBG("%s", hdev->name);
1905
1906         /* Set the default boot parameter to 0x0 and it is updated to
1907          * SKU specific boot parameter after reading Intel_Write_Boot_Params
1908          * command while downloading the firmware.
1909          */
1910         boot_param = 0x00000000;
1911
1912         btintel_set_flag(hdev, INTEL_BOOTLOADER);
1913
1914         err = btintel_download_fw(hdev, ver, &params, &boot_param);
1915         if (err)
1916                 return err;
1917
1918         /* controller is already having an operational firmware */
1919         if (ver->fw_variant == 0x23)
1920                 goto finish;
1921
1922         err = btintel_boot(hdev, boot_param);
1923         if (err)
1924                 return err;
1925
1926         btintel_clear_flag(hdev, INTEL_BOOTLOADER);
1927
1928         err = btintel_get_fw_name(ver, &params, ddcname,
1929                                                 sizeof(ddcname), "ddc");
1930
1931         if (err < 0) {
1932                 bt_dev_err(hdev, "Unsupported Intel firmware naming");
1933         } else {
1934                 /* Once the device is running in operational mode, it needs to
1935                  * apply the device configuration (DDC) parameters.
1936                  *
1937                  * The device can work without DDC parameters, so even if it
1938                  * fails to load the file, no need to fail the setup.
1939                  */
1940                 btintel_load_ddc_config(hdev, ddcname);
1941         }
1942
1943         /* Read the Intel supported features and if new exception formats
1944          * supported, need to load the additional DDC config to enable.
1945          */
1946         err = btintel_read_debug_features(hdev, &features);
1947         if (!err) {
1948                 /* Set DDC mask for available debug features */
1949                 btintel_set_debug_features(hdev, &features);
1950         }
1951
1952         /* Read the Intel version information after loading the FW  */
1953         err = btintel_read_version(hdev, &new_ver);
1954         if (err)
1955                 return err;
1956
1957         btintel_version_info(hdev, &new_ver);
1958
1959 finish:
1960         /* All Intel controllers that support the Microsoft vendor
1961          * extension are using 0xFC1E for VsMsftOpCode.
1962          */
1963         switch (ver->hw_variant) {
1964         case 0x11:      /* JfP */
1965         case 0x12:      /* ThP */
1966         case 0x13:      /* HrP */
1967         case 0x14:      /* CcP */
1968                 hci_set_msft_opcode(hdev, 0xFC1E);
1969                 break;
1970         }
1971
1972         /* Set the event mask for Intel specific vendor events. This enables
1973          * a few extra events that are useful during general operation. It
1974          * does not enable any debugging related events.
1975          *
1976          * The device will function correctly without these events enabled
1977          * and thus no need to fail the setup.
1978          */
1979         btintel_set_event_mask(hdev, false);
1980
1981         return 0;
1982 }
1983
1984 static void btintel_get_fw_name_tlv(const struct intel_version_tlv *ver,
1985                                     char *fw_name, size_t len,
1986                                     const char *suffix)
1987 {
1988         /* The firmware file name for new generation controllers will be
1989          * ibt-<cnvi_top type+cnvi_top step>-<cnvr_top type+cnvr_top step>
1990          */
1991         snprintf(fw_name, len, "intel/ibt-%04x-%04x.%s",
1992                  INTEL_CNVX_TOP_PACK_SWAB(INTEL_CNVX_TOP_TYPE(ver->cnvi_top),
1993                                           INTEL_CNVX_TOP_STEP(ver->cnvi_top)),
1994                  INTEL_CNVX_TOP_PACK_SWAB(INTEL_CNVX_TOP_TYPE(ver->cnvr_top),
1995                                           INTEL_CNVX_TOP_STEP(ver->cnvr_top)),
1996                  suffix);
1997 }
1998
1999 static int btintel_prepare_fw_download_tlv(struct hci_dev *hdev,
2000                                            struct intel_version_tlv *ver,
2001                                            u32 *boot_param)
2002 {
2003         const struct firmware *fw;
2004         char fwname[64];
2005         int err;
2006         ktime_t calltime;
2007
2008         if (!ver || !boot_param)
2009                 return -EINVAL;
2010
2011         /* The firmware variant determines if the device is in bootloader
2012          * mode or is running operational firmware. The value 0x03 identifies
2013          * the bootloader and the value 0x23 identifies the operational
2014          * firmware.
2015          *
2016          * When the operational firmware is already present, then only
2017          * the check for valid Bluetooth device address is needed. This
2018          * determines if the device will be added as configured or
2019          * unconfigured controller.
2020          *
2021          * It is not possible to use the Secure Boot Parameters in this
2022          * case since that command is only available in bootloader mode.
2023          */
2024         if (ver->img_type == 0x03) {
2025                 btintel_clear_flag(hdev, INTEL_BOOTLOADER);
2026                 btintel_check_bdaddr(hdev);
2027         }
2028
2029         /* If the OTP has no valid Bluetooth device address, then there will
2030          * also be no valid address for the operational firmware.
2031          */
2032         if (!bacmp(&ver->otp_bd_addr, BDADDR_ANY)) {
2033                 bt_dev_info(hdev, "No device address configured");
2034                 set_bit(HCI_QUIRK_INVALID_BDADDR, &hdev->quirks);
2035         }
2036
2037         btintel_get_fw_name_tlv(ver, fwname, sizeof(fwname), "sfi");
2038         err = firmware_request_nowarn(&fw, fwname, &hdev->dev);
2039         if (err < 0) {
2040                 if (!btintel_test_flag(hdev, INTEL_BOOTLOADER)) {
2041                         /* Firmware has already been loaded */
2042                         btintel_set_flag(hdev, INTEL_FIRMWARE_LOADED);
2043                         return 0;
2044                 }
2045
2046                 bt_dev_err(hdev, "Failed to load Intel firmware file %s (%d)",
2047                            fwname, err);
2048
2049                 return err;
2050         }
2051
2052         bt_dev_info(hdev, "Found device firmware: %s", fwname);
2053
2054         if (fw->size < 644) {
2055                 bt_dev_err(hdev, "Invalid size of firmware file (%zu)",
2056                            fw->size);
2057                 err = -EBADF;
2058                 goto done;
2059         }
2060
2061         calltime = ktime_get();
2062
2063         btintel_set_flag(hdev, INTEL_DOWNLOADING);
2064
2065         /* Start firmware downloading and get boot parameter */
2066         err = btintel_download_fw_tlv(hdev, ver, fw, boot_param,
2067                                                INTEL_HW_VARIANT(ver->cnvi_bt),
2068                                                ver->sbe_type);
2069         if (err < 0) {
2070                 if (err == -EALREADY) {
2071                         /* Firmware has already been loaded */
2072                         btintel_set_flag(hdev, INTEL_FIRMWARE_LOADED);
2073                         err = 0;
2074                         goto done;
2075                 }
2076
2077                 /* When FW download fails, send Intel Reset to retry
2078                  * FW download.
2079                  */
2080                 btintel_reset_to_bootloader(hdev);
2081                 goto done;
2082         }
2083
2084         /* Before switching the device into operational mode and with that
2085          * booting the loaded firmware, wait for the bootloader notification
2086          * that all fragments have been successfully received.
2087          *
2088          * When the event processing receives the notification, then the
2089          * BTUSB_DOWNLOADING flag will be cleared.
2090          *
2091          * The firmware loading should not take longer than 5 seconds
2092          * and thus just timeout if that happens and fail the setup
2093          * of this device.
2094          */
2095         err = btintel_download_wait(hdev, calltime, 5000);
2096         if (err == -ETIMEDOUT)
2097                 btintel_reset_to_bootloader(hdev);
2098
2099 done:
2100         release_firmware(fw);
2101         return err;
2102 }
2103
2104 static int btintel_bootloader_setup_tlv(struct hci_dev *hdev,
2105                                         struct intel_version_tlv *ver)
2106 {
2107         u32 boot_param;
2108         char ddcname[64];
2109         int err;
2110         struct intel_debug_features features;
2111         struct intel_version_tlv new_ver;
2112
2113         bt_dev_dbg(hdev, "");
2114
2115         /* Set the default boot parameter to 0x0 and it is updated to
2116          * SKU specific boot parameter after reading Intel_Write_Boot_Params
2117          * command while downloading the firmware.
2118          */
2119         boot_param = 0x00000000;
2120
2121         btintel_set_flag(hdev, INTEL_BOOTLOADER);
2122
2123         err = btintel_prepare_fw_download_tlv(hdev, ver, &boot_param);
2124         if (err)
2125                 return err;
2126
2127         /* check if controller is already having an operational firmware */
2128         if (ver->img_type == 0x03)
2129                 goto finish;
2130
2131         err = btintel_boot(hdev, boot_param);
2132         if (err)
2133                 return err;
2134
2135         btintel_clear_flag(hdev, INTEL_BOOTLOADER);
2136
2137         btintel_get_fw_name_tlv(ver, ddcname, sizeof(ddcname), "ddc");
2138         /* Once the device is running in operational mode, it needs to
2139          * apply the device configuration (DDC) parameters.
2140          *
2141          * The device can work without DDC parameters, so even if it
2142          * fails to load the file, no need to fail the setup.
2143          */
2144         btintel_load_ddc_config(hdev, ddcname);
2145
2146         /* Read the Intel supported features and if new exception formats
2147          * supported, need to load the additional DDC config to enable.
2148          */
2149         err = btintel_read_debug_features(hdev, &features);
2150         if (!err) {
2151                 /* Set DDC mask for available debug features */
2152                 btintel_set_debug_features(hdev, &features);
2153         }
2154
2155         /* Read the Intel version information after loading the FW  */
2156         err = btintel_read_version_tlv(hdev, &new_ver);
2157         if (err)
2158                 return err;
2159
2160         btintel_version_info_tlv(hdev, &new_ver);
2161
2162 finish:
2163         /* Set the event mask for Intel specific vendor events. This enables
2164          * a few extra events that are useful during general operation. It
2165          * does not enable any debugging related events.
2166          *
2167          * The device will function correctly without these events enabled
2168          * and thus no need to fail the setup.
2169          */
2170         btintel_set_event_mask(hdev, false);
2171
2172         return 0;
2173 }
2174
2175 static int btintel_setup_combined(struct hci_dev *hdev)
2176 {
2177         const u8 param[1] = { 0xFF };
2178         struct intel_version ver;
2179         struct intel_version_tlv ver_tlv;
2180         struct sk_buff *skb;
2181         int err;
2182
2183         BT_DBG("%s", hdev->name);
2184
2185         /* The some controllers have a bug with the first HCI command sent to it
2186          * returning number of completed commands as zero. This would stall the
2187          * command processing in the Bluetooth core.
2188          *
2189          * As a workaround, send HCI Reset command first which will reset the
2190          * number of completed commands and allow normal command processing
2191          * from now on.
2192          */
2193         if (btintel_test_flag(hdev, INTEL_BROKEN_INITIAL_NCMD)) {
2194                 skb = __hci_cmd_sync(hdev, HCI_OP_RESET, 0, NULL,
2195                                      HCI_INIT_TIMEOUT);
2196                 if (IS_ERR(skb)) {
2197                         bt_dev_err(hdev,
2198                                    "sending initial HCI reset failed (%ld)",
2199                                    PTR_ERR(skb));
2200                         return PTR_ERR(skb);
2201                 }
2202                 kfree_skb(skb);
2203         }
2204
2205         /* Starting from TyP device, the command parameter and response are
2206          * changed even though the OCF for HCI_Intel_Read_Version command
2207          * remains same. The legacy devices can handle even if the
2208          * command has a parameter and returns a correct version information.
2209          * So, it uses new format to support both legacy and new format.
2210          */
2211         skb = __hci_cmd_sync(hdev, 0xfc05, 1, param, HCI_CMD_TIMEOUT);
2212         if (IS_ERR(skb)) {
2213                 bt_dev_err(hdev, "Reading Intel version command failed (%ld)",
2214                            PTR_ERR(skb));
2215                 return PTR_ERR(skb);
2216         }
2217
2218         /* Check the status */
2219         if (skb->data[0]) {
2220                 bt_dev_err(hdev, "Intel Read Version command failed (%02x)",
2221                            skb->data[0]);
2222                 err = -EIO;
2223                 goto exit_error;
2224         }
2225
2226         /* Apply the common HCI quirks for Intel device */
2227         set_bit(HCI_QUIRK_STRICT_DUPLICATE_FILTER, &hdev->quirks);
2228         set_bit(HCI_QUIRK_SIMULTANEOUS_DISCOVERY, &hdev->quirks);
2229         set_bit(HCI_QUIRK_NON_PERSISTENT_DIAG, &hdev->quirks);
2230
2231         /* For Legacy device, check the HW platform value and size */
2232         if (skb->len == sizeof(ver) && skb->data[1] == 0x37) {
2233                 bt_dev_dbg(hdev, "Read the legacy Intel version information");
2234
2235                 memcpy(&ver, skb->data, sizeof(ver));
2236
2237                 /* Display version information */
2238                 btintel_version_info(hdev, &ver);
2239
2240                 /* Check for supported iBT hardware variants of this firmware
2241                  * loading method.
2242                  *
2243                  * This check has been put in place to ensure correct forward
2244                  * compatibility options when newer hardware variants come
2245                  * along.
2246                  */
2247                 switch (ver.hw_variant) {
2248                 case 0x07:      /* WP */
2249                 case 0x08:      /* StP */
2250                         /* Legacy ROM product */
2251                         btintel_set_flag(hdev, INTEL_ROM_LEGACY);
2252
2253                         /* Apply the device specific HCI quirks
2254                          *
2255                          * WBS for SdP - SdP and Stp have a same hw_varaint but
2256                          * different fw_variant
2257                          */
2258                         if (ver.hw_variant == 0x08 && ver.fw_variant == 0x22)
2259                                 set_bit(HCI_QUIRK_WIDEBAND_SPEECH_SUPPORTED,
2260                                         &hdev->quirks);
2261
2262                         /* These devices have an issue with LED which doesn't
2263                          * go off immediately during shutdown. Set the flag
2264                          * here to send the LED OFF command during shutdown.
2265                          */
2266                         btintel_set_flag(hdev, INTEL_BROKEN_LED);
2267
2268                         err = btintel_legacy_rom_setup(hdev, &ver);
2269                         break;
2270                 case 0x0b:      /* SfP */
2271                 case 0x0c:      /* WsP */
2272                 case 0x11:      /* JfP */
2273                 case 0x12:      /* ThP */
2274                 case 0x13:      /* HrP */
2275                 case 0x14:      /* CcP */
2276                         /* Apply the device specific HCI quirks
2277                          *
2278                          * All Legacy bootloader devices support WBS
2279                          */
2280                         set_bit(HCI_QUIRK_WIDEBAND_SPEECH_SUPPORTED,
2281                                 &hdev->quirks);
2282
2283                         /* Valid LE States quirk for JfP/ThP familiy */
2284                         if (ver.hw_variant == 0x11 || ver.hw_variant == 0x12)
2285                                 set_bit(HCI_QUIRK_VALID_LE_STATES,
2286                                         &hdev->quirks);
2287
2288                         err = btintel_bootloader_setup(hdev, &ver);
2289                         break;
2290                 default:
2291                         bt_dev_err(hdev, "Unsupported Intel hw variant (%u)",
2292                                    ver.hw_variant);
2293                         err = -EINVAL;
2294                 }
2295
2296                 goto exit_error;
2297         }
2298
2299         /* For TLV type device, parse the tlv data */
2300         err = btintel_parse_version_tlv(hdev, &ver_tlv, skb);
2301         if (err) {
2302                 bt_dev_err(hdev, "Failed to parse TLV version information");
2303                 goto exit_error;
2304         }
2305
2306         if (INTEL_HW_PLATFORM(ver_tlv.cnvi_bt) != 0x37) {
2307                 bt_dev_err(hdev, "Unsupported Intel hardware platform (0x%2x)",
2308                            INTEL_HW_PLATFORM(ver_tlv.cnvi_bt));
2309                 err = -EINVAL;
2310                 goto exit_error;
2311         }
2312
2313         /* Check for supported iBT hardware variants of this firmware
2314          * loading method.
2315          *
2316          * This check has been put in place to ensure correct forward
2317          * compatibility options when newer hardware variants come
2318          * along.
2319          */
2320         switch (INTEL_HW_VARIANT(ver_tlv.cnvi_bt)) {
2321         case 0x17:
2322         case 0x18:
2323         case 0x19:
2324                 /* Display version information of TLV type */
2325                 btintel_version_info_tlv(hdev, &ver_tlv);
2326
2327                 /* Apply the device specific HCI quirks for TLV based devices
2328                  *
2329                  * All TLV based devices support WBS
2330                  */
2331                 set_bit(HCI_QUIRK_WIDEBAND_SPEECH_SUPPORTED, &hdev->quirks);
2332
2333                 /* Valid LE States quirk for GfP */
2334                 if (INTEL_HW_VARIANT(ver_tlv.cnvi_bt) == 0x18)
2335                         set_bit(HCI_QUIRK_VALID_LE_STATES, &hdev->quirks);
2336
2337                 err = btintel_bootloader_setup_tlv(hdev, &ver_tlv);
2338                 break;
2339         default:
2340                 bt_dev_err(hdev, "Unsupported Intel hw variant (%u)",
2341                            INTEL_HW_VARIANT(ver_tlv.cnvi_bt));
2342                 return -EINVAL;
2343         }
2344
2345 exit_error:
2346         kfree_skb(skb);
2347
2348         return err;
2349 }
2350
2351 static int btintel_shutdown_combined(struct hci_dev *hdev)
2352 {
2353         struct sk_buff *skb;
2354         int ret;
2355
2356         /* Send HCI Reset to the controller to stop any BT activity which
2357          * were triggered. This will help to save power and maintain the
2358          * sync b/w Host and controller
2359          */
2360         skb = __hci_cmd_sync(hdev, HCI_OP_RESET, 0, NULL, HCI_INIT_TIMEOUT);
2361         if (IS_ERR(skb)) {
2362                 bt_dev_err(hdev, "HCI reset during shutdown failed");
2363                 return PTR_ERR(skb);
2364         }
2365         kfree_skb(skb);
2366
2367
2368         /* Some platforms have an issue with BT LED when the interface is
2369          * down or BT radio is turned off, which takes 5 seconds to BT LED
2370          * goes off. This command turns off the BT LED immediately.
2371          */
2372         if (btintel_test_flag(hdev, INTEL_BROKEN_LED)) {
2373                 skb = __hci_cmd_sync(hdev, 0xfc3f, 0, NULL, HCI_INIT_TIMEOUT);
2374                 if (IS_ERR(skb)) {
2375                         ret = PTR_ERR(skb);
2376                         bt_dev_err(hdev, "turning off Intel device LED failed");
2377                         return ret;
2378                 }
2379                 kfree_skb(skb);
2380         }
2381
2382         return 0;
2383 }
2384
2385 int btintel_configure_setup(struct hci_dev *hdev)
2386 {
2387         hdev->manufacturer = 2;
2388         hdev->setup = btintel_setup_combined;
2389         hdev->shutdown = btintel_shutdown_combined;
2390         hdev->hw_error = btintel_hw_error;
2391         hdev->set_diag = btintel_set_diag_combined;
2392         hdev->set_bdaddr = btintel_set_bdaddr;
2393
2394         return 0;
2395 }
2396 EXPORT_SYMBOL_GPL(btintel_configure_setup);
2397
2398 void btintel_bootup(struct hci_dev *hdev, const void *ptr, unsigned int len)
2399 {
2400         const struct intel_bootup *evt = ptr;
2401
2402         if (len != sizeof(*evt))
2403                 return;
2404
2405         if (btintel_test_and_clear_flag(hdev, INTEL_BOOTING))
2406                 btintel_wake_up_flag(hdev, INTEL_BOOTING);
2407 }
2408 EXPORT_SYMBOL_GPL(btintel_bootup);
2409
2410 void btintel_secure_send_result(struct hci_dev *hdev,
2411                                 const void *ptr, unsigned int len)
2412 {
2413         const struct intel_secure_send_result *evt = ptr;
2414
2415         if (len != sizeof(*evt))
2416                 return;
2417
2418         if (evt->result)
2419                 btintel_set_flag(hdev, INTEL_FIRMWARE_FAILED);
2420
2421         if (btintel_test_and_clear_flag(hdev, INTEL_DOWNLOADING) &&
2422             btintel_test_flag(hdev, INTEL_FIRMWARE_LOADED))
2423                 btintel_wake_up_flag(hdev, INTEL_DOWNLOADING);
2424 }
2425 EXPORT_SYMBOL_GPL(btintel_secure_send_result);
2426
2427 MODULE_AUTHOR("Marcel Holtmann <marcel@holtmann.org>");
2428 MODULE_DESCRIPTION("Bluetooth support for Intel devices ver " VERSION);
2429 MODULE_VERSION(VERSION);
2430 MODULE_LICENSE("GPL");
2431 MODULE_FIRMWARE("intel/ibt-11-5.sfi");
2432 MODULE_FIRMWARE("intel/ibt-11-5.ddc");
2433 MODULE_FIRMWARE("intel/ibt-12-16.sfi");
2434 MODULE_FIRMWARE("intel/ibt-12-16.ddc");