@@ -492,28 +492,43 @@ bool TCP::unbind(const Socket& socket)
492492 return false ;
493493}
494494
495- bool TCP::add_connection (tcp::Connection_ptr conn) {
495+ bool TCP::add_connection (tcp::Connection_ptr conn)
496+ {
497+ const size_t alloc_thres = max_bufsize () * Read_request::buffer_limit;
496498 // Stat increment number of incoming connections
497499 (*incoming_connections_)++;
498500
499501 debug (" <TCP::add_connection> Connection added %s \n " , conn->to_string ().c_str ());
500- conn-> bufalloc = mempool_.get_resource ();
502+ auto resource = mempool_.get_resource ();
501503
502504 // Reject connection if we can't allocate memory
503- if (conn-> bufalloc == nullptr
504- or conn-> bufalloc -> allocatable () < max_bufsize () * Read_request::buffer_limit) {
505+ if ( UNLIKELY (resource == nullptr or resource-> allocatable () < alloc_thres))
506+ {
505507 conn->_on_cleanup_ = nullptr ;
506508 conn->abort ();
507509 return false ;
508510 }
509511
512+ conn->bufalloc = std::move (resource);
513+
514+ // printf("New inc conn %s allocatable=%zu\n", conn->to_string().c_str(), conn->bufalloc->allocatable());
515+
510516 Expects (conn->bufalloc != nullptr );
511517 conn->_on_cleanup ({this , &TCP::close_connection});
512518 return connections_.emplace (conn->tuple (), conn).second ;
513519}
514520
515521Connection_ptr TCP::create_connection (Socket local, Socket remote, ConnectCallback cb)
516522{
523+ const size_t alloc_thres = max_bufsize () * Read_request::buffer_limit;
524+
525+ auto resource = mempool_.get_resource ();
526+ // Don't create connection if we can't allocate memory
527+ if (UNLIKELY (resource == nullptr or resource->allocatable () < alloc_thres))
528+ {
529+ throw TCP_error{" Unable to create new connection: Not enough allocatable memory" };
530+ }
531+
517532 // Stat increment number of outgoing connections
518533 (*outgoing_connections_)++;
519534
@@ -523,7 +538,10 @@ Connection_ptr TCP::create_connection(Socket local, Socket remote, ConnectCallba
523538 )
524539 ).first ->second ;
525540 conn->_on_cleanup ({this , &TCP::close_connection});
526- conn->bufalloc = mempool_.get_resource ();
541+ conn->bufalloc = std::move (resource);
542+
543+ // printf("New out conn %s allocatable=%zu\n", conn->to_string().c_str(), conn->bufalloc->allocatable());
544+
527545 Expects (conn->bufalloc != nullptr );
528546 return conn;
529547}
0 commit comments