2021-02-06 06:36:38 +00:00
|
|
|
/*
|
2021-04-28 20:46:44 +00:00
|
|
|
* Copyright (c) 2021, the SerenityOS developers.
|
2021-10-26 08:44:10 +00:00
|
|
|
* Copyright (c) 2021, Andreas Kling <kling@serenityos.org>
|
2021-02-06 06:36:38 +00:00
|
|
|
*
|
2021-04-22 08:24:48 +00:00
|
|
|
* SPDX-License-Identifier: BSD-2-Clause
|
2021-02-06 06:36:38 +00:00
|
|
|
*/
|
|
|
|
|
|
|
|
#pragma once
|
|
|
|
|
2022-03-06 20:07:04 +00:00
|
|
|
#include <AK/Error.h>
|
2021-02-06 06:36:38 +00:00
|
|
|
#include <AK/IntrusiveList.h>
|
|
|
|
#include <Kernel/Forward.h>
|
2021-10-26 08:44:10 +00:00
|
|
|
#include <Kernel/Locking/SpinlockProtected.h>
|
2021-12-28 23:41:58 +00:00
|
|
|
#include <Kernel/WaitQueue.h>
|
2021-02-06 06:36:38 +00:00
|
|
|
|
|
|
|
namespace Kernel {
|
|
|
|
|
|
|
|
extern WorkQueue* g_io_work;
|
2021-11-26 17:39:26 +00:00
|
|
|
extern WorkQueue* g_ata_work;
|
2021-02-06 06:36:38 +00:00
|
|
|
|
|
|
|
class WorkQueue {
|
|
|
|
AK_MAKE_NONCOPYABLE(WorkQueue);
|
|
|
|
AK_MAKE_NONMOVABLE(WorkQueue);
|
|
|
|
|
|
|
|
public:
|
|
|
|
static void initialize();
|
|
|
|
|
2022-03-06 20:07:04 +00:00
|
|
|
ErrorOr<void> try_queue(void (*function)(void*), void* data = nullptr, void (*free_data)(void*) = nullptr)
|
2021-02-06 06:36:38 +00:00
|
|
|
{
|
2022-03-06 20:07:04 +00:00
|
|
|
auto item = new (nothrow) WorkItem; // TODO: use a pool
|
|
|
|
if (!item)
|
|
|
|
return Error::from_errno(ENOMEM);
|
2021-05-19 12:42:16 +00:00
|
|
|
item->function = [function, data, free_data] {
|
|
|
|
function(data);
|
|
|
|
if (free_data)
|
|
|
|
free_data(data);
|
|
|
|
};
|
2022-03-09 19:26:08 +00:00
|
|
|
do_queue(*item);
|
2022-03-06 20:07:04 +00:00
|
|
|
return {};
|
2021-02-06 06:36:38 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
template<typename Function>
|
2022-03-06 20:07:04 +00:00
|
|
|
ErrorOr<void> try_queue(Function function)
|
2021-02-06 06:36:38 +00:00
|
|
|
{
|
2022-03-06 20:07:04 +00:00
|
|
|
auto item = new (nothrow) WorkItem; // TODO: use a pool
|
|
|
|
if (!item)
|
|
|
|
return Error::from_errno(ENOMEM);
|
2021-05-19 12:42:16 +00:00
|
|
|
item->function = Function(function);
|
2022-03-09 19:26:08 +00:00
|
|
|
do_queue(*item);
|
2022-03-06 20:07:04 +00:00
|
|
|
return {};
|
2021-02-06 06:36:38 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
private:
|
2021-09-07 10:53:28 +00:00
|
|
|
explicit WorkQueue(StringView);
|
|
|
|
|
2021-02-06 06:36:38 +00:00
|
|
|
struct WorkItem {
|
2021-10-26 08:50:44 +00:00
|
|
|
public:
|
2021-04-16 12:03:24 +00:00
|
|
|
IntrusiveListNode<WorkItem> m_node;
|
2021-05-19 12:42:16 +00:00
|
|
|
Function<void()> function;
|
2021-02-06 06:36:38 +00:00
|
|
|
};
|
|
|
|
|
2022-03-09 19:26:08 +00:00
|
|
|
void do_queue(WorkItem&);
|
2021-02-06 06:36:38 +00:00
|
|
|
|
2022-08-19 18:53:40 +00:00
|
|
|
LockRefPtr<Thread> m_thread;
|
2021-02-06 06:36:38 +00:00
|
|
|
WaitQueue m_wait_queue;
|
2022-08-18 19:46:28 +00:00
|
|
|
SpinlockProtected<IntrusiveList<&WorkItem::m_node>> m_items { LockRank::None };
|
2021-02-06 06:36:38 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
}
|