1 // Copyright 2016 The Fuchsia Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #include <assert.h>
6 #include <ddk/debug.h>
7 #include <ddk/device.h>
8 #include <ddk/driver.h>
9 #include <ddk/protocol/auxdata.h>
10 #include <ddk/protocol/i2c.h>
11 #include <ddk/protocol/pci-lib.h>
12 #include <ddk/protocol/pci.h>
13 #include <errno.h>
14 #include <fcntl.h>
15 #include <fuchsia/hardware/i2c/c/fidl.h>
16 #include <hw/pci.h>
17 #include <hw/reg.h>
18 #include <stdio.h>
19 #include <stdlib.h>
20 #include <string.h>
21 #include <threads.h>
22 #include <unistd.h>
23 #include <zircon/listnode.h>
24 #include <zircon/syscalls.h>
25 #include <zircon/types.h>
26 
27 #include "binding.h"
28 #include "intel-i2c-controller.h"
29 #include "intel-i2c-slave.h"
30 
31 #define DEVIDLE_CONTROL 0x24c
32 #define DEVIDLE_CONTROL_CMD_IN_PROGRESS 0
33 #define DEVIDLE_CONTROL_DEVIDLE 2
34 #define DEVIDLE_CONTROL_RESTORE_REQUIRED 3
35 
36 #define ACER_I2C_TOUCH INTEL_SUNRISE_POINT_SERIALIO_I2C1_DID
37 
38 // Number of entries at which the FIFO level triggers happen
39 #define DEFAULT_RX_FIFO_TRIGGER_LEVEL 8
40 #define DEFAULT_TX_FIFO_TRIGGER_LEVEL 8
41 
42 // Signals used on the controller's event_handle
43 #define RX_FULL_SIGNAL ZX_USER_SIGNAL_0
44 #define TX_EMPTY_SIGNAL ZX_USER_SIGNAL_1
45 #define STOP_DETECTED_SIGNAL ZX_USER_SIGNAL_2
46 #define ERROR_DETECTED_SIGNAL ZX_USER_SIGNAL_3
47 
48 // More than enough
49 #define MAX_TRANSFER_SIZE (UINT16_MAX - 1)
50 
51 // Implement the functionality of the i2c bus device.
52 
intel_i2c_transact(void * ctx,const i2c_op_t ops[],size_t cnt,i2c_transact_callback transact_cb,void * cookie)53 static void intel_i2c_transact(void* ctx, const i2c_op_t ops[], size_t cnt,
54                                i2c_transact_callback transact_cb, void* cookie) {
55     intel_serialio_i2c_slave_device_t* slave = ctx;
56     i2c_slave_segment_t segs[I2C_MAX_RW_OPS];
57     if (cnt >= I2C_MAX_RW_OPS) {
58         transact_cb(cookie, ZX_ERR_NOT_SUPPORTED, NULL, 0);
59         return;
60     }
61     uint8_t* read_buffer = malloc(MAX_TRANSFER_SIZE);
62     if (read_buffer == NULL) {
63         zxlogf(ERROR, "intel-i2c-controller: out of memory\n");
64         transact_cb(cookie, ZX_ERR_NO_MEMORY, NULL, 0);
65         return;
66     }
67     uint8_t* p_reads = read_buffer;
68     for (size_t i = 0; i < cnt; ++i) {
69         if (ops[i].is_read) {
70             segs[i].buf = p_reads;
71             segs[i].type = fuchsia_hardware_i2c_SegmentType_READ;
72             p_reads += ops[i].data_size;
73             if (p_reads - read_buffer > MAX_TRANSFER_SIZE) {
74                 free(read_buffer);
75                 transact_cb(cookie, ZX_ERR_INVALID_ARGS, NULL, 0);
76                 return;
77             }
78         } else {
79             segs[i].buf = (void*)ops[i].data_buffer;
80             segs[i].type = fuchsia_hardware_i2c_SegmentType_WRITE;
81         }
82         segs[i].len = ops[i].data_size;
83     }
84     zx_status_t status = intel_serialio_i2c_slave_transfer(slave, segs, cnt);
85     if (status != ZX_OK) {
86         zxlogf(ERROR, "intel-i2c-controller: intel_serialio_i2c_slave_transfer: %d\n", status);
87         free(read_buffer);
88         transact_cb(cookie, status, NULL, 0);
89         return;
90     }
91     i2c_op_t read_ops[I2C_MAX_RW_OPS];
92     size_t read_ops_cnt = 0;
93     p_reads = read_buffer;
94     for (size_t i = 0; i < cnt; ++i) {
95         if (ops[i].is_read) {
96             read_ops[read_ops_cnt] = ops[i];
97             read_ops[read_ops_cnt].data_buffer = p_reads;
98             read_ops_cnt++;
99             p_reads += ops[i].data_size;
100         }
101     }
102     transact_cb(cookie, status, read_ops, read_ops_cnt);
103     free(read_buffer);
104     return;
105 }
106 
intel_i2c_get_max_transfer_size(void * ctx,size_t * out_size)107 static zx_status_t intel_i2c_get_max_transfer_size(void* ctx, size_t* out_size) {
108     *out_size = MAX_TRANSFER_SIZE;
109     return ZX_OK;
110 }
111 
intel_i2c_get_interrupt(void * ctx,uint32_t flags,zx_handle_t * out_handle)112 static zx_status_t intel_i2c_get_interrupt(void* ctx, uint32_t flags, zx_handle_t* out_handle) {
113     intel_serialio_i2c_slave_device_t* slave = ctx;
114     return intel_serialio_i2c_slave_get_irq(slave, out_handle);
115 }
116 
117 i2c_protocol_ops_t i2c_protocol_ops = {
118     .transact = intel_i2c_transact,
119     .get_max_transfer_size = intel_i2c_get_max_transfer_size,
120     .get_interrupt = intel_i2c_get_interrupt,
121 };
122 
chip_addr_mask(int width)123 static uint32_t chip_addr_mask(int width) {
124     return ((1 << width) - 1);
125 }
126 
intel_serialio_i2c_find_slave(intel_serialio_i2c_slave_device_t ** slave,intel_serialio_i2c_device_t * device,uint16_t address)127 static zx_status_t intel_serialio_i2c_find_slave(
128     intel_serialio_i2c_slave_device_t** slave,
129     intel_serialio_i2c_device_t* device, uint16_t address) {
130     assert(slave);
131 
132     list_for_every_entry (&device->slave_list, *slave,
133                           intel_serialio_i2c_slave_device_t,
134                           slave_list_node) {
135         if ((*slave)->chip_address == address)
136             return ZX_OK;
137     }
138 
139     return ZX_ERR_NOT_FOUND;
140 }
141 
intel_serialio_i2c_add_slave(intel_serialio_i2c_device_t * device,uint8_t width,uint16_t address,uint32_t protocol_id,zx_device_prop_t * moreprops,uint32_t propcount)142 static zx_status_t intel_serialio_i2c_add_slave(intel_serialio_i2c_device_t* device,
143                                                 uint8_t width, uint16_t address,
144                                                 uint32_t protocol_id,
145                                                 zx_device_prop_t* moreprops, uint32_t propcount) {
146     zx_status_t status;
147 
148     if ((width != I2C_7BIT_ADDRESS && width != I2C_10BIT_ADDRESS) ||
149         (address & ~chip_addr_mask(width)) != 0) {
150         return ZX_ERR_INVALID_ARGS;
151     }
152 
153     intel_serialio_i2c_slave_device_t* slave;
154 
155     mtx_lock(&device->mutex);
156 
157     // Make sure a slave with the given address doesn't already exist.
158     status = intel_serialio_i2c_find_slave(&slave, device, address);
159     if (status == ZX_OK) {
160         status = ZX_ERR_ALREADY_EXISTS;
161     }
162     if (status != ZX_ERR_NOT_FOUND) {
163         mtx_unlock(&device->mutex);
164         return status;
165     }
166 
167     slave = calloc(1, sizeof(*slave));
168     if (!slave) {
169         status = ZX_ERR_NO_MEMORY;
170         mtx_unlock(&device->mutex);
171         return status;
172     }
173     slave->chip_address_width = width;
174     slave->chip_address = address;
175     slave->controller = device;
176 
177     list_add_head(&device->slave_list, &slave->slave_list_node);
178     mtx_unlock(&device->mutex);
179 
180     // Temporarily add binding support for the i2c slave. The real way to do
181     // this will involve ACPI/devicetree enumeration, but for now we publish PCI
182     // VID/DID and i2c ADDR as binding properties.
183     pci_protocol_t pci;
184     status = device_get_protocol(device->pcidev, ZX_PROTOCOL_PCI, &pci);
185     if (status != ZX_OK) {
186         goto fail;
187     }
188 
189     uint16_t vendor_id;
190     uint16_t device_id;
191     int count = 0;
192 
193     pci_config_read16(&pci, PCI_CONFIG_VENDOR_ID, &vendor_id);
194     pci_config_read16(&pci, PCI_CONFIG_DEVICE_ID, &device_id);
195 
196     zx_device_prop_t props[8];
197     if (countof(props) < 3 + propcount) {
198         zxlogf(ERROR, "i2c: slave at 0x%02x has too many props! (%u)\n", address, propcount);
199         status = ZX_ERR_INVALID_ARGS;
200         goto fail;
201     }
202     props[count++] = (zx_device_prop_t){BIND_PCI_VID, 0, vendor_id};
203     props[count++] = (zx_device_prop_t){BIND_PCI_DID, 0, device_id};
204     props[count++] = (zx_device_prop_t){BIND_I2C_ADDR, 0, address};
205     memcpy(&props[count], moreprops, sizeof(zx_device_prop_t) * propcount);
206     count += propcount;
207 
208     char name[sizeof(address) * 2 + 2] = {
209             [sizeof(name) - 1] = '\0',
210     };
211     snprintf(name, sizeof(name) - 1, "%04x", address);
212 
213     device_add_args_t args = {
214         .version = DEVICE_ADD_ARGS_VERSION,
215         .name = name,
216         .ctx = slave,
217         .ops = &intel_serialio_i2c_slave_device_proto,
218         .proto_id = protocol_id,
219         .props = props,
220         .prop_count = count,
221     };
222 
223     if (protocol_id == ZX_PROTOCOL_I2C) {
224         args.proto_ops = &i2c_protocol_ops;
225     }
226 
227     status = device_add(device->zxdev, &args, &slave->zxdev);
228     if (status != ZX_OK) {
229         goto fail;
230     }
231     return ZX_OK;
232 
233 fail:
234     mtx_lock(&device->mutex);
235     list_delete(&slave->slave_list_node);
236     mtx_unlock(&device->mutex);
237     free(slave);
238     return status;
239 }
240 
intel_serialio_i2c_remove_slave(intel_serialio_i2c_device_t * device,uint8_t width,uint16_t address)241 static zx_status_t intel_serialio_i2c_remove_slave(
242     intel_serialio_i2c_device_t* device, uint8_t width, uint16_t address) {
243     zx_status_t status;
244 
245     if ((width != I2C_7BIT_ADDRESS && width != I2C_10BIT_ADDRESS) ||
246         (address & ~chip_addr_mask(width)) != 0) {
247         return ZX_ERR_INVALID_ARGS;
248     }
249 
250     intel_serialio_i2c_slave_device_t* slave;
251 
252     mtx_lock(&device->mutex);
253 
254     // Find the slave we're trying to remove.
255     status = intel_serialio_i2c_find_slave(&slave, device, address);
256     if (status < 0)
257         goto remove_slave_finish;
258     if (slave->chip_address_width != width) {
259         zxlogf(ERROR, "Chip address width mismatch.\n");
260         status = ZX_ERR_NOT_FOUND;
261         goto remove_slave_finish;
262     }
263 
264     status = device_remove(slave->zxdev);
265     if (status < 0)
266         goto remove_slave_finish;
267 
268     list_delete(&slave->slave_list_node);
269     free(slave);
270 
271 remove_slave_finish:
272     mtx_unlock(&device->mutex);
273     return status;
274 }
275 
intel_serialio_compute_scl_hcnt(uint32_t controller_freq,uint32_t t_high_nanos,uint32_t t_r_nanos)276 static uint32_t intel_serialio_compute_scl_hcnt(
277     uint32_t controller_freq,
278     uint32_t t_high_nanos,
279     uint32_t t_r_nanos) {
280 
281     uint32_t clock_freq_kilohz = controller_freq / 1000;
282 
283     // We need high count to satisfy highcount + 3 >= clock * (t_HIGH + t_r_max)
284     // Apparently the counter starts as soon as the controller releases SCL, so
285     // include t_r to account for potential delay in rising.
286     //
287     // In terms of units, the division should really be thought of as a
288     // (1 s)/(1000000000 ns) factor to get this into the right scale.
289     uint32_t high_count =
290         (clock_freq_kilohz * (t_high_nanos + t_r_nanos) + 500000);
291     return high_count / 1000000 - 3;
292 }
293 
intel_serialio_compute_scl_lcnt(uint32_t controller_freq,uint32_t t_low_nanos,uint32_t t_f_nanos)294 static uint32_t intel_serialio_compute_scl_lcnt(
295     uint32_t controller_freq,
296     uint32_t t_low_nanos,
297     uint32_t t_f_nanos) {
298 
299     uint32_t clock_freq_kilohz = controller_freq / 1000;
300 
301     // We need low count to satisfy lowcount + 1 >= clock * (t_LOW + t_f_max)
302     // Apparently the counter starts as soon as the controller pulls SCL low, so
303     // include t_f to account for potential delay in falling.
304     //
305     // In terms of units, the division should really be thought of as a
306     // (1 s)/(1000000000 ns) factor to get this into the right scale.
307     uint32_t low_count =
308         (clock_freq_kilohz * (t_low_nanos + t_f_nanos) + 500000);
309     return low_count / 1000000 - 1;
310 }
311 
intel_serialio_compute_bus_timing(intel_serialio_i2c_device_t * device)312 static zx_status_t intel_serialio_compute_bus_timing(
313     intel_serialio_i2c_device_t* device) {
314 
315     uint32_t clock_frequency = device->controller_freq;
316 
317     // These constants are from the i2c timing requirements
318     uint32_t fmp_hcnt = intel_serialio_compute_scl_hcnt(
319         clock_frequency, 260, 120);
320     uint32_t fmp_lcnt = intel_serialio_compute_scl_lcnt(
321         clock_frequency, 500, 120);
322     uint32_t fs_hcnt = intel_serialio_compute_scl_hcnt(
323         clock_frequency, 600, 300);
324     uint32_t fs_lcnt = intel_serialio_compute_scl_lcnt(
325         clock_frequency, 1300, 300);
326     uint32_t ss_hcnt = intel_serialio_compute_scl_hcnt(
327         clock_frequency, 4000, 300);
328     uint32_t ss_lcnt = intel_serialio_compute_scl_lcnt(
329         clock_frequency, 4700, 300);
330 
331     // Make sure the counts are within bounds.
332     if (fmp_hcnt >= (1 << 16) || fmp_hcnt < 6 ||
333         fmp_lcnt >= (1 << 16) || fmp_lcnt < 8) {
334         return ZX_ERR_OUT_OF_RANGE;
335     }
336     if (fs_hcnt >= (1 << 16) || fs_hcnt < 6 ||
337         fs_lcnt >= (1 << 16) || fs_lcnt < 8) {
338         return ZX_ERR_OUT_OF_RANGE;
339     }
340     if (ss_hcnt >= (1 << 16) || ss_hcnt < 6 ||
341         ss_lcnt >= (1 << 16) || ss_lcnt < 8) {
342         return ZX_ERR_OUT_OF_RANGE;
343     }
344 
345     device->fmp_scl_hcnt = fmp_hcnt;
346     device->fmp_scl_lcnt = fmp_lcnt;
347     device->fs_scl_hcnt = fs_hcnt;
348     device->fs_scl_lcnt = fs_lcnt;
349     device->ss_scl_hcnt = ss_hcnt;
350     device->ss_scl_lcnt = ss_lcnt;
351     device->sda_hold = 1;
352     return ZX_OK;
353 }
354 
intel_serialio_i2c_set_bus_frequency(intel_serialio_i2c_device_t * device,uint32_t frequency)355 static zx_status_t intel_serialio_i2c_set_bus_frequency(intel_serialio_i2c_device_t* device,
356                                                         uint32_t frequency) {
357     if (frequency != I2C_MAX_FAST_SPEED_HZ &&
358         frequency != I2C_MAX_STANDARD_SPEED_HZ &&
359         frequency != I2C_MAX_FAST_PLUS_SPEED_HZ) {
360         return ZX_ERR_INVALID_ARGS;
361     }
362 
363     mtx_lock(&device->mutex);
364     device->bus_freq = frequency;
365 
366     zx_status_t status = intel_serialio_i2c_reset_controller(device);
367     if (status != ZX_OK) {
368         mtx_unlock(&device->mutex);
369         return status;
370     }
371 
372     mtx_unlock(&device->mutex);
373     return ZX_OK;
374 }
375 
intel_serialio_i2c_irq_thread(void * arg)376 static int intel_serialio_i2c_irq_thread(void* arg) {
377     intel_serialio_i2c_device_t* dev = (intel_serialio_i2c_device_t*)arg;
378     zx_status_t status;
379     for (;;) {
380         status = zx_interrupt_wait(dev->irq_handle, NULL);
381         if (status != ZX_OK) {
382             zxlogf(ERROR, "i2c: error waiting for interrupt: %d\n", status);
383             break;
384         }
385         uint32_t intr_stat = readl(&dev->regs->intr_stat);
386         zxlogf(SPEW, "Received i2c interrupt: %x %x\n",
387                intr_stat, readl(&dev->regs->raw_intr_stat));
388         if (intr_stat & (1u << INTR_RX_UNDER)) {
389             // If we hit an underflow, it's a bug.
390             zx_object_signal(dev->event_handle, 0, ERROR_DETECTED_SIGNAL);
391             readl(&dev->regs->clr_rx_under);
392             zxlogf(ERROR, "i2c: rx underflow detected!\n");
393         }
394         if (intr_stat & (1u << INTR_RX_OVER)) {
395             // If we hit an overflow, it's a bug.
396             zx_object_signal(dev->event_handle, 0, ERROR_DETECTED_SIGNAL);
397             readl(&dev->regs->clr_rx_over);
398             zxlogf(ERROR, "i2c: rx overflow detected!\n");
399         }
400         if (intr_stat & (1u << INTR_RX_FULL)) {
401             mtx_lock(&dev->irq_mask_mutex);
402             zx_object_signal(dev->event_handle, 0, RX_FULL_SIGNAL);
403             RMWREG32(&dev->regs->intr_mask, INTR_RX_FULL, 1, 0);
404             mtx_unlock(&dev->irq_mask_mutex);
405         }
406         if (intr_stat & (1u << INTR_TX_OVER)) {
407             // If we hit an overflow, it's a bug.
408             zx_object_signal(dev->event_handle, 0, ERROR_DETECTED_SIGNAL);
409             readl(&dev->regs->clr_tx_over);
410             zxlogf(ERROR, "i2c: tx overflow detected!\n");
411         }
412         if (intr_stat & (1u << INTR_TX_EMPTY)) {
413             mtx_lock(&dev->irq_mask_mutex);
414             zx_object_signal(dev->event_handle, 0, TX_EMPTY_SIGNAL);
415             RMWREG32(&dev->regs->intr_mask, INTR_TX_EMPTY, 1, 0);
416             mtx_unlock(&dev->irq_mask_mutex);
417         }
418         if (intr_stat & (1u << INTR_TX_ABORT)) {
419             zxlogf(ERROR, "i2c: tx abort detected: 0x%08x\n",
420                    readl(&dev->regs->tx_abrt_source));
421             zx_object_signal(dev->event_handle, 0, ERROR_DETECTED_SIGNAL);
422             readl(&dev->regs->clr_tx_abort);
423         }
424         if (intr_stat & (1u << INTR_ACTIVITY)) {
425             // Should always be masked...remask it.
426             mtx_lock(&dev->irq_mask_mutex);
427             RMWREG32(&dev->regs->intr_mask, INTR_ACTIVITY, 1, 0);
428             mtx_unlock(&dev->irq_mask_mutex);
429             zxlogf(INFO, "i2c: spurious activity irq\n");
430         }
431         if (intr_stat & (1u << INTR_STOP_DETECTION)) {
432             zx_object_signal(dev->event_handle, 0, STOP_DETECTED_SIGNAL);
433             readl(&dev->regs->clr_stop_det);
434         }
435         if (intr_stat & (1u << INTR_START_DETECTION)) {
436             readl(&dev->regs->clr_start_det);
437         }
438         if (intr_stat & (1u << INTR_GENERAL_CALL)) {
439             // Should always be masked...remask it.
440             mtx_lock(&dev->irq_mask_mutex);
441             RMWREG32(&dev->regs->intr_mask, INTR_GENERAL_CALL, 1, 0);
442             mtx_unlock(&dev->irq_mask_mutex);
443             zxlogf(INFO, "i2c: spurious general call irq\n");
444         }
445     }
446     return 0;
447 }
448 
intel_serialio_i2c_wait_for_rx_full(intel_serialio_i2c_device_t * controller,zx_time_t deadline)449 zx_status_t intel_serialio_i2c_wait_for_rx_full(
450     intel_serialio_i2c_device_t* controller,
451     zx_time_t deadline) {
452 
453     uint32_t observed;
454     zx_status_t status = zx_object_wait_one(controller->event_handle,
455                                             RX_FULL_SIGNAL | ERROR_DETECTED_SIGNAL,
456                                             deadline, &observed);
457     if (status != ZX_OK) {
458         return status;
459     }
460     if (observed & ERROR_DETECTED_SIGNAL) {
461         return ZX_ERR_IO;
462     }
463     return ZX_OK;
464 }
465 
intel_serialio_i2c_wait_for_tx_empty(intel_serialio_i2c_device_t * controller,zx_time_t deadline)466 zx_status_t intel_serialio_i2c_wait_for_tx_empty(
467     intel_serialio_i2c_device_t* controller,
468     zx_time_t deadline) {
469 
470     uint32_t observed;
471     zx_status_t status = zx_object_wait_one(controller->event_handle,
472                                             TX_EMPTY_SIGNAL | ERROR_DETECTED_SIGNAL,
473                                             deadline, &observed);
474     if (status != ZX_OK) {
475         return status;
476     }
477     if (observed & ERROR_DETECTED_SIGNAL) {
478         return ZX_ERR_IO;
479     }
480     return ZX_OK;
481 }
482 
intel_serialio_i2c_wait_for_stop_detect(intel_serialio_i2c_device_t * controller,zx_time_t deadline)483 zx_status_t intel_serialio_i2c_wait_for_stop_detect(
484     intel_serialio_i2c_device_t* controller,
485     zx_time_t deadline) {
486 
487     uint32_t observed;
488     zx_status_t status = zx_object_wait_one(controller->event_handle,
489                                             STOP_DETECTED_SIGNAL | ERROR_DETECTED_SIGNAL,
490                                             deadline, &observed);
491     if (status != ZX_OK) {
492         return status;
493     }
494     if (observed & ERROR_DETECTED_SIGNAL) {
495         return ZX_ERR_IO;
496     }
497     return ZX_OK;
498 }
499 
intel_serialio_i2c_check_for_error(intel_serialio_i2c_device_t * controller)500 zx_status_t intel_serialio_i2c_check_for_error(intel_serialio_i2c_device_t* controller) {
501 
502     uint32_t observed;
503     zx_status_t status = zx_object_wait_one(controller->event_handle, ERROR_DETECTED_SIGNAL, 0,
504                                             &observed);
505     if (status != ZX_OK && status != ZX_ERR_TIMED_OUT) {
506         return status;
507     }
508     if (observed & ERROR_DETECTED_SIGNAL) {
509         return ZX_ERR_IO;
510     }
511     return ZX_OK;
512 }
513 
intel_serialio_i2c_clear_stop_detect(intel_serialio_i2c_device_t * controller)514 zx_status_t intel_serialio_i2c_clear_stop_detect(intel_serialio_i2c_device_t* controller) {
515     return zx_object_signal(controller->event_handle, STOP_DETECTED_SIGNAL, 0);
516 }
517 
518 // Perform a write to the DATA_CMD register, and clear
519 // interrupt masks as appropriate
intel_serialio_i2c_issue_rx(intel_serialio_i2c_device_t * controller,uint32_t data_cmd)520 zx_status_t intel_serialio_i2c_issue_rx(
521     intel_serialio_i2c_device_t* controller,
522     uint32_t data_cmd) {
523 
524     writel(data_cmd, &controller->regs->data_cmd);
525     return ZX_OK;
526 }
527 
intel_serialio_i2c_read_rx(intel_serialio_i2c_device_t * controller,uint8_t * data)528 zx_status_t intel_serialio_i2c_read_rx(
529     intel_serialio_i2c_device_t* controller,
530     uint8_t* data) {
531 
532     *data = readl(&controller->regs->data_cmd);
533 
534     uint32_t rx_tl;
535     intel_serialio_i2c_get_rx_fifo_threshold(controller, &rx_tl);
536     const uint32_t rxflr = readl(&controller->regs->rxflr) & 0x1ff;
537     // If we've dropped the RX queue level below the threshold, clear the signal
538     // and unmask the interrupt.
539     if (rxflr < rx_tl) {
540         mtx_lock(&controller->irq_mask_mutex);
541         zx_status_t status = zx_object_signal(controller->event_handle, RX_FULL_SIGNAL, 0);
542         RMWREG32(&controller->regs->intr_mask, INTR_RX_FULL, 1, 1);
543         mtx_unlock(&controller->irq_mask_mutex);
544         return status;
545     }
546     return ZX_OK;
547 }
548 
intel_serialio_i2c_issue_tx(intel_serialio_i2c_device_t * controller,uint32_t data_cmd)549 zx_status_t intel_serialio_i2c_issue_tx(
550     intel_serialio_i2c_device_t* controller,
551     uint32_t data_cmd) {
552 
553     writel(data_cmd, &controller->regs->data_cmd);
554     uint32_t tx_tl;
555     intel_serialio_i2c_get_tx_fifo_threshold(controller, &tx_tl);
556     const uint32_t txflr = readl(&controller->regs->txflr) & 0x1ff;
557     // If we've raised the TX queue level above the threshold, clear the signal
558     // and unmask the interrupt.
559     if (txflr > tx_tl) {
560         mtx_lock(&controller->irq_mask_mutex);
561         zx_status_t status = zx_object_signal(controller->event_handle, TX_EMPTY_SIGNAL, 0);
562         RMWREG32(&controller->regs->intr_mask, INTR_TX_EMPTY, 1, 1);
563         mtx_unlock(&controller->irq_mask_mutex);
564         return status;
565     }
566     return ZX_OK;
567 }
568 
intel_serialio_i2c_get_rx_fifo_threshold(intel_serialio_i2c_device_t * controller,uint32_t * threshold)569 void intel_serialio_i2c_get_rx_fifo_threshold(
570     intel_serialio_i2c_device_t* controller,
571     uint32_t* threshold) {
572 
573     *threshold = (readl(&controller->regs->rx_tl) & 0xff) + 1;
574 }
575 
576 // Get an RX interrupt whenever the RX FIFO size is >= the threshold.
intel_serialio_i2c_set_rx_fifo_threshold(intel_serialio_i2c_device_t * controller,uint32_t threshold)577 zx_status_t intel_serialio_i2c_set_rx_fifo_threshold(
578     intel_serialio_i2c_device_t* controller,
579     uint32_t threshold) {
580 
581     if (threshold - 1 > UINT8_MAX) {
582         return ZX_ERR_INVALID_ARGS;
583     }
584 
585     RMWREG32(&controller->regs->rx_tl, 0, 8, threshold - 1);
586     return ZX_OK;
587 }
588 
intel_serialio_i2c_get_tx_fifo_threshold(intel_serialio_i2c_device_t * controller,uint32_t * threshold)589 void intel_serialio_i2c_get_tx_fifo_threshold(
590     intel_serialio_i2c_device_t* controller,
591     uint32_t* threshold) {
592 
593     *threshold = (readl(&controller->regs->tx_tl) & 0xff) + 1;
594 }
595 
596 // Get a TX interrupt whenever the TX FIFO size is <= the threshold.
intel_serialio_i2c_set_tx_fifo_threshold(intel_serialio_i2c_device_t * controller,uint32_t threshold)597 zx_status_t intel_serialio_i2c_set_tx_fifo_threshold(
598     intel_serialio_i2c_device_t* controller,
599     uint32_t threshold) {
600 
601     if (threshold - 1 > UINT8_MAX) {
602         return ZX_ERR_INVALID_ARGS;
603     }
604 
605     RMWREG32(&controller->regs->tx_tl, 0, 8, threshold - 1);
606     return ZX_OK;
607 }
608 
intel_serialio_i2c_unbind(void * ctx)609 static void intel_serialio_i2c_unbind(void* ctx) {
610     intel_serialio_i2c_device_t* dev = ctx;
611     if (dev) {
612         zxlogf(INFO, "intel-i2c: unbind irq_handle %d irq_thread %p\n", dev->irq_handle,
613                 dev->irq_thread);
614         if ((dev->irq_handle != ZX_HANDLE_INVALID) && dev->irq_thread) {
615             zx_interrupt_destroy(dev->irq_handle);
616             thrd_join(dev->irq_thread, NULL);
617         }
618         if (dev->zxdev) {
619             device_remove(dev->zxdev);
620         }
621     }
622 }
623 
intel_serialio_i2c_release(void * ctx)624 static void intel_serialio_i2c_release(void* ctx) {
625     intel_serialio_i2c_device_t* dev = ctx;
626     if (dev) {
627         mmio_buffer_release(&dev->mmio);
628         zx_handle_close(dev->irq_handle);
629         zx_handle_close(dev->event_handle);
630     }
631     free(dev);
632 }
633 
634 static zx_protocol_device_t intel_serialio_i2c_device_proto = {
635     .version = DEVICE_OPS_VERSION,
636     .unbind = intel_serialio_i2c_unbind,
637     .release = intel_serialio_i2c_release,
638 };
639 
640 // The controller lock should already be held when entering this function.
intel_serialio_i2c_reset_controller(intel_serialio_i2c_device_t * device)641 zx_status_t intel_serialio_i2c_reset_controller(
642     intel_serialio_i2c_device_t* device) {
643     zx_status_t status = ZX_OK;
644 
645     // The register will only return valid values if the ACPI _PS0 has been
646     // evaluated.
647     if (readl((void*)device->regs + DEVIDLE_CONTROL) != 0xffffffff) {
648         // Wake up device if it is in DevIdle state
649         RMWREG32((void*)device->regs + DEVIDLE_CONTROL, DEVIDLE_CONTROL_DEVIDLE, 1, 0);
650 
651         // Wait for wakeup to finish processing
652         int retry = 10;
653         while (retry-- &&
654                (readl((void*)device->regs + DEVIDLE_CONTROL) &
655                 (1 << DEVIDLE_CONTROL_CMD_IN_PROGRESS))) {
656             usleep(10);
657         }
658         if (!retry) {
659             printf("i2c-controller: timed out waiting for device idle\n");
660             return ZX_ERR_TIMED_OUT;
661         }
662     }
663 
664     // Reset the device.
665     RMWREG32(device->soft_reset, 0, 2, 0x0);
666     RMWREG32(device->soft_reset, 0, 2, 0x3);
667 
668     // Clear the "Restore Required" flag
669     RMWREG32((void*)device->regs + DEVIDLE_CONTROL, DEVIDLE_CONTROL_RESTORE_REQUIRED, 1, 0);
670 
671     // Disable the controller.
672     RMWREG32(&device->regs->i2c_en, I2C_EN_ENABLE, 1, 0);
673 
674     // Reconfigure the bus timing
675     if (device->bus_freq == I2C_MAX_FAST_PLUS_SPEED_HZ) {
676         RMWREG32(&device->regs->fs_scl_hcnt, 0, 16, device->fmp_scl_hcnt);
677         RMWREG32(&device->regs->fs_scl_lcnt, 0, 16, device->fmp_scl_lcnt);
678     } else {
679         RMWREG32(&device->regs->fs_scl_hcnt, 0, 16, device->fs_scl_hcnt);
680         RMWREG32(&device->regs->fs_scl_lcnt, 0, 16, device->fs_scl_lcnt);
681     }
682     RMWREG32(&device->regs->ss_scl_hcnt, 0, 16, device->ss_scl_hcnt);
683     RMWREG32(&device->regs->ss_scl_lcnt, 0, 16, device->ss_scl_lcnt);
684     RMWREG32(&device->regs->sda_hold, 0, 16, device->sda_hold);
685 
686     unsigned int speed = CTL_SPEED_STANDARD;
687     if (device->bus_freq == I2C_MAX_FAST_SPEED_HZ ||
688         device->bus_freq == I2C_MAX_FAST_PLUS_SPEED_HZ) {
689 
690         speed = CTL_SPEED_FAST;
691     }
692 
693     writel((0x1 << CTL_SLAVE_DISABLE) |
694            (0x1 << CTL_RESTART_ENABLE) |
695            (speed << CTL_SPEED) |
696            (CTL_MASTER_MODE_ENABLED << CTL_MASTER_MODE),
697            &device->regs->ctl);
698 
699     mtx_lock(&device->irq_mask_mutex);
700     // Mask all interrupts
701     writel(0, &device->regs->intr_mask);
702 
703     status = intel_serialio_i2c_set_rx_fifo_threshold(device, DEFAULT_RX_FIFO_TRIGGER_LEVEL);
704     if (status != ZX_OK) {
705         goto cleanup;
706     }
707     status = intel_serialio_i2c_set_tx_fifo_threshold(device, DEFAULT_TX_FIFO_TRIGGER_LEVEL);
708     if (status != ZX_OK) {
709         goto cleanup;
710     }
711 
712     // Clear the signals
713     status = zx_object_signal(device->event_handle,
714                               RX_FULL_SIGNAL | TX_EMPTY_SIGNAL | STOP_DETECTED_SIGNAL |
715                               ERROR_DETECTED_SIGNAL, 0);
716     if (status != ZX_OK) {
717         goto cleanup;
718     }
719 
720     // Reading this register clears all interrupts.
721     readl(&device->regs->clr_intr);
722 
723     // Unmask the interrupts we care about
724     writel((1u<<INTR_STOP_DETECTION) | (1u<<INTR_TX_ABORT) |
725            (1u<<INTR_TX_EMPTY) | (1u<<INTR_TX_OVER) | (1u<<INTR_RX_FULL) |
726            (1u<<INTR_RX_OVER) | (1u<<INTR_RX_UNDER),
727            &device->regs->intr_mask);
728 
729 cleanup:
730     mtx_unlock(&device->irq_mask_mutex);
731     return status;
732 }
733 
intel_serialio_i2c_device_specific_init(intel_serialio_i2c_device_t * device,uint16_t device_id)734 static zx_status_t intel_serialio_i2c_device_specific_init(
735     intel_serialio_i2c_device_t* device,
736     uint16_t device_id) {
737 
738     static const struct {
739         uint16_t device_ids[16];
740         // Offset of the soft reset register
741         size_t reset_offset;
742         // Internal controller frequency, in hertz
743         uint32_t controller_clock_frequency;
744     } dev_props[] = {
745         {
746             .device_ids = {
747                 INTEL_SUNRISE_POINT_SERIALIO_I2C0_DID,
748                 INTEL_SUNRISE_POINT_SERIALIO_I2C1_DID,
749                 INTEL_SUNRISE_POINT_SERIALIO_I2C2_DID,
750                 INTEL_SUNRISE_POINT_SERIALIO_I2C3_DID,
751                 INTEL_SUNRISE_POINT_SERIALIO_I2C4_DID,
752             },
753             .reset_offset = 0x204,
754             .controller_clock_frequency = 120 * 1000 * 1000,
755         },
756         {
757             .device_ids = {
758                 INTEL_WILDCAT_POINT_SERIALIO_I2C0_DID, INTEL_WILDCAT_POINT_SERIALIO_I2C1_DID,
759             },
760             .reset_offset = 0x804,
761             .controller_clock_frequency = 100 * 1000 * 1000,
762         },
763     };
764 
765     for (unsigned int i = 0; i < countof(dev_props); ++i) {
766         const unsigned int num_dev_ids = countof(dev_props[0].device_ids);
767         for (unsigned int dev_idx = 0; dev_idx < num_dev_ids; ++dev_idx) {
768             if (!dev_props[i].device_ids[dev_idx]) {
769                 break;
770             }
771             if (dev_props[i].device_ids[dev_idx] != device_id) {
772                 continue;
773             }
774 
775             device->controller_freq = dev_props[i].controller_clock_frequency;
776             device->soft_reset = (void*)device->regs +
777                                  dev_props[i].reset_offset;
778             return ZX_OK;
779         }
780     }
781 
782     return ZX_ERR_NOT_SUPPORTED;
783 }
784 
intel_serialio_add_devices(intel_serialio_i2c_device_t * parent,pci_protocol_t * pci)785 static void intel_serialio_add_devices(intel_serialio_i2c_device_t* parent,
786                                        pci_protocol_t* pci) {
787     // get child info from aux data, max 4
788     // TODO: this seems nonstandard to device model
789     auxdata_i2c_device_t childdata[4];
790     memset(childdata, 0, sizeof(childdata));
791 
792     size_t actual;
793     zx_status_t status = pci_get_auxdata(pci, "i2c-child", childdata, sizeof(childdata), &actual);
794     if (status != ZX_OK) {
795         return;
796     }
797 
798     auxdata_i2c_device_t* child = &childdata[0];
799     uint32_t count = actual / sizeof(auxdata_i2c_device_t);
800     uint32_t bus_speed = 0;
801     while (count--) {
802         zxlogf(TRACE, "i2c: got child[%u] bus_master=%d ten_bit=%d address=0x%x bus_speed=%u"
803                      " protocol_id=0x%08x\n",
804                count, child->bus_master, child->ten_bit, child->address, child->bus_speed,
805                child->protocol_id);
806 
807         if (bus_speed && bus_speed != child->bus_speed) {
808             zxlogf(ERROR, "i2c: cannot add devices with different bus speeds (%u, %u)\n",
809                     bus_speed, child->bus_speed);
810         }
811         if (!bus_speed) {
812             intel_serialio_i2c_set_bus_frequency(parent, child->bus_speed);
813             bus_speed = child->bus_speed;
814         }
815         intel_serialio_i2c_add_slave(parent,
816                 child->ten_bit ? I2C_10BIT_ADDRESS : I2C_7BIT_ADDRESS,
817                 child->address, child->protocol_id, child->props, child->propcount);
818         child += 1;
819     }
820 }
821 
intel_i2c_bind(void * ctx,zx_device_t * dev)822 zx_status_t intel_i2c_bind(void* ctx, zx_device_t* dev) {
823     pci_protocol_t pci;
824     if (device_get_protocol(dev, ZX_PROTOCOL_PCI, &pci))
825         return ZX_ERR_NOT_SUPPORTED;
826 
827     intel_serialio_i2c_device_t* device = calloc(1, sizeof(*device));
828     if (!device)
829         return ZX_ERR_NO_MEMORY;
830 
831     list_initialize(&device->slave_list);
832     mtx_init(&device->mutex, mtx_plain);
833     mtx_init(&device->irq_mask_mutex, mtx_plain);
834     device->pcidev = dev;
835 
836     uint16_t vendor_id;
837     uint16_t device_id;
838     pci_config_read16(&pci, PCI_CONFIG_VENDOR_ID, &vendor_id);
839     pci_config_read16(&pci, PCI_CONFIG_DEVICE_ID, &device_id);
840 
841     zx_status_t status = pci_map_bar_buffer(&pci, 0u, ZX_CACHE_POLICY_UNCACHED_DEVICE,
842                                             &device->mmio);
843     if (status != ZX_OK) {
844         zxlogf(ERROR,"i2c: failed to mape pci bar 0: %d\n", status);
845         goto fail;
846     }
847     device->regs = device->mmio.vaddr;
848 
849     // set msi irq mode
850     status = pci_set_irq_mode(&pci, ZX_PCIE_IRQ_MODE_LEGACY, 1);
851     if (status < 0) {
852         zxlogf(ERROR,"i2c: failed to set irq mode: %d\n", status);
853         goto fail;
854     }
855 
856     // get irq handle
857     status = pci_map_interrupt(&pci, 0, &device->irq_handle);
858     if (status != ZX_OK) {
859         zxlogf(ERROR,"i2c: failed to get irq handle: %d\n", status);
860         goto fail;
861     }
862 
863     status = zx_event_create(0, &device->event_handle);
864     if (status != ZX_OK) {
865         zxlogf(ERROR,"i2c: failed to create event handle: %d\n", status);
866         goto fail;
867     }
868 
869     // start irq thread
870     int ret = thrd_create_with_name(&device->irq_thread, intel_serialio_i2c_irq_thread, device, "i2c-irq");
871     if (ret != thrd_success) {
872         zxlogf(ERROR,"i2c: failed to create irq thread: %d\n", ret);
873         goto fail;
874     }
875 
876     // Run the bus at standard speed by default.
877     device->bus_freq = I2C_MAX_STANDARD_SPEED_HZ;
878 
879     status = intel_serialio_i2c_device_specific_init(device, device_id);
880     if (status != ZX_OK) {
881         zxlogf(ERROR, "i2c: device specific init failed: %d\n", status);
882         goto fail;
883     }
884 
885     status = intel_serialio_compute_bus_timing(device);
886     if (status < 0) {
887         zxlogf(ERROR, "i2c: compute bus timing failed: %d\n", status);
888         goto fail;
889     }
890 
891     // Temporary hack until we have routed through the FMCN ACPI tables.
892     if (vendor_id == INTEL_VID &&
893         device_id == INTEL_SUNRISE_POINT_SERIALIO_I2C0_DID) {
894         // TODO: These should all be extracted from FPCN in the ACPI tables.
895         device->fmp_scl_lcnt = 0x0042;
896         device->fmp_scl_hcnt = 0x001b;
897         device->sda_hold = 0x24;
898     } else if (vendor_id == INTEL_VID &&
899         device_id == INTEL_SUNRISE_POINT_SERIALIO_I2C1_DID) {
900         // TODO(yky): These should all be extracted from FMCN in the ACPI tables.
901         device->fs_scl_lcnt = 0x00b6;
902         device->fs_scl_hcnt = 0x0059;
903         device->sda_hold = 0x24;
904     } else if (vendor_id == INTEL_VID &&
905                device_id == INTEL_SUNRISE_POINT_SERIALIO_I2C2_DID) {
906         // TODO: These should all be extracted from FMCN in the ACPI tables.
907         device->fs_scl_lcnt = 0x00ba;
908         device->fs_scl_hcnt = 0x005d;
909         device->sda_hold = 0x24;
910     } else if (vendor_id == INTEL_VID &&
911                device_id == INTEL_SUNRISE_POINT_SERIALIO_I2C4_DID) {
912         // TODO: These should all be extracted from FMCN in the ACPI tables.
913         device->fs_scl_lcnt = 0x005a;
914         device->fs_scl_hcnt = 0x00a6;
915         device->sda_hold = 0x24;
916     }
917 
918     // Configure the I2C controller. We don't need to hold the lock because
919     // nobody else can see this controller yet.
920     status = intel_serialio_i2c_reset_controller(device);
921     if (status < 0) {
922         zxlogf(ERROR, "i2c: reset controller failed: %d\n", status);
923         goto fail;
924     }
925 
926     char name[ZX_DEVICE_NAME_MAX];
927     snprintf(name, sizeof(name), "i2c-bus-%04x", device_id);
928 
929     device_add_args_t args = {
930         .version = DEVICE_ADD_ARGS_VERSION,
931         .name = name,
932         .ctx = device,
933         .ops = &intel_serialio_i2c_device_proto,
934     };
935 
936     status = device_add(dev, &args, &device->zxdev);
937     if (status < 0) {
938         zxlogf(ERROR, "device add failed: %d\n", status);
939         goto fail;
940     }
941 
942     zxlogf(INFO,
943         "initialized intel serialio i2c driver, "
944         "reg=%p regsize=%ld\n",
945         device->regs, device->mmio.size);
946 
947     intel_serialio_add_devices(device, &pci);
948     return ZX_OK;
949 
950 fail:
951     intel_serialio_i2c_unbind(device);
952     intel_serialio_i2c_release(device);
953     return status;
954 }
955 
956 static zx_driver_ops_t intel_i2c_driver_ops = {
957     .version = DRIVER_OPS_VERSION,
958     .bind = intel_i2c_bind,
959 };
960 
961 ZIRCON_DRIVER_BEGIN(intel_i2c, intel_i2c_driver_ops, "zircon", "0.1", 9)
962     BI_ABORT_IF(NE, BIND_PROTOCOL, ZX_PROTOCOL_PCI),
963     BI_ABORT_IF(NE, BIND_PCI_VID, 0x8086),
964     BI_MATCH_IF(EQ, BIND_PCI_DID, INTEL_WILDCAT_POINT_SERIALIO_I2C0_DID),
965     BI_MATCH_IF(EQ, BIND_PCI_DID, INTEL_WILDCAT_POINT_SERIALIO_I2C1_DID),
966     BI_MATCH_IF(EQ, BIND_PCI_DID, INTEL_SUNRISE_POINT_SERIALIO_I2C0_DID),
967     BI_MATCH_IF(EQ, BIND_PCI_DID, INTEL_SUNRISE_POINT_SERIALIO_I2C1_DID),
968     BI_MATCH_IF(EQ, BIND_PCI_DID, INTEL_SUNRISE_POINT_SERIALIO_I2C2_DID),
969     BI_MATCH_IF(EQ, BIND_PCI_DID, INTEL_SUNRISE_POINT_SERIALIO_I2C3_DID),
970     BI_MATCH_IF(EQ, BIND_PCI_DID, INTEL_SUNRISE_POINT_SERIALIO_I2C4_DID),
971 ZIRCON_DRIVER_END(intel_i2c)
972