1 /*
2  * Copyright 2020 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #pragma once
18 
19 #include <stdint.h>
20 
21 #include "common/bidi_queue.h"
22 #include "hci/acl_manager.h"
23 #include "hci/controller.h"
24 #include "hci/hci_packets.h"
25 #include "os/handler.h"
26 
27 namespace bluetooth {
28 namespace hci {
29 namespace acl_manager {
30 
31 class RoundRobinScheduler {
32  public:
33   RoundRobinScheduler(os::Handler* handler, Controller* controller,
34                       common::BidiQueueEnd<AclPacketBuilder, AclPacketView>* hci_queue_end);
35   ~RoundRobinScheduler();
36 
37   enum ConnectionType { CLASSIC, LE };
38 
39   struct acl_queue_handler {
40     ConnectionType connection_type_;
41     std::shared_ptr<acl_manager::AclConnection::Queue> queue_;
42     bool dequeue_is_registered_ = false;
43     uint16_t number_of_sent_packets_ = 0;  // Track credits
44   };
45 
46   void Register(ConnectionType connection_type, uint16_t handle,
47                 std::shared_ptr<acl_manager::AclConnection::Queue> queue);
48   void Unregister(uint16_t handle);
49   uint16_t GetCredits();
50   uint16_t GetLeCredits();
51 
52  private:
53   void start_round_robin();
54   void buffer_packet(std::map<uint16_t, acl_queue_handler>::iterator acl_queue_handler);
55   void unregister_all_connections();
56   void send_next_fragment();
57   std::unique_ptr<AclPacketBuilder> handle_enqueue_next_fragment();
58   void incoming_acl_credits(uint16_t handle, uint16_t credits);
59 
60   os::Handler* handler_ = nullptr;
61   Controller* controller_ = nullptr;
62   std::map<uint16_t, acl_queue_handler> acl_queue_handlers_;
63   std::queue<std::pair<ConnectionType, std::unique_ptr<AclPacketBuilder>>> fragments_to_send_;
64   uint16_t max_acl_packet_credits_ = 0;
65   uint16_t acl_packet_credits_ = 0;
66   uint16_t le_max_acl_packet_credits_ = 0;
67   uint16_t le_acl_packet_credits_ = 0;
68   size_t hci_mtu_{0};
69   size_t le_hci_mtu_{0};
70   std::atomic_bool enqueue_registered_ = false;
71   common::BidiQueueEnd<AclPacketBuilder, AclPacketView>* hci_queue_end_ = nullptr;
72   // first register queue end for the Round-robin schedule
73   std::map<uint16_t, acl_queue_handler>::iterator starting_point_;
74 };
75 
76 }  // namespace acl_manager
77 }  // namespace hci
78 }  // namespace bluetooth