Bluetooth: hci_intel: Add runtime PM support
[firefly-linux-kernel-4.4.55.git] / drivers / bluetooth / hci_intel.c
1 /*
2  *
3  *  Bluetooth HCI UART driver for Intel devices
4  *
5  *  Copyright (C) 2015  Intel Corporation
6  *
7  *
8  *  This program is free software; you can redistribute it and/or modify
9  *  it under the terms of the GNU General Public License as published by
10  *  the Free Software Foundation; either version 2 of the License, or
11  *  (at your option) any later version.
12  *
13  *  This program is distributed in the hope that it will be useful,
14  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
15  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  *  GNU General Public License for more details.
17  *
18  *  You should have received a copy of the GNU General Public License
19  *  along with this program; if not, write to the Free Software
20  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
21  *
22  */
23
24 #include <linux/kernel.h>
25 #include <linux/errno.h>
26 #include <linux/skbuff.h>
27 #include <linux/firmware.h>
28 #include <linux/module.h>
29 #include <linux/wait.h>
30 #include <linux/tty.h>
31 #include <linux/platform_device.h>
32 #include <linux/gpio/consumer.h>
33 #include <linux/acpi.h>
34 #include <linux/interrupt.h>
35 #include <linux/pm_runtime.h>
36
37 #include <net/bluetooth/bluetooth.h>
38 #include <net/bluetooth/hci_core.h>
39
40 #include "hci_uart.h"
41 #include "btintel.h"
42
43 #define STATE_BOOTLOADER        0
44 #define STATE_DOWNLOADING       1
45 #define STATE_FIRMWARE_LOADED   2
46 #define STATE_FIRMWARE_FAILED   3
47 #define STATE_BOOTING           4
48 #define STATE_LPM_ENABLED       5
49 #define STATE_TX_ACTIVE         6
50 #define STATE_SUSPENDED         7
51 #define STATE_LPM_TRANSACTION   8
52
53 #define HCI_LPM_WAKE_PKT 0xf0
54 #define HCI_LPM_PKT 0xf1
55 #define HCI_LPM_MAX_SIZE 10
56 #define HCI_LPM_HDR_SIZE HCI_EVENT_HDR_SIZE
57
58 #define LPM_OP_TX_NOTIFY 0x00
59 #define LPM_OP_SUSPEND_ACK 0x02
60 #define LPM_OP_RESUME_ACK 0x03
61
62 #define LPM_SUSPEND_DELAY_MS 1000
63
64 struct hci_lpm_pkt {
65         __u8 opcode;
66         __u8 dlen;
67         __u8 data[0];
68 } __packed;
69
70 struct intel_device {
71         struct list_head list;
72         struct platform_device *pdev;
73         struct gpio_desc *reset;
74         struct hci_uart *hu;
75         struct mutex hu_lock;
76         int irq;
77 };
78
79 static LIST_HEAD(intel_device_list);
80 static DEFINE_MUTEX(intel_device_list_lock);
81
82 struct intel_data {
83         struct sk_buff *rx_skb;
84         struct sk_buff_head txq;
85         struct work_struct busy_work;
86         struct hci_uart *hu;
87         unsigned long flags;
88 };
89
90 static u8 intel_convert_speed(unsigned int speed)
91 {
92         switch (speed) {
93         case 9600:
94                 return 0x00;
95         case 19200:
96                 return 0x01;
97         case 38400:
98                 return 0x02;
99         case 57600:
100                 return 0x03;
101         case 115200:
102                 return 0x04;
103         case 230400:
104                 return 0x05;
105         case 460800:
106                 return 0x06;
107         case 921600:
108                 return 0x07;
109         case 1843200:
110                 return 0x08;
111         case 3250000:
112                 return 0x09;
113         case 2000000:
114                 return 0x0a;
115         case 3000000:
116                 return 0x0b;
117         default:
118                 return 0xff;
119         }
120 }
121
122 static int intel_wait_booting(struct hci_uart *hu)
123 {
124         struct intel_data *intel = hu->priv;
125         int err;
126
127         err = wait_on_bit_timeout(&intel->flags, STATE_BOOTING,
128                                   TASK_INTERRUPTIBLE,
129                                   msecs_to_jiffies(1000));
130
131         if (err == 1) {
132                 bt_dev_err(hu->hdev, "Device boot interrupted");
133                 return -EINTR;
134         }
135
136         if (err) {
137                 bt_dev_err(hu->hdev, "Device boot timeout");
138                 return -ETIMEDOUT;
139         }
140
141         return err;
142 }
143
144 static int intel_wait_lpm_transaction(struct hci_uart *hu)
145 {
146         struct intel_data *intel = hu->priv;
147         int err;
148
149         err = wait_on_bit_timeout(&intel->flags, STATE_LPM_TRANSACTION,
150                                   TASK_INTERRUPTIBLE,
151                                   msecs_to_jiffies(1000));
152
153         if (err == 1) {
154                 bt_dev_err(hu->hdev, "LPM transaction interrupted");
155                 return -EINTR;
156         }
157
158         if (err) {
159                 bt_dev_err(hu->hdev, "LPM transaction timeout");
160                 return -ETIMEDOUT;
161         }
162
163         return err;
164 }
165
166 static int intel_lpm_suspend(struct hci_uart *hu)
167 {
168         static const u8 suspend[] = { 0x01, 0x01, 0x01 };
169         struct intel_data *intel = hu->priv;
170         struct sk_buff *skb;
171
172         if (!test_bit(STATE_LPM_ENABLED, &intel->flags) ||
173             test_bit(STATE_SUSPENDED, &intel->flags))
174                 return 0;
175
176         if (test_bit(STATE_TX_ACTIVE, &intel->flags))
177                 return -EAGAIN;
178
179         bt_dev_dbg(hu->hdev, "Suspending");
180
181         skb = bt_skb_alloc(sizeof(suspend), GFP_KERNEL);
182         if (!skb) {
183                 bt_dev_err(hu->hdev, "Failed to alloc memory for LPM packet");
184                 return -ENOMEM;
185         }
186
187         memcpy(skb_put(skb, sizeof(suspend)), suspend, sizeof(suspend));
188         bt_cb(skb)->pkt_type = HCI_LPM_PKT;
189
190         set_bit(STATE_LPM_TRANSACTION, &intel->flags);
191
192         skb_queue_tail(&intel->txq, skb);
193         hci_uart_tx_wakeup(hu);
194
195         intel_wait_lpm_transaction(hu);
196         /* Even in case of failure, continue and test the suspended flag */
197
198         clear_bit(STATE_LPM_TRANSACTION, &intel->flags);
199
200         if (!test_bit(STATE_SUSPENDED, &intel->flags)) {
201                 bt_dev_err(hu->hdev, "Device suspend error");
202                 return -EINVAL;
203         }
204
205         bt_dev_dbg(hu->hdev, "Suspended");
206
207         hci_uart_set_flow_control(hu, true);
208
209         return 0;
210 }
211
212 static int intel_lpm_resume(struct hci_uart *hu)
213 {
214         struct intel_data *intel = hu->priv;
215         struct sk_buff *skb;
216
217         if (!test_bit(STATE_LPM_ENABLED, &intel->flags) ||
218             !test_bit(STATE_SUSPENDED, &intel->flags))
219                 return 0;
220
221         bt_dev_dbg(hu->hdev, "Resuming");
222
223         hci_uart_set_flow_control(hu, false);
224
225         skb = bt_skb_alloc(0, GFP_KERNEL);
226         if (!skb) {
227                 bt_dev_err(hu->hdev, "Failed to alloc memory for LPM packet");
228                 return -ENOMEM;
229         }
230
231         bt_cb(skb)->pkt_type = HCI_LPM_WAKE_PKT;
232
233         set_bit(STATE_LPM_TRANSACTION, &intel->flags);
234
235         skb_queue_tail(&intel->txq, skb);
236         hci_uart_tx_wakeup(hu);
237
238         intel_wait_lpm_transaction(hu);
239         /* Even in case of failure, continue and test the suspended flag */
240
241         clear_bit(STATE_LPM_TRANSACTION, &intel->flags);
242
243         if (test_bit(STATE_SUSPENDED, &intel->flags)) {
244                 bt_dev_err(hu->hdev, "Device resume error");
245                 return -EINVAL;
246         }
247
248         bt_dev_dbg(hu->hdev, "Resumed");
249
250         return 0;
251 }
252
253 static int intel_lpm_host_wake(struct hci_uart *hu)
254 {
255         static const u8 lpm_resume_ack[] = { LPM_OP_RESUME_ACK, 0x00 };
256         struct intel_data *intel = hu->priv;
257         struct sk_buff *skb;
258
259         hci_uart_set_flow_control(hu, false);
260
261         clear_bit(STATE_SUSPENDED, &intel->flags);
262
263         skb = bt_skb_alloc(sizeof(lpm_resume_ack), GFP_KERNEL);
264         if (!skb) {
265                 bt_dev_err(hu->hdev, "Failed to alloc memory for LPM packet");
266                 return -ENOMEM;
267         }
268
269         memcpy(skb_put(skb, sizeof(lpm_resume_ack)), lpm_resume_ack,
270                sizeof(lpm_resume_ack));
271         bt_cb(skb)->pkt_type = HCI_LPM_PKT;
272
273         skb_queue_tail(&intel->txq, skb);
274         hci_uart_tx_wakeup(hu);
275
276         bt_dev_dbg(hu->hdev, "Resumed by controller");
277
278         return 0;
279 }
280
281 static irqreturn_t intel_irq(int irq, void *dev_id)
282 {
283         struct intel_device *idev = dev_id;
284
285         dev_info(&idev->pdev->dev, "hci_intel irq\n");
286
287         mutex_lock(&idev->hu_lock);
288         if (idev->hu)
289                 intel_lpm_host_wake(idev->hu);
290         mutex_unlock(&idev->hu_lock);
291
292         /* Host/Controller are now LPM resumed, trigger a new delayed suspend */
293         pm_runtime_get(&idev->pdev->dev);
294         pm_runtime_mark_last_busy(&idev->pdev->dev);
295         pm_runtime_put_autosuspend(&idev->pdev->dev);
296
297         return IRQ_HANDLED;
298 }
299
300 static int intel_set_power(struct hci_uart *hu, bool powered)
301 {
302         struct list_head *p;
303         int err = -ENODEV;
304
305         mutex_lock(&intel_device_list_lock);
306
307         list_for_each(p, &intel_device_list) {
308                 struct intel_device *idev = list_entry(p, struct intel_device,
309                                                        list);
310
311                 /* tty device and pdev device should share the same parent
312                  * which is the UART port.
313                  */
314                 if (hu->tty->dev->parent != idev->pdev->dev.parent)
315                         continue;
316
317                 if (!idev->reset) {
318                         err = -ENOTSUPP;
319                         break;
320                 }
321
322                 BT_INFO("hu %p, Switching compatible pm device (%s) to %u",
323                         hu, dev_name(&idev->pdev->dev), powered);
324
325                 gpiod_set_value(idev->reset, powered);
326
327                 /* Provide to idev a hu reference which is used to run LPM
328                  * transactions (lpm suspend/resume) from PM callbacks.
329                  * hu needs to be protected against concurrent removing during
330                  * these PM ops.
331                  */
332                 mutex_lock(&idev->hu_lock);
333                 idev->hu = powered ? hu : NULL;
334                 mutex_unlock(&idev->hu_lock);
335
336                 if (idev->irq < 0)
337                         break;
338
339                 if (powered && device_can_wakeup(&idev->pdev->dev)) {
340                         err = devm_request_threaded_irq(&idev->pdev->dev,
341                                                         idev->irq, NULL,
342                                                         intel_irq,
343                                                         IRQF_ONESHOT,
344                                                         "bt-host-wake", idev);
345                         if (err) {
346                                 BT_ERR("hu %p, unable to allocate irq-%d",
347                                        hu, idev->irq);
348                                 break;
349                         }
350
351                         device_wakeup_enable(&idev->pdev->dev);
352
353                         pm_runtime_set_active(&idev->pdev->dev);
354                         pm_runtime_use_autosuspend(&idev->pdev->dev);
355                         pm_runtime_set_autosuspend_delay(&idev->pdev->dev,
356                                                          LPM_SUSPEND_DELAY_MS);
357                         pm_runtime_enable(&idev->pdev->dev);
358                 } else if (!powered && device_may_wakeup(&idev->pdev->dev)) {
359                         devm_free_irq(&idev->pdev->dev, idev->irq, idev);
360                         device_wakeup_disable(&idev->pdev->dev);
361
362                         pm_runtime_disable(&idev->pdev->dev);
363                 }
364         }
365
366         mutex_unlock(&intel_device_list_lock);
367
368         return err;
369 }
370
371 static void intel_busy_work(struct work_struct *work)
372 {
373         struct list_head *p;
374         struct intel_data *intel = container_of(work, struct intel_data,
375                                                 busy_work);
376
377         /* Link is busy, delay the suspend */
378         mutex_lock(&intel_device_list_lock);
379         list_for_each(p, &intel_device_list) {
380                 struct intel_device *idev = list_entry(p, struct intel_device,
381                                                        list);
382
383                 if (intel->hu->tty->dev->parent == idev->pdev->dev.parent) {
384                         pm_runtime_get(&idev->pdev->dev);
385                         pm_runtime_mark_last_busy(&idev->pdev->dev);
386                         pm_runtime_put_autosuspend(&idev->pdev->dev);
387                         break;
388                 }
389         }
390         mutex_unlock(&intel_device_list_lock);
391 }
392
393 static int intel_open(struct hci_uart *hu)
394 {
395         struct intel_data *intel;
396
397         BT_DBG("hu %p", hu);
398
399         intel = kzalloc(sizeof(*intel), GFP_KERNEL);
400         if (!intel)
401                 return -ENOMEM;
402
403         skb_queue_head_init(&intel->txq);
404         INIT_WORK(&intel->busy_work, intel_busy_work);
405
406         intel->hu = hu;
407
408         hu->priv = intel;
409
410         if (!intel_set_power(hu, true))
411                 set_bit(STATE_BOOTING, &intel->flags);
412
413         return 0;
414 }
415
416 static int intel_close(struct hci_uart *hu)
417 {
418         struct intel_data *intel = hu->priv;
419
420         BT_DBG("hu %p", hu);
421
422         cancel_work_sync(&intel->busy_work);
423
424         intel_set_power(hu, false);
425
426         skb_queue_purge(&intel->txq);
427         kfree_skb(intel->rx_skb);
428         kfree(intel);
429
430         hu->priv = NULL;
431         return 0;
432 }
433
434 static int intel_flush(struct hci_uart *hu)
435 {
436         struct intel_data *intel = hu->priv;
437
438         BT_DBG("hu %p", hu);
439
440         skb_queue_purge(&intel->txq);
441
442         return 0;
443 }
444
445 static int inject_cmd_complete(struct hci_dev *hdev, __u16 opcode)
446 {
447         struct sk_buff *skb;
448         struct hci_event_hdr *hdr;
449         struct hci_ev_cmd_complete *evt;
450
451         skb = bt_skb_alloc(sizeof(*hdr) + sizeof(*evt) + 1, GFP_ATOMIC);
452         if (!skb)
453                 return -ENOMEM;
454
455         hdr = (struct hci_event_hdr *)skb_put(skb, sizeof(*hdr));
456         hdr->evt = HCI_EV_CMD_COMPLETE;
457         hdr->plen = sizeof(*evt) + 1;
458
459         evt = (struct hci_ev_cmd_complete *)skb_put(skb, sizeof(*evt));
460         evt->ncmd = 0x01;
461         evt->opcode = cpu_to_le16(opcode);
462
463         *skb_put(skb, 1) = 0x00;
464
465         bt_cb(skb)->pkt_type = HCI_EVENT_PKT;
466
467         return hci_recv_frame(hdev, skb);
468 }
469
470 static int intel_set_baudrate(struct hci_uart *hu, unsigned int speed)
471 {
472         struct intel_data *intel = hu->priv;
473         struct hci_dev *hdev = hu->hdev;
474         u8 speed_cmd[] = { 0x06, 0xfc, 0x01, 0x00 };
475         struct sk_buff *skb;
476         int err;
477
478         /* This can be the first command sent to the chip, check
479          * that the controller is ready.
480          */
481         err = intel_wait_booting(hu);
482
483         clear_bit(STATE_BOOTING, &intel->flags);
484
485         /* In case of timeout, try to continue anyway */
486         if (err && err != ETIMEDOUT)
487                 return err;
488
489         bt_dev_info(hdev, "Change controller speed to %d", speed);
490
491         speed_cmd[3] = intel_convert_speed(speed);
492         if (speed_cmd[3] == 0xff) {
493                 bt_dev_err(hdev, "Unsupported speed");
494                 return -EINVAL;
495         }
496
497         /* Device will not accept speed change if Intel version has not been
498          * previously requested.
499          */
500         skb = __hci_cmd_sync(hdev, 0xfc05, 0, NULL, HCI_INIT_TIMEOUT);
501         if (IS_ERR(skb)) {
502                 bt_dev_err(hdev, "Reading Intel version information failed (%ld)",
503                            PTR_ERR(skb));
504                 return PTR_ERR(skb);
505         }
506         kfree_skb(skb);
507
508         skb = bt_skb_alloc(sizeof(speed_cmd), GFP_KERNEL);
509         if (!skb) {
510                 bt_dev_err(hdev, "Failed to alloc memory for baudrate packet");
511                 return -ENOMEM;
512         }
513
514         memcpy(skb_put(skb, sizeof(speed_cmd)), speed_cmd, sizeof(speed_cmd));
515         bt_cb(skb)->pkt_type = HCI_COMMAND_PKT;
516
517         hci_uart_set_flow_control(hu, true);
518
519         skb_queue_tail(&intel->txq, skb);
520         hci_uart_tx_wakeup(hu);
521
522         /* wait 100ms to change baudrate on controller side */
523         msleep(100);
524
525         hci_uart_set_baudrate(hu, speed);
526         hci_uart_set_flow_control(hu, false);
527
528         return 0;
529 }
530
531 static int intel_setup(struct hci_uart *hu)
532 {
533         static const u8 reset_param[] = { 0x00, 0x01, 0x00, 0x01,
534                                           0x00, 0x08, 0x04, 0x00 };
535         static const u8 lpm_param[] = { 0x03, 0x07, 0x01, 0x0b };
536         struct intel_data *intel = hu->priv;
537         struct intel_device *idev = NULL;
538         struct hci_dev *hdev = hu->hdev;
539         struct sk_buff *skb;
540         struct intel_version *ver;
541         struct intel_boot_params *params;
542         struct list_head *p;
543         const struct firmware *fw;
544         const u8 *fw_ptr;
545         char fwname[64];
546         u32 frag_len;
547         ktime_t calltime, delta, rettime;
548         unsigned long long duration;
549         unsigned int init_speed, oper_speed;
550         int speed_change = 0;
551         int err;
552
553         bt_dev_dbg(hdev, "start intel_setup");
554
555         hu->hdev->set_bdaddr = btintel_set_bdaddr;
556
557         calltime = ktime_get();
558
559         if (hu->init_speed)
560                 init_speed = hu->init_speed;
561         else
562                 init_speed = hu->proto->init_speed;
563
564         if (hu->oper_speed)
565                 oper_speed = hu->oper_speed;
566         else
567                 oper_speed = hu->proto->oper_speed;
568
569         if (oper_speed && init_speed && oper_speed != init_speed)
570                 speed_change = 1;
571
572         /* Check that the controller is ready */
573         err = intel_wait_booting(hu);
574
575         clear_bit(STATE_BOOTING, &intel->flags);
576
577         /* In case of timeout, try to continue anyway */
578         if (err && err != ETIMEDOUT)
579                 return err;
580
581         set_bit(STATE_BOOTLOADER, &intel->flags);
582
583         /* Read the Intel version information to determine if the device
584          * is in bootloader mode or if it already has operational firmware
585          * loaded.
586          */
587         skb = __hci_cmd_sync(hdev, 0xfc05, 0, NULL, HCI_INIT_TIMEOUT);
588         if (IS_ERR(skb)) {
589                 bt_dev_err(hdev, "Reading Intel version information failed (%ld)",
590                            PTR_ERR(skb));
591                 return PTR_ERR(skb);
592         }
593
594         if (skb->len != sizeof(*ver)) {
595                 bt_dev_err(hdev, "Intel version event size mismatch");
596                 kfree_skb(skb);
597                 return -EILSEQ;
598         }
599
600         ver = (struct intel_version *)skb->data;
601         if (ver->status) {
602                 bt_dev_err(hdev, "Intel version command failure (%02x)",
603                            ver->status);
604                 err = -bt_to_errno(ver->status);
605                 kfree_skb(skb);
606                 return err;
607         }
608
609         /* The hardware platform number has a fixed value of 0x37 and
610          * for now only accept this single value.
611          */
612         if (ver->hw_platform != 0x37) {
613                 bt_dev_err(hdev, "Unsupported Intel hardware platform (%u)",
614                            ver->hw_platform);
615                 kfree_skb(skb);
616                 return -EINVAL;
617         }
618
619         /* At the moment only the hardware variant iBT 3.0 (LnP/SfP) is
620          * supported by this firmware loading method. This check has been
621          * put in place to ensure correct forward compatibility options
622          * when newer hardware variants come along.
623          */
624         if (ver->hw_variant != 0x0b) {
625                 bt_dev_err(hdev, "Unsupported Intel hardware variant (%u)",
626                            ver->hw_variant);
627                 kfree_skb(skb);
628                 return -EINVAL;
629         }
630
631         btintel_version_info(hdev, ver);
632
633         /* The firmware variant determines if the device is in bootloader
634          * mode or is running operational firmware. The value 0x06 identifies
635          * the bootloader and the value 0x23 identifies the operational
636          * firmware.
637          *
638          * When the operational firmware is already present, then only
639          * the check for valid Bluetooth device address is needed. This
640          * determines if the device will be added as configured or
641          * unconfigured controller.
642          *
643          * It is not possible to use the Secure Boot Parameters in this
644          * case since that command is only available in bootloader mode.
645          */
646         if (ver->fw_variant == 0x23) {
647                 kfree_skb(skb);
648                 clear_bit(STATE_BOOTLOADER, &intel->flags);
649                 btintel_check_bdaddr(hdev);
650                 return 0;
651         }
652
653         /* If the device is not in bootloader mode, then the only possible
654          * choice is to return an error and abort the device initialization.
655          */
656         if (ver->fw_variant != 0x06) {
657                 bt_dev_err(hdev, "Unsupported Intel firmware variant (%u)",
658                            ver->fw_variant);
659                 kfree_skb(skb);
660                 return -ENODEV;
661         }
662
663         kfree_skb(skb);
664
665         /* Read the secure boot parameters to identify the operating
666          * details of the bootloader.
667          */
668         skb = __hci_cmd_sync(hdev, 0xfc0d, 0, NULL, HCI_INIT_TIMEOUT);
669         if (IS_ERR(skb)) {
670                 bt_dev_err(hdev, "Reading Intel boot parameters failed (%ld)",
671                            PTR_ERR(skb));
672                 return PTR_ERR(skb);
673         }
674
675         if (skb->len != sizeof(*params)) {
676                 bt_dev_err(hdev, "Intel boot parameters size mismatch");
677                 kfree_skb(skb);
678                 return -EILSEQ;
679         }
680
681         params = (struct intel_boot_params *)skb->data;
682         if (params->status) {
683                 bt_dev_err(hdev, "Intel boot parameters command failure (%02x)",
684                            params->status);
685                 err = -bt_to_errno(params->status);
686                 kfree_skb(skb);
687                 return err;
688         }
689
690         bt_dev_info(hdev, "Device revision is %u",
691                     le16_to_cpu(params->dev_revid));
692
693         bt_dev_info(hdev, "Secure boot is %s",
694                     params->secure_boot ? "enabled" : "disabled");
695
696         bt_dev_info(hdev, "Minimum firmware build %u week %u %u",
697                 params->min_fw_build_nn, params->min_fw_build_cw,
698                 2000 + params->min_fw_build_yy);
699
700         /* It is required that every single firmware fragment is acknowledged
701          * with a command complete event. If the boot parameters indicate
702          * that this bootloader does not send them, then abort the setup.
703          */
704         if (params->limited_cce != 0x00) {
705                 bt_dev_err(hdev, "Unsupported Intel firmware loading method (%u)",
706                            params->limited_cce);
707                 kfree_skb(skb);
708                 return -EINVAL;
709         }
710
711         /* If the OTP has no valid Bluetooth device address, then there will
712          * also be no valid address for the operational firmware.
713          */
714         if (!bacmp(&params->otp_bdaddr, BDADDR_ANY)) {
715                 bt_dev_info(hdev, "No device address configured");
716                 set_bit(HCI_QUIRK_INVALID_BDADDR, &hdev->quirks);
717         }
718
719         /* With this Intel bootloader only the hardware variant and device
720          * revision information are used to select the right firmware.
721          *
722          * Currently this bootloader support is limited to hardware variant
723          * iBT 3.0 (LnP/SfP) which is identified by the value 11 (0x0b).
724          */
725         snprintf(fwname, sizeof(fwname), "intel/ibt-11-%u.sfi",
726                  le16_to_cpu(params->dev_revid));
727
728         err = request_firmware(&fw, fwname, &hdev->dev);
729         if (err < 0) {
730                 bt_dev_err(hdev, "Failed to load Intel firmware file (%d)",
731                            err);
732                 kfree_skb(skb);
733                 return err;
734         }
735
736         bt_dev_info(hdev, "Found device firmware: %s", fwname);
737
738         kfree_skb(skb);
739
740         if (fw->size < 644) {
741                 bt_dev_err(hdev, "Invalid size of firmware file (%zu)",
742                            fw->size);
743                 err = -EBADF;
744                 goto done;
745         }
746
747         set_bit(STATE_DOWNLOADING, &intel->flags);
748
749         /* Start the firmware download transaction with the Init fragment
750          * represented by the 128 bytes of CSS header.
751          */
752         err = btintel_secure_send(hdev, 0x00, 128, fw->data);
753         if (err < 0) {
754                 bt_dev_err(hdev, "Failed to send firmware header (%d)", err);
755                 goto done;
756         }
757
758         /* Send the 256 bytes of public key information from the firmware
759          * as the PKey fragment.
760          */
761         err = btintel_secure_send(hdev, 0x03, 256, fw->data + 128);
762         if (err < 0) {
763                 bt_dev_err(hdev, "Failed to send firmware public key (%d)",
764                            err);
765                 goto done;
766         }
767
768         /* Send the 256 bytes of signature information from the firmware
769          * as the Sign fragment.
770          */
771         err = btintel_secure_send(hdev, 0x02, 256, fw->data + 388);
772         if (err < 0) {
773                 bt_dev_err(hdev, "Failed to send firmware signature (%d)",
774                            err);
775                 goto done;
776         }
777
778         fw_ptr = fw->data + 644;
779         frag_len = 0;
780
781         while (fw_ptr - fw->data < fw->size) {
782                 struct hci_command_hdr *cmd = (void *)(fw_ptr + frag_len);
783
784                 frag_len += sizeof(*cmd) + cmd->plen;
785
786                 bt_dev_dbg(hdev, "Patching %td/%zu", (fw_ptr - fw->data),
787                            fw->size);
788
789                 /* The parameter length of the secure send command requires
790                  * a 4 byte alignment. It happens so that the firmware file
791                  * contains proper Intel_NOP commands to align the fragments
792                  * as needed.
793                  *
794                  * Send set of commands with 4 byte alignment from the
795                  * firmware data buffer as a single Data fragement.
796                  */
797                 if (frag_len % 4)
798                         continue;
799
800                 /* Send each command from the firmware data buffer as
801                  * a single Data fragment.
802                  */
803                 err = btintel_secure_send(hdev, 0x01, frag_len, fw_ptr);
804                 if (err < 0) {
805                         bt_dev_err(hdev, "Failed to send firmware data (%d)",
806                                    err);
807                         goto done;
808                 }
809
810                 fw_ptr += frag_len;
811                 frag_len = 0;
812         }
813
814         set_bit(STATE_FIRMWARE_LOADED, &intel->flags);
815
816         bt_dev_info(hdev, "Waiting for firmware download to complete");
817
818         /* Before switching the device into operational mode and with that
819          * booting the loaded firmware, wait for the bootloader notification
820          * that all fragments have been successfully received.
821          *
822          * When the event processing receives the notification, then the
823          * STATE_DOWNLOADING flag will be cleared.
824          *
825          * The firmware loading should not take longer than 5 seconds
826          * and thus just timeout if that happens and fail the setup
827          * of this device.
828          */
829         err = wait_on_bit_timeout(&intel->flags, STATE_DOWNLOADING,
830                                   TASK_INTERRUPTIBLE,
831                                   msecs_to_jiffies(5000));
832         if (err == 1) {
833                 bt_dev_err(hdev, "Firmware loading interrupted");
834                 err = -EINTR;
835                 goto done;
836         }
837
838         if (err) {
839                 bt_dev_err(hdev, "Firmware loading timeout");
840                 err = -ETIMEDOUT;
841                 goto done;
842         }
843
844         if (test_bit(STATE_FIRMWARE_FAILED, &intel->flags)) {
845                 bt_dev_err(hdev, "Firmware loading failed");
846                 err = -ENOEXEC;
847                 goto done;
848         }
849
850         rettime = ktime_get();
851         delta = ktime_sub(rettime, calltime);
852         duration = (unsigned long long) ktime_to_ns(delta) >> 10;
853
854         bt_dev_info(hdev, "Firmware loaded in %llu usecs", duration);
855
856 done:
857         release_firmware(fw);
858
859         if (err < 0)
860                 return err;
861
862         /* We need to restore the default speed before Intel reset */
863         if (speed_change) {
864                 err = intel_set_baudrate(hu, init_speed);
865                 if (err)
866                         return err;
867         }
868
869         calltime = ktime_get();
870
871         set_bit(STATE_BOOTING, &intel->flags);
872
873         skb = __hci_cmd_sync(hdev, 0xfc01, sizeof(reset_param), reset_param,
874                              HCI_INIT_TIMEOUT);
875         if (IS_ERR(skb))
876                 return PTR_ERR(skb);
877
878         kfree_skb(skb);
879
880         /* The bootloader will not indicate when the device is ready. This
881          * is done by the operational firmware sending bootup notification.
882          *
883          * Booting into operational firmware should not take longer than
884          * 1 second. However if that happens, then just fail the setup
885          * since something went wrong.
886          */
887         bt_dev_info(hdev, "Waiting for device to boot");
888
889         err = intel_wait_booting(hu);
890         if (err)
891                 return err;
892
893         clear_bit(STATE_BOOTING, &intel->flags);
894
895         rettime = ktime_get();
896         delta = ktime_sub(rettime, calltime);
897         duration = (unsigned long long) ktime_to_ns(delta) >> 10;
898
899         bt_dev_info(hdev, "Device booted in %llu usecs", duration);
900
901         /* Enable LPM if matching pdev with wakeup enabled */
902         mutex_lock(&intel_device_list_lock);
903         list_for_each(p, &intel_device_list) {
904                 struct intel_device *dev = list_entry(p, struct intel_device,
905                                                       list);
906                 if (hu->tty->dev->parent == dev->pdev->dev.parent) {
907                         if (device_may_wakeup(&dev->pdev->dev))
908                                 idev = dev;
909                         break;
910                 }
911         }
912         mutex_unlock(&intel_device_list_lock);
913
914         if (!idev)
915                 goto no_lpm;
916
917         bt_dev_info(hdev, "Enabling LPM");
918
919         skb = __hci_cmd_sync(hdev, 0xfc8b, sizeof(lpm_param), lpm_param,
920                              HCI_CMD_TIMEOUT);
921         if (IS_ERR(skb)) {
922                 bt_dev_err(hdev, "Failed to enable LPM");
923                 goto no_lpm;
924         }
925         kfree_skb(skb);
926
927         set_bit(STATE_LPM_ENABLED, &intel->flags);
928
929 no_lpm:
930         skb = __hci_cmd_sync(hdev, HCI_OP_RESET, 0, NULL, HCI_CMD_TIMEOUT);
931         if (IS_ERR(skb))
932                 return PTR_ERR(skb);
933         kfree_skb(skb);
934
935         if (speed_change) {
936                 err = intel_set_baudrate(hu, oper_speed);
937                 if (err)
938                         return err;
939         }
940
941         bt_dev_info(hdev, "Setup complete");
942
943         clear_bit(STATE_BOOTLOADER, &intel->flags);
944
945         return 0;
946 }
947
948 static int intel_recv_event(struct hci_dev *hdev, struct sk_buff *skb)
949 {
950         struct hci_uart *hu = hci_get_drvdata(hdev);
951         struct intel_data *intel = hu->priv;
952         struct hci_event_hdr *hdr;
953
954         if (!test_bit(STATE_BOOTLOADER, &intel->flags) &&
955             !test_bit(STATE_BOOTING, &intel->flags))
956                 goto recv;
957
958         hdr = (void *)skb->data;
959
960         /* When the firmware loading completes the device sends
961          * out a vendor specific event indicating the result of
962          * the firmware loading.
963          */
964         if (skb->len == 7 && hdr->evt == 0xff && hdr->plen == 0x05 &&
965             skb->data[2] == 0x06) {
966                 if (skb->data[3] != 0x00)
967                         set_bit(STATE_FIRMWARE_FAILED, &intel->flags);
968
969                 if (test_and_clear_bit(STATE_DOWNLOADING, &intel->flags) &&
970                     test_bit(STATE_FIRMWARE_LOADED, &intel->flags)) {
971                         smp_mb__after_atomic();
972                         wake_up_bit(&intel->flags, STATE_DOWNLOADING);
973                 }
974
975         /* When switching to the operational firmware the device
976          * sends a vendor specific event indicating that the bootup
977          * completed.
978          */
979         } else if (skb->len == 9 && hdr->evt == 0xff && hdr->plen == 0x07 &&
980                    skb->data[2] == 0x02) {
981                 if (test_and_clear_bit(STATE_BOOTING, &intel->flags)) {
982                         smp_mb__after_atomic();
983                         wake_up_bit(&intel->flags, STATE_BOOTING);
984                 }
985         }
986 recv:
987         return hci_recv_frame(hdev, skb);
988 }
989
990 static void intel_recv_lpm_notify(struct hci_dev *hdev, int value)
991 {
992         struct hci_uart *hu = hci_get_drvdata(hdev);
993         struct intel_data *intel = hu->priv;
994
995         bt_dev_dbg(hdev, "TX idle notification (%d)", value);
996
997         if (value) {
998                 set_bit(STATE_TX_ACTIVE, &intel->flags);
999                 schedule_work(&intel->busy_work);
1000         } else {
1001                 clear_bit(STATE_TX_ACTIVE, &intel->flags);
1002         }
1003 }
1004
1005 static int intel_recv_lpm(struct hci_dev *hdev, struct sk_buff *skb)
1006 {
1007         struct hci_lpm_pkt *lpm = (void *)skb->data;
1008         struct hci_uart *hu = hci_get_drvdata(hdev);
1009         struct intel_data *intel = hu->priv;
1010
1011         switch (lpm->opcode) {
1012         case LPM_OP_TX_NOTIFY:
1013                 if (lpm->dlen)
1014                         intel_recv_lpm_notify(hdev, lpm->data[0]);
1015                 break;
1016         case LPM_OP_SUSPEND_ACK:
1017                 set_bit(STATE_SUSPENDED, &intel->flags);
1018                 if (test_and_clear_bit(STATE_LPM_TRANSACTION, &intel->flags)) {
1019                         smp_mb__after_atomic();
1020                         wake_up_bit(&intel->flags, STATE_LPM_TRANSACTION);
1021                 }
1022                 break;
1023         case LPM_OP_RESUME_ACK:
1024                 clear_bit(STATE_SUSPENDED, &intel->flags);
1025                 if (test_and_clear_bit(STATE_LPM_TRANSACTION, &intel->flags)) {
1026                         smp_mb__after_atomic();
1027                         wake_up_bit(&intel->flags, STATE_LPM_TRANSACTION);
1028                 }
1029                 break;
1030         default:
1031                 bt_dev_err(hdev, "Unknown LPM opcode (%02x)", lpm->opcode);
1032                 break;
1033         }
1034
1035         kfree_skb(skb);
1036
1037         return 0;
1038 }
1039
1040 #define INTEL_RECV_LPM \
1041         .type = HCI_LPM_PKT, \
1042         .hlen = HCI_LPM_HDR_SIZE, \
1043         .loff = 1, \
1044         .lsize = 1, \
1045         .maxlen = HCI_LPM_MAX_SIZE
1046
1047 static const struct h4_recv_pkt intel_recv_pkts[] = {
1048         { H4_RECV_ACL,    .recv = hci_recv_frame   },
1049         { H4_RECV_SCO,    .recv = hci_recv_frame   },
1050         { H4_RECV_EVENT,  .recv = intel_recv_event },
1051         { INTEL_RECV_LPM, .recv = intel_recv_lpm   },
1052 };
1053
1054 static int intel_recv(struct hci_uart *hu, const void *data, int count)
1055 {
1056         struct intel_data *intel = hu->priv;
1057
1058         if (!test_bit(HCI_UART_REGISTERED, &hu->flags))
1059                 return -EUNATCH;
1060
1061         intel->rx_skb = h4_recv_buf(hu->hdev, intel->rx_skb, data, count,
1062                                     intel_recv_pkts,
1063                                     ARRAY_SIZE(intel_recv_pkts));
1064         if (IS_ERR(intel->rx_skb)) {
1065                 int err = PTR_ERR(intel->rx_skb);
1066                 bt_dev_err(hu->hdev, "Frame reassembly failed (%d)", err);
1067                 intel->rx_skb = NULL;
1068                 return err;
1069         }
1070
1071         return count;
1072 }
1073
1074 static int intel_enqueue(struct hci_uart *hu, struct sk_buff *skb)
1075 {
1076         struct intel_data *intel = hu->priv;
1077         struct list_head *p;
1078
1079         BT_DBG("hu %p skb %p", hu, skb);
1080
1081         /* Be sure our controller is resumed and potential LPM transaction
1082          * completed before enqueuing any packet.
1083          */
1084         mutex_lock(&intel_device_list_lock);
1085         list_for_each(p, &intel_device_list) {
1086                 struct intel_device *idev = list_entry(p, struct intel_device,
1087                                                        list);
1088
1089                 if (hu->tty->dev->parent == idev->pdev->dev.parent) {
1090                         pm_runtime_get_sync(&idev->pdev->dev);
1091                         pm_runtime_mark_last_busy(&idev->pdev->dev);
1092                         pm_runtime_put_autosuspend(&idev->pdev->dev);
1093                         break;
1094                 }
1095         }
1096         mutex_unlock(&intel_device_list_lock);
1097
1098         skb_queue_tail(&intel->txq, skb);
1099
1100         return 0;
1101 }
1102
1103 static struct sk_buff *intel_dequeue(struct hci_uart *hu)
1104 {
1105         struct intel_data *intel = hu->priv;
1106         struct sk_buff *skb;
1107
1108         skb = skb_dequeue(&intel->txq);
1109         if (!skb)
1110                 return skb;
1111
1112         if (test_bit(STATE_BOOTLOADER, &intel->flags) &&
1113             (bt_cb(skb)->pkt_type == HCI_COMMAND_PKT)) {
1114                 struct hci_command_hdr *cmd = (void *)skb->data;
1115                 __u16 opcode = le16_to_cpu(cmd->opcode);
1116
1117                 /* When the 0xfc01 command is issued to boot into
1118                  * the operational firmware, it will actually not
1119                  * send a command complete event. To keep the flow
1120                  * control working inject that event here.
1121                  */
1122                 if (opcode == 0xfc01)
1123                         inject_cmd_complete(hu->hdev, opcode);
1124         }
1125
1126         /* Prepend skb with frame type */
1127         memcpy(skb_push(skb, 1), &bt_cb(skb)->pkt_type, 1);
1128
1129         return skb;
1130 }
1131
1132 static const struct hci_uart_proto intel_proto = {
1133         .id             = HCI_UART_INTEL,
1134         .name           = "Intel",
1135         .init_speed     = 115200,
1136         .oper_speed     = 3000000,
1137         .open           = intel_open,
1138         .close          = intel_close,
1139         .flush          = intel_flush,
1140         .setup          = intel_setup,
1141         .set_baudrate   = intel_set_baudrate,
1142         .recv           = intel_recv,
1143         .enqueue        = intel_enqueue,
1144         .dequeue        = intel_dequeue,
1145 };
1146
1147 #ifdef CONFIG_ACPI
1148 static const struct acpi_device_id intel_acpi_match[] = {
1149         { "INT33E1", 0 },
1150         { },
1151 };
1152 MODULE_DEVICE_TABLE(acpi, intel_acpi_match);
1153
1154 static int intel_acpi_probe(struct intel_device *idev)
1155 {
1156         const struct acpi_device_id *id;
1157
1158         id = acpi_match_device(intel_acpi_match, &idev->pdev->dev);
1159         if (!id)
1160                 return -ENODEV;
1161
1162         return 0;
1163 }
1164 #else
1165 static int intel_acpi_probe(struct intel_device *idev)
1166 {
1167         return -ENODEV;
1168 }
1169 #endif
1170
1171 #ifdef CONFIG_PM
1172 static int intel_suspend(struct device *dev)
1173 {
1174         struct intel_device *idev = dev_get_drvdata(dev);
1175
1176         dev_dbg(dev, "intel_suspend");
1177
1178         mutex_lock(&idev->hu_lock);
1179         if (idev->hu)
1180                 intel_lpm_suspend(idev->hu);
1181         mutex_unlock(&idev->hu_lock);
1182
1183         return 0;
1184 }
1185
1186 static int intel_resume(struct device *dev)
1187 {
1188         struct intel_device *idev = dev_get_drvdata(dev);
1189
1190         dev_dbg(dev, "intel_resume");
1191
1192         mutex_lock(&idev->hu_lock);
1193         if (idev->hu)
1194                 intel_lpm_resume(idev->hu);
1195         mutex_unlock(&idev->hu_lock);
1196
1197         return 0;
1198 }
1199 #endif
1200
1201 static const struct dev_pm_ops intel_pm_ops = {
1202         SET_SYSTEM_SLEEP_PM_OPS(intel_suspend, intel_resume)
1203         SET_RUNTIME_PM_OPS(intel_suspend, intel_resume, NULL)
1204 };
1205
1206 static int intel_probe(struct platform_device *pdev)
1207 {
1208         struct intel_device *idev;
1209
1210         idev = devm_kzalloc(&pdev->dev, sizeof(*idev), GFP_KERNEL);
1211         if (!idev)
1212                 return -ENOMEM;
1213
1214         mutex_init(&idev->hu_lock);
1215
1216         idev->pdev = pdev;
1217
1218         if (ACPI_HANDLE(&pdev->dev)) {
1219                 int err = intel_acpi_probe(idev);
1220                 if (err)
1221                         return err;
1222         } else {
1223                 return -ENODEV;
1224         }
1225
1226         idev->reset = devm_gpiod_get_optional(&pdev->dev, "reset",
1227                                               GPIOD_OUT_LOW);
1228         if (IS_ERR(idev->reset)) {
1229                 dev_err(&pdev->dev, "Unable to retrieve gpio\n");
1230                 return PTR_ERR(idev->reset);
1231         }
1232
1233         idev->irq = platform_get_irq(pdev, 0);
1234         if (idev->irq < 0) {
1235                 struct gpio_desc *host_wake;
1236
1237                 dev_err(&pdev->dev, "No IRQ, falling back to gpio-irq\n");
1238
1239                 host_wake = devm_gpiod_get_optional(&pdev->dev, "host-wake",
1240                                                     GPIOD_IN);
1241                 if (IS_ERR(host_wake)) {
1242                         dev_err(&pdev->dev, "Unable to retrieve IRQ\n");
1243                         goto no_irq;
1244                 }
1245
1246                 idev->irq = gpiod_to_irq(host_wake);
1247                 if (idev->irq < 0) {
1248                         dev_err(&pdev->dev, "No corresponding irq for gpio\n");
1249                         goto no_irq;
1250                 }
1251         }
1252
1253         /* Only enable wake-up/irq when controller is powered */
1254         device_set_wakeup_capable(&pdev->dev, true);
1255         device_wakeup_disable(&pdev->dev);
1256
1257 no_irq:
1258         platform_set_drvdata(pdev, idev);
1259
1260         /* Place this instance on the device list */
1261         mutex_lock(&intel_device_list_lock);
1262         list_add_tail(&idev->list, &intel_device_list);
1263         mutex_unlock(&intel_device_list_lock);
1264
1265         dev_info(&pdev->dev, "registered, gpio(%d)/irq(%d).\n",
1266                  desc_to_gpio(idev->reset), idev->irq);
1267
1268         return 0;
1269 }
1270
1271 static int intel_remove(struct platform_device *pdev)
1272 {
1273         struct intel_device *idev = platform_get_drvdata(pdev);
1274
1275         device_wakeup_disable(&pdev->dev);
1276
1277         mutex_lock(&intel_device_list_lock);
1278         list_del(&idev->list);
1279         mutex_unlock(&intel_device_list_lock);
1280
1281         dev_info(&pdev->dev, "unregistered.\n");
1282
1283         return 0;
1284 }
1285
1286 static struct platform_driver intel_driver = {
1287         .probe = intel_probe,
1288         .remove = intel_remove,
1289         .driver = {
1290                 .name = "hci_intel",
1291                 .acpi_match_table = ACPI_PTR(intel_acpi_match),
1292                 .pm = &intel_pm_ops,
1293         },
1294 };
1295
1296 int __init intel_init(void)
1297 {
1298         platform_driver_register(&intel_driver);
1299
1300         return hci_uart_register_proto(&intel_proto);
1301 }
1302
1303 int __exit intel_deinit(void)
1304 {
1305         platform_driver_unregister(&intel_driver);
1306
1307         return hci_uart_unregister_proto(&intel_proto);
1308 }