1 /* 2 * Copyright (C) 2017 BlueKitchen GmbH 3 * 4 * Redistribution and use in source and binary forms, with or without 5 * modification, are permitted provided that the following conditions 6 * are met: 7 * 8 * 1. Redistributions of source code must retain the above copyright 9 * notice, this list of conditions and the following disclaimer. 10 * 2. Redistributions in binary form must reproduce the above copyright 11 * notice, this list of conditions and the following disclaimer in the 12 * documentation and/or other materials provided with the distribution. 13 * 3. Neither the name of the copyright holders nor the names of 14 * contributors may be used to endorse or promote products derived 15 * from this software without specific prior written permission. 16 * 4. Any redistribution, use, or modification is done solely for 17 * personal benefit and not for any commercial purpose or for 18 * monetary gain. 19 * 20 * THIS SOFTWARE IS PROVIDED BY BLUEKITCHEN GMBH AND CONTRIBUTORS 21 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 22 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS 23 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL MATTHIAS 24 * RINGWALD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, 25 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 26 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS 27 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED 28 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 29 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF 30 * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 31 * SUCH DAMAGE. 32 * 33 * Please inquire about commercial licensing options at 34 * [email protected] 35 * 36 */ 37 38 #define BTSTACK_FILE__ "bnep_lwip_lwip.c" 39 40 /* 41 * bnep_lwip_lwip_.c 42 */ 43 44 #include "lwip/netif.h" 45 #include "lwip/sys.h" 46 #include "lwip/arch.h" 47 #include "lwip/api.h" 48 #include "lwip/netifapi.h" 49 #include "lwip/tcpip.h" 50 #include "lwip/ip.h" 51 #include "lwip/dhcp.h" 52 #include "lwip/sockets.h" 53 #include "lwip/prot/dhcp.h" 54 #include "netif/etharp.h" 55 56 #if LWIP_IPV6 57 #include "lwip/ethip6.h" 58 #endif 59 60 #include "bnep_lwip.h" 61 62 #include "btstack_config.h" 63 #include "btstack_debug.h" 64 #include "btstack_util.h" 65 #include "btstack_event.h" 66 #include "classic/bnep.h" 67 68 #if NO_SYS 69 #include "btstack_ring_buffer.h" 70 #include "btstack_run_loop.h" 71 #include "lwip/timeouts.h" 72 #else 73 #include "btstack_run_loop_freertos.h" 74 #endif 75 76 /* Short name used for netif in lwIP */ 77 #define IFNAME0 'b' 78 #define IFNAME1 't' 79 80 #define LWIP_TIMER_INTERVAL_MS 25 81 82 static void bnep_lwip_outgoing_process(void * arg); 83 static int bnep_lwip_outgoing_packets_empty(void); 84 85 // lwip data 86 static struct netif btstack_netif; 87 88 // outgoing queue 89 #if NO_SYS 90 static uint8_t bnep_lwip_outgoing_queue_storage[ (TCP_SND_QUEUELEN+1) * sizeof(struct pbuf *)]; 91 static btstack_ring_buffer_t bnep_lwip_outgoing_queue; 92 #else 93 static QueueHandle_t bnep_lwip_outgoing_queue; 94 #endif 95 96 #if NO_SYS 97 static btstack_timer_source_t bnep_lwip_timer; 98 #endif 99 100 // bnep data 101 static uint16_t bnep_cid; 102 static btstack_packet_handler_t client_handler; 103 104 // next packet only modified from btstack context 105 static struct pbuf * bnep_lwip_outgoing_next_packet; 106 107 // temp buffer to unchain buffer 108 static uint8_t btstack_network_outgoing_buffer[HCI_ACL_PAYLOAD_SIZE]; 109 110 // helper functions to hide NO_SYS vs. FreeRTOS implementations 111 112 static int bnep_lwip_outgoing_init_queue(void){ 113 #if NO_SYS 114 btstack_ring_buffer_init(&bnep_lwip_outgoing_queue, bnep_lwip_outgoing_queue_storage, sizeof(bnep_lwip_outgoing_queue_storage)); 115 #else 116 bnep_lwip_outgoing_queue = xQueueCreate(TCP_SND_QUEUELEN, sizeof(struct pbuf *)); 117 if (bnep_lwip_outgoing_queue == NULL){ 118 log_error("cannot allocate outgoing queue"); 119 return 1; 120 } 121 #endif 122 return 0; 123 } 124 125 static void bnep_lwip_outgoing_reset_queue(void){ 126 #if NO_SYS 127 btstack_ring_buffer_init(&bnep_lwip_outgoing_queue, bnep_lwip_outgoing_queue_storage, sizeof(bnep_lwip_outgoing_queue_storage)); 128 #else 129 xQueueReset(bnep_lwip_outgoing_queue); 130 #endif 131 } 132 133 static void bnep_lwip_outgoing_queue_packet(struct pbuf *p){ 134 #if NO_SYS 135 // queue up 136 btstack_ring_buffer_write(&bnep_lwip_outgoing_queue, (uint8_t *) &p, sizeof(struct pbuf *)); 137 #else 138 // queue up 139 xQueueSendToBack(bnep_lwip_outgoing_queue, &p, portMAX_DELAY); 140 #endif 141 } 142 143 static struct pbuf * bnep_lwip_outgoing_pop_packet(void){ 144 struct pbuf * p = NULL; 145 #if NO_SYS 146 uint32_t bytes_read = 0; 147 btstack_ring_buffer_read(&bnep_lwip_outgoing_queue, (uint8_t *) &p, sizeof(struct pbuf *), &bytes_read); 148 (void) bytes_read; 149 #else 150 xQueueReceive(bnep_lwip_outgoing_queue, &p, portMAX_DELAY); 151 #endif 152 return p; 153 } 154 155 static int bnep_lwip_outgoing_packets_empty(void){ 156 #if NO_SYS 157 return btstack_ring_buffer_empty(&bnep_lwip_outgoing_queue); 158 #else 159 return uxQueueMessagesWaiting(bnep_lwip_outgoing_queue) == 0; 160 #endif 161 } 162 163 static void bnep_lwip_free_pbuf(struct pbuf * p){ 164 #if NO_SYS 165 // release buffer / decrease refcount 166 pbuf_free(p); 167 #else 168 // release buffer / decrease refcount 169 pbuf_free_callback(p); 170 #endif 171 } 172 173 static void bnep_lwip_outgoing_packet_processed(void){ 174 // free pbuf 175 bnep_lwip_free_pbuf(bnep_lwip_outgoing_next_packet); 176 // mark as done 177 bnep_lwip_outgoing_next_packet = NULL; 178 } 179 180 static void bnep_lwip_trigger_outgoing_process(void){ 181 #if NO_SYS 182 bnep_lwip_outgoing_process(NULL); 183 #else 184 btstack_run_loop_freertos_execute_code_on_main_thread(&bnep_lwip_outgoing_process, NULL); 185 #endif 186 } 187 188 /// lwIP functions 189 190 /** 191 * This function should do the actual transmission of the packet. The packet is 192 * contained in the pbuf that is passed to the function. This pbuf 193 * might be chained. 194 * 195 * @param netif the lwip network interface structure 196 * @param p the MAC packet to send (e.g. IP packet including MAC addresses and type) 197 * @return ERR_OK if the packet could be sent 198 * an err_t value if the packet couldn't be sent 199 * 200 * @note Returning ERR_MEM here if a DMA queue of your MAC is full can lead to 201 * strange results. You might consider waiting for space in the DMA queue 202 * to become availale since the stack doesn't retry to send a packet 203 * dropped because of memory failure (except for the TCP timers). 204 */ 205 206 static err_t low_level_output( struct netif *netif, struct pbuf *p ){ 207 UNUSED(netif); 208 209 log_info("low_level_output: packet %p, len %u, total len %u ", p, p->len, p->tot_len); 210 211 // bnep up? 212 if (bnep_cid == 0) return ERR_OK; 213 214 // inc refcount 215 pbuf_ref( p ); 216 217 // queue empty now? 218 int queue_empty = bnep_lwip_outgoing_packets_empty(); 219 220 // queue up 221 bnep_lwip_outgoing_queue_packet(p); 222 223 // trigger processing if queue was empty (might be new packet) 224 if (queue_empty){ 225 bnep_lwip_trigger_outgoing_process(); 226 } 227 228 return ERR_OK; 229 } 230 231 /** 232 * Should be called at the beginning of the program to set up the 233 * network interface. It calls the function low_level_init() to do the 234 * actual setup of the hardware. 235 * 236 * This function should be passed as a parameter to netif_add(). 237 * 238 * @param netif the lwip network interface structure for this ethernetif 239 * @return ERR_OK if the loopif is initialized 240 * ERR_MEM if private data couldn't be allocated 241 * any other err_t on error 242 */ 243 244 static err_t bnep_lwip_netif_init(struct netif *netif){ 245 246 // interface short name 247 netif->name[0] = IFNAME0; 248 netif->name[1] = IFNAME1; 249 250 // mtu 251 netif->mtu = 1600; 252 253 /* device capabilities */ 254 netif->flags |= NETIF_FLAG_BROADCAST | NETIF_FLAG_ETHARP; 255 256 /* We directly use etharp_output() here to save a function call. 257 * You can instead declare your own function an call etharp_output() 258 * from it if you have to do some checks before sending (e.g. if link 259 * is available...) 260 */ 261 netif->output = etharp_output; 262 #if LWIP_IPV6 263 netif->output_ip6 = ethip6_output; 264 #endif 265 netif->linkoutput = low_level_output; 266 267 return ERR_OK; 268 } 269 270 static int bnep_lwip_netif_up(bd_addr_t network_address){ 271 log_info("bnep_lwip_netif_up start addr %s", bd_addr_to_str(network_address)); 272 273 // set mac address 274 btstack_netif.hwaddr_len = 6; 275 memcpy(btstack_netif.hwaddr, network_address, 6); 276 277 // link is up 278 btstack_netif.flags |= NETIF_FLAG_LINK_UP; 279 280 // if up 281 netif_set_up(&btstack_netif); 282 283 return 0; 284 } 285 286 /** 287 * @brief Bring up network interfacd 288 * @param network_address 289 * @return 0 if ok 290 */ 291 static int bnep_lwip_netif_down(void){ 292 log_info("bnep_lwip_netif_down"); 293 294 // link is down 295 btstack_netif.flags &= ~NETIF_FLAG_LINK_UP; 296 297 netif_set_down(&btstack_netif); 298 return 0; 299 } 300 301 /** 302 * @brief Forward packet to TCP/IP stack 303 * @param packet 304 * @param size 305 */ 306 static void bnep_lwip_netif_process_packet(const uint8_t * packet, uint16_t size){ 307 308 /* We allocate a pbuf chain of pbufs from the pool. */ 309 struct pbuf * p = pbuf_alloc(PBUF_RAW, size, PBUF_POOL); 310 log_debug("bnep_lwip_netif_process_packet, pbuf_alloc = %p", p); 311 312 if (!p) return; 313 314 /* store packet in pbuf chain */ 315 struct pbuf * q = p; 316 while (q != NULL && size){ 317 memcpy(q->payload, packet, q->len); 318 packet += q->len; 319 size -= q->len; 320 q = q->next; 321 } 322 323 if (size != 0){ 324 log_error("failed to copy data into pbuf"); 325 bnep_lwip_free_pbuf(p); 326 return; 327 } 328 329 /* pass all packets to ethernet_input, which decides what packets it supports */ 330 int res = btstack_netif.input(p, &btstack_netif); 331 if (res != ERR_OK){ 332 log_error("bnep_lwip_netif_process_packet: IP input error\n"); 333 bnep_lwip_free_pbuf(p); 334 p = NULL; 335 } 336 } 337 338 339 // BNEP Functions & Handler 340 341 #if NO_SYS 342 static void bnep_lwip_timeout_handler(btstack_timer_source_t * ts){ 343 344 // process lwIP timers 345 sys_check_timeouts(); 346 347 // check if link is still up 348 if ((btstack_netif.flags & NETIF_FLAG_LINK_UP) == 0) return; 349 350 // restart timer 351 btstack_run_loop_set_timer(ts, LWIP_TIMER_INTERVAL_MS); 352 btstack_run_loop_add_timer(ts); 353 } 354 #endif 355 356 static void bnep_lwip_outgoing_process(void * arg){ 357 UNUSED(arg); 358 359 // previous packet not sent yet 360 if (bnep_lwip_outgoing_next_packet) return; 361 362 bnep_lwip_outgoing_next_packet = bnep_lwip_outgoing_pop_packet(); 363 364 // request can send now 365 bnep_request_can_send_now_event(bnep_cid); 366 } 367 368 static void bnep_lwip_send_packet(void){ 369 if (bnep_lwip_outgoing_next_packet == NULL){ 370 log_error("CAN SEND NOW, but now packet queued"); 371 return; 372 } 373 374 // flatten into our buffer 375 uint32_t len = btstack_min(sizeof(btstack_network_outgoing_buffer), bnep_lwip_outgoing_next_packet->tot_len); 376 pbuf_copy_partial(bnep_lwip_outgoing_next_packet, btstack_network_outgoing_buffer, len, 0); 377 bnep_send(bnep_cid, (uint8_t*) btstack_network_outgoing_buffer, len); 378 } 379 380 static void bnep_lwip_packet_sent(void){ 381 log_debug("bnep_lwip_packet_sent: %p", bnep_lwip_outgoing_next_packet); 382 383 // release current packet 384 bnep_lwip_outgoing_packet_processed(); 385 386 // more ? 387 if (bnep_lwip_outgoing_packets_empty()) return; 388 bnep_lwip_trigger_outgoing_process(); 389 } 390 391 static void bnep_lwip_discard_packets(void){ 392 // discard current packet 393 if (bnep_lwip_outgoing_next_packet){ 394 bnep_lwip_outgoing_packet_processed(); 395 } 396 397 // reset queue 398 bnep_lwip_outgoing_reset_queue(); 399 } 400 401 static void packet_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size) 402 { 403 /* LISTING_PAUSE */ 404 UNUSED(channel); 405 406 bd_addr_t local_addr; 407 408 switch (packet_type) { 409 case HCI_EVENT_PACKET: 410 switch (hci_event_packet_get_type(packet)) { 411 412 /* @text BNEP_EVENT_CHANNEL_OPENED is received after a BNEP connection was established or 413 * or when the connection fails. The status field returns the error code. 414 * 415 * The TAP network interface is then configured. A data source is set up and registered with the 416 * run loop to receive Ethernet packets from the TAP interface. 417 * 418 * The event contains both the source and destination UUIDs, as well as the MTU for this connection and 419 * the BNEP Channel ID, which is used for sending Ethernet packets over BNEP. 420 */ 421 case BNEP_EVENT_CHANNEL_OPENED: 422 if (bnep_event_channel_opened_get_status(packet) != 0) break; 423 424 bnep_cid = bnep_event_channel_opened_get_bnep_cid(packet); 425 426 /* Setup network interface */ 427 gap_local_bd_addr(local_addr); 428 bnep_lwip_netif_up(local_addr); 429 430 #if NO_SYS 431 // start timer 432 btstack_run_loop_set_timer_handler(&bnep_lwip_timer, bnep_lwip_timeout_handler); 433 btstack_run_loop_set_timer(&bnep_lwip_timer, LWIP_TIMER_INTERVAL_MS); 434 btstack_run_loop_add_timer(&bnep_lwip_timer); 435 #endif 436 break; 437 438 /* @text BNEP_EVENT_CHANNEL_CLOSED is received when the connection gets closed. 439 */ 440 case BNEP_EVENT_CHANNEL_CLOSED: 441 bnep_cid = 0; 442 bnep_lwip_discard_packets(); 443 444 // Mark Link as Down 445 bnep_lwip_netif_down(); 446 break; 447 448 /* @text BNEP_EVENT_CAN_SEND_NOW indicates that a new packet can be send. This triggers the send of a 449 * stored network packet. The tap datas source can be enabled again 450 */ 451 case BNEP_EVENT_CAN_SEND_NOW: 452 bnep_lwip_send_packet(); 453 bnep_lwip_packet_sent(); 454 break; 455 456 default: 457 break; 458 } 459 break; 460 461 /* @text Ethernet packets from the remote device are received in the packet handler with type BNEP_DATA_PACKET. 462 * It is forwarded to the TAP interface. 463 */ 464 case BNEP_DATA_PACKET: 465 if (bnep_cid == 0) break; 466 // Write out the ethernet frame to the network interface 467 bnep_lwip_netif_process_packet(packet, size); 468 break; 469 470 default: 471 break; 472 } 473 474 // forward to app 475 if (!client_handler) return; 476 (*client_handler)(packet_type, channel, packet, size); 477 } 478 479 /// API 480 481 /** 482 * @brief Initialize network interface 483 * @param send_packet_callback 484 */ 485 void bnep_lwip_init(void){ 486 487 // set up outgoing queue 488 int error = bnep_lwip_outgoing_init_queue(); 489 if (error) return; 490 491 ip4_addr_t fsl_netif0_ipaddr, fsl_netif0_netmask, fsl_netif0_gw; 492 #if 0 493 // when using DHCP Client, no address 494 IP4_ADDR(&fsl_netif0_ipaddr, 0U, 0U, 0U, 0U); 495 IP4_ADDR(&fsl_netif0_netmask, 0U, 0U, 0U, 0U); 496 #else 497 // when playing DHCP Server, set address 498 IP4_ADDR(&fsl_netif0_ipaddr, 192U, 168U, 7U, 1U); 499 IP4_ADDR(&fsl_netif0_netmask, 255U, 255U, 255U, 0U); 500 #endif 501 IP4_ADDR(&fsl_netif0_gw, 0U, 0U, 0U, 0U); 502 503 // input function differs for sys vs nosys 504 netif_input_fn input_function; 505 #if NO_SYS 506 input_function = ethernet_input; 507 #else 508 input_function = tcpip_input; 509 #endif 510 511 netif_add(&btstack_netif, &fsl_netif0_ipaddr, &fsl_netif0_netmask, &fsl_netif0_gw, NULL, bnep_lwip_netif_init, input_function); 512 netif_set_default(&btstack_netif); 513 } 514 515 /** 516 * @brief Register packet handler for BNEP events 517 */ 518 void bnep_lwip_register_packet_handler(btstack_packet_handler_t handler){ 519 client_handler = handler; 520 } 521 522 /** 523 * @brief Register BNEP service 524 * @brief Same as benp_register_service, but bnep lwip adapter handles all events 525 * @param service_uuid 526 * @Param max_frame_size 527 */ 528 uint8_t bnep_lwip_register_service(uint16_t service_uuid, uint16_t max_frame_size){ 529 return bnep_register_service(packet_handler, service_uuid, max_frame_size); 530 } 531 532 /** 533 * @brief Creates BNEP connection (channel) to a given server on a remote device with baseband address. A new baseband connection will be initiated if necessary. 534 * @note: uses our packet handler to manage lwIP network interface 535 * @param addr 536 * @param l2cap_psm 537 * @param uuid_src 538 * @param uuid_dest 539 * @return status 540 */ 541 uint8_t bnep_lwip_connect(bd_addr_t addr, uint16_t l2cap_psm, uint16_t uuid_src, uint16_t uuid_dest){ 542 int status = bnep_connect(packet_handler, addr, l2cap_psm, uuid_src, uuid_dest); 543 if (status != 0){ 544 return ERROR_CODE_UNSPECIFIED_ERROR; 545 } else { 546 return ERROR_CODE_SUCCESS; 547 } 548 } 549