Subversion Repositories HelenOS

Rev

Rev 2486 | Rev 2490 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | Download | RSS feed

  1. /*
  2.  * Copyright (c) 2006 Ondrej Palkovsky
  3.  * All rights reserved.
  4.  *
  5.  * Redistribution and use in source and binary forms, with or without
  6.  * modification, are permitted provided that the following conditions
  7.  * are met:
  8.  *
  9.  * - Redistributions of source code must retain the above copyright
  10.  *   notice, this list of conditions and the following disclaimer.
  11.  * - Redistributions in binary form must reproduce the above copyright
  12.  *   notice, this list of conditions and the following disclaimer in the
  13.  *   documentation and/or other materials provided with the distribution.
  14.  * - The name of the author may not be used to endorse or promote products
  15.  *   derived from this software without specific prior written permission.
  16.  *
  17.  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
  18.  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  19.  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
  20.  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
  21.  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  22.  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  23.  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  24.  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  25.  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  26.  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  27.  */
  28.  
  29. /** @addtogroup libc
  30.  * @{
  31.  */
  32. /** @file
  33.  */
  34.  
  35. /**
  36.  * Asynchronous library
  37.  *
  38.  * The aim of this library is facilitating writing programs utilizing the
  39.  * asynchronous nature of HelenOS IPC, yet using a normal way of programming.
  40.  *
  41.  * You should be able to write very simple multithreaded programs, the async
  42.  * framework will automatically take care of most synchronization problems.
  43.  *
  44.  * Default semantics:
  45.  * - async_send_*():    send asynchronously. If the kernel refuses to send
  46.  *          more messages, [ try to get responses from kernel, if
  47.  *          nothing found, might try synchronous ]
  48.  *
  49.  * Example of use (pseudo C):
  50.  *
  51.  * 1) Multithreaded client application
  52.  *
  53.  * fibril_create(fibril1, ...);
  54.  * fibril_create(fibril2, ...);
  55.  * ...
  56.  *  
  57.  * int fibril1(void *arg)
  58.  * {
  59.  *  conn = ipc_connect_me_to();
  60.  *  c1 = async_send(conn);
  61.  *  c2 = async_send(conn);
  62.  *  async_wait_for(c1);
  63.  *  async_wait_for(c2);
  64.  *  ...
  65.  * }
  66.  *
  67.  *
  68.  * 2) Multithreaded server application
  69.  * main()
  70.  * {
  71.  *  async_manager();
  72.  * }
  73.  *
  74.  *
  75.  * client_connection(icallid, *icall)
  76.  * {
  77.  *  if (want_refuse) {
  78.  *      ipc_answer_fast(icallid, ELIMIT, 0, 0);
  79.  *      return;
  80.  *  }
  81.  *  ipc_answer_fast(icallid, EOK, 0, 0);
  82.  *
  83.  *  callid = async_get_call(&call);
  84.  *  handle_call(callid, call);
  85.  *  ipc_answer_fast(callid, 1, 2, 3);
  86.  *
  87.  *  callid = async_get_call(&call);
  88.  *  ....
  89.  * }
  90.  *
  91.  */
  92.  
  93. #include <futex.h>
  94. #include <async.h>
  95. #include <fibril.h>
  96. #include <stdio.h>
  97. #include <libadt/hash_table.h>
  98. #include <libadt/list.h>
  99. #include <ipc/ipc.h>
  100. #include <assert.h>
  101. #include <errno.h>
  102. #include <sys/time.h>
  103. #include <arch/barrier.h>
  104.  
  105. atomic_t async_futex = FUTEX_INITIALIZER;
  106. static hash_table_t conn_hash_table;
  107. static LIST_INITIALIZE(timeout_list);
  108.  
  109. /** Structures of this type represent a waiting fibril. */
  110. typedef struct {
  111.     /** Expiration time. */
  112.     struct timeval expires;    
  113.     /** If true, this struct is in the timeout list. */
  114.     int inlist;
  115.     /** Timeout list link. */
  116.     link_t link;
  117.  
  118.     /** Fibril waiting for this message. */
  119.     fid_t fid;
  120.     /** If true, this fibril is currently active. */
  121.     int active;
  122.     /** If true, we have timed out. */
  123.     int timedout;
  124. } awaiter_t;
  125.  
  126. typedef struct {
  127.     awaiter_t wdata;
  128.    
  129.     /** If reply was received. */
  130.     int done;
  131.     /** Pointer to where the answer data is stored. */
  132.     ipc_call_t *dataptr;
  133.  
  134.     ipcarg_t retval;
  135. } amsg_t;
  136.  
  137. typedef struct {
  138.     link_t link;
  139.     ipc_callid_t callid;
  140.     ipc_call_t call;
  141. } msg_t;
  142.  
  143. typedef struct {
  144.     awaiter_t wdata;
  145.  
  146.     /** Hash table link. */
  147.     link_t link;
  148.  
  149.     /** Incoming phone hash. */
  150.     ipcarg_t in_phone_hash;    
  151.  
  152.     /** Messages that should be delivered to this fibril. */
  153.     link_t msg_queue;      
  154.                      
  155.     /** Identification of the opening call. */
  156.     ipc_callid_t callid;
  157.     /** Call data of the opening call. */
  158.     ipc_call_t call;
  159.  
  160.     /** Identification of the closing call. */
  161.     ipc_callid_t close_callid;
  162.  
  163.     /** Fibril function that will be used to handle the connection. */
  164.     void (*cfibril)(ipc_callid_t, ipc_call_t *);
  165. } connection_t;
  166.  
  167. /** Identifier of the incoming connection handled by the current fibril. */
  168. __thread connection_t *FIBRIL_connection;
  169.  
  170. /** If true, it is forbidden to use async_req functions and all preemption is
  171.  * disabled. */
  172. __thread int in_interrupt_handler;
  173.  
  174. static void default_client_connection(ipc_callid_t callid, ipc_call_t *call);
  175. static void default_interrupt_received(ipc_callid_t callid, ipc_call_t *call);
  176. static async_client_conn_t client_connection = default_client_connection;
  177. static async_client_conn_t interrupt_received = default_interrupt_received;
  178.  
  179. #define CONN_HASH_TABLE_CHAINS  32
  180.  
  181. /** Compute hash into the connection hash table based on the source phone hash.
  182.  *
  183.  * @param key       Pointer to source phone hash.
  184.  *
  185.  * @return      Index into the connection hash table.
  186.  */
  187. static hash_index_t conn_hash(unsigned long *key)
  188. {
  189.     assert(key);
  190.     return ((*key) >> 4) % CONN_HASH_TABLE_CHAINS;
  191. }
  192.  
  193. /** Compare hash table item with a key.
  194.  *
  195.  * @param key       Array containing the source phone hash as the only item.
  196.  * @param keys      Expected 1 but ignored.
  197.  * @param item      Connection hash table item.
  198.  *
  199.  * @return      True on match, false otherwise.
  200.  */
  201. static int conn_compare(unsigned long key[], hash_count_t keys, link_t *item)
  202. {
  203.     connection_t *hs;
  204.  
  205.     hs = hash_table_get_instance(item, connection_t, link);
  206.    
  207.     return key[0] == hs->in_phone_hash;
  208. }
  209.  
  210. /** Connection hash table removal callback function.
  211.  *
  212.  * This function is called whenever a connection is removed from the connection
  213.  * hash table.
  214.  *
  215.  * @param item      Connection hash table item being removed.
  216.  */
  217. static void conn_remove(link_t *item)
  218. {
  219.     free(hash_table_get_instance(item, connection_t, link));
  220. }
  221.  
  222.  
  223. /** Operations for the connection hash table. */
  224. static hash_table_operations_t conn_hash_table_ops = {
  225.     .hash = conn_hash,
  226.     .compare = conn_compare,
  227.     .remove_callback = conn_remove
  228. };
  229.  
  230. /** Sort in current fibril's timeout request.
  231.  *
  232.  * @param wd        Wait data of the current fibril.
  233.  */
  234. static void insert_timeout(awaiter_t *wd)
  235. {
  236.     link_t *tmp;
  237.     awaiter_t *cur;
  238.  
  239.     wd->timedout = 0;
  240.     wd->inlist = 1;
  241.  
  242.     tmp = timeout_list.next;
  243.     while (tmp != &timeout_list) {
  244.         cur = list_get_instance(tmp, awaiter_t, link);
  245.         if (tv_gteq(&cur->expires, &wd->expires))
  246.             break;
  247.         tmp = tmp->next;
  248.     }
  249.     list_append(&wd->link, tmp);
  250. }
  251.  
  252. /** Try to route a call to an appropriate connection fibril.
  253.  *
  254.  */
  255. static int route_call(ipc_callid_t callid, ipc_call_t *call)
  256. {
  257.     connection_t *conn;
  258.     msg_t *msg;
  259.     link_t *hlp;
  260.     unsigned long key;
  261.  
  262.     futex_down(&async_futex);
  263.  
  264.     key = call->in_phone_hash;
  265.     hlp = hash_table_find(&conn_hash_table, &key);
  266.     if (!hlp) {
  267.         futex_up(&async_futex);
  268.         return 0;
  269.     }
  270.     conn = hash_table_get_instance(hlp, connection_t, link);
  271.  
  272.     msg = malloc(sizeof(*msg));
  273.     msg->callid = callid;
  274.     msg->call = *call;
  275.     list_append(&msg->link, &conn->msg_queue);
  276.  
  277.     if (IPC_GET_METHOD(*call) == IPC_M_PHONE_HUNGUP)
  278.         conn->close_callid = callid;
  279.    
  280.     /* If the call is waiting for event, run it */
  281.     if (!conn->wdata.active) {
  282.         /* If in timeout list, remove it */
  283.         if (conn->wdata.inlist) {
  284.             conn->wdata.inlist = 0;
  285.             list_remove(&conn->wdata.link);
  286.         }
  287.         conn->wdata.active = 1;
  288.         fibril_add_ready(conn->wdata.fid);
  289.     }
  290.  
  291.     futex_up(&async_futex);
  292.  
  293.     return 1;
  294. }
  295.  
  296. /** Return new incoming message for the current (fibril-local) connection.
  297.  *
  298.  * @param call      Storage where the incoming call data will be stored.
  299.  * @param usecs     Timeout in microseconds. Zero denotes no timeout.
  300.  *
  301.  * @return      If no timeout was specified, then a hash of the
  302.  *          incoming call is returned. If a timeout is specified,
  303.  *          then a hash of the incoming call is returned unless
  304.  *          the timeout expires prior to receiving a message. In
  305.  *          that case zero is returned.
  306.  */
  307. ipc_callid_t async_get_call_timeout(ipc_call_t *call, suseconds_t usecs)
  308. {
  309.     msg_t *msg;
  310.     ipc_callid_t callid;
  311.     connection_t *conn;
  312.    
  313.     assert(FIBRIL_connection);
  314.     /* GCC 4.1.0 coughs on FIBRIL_connection-> dereference,
  315.      * GCC 4.1.1 happilly puts the rdhwr instruction in delay slot.
  316.      *           I would never expect to find so many errors in
  317.      *           compiler *($&$(*&$
  318.      */
  319.     conn = FIBRIL_connection;
  320.  
  321.     futex_down(&async_futex);
  322.  
  323.     if (usecs) {
  324.         gettimeofday(&conn->wdata.expires, NULL);
  325.         tv_add(&conn->wdata.expires, usecs);
  326.     } else {
  327.         conn->wdata.inlist = 0;
  328.     }
  329.     /* If nothing in queue, wait until something arrives */
  330.     while (list_empty(&conn->msg_queue)) {
  331.         if (usecs)
  332.             insert_timeout(&conn->wdata);
  333.  
  334.         conn->wdata.active = 0;
  335.         fibril_schedule_next_adv(FIBRIL_TO_MANAGER);
  336.         /*
  337.          * Futex is up after getting back from async_manager get it
  338.          * again.
  339.         */
  340.         futex_down(&async_futex);
  341.         if (usecs && conn->wdata.timedout &&
  342.             list_empty(&conn->msg_queue)) {
  343.             /* If we timed out -> exit */
  344.             futex_up(&async_futex);
  345.             return 0;
  346.         }
  347.     }
  348.    
  349.     msg = list_get_instance(conn->msg_queue.next, msg_t, link);
  350.     list_remove(&msg->link);
  351.     callid = msg->callid;
  352.     *call = msg->call;
  353.     free(msg);
  354.    
  355.     futex_up(&async_futex);
  356.     return callid;
  357. }
  358.  
  359. /** Fibril function that gets created on new connection
  360.  *
  361.  * This function is defined as a weak symbol - to be redefined in user code.
  362.  */
  363. static void default_client_connection(ipc_callid_t callid, ipc_call_t *call)
  364. {
  365.     ipc_answer_fast(callid, ENOENT, 0, 0);
  366. }
  367. static void default_interrupt_received(ipc_callid_t callid, ipc_call_t *call)
  368. {
  369. }
  370.  
  371. /** Wrapper for client connection fibril.
  372.  *
  373.  * When new connection arrives, a fibril with this implementing function is
  374.  * created. It calls client_connection() and does the final cleanup.
  375.  *
  376.  * @param arg       Connection structure pointer
  377.  *
  378.  * @return      Always zero.
  379.  */
  380. static int connection_fibril(void  *arg)
  381. {
  382.     unsigned long key;
  383.     msg_t *msg;
  384.     int close_answered = 0;
  385.  
  386.     /* Setup fibril-local connection pointer */
  387.     FIBRIL_connection = (connection_t *) arg;
  388.     FIBRIL_connection->cfibril(FIBRIL_connection->callid,
  389.         &FIBRIL_connection->call);
  390.    
  391.     /* Remove myself from connection hash table */
  392.     futex_down(&async_futex);
  393.     key = FIBRIL_connection->in_phone_hash;
  394.     hash_table_remove(&conn_hash_table, &key, 1);
  395.     futex_up(&async_futex);
  396.    
  397.     /* Answer all remaining messages with ehangup */
  398.     while (!list_empty(&FIBRIL_connection->msg_queue)) {
  399.         msg = list_get_instance(FIBRIL_connection->msg_queue.next,
  400.             msg_t, link);
  401.         list_remove(&msg->link);
  402.         if (msg->callid == FIBRIL_connection->close_callid)
  403.             close_answered = 1;
  404.         ipc_answer_fast(msg->callid, EHANGUP, 0, 0);
  405.         free(msg);
  406.     }
  407.     if (FIBRIL_connection->close_callid)
  408.         ipc_answer_fast(FIBRIL_connection->close_callid, 0, 0, 0);
  409.    
  410.     return 0;
  411. }
  412.  
  413. /** Create a new fibril for a new connection.
  414.  *
  415.  * Creates new fibril for connection, fills in connection structures and inserts
  416.  * it into the hash table, so that later we can easily do routing of messages to
  417.  * particular fibrils.
  418.  *
  419.  * @param in_phone_hash Identification of the incoming connection
  420.  * @param callid    Callid of the IPC_M_CONNECT_ME_TO packet
  421.  * @param call      Call data of the opening packet
  422.  * @param cfibril   Fibril function that should be called upon
  423.  *                  opening the connection
  424.  * @return      New fibril id.
  425.  */
  426. fid_t async_new_connection(ipcarg_t in_phone_hash, ipc_callid_t callid,
  427.     ipc_call_t *call, void (*cfibril)(ipc_callid_t, ipc_call_t *))
  428. {
  429.     connection_t *conn;
  430.     unsigned long key;
  431.  
  432.     conn = malloc(sizeof(*conn));
  433.     if (!conn) {
  434.         ipc_answer_fast(callid, ENOMEM, 0, 0);
  435.         return NULL;
  436.     }
  437.     conn->in_phone_hash = in_phone_hash;
  438.     list_initialize(&conn->msg_queue);
  439.     conn->callid = callid;
  440.     conn->close_callid = 0;
  441.     if (call)
  442.         conn->call = *call;
  443.     conn->wdata.active = 1; /* We will activate it asap */
  444.     conn->cfibril = cfibril;
  445.  
  446.     conn->wdata.fid = fibril_create(connection_fibril, conn);
  447.     if (!conn->wdata.fid) {
  448.         free(conn);
  449.         ipc_answer_fast(callid, ENOMEM, 0, 0);
  450.         return NULL;
  451.     }
  452.     /* Add connection to hash table */
  453.     key = conn->in_phone_hash;
  454.     futex_down(&async_futex);
  455.     hash_table_insert(&conn_hash_table, &key, &conn->link);
  456.     futex_up(&async_futex);
  457.  
  458.     fibril_add_ready(conn->wdata.fid);
  459.  
  460.     return conn->wdata.fid;
  461. }
  462.  
  463. /** Handle a call that was received. */
  464. static void handle_call(ipc_callid_t callid, ipc_call_t *call)
  465. {
  466.     /* Unrouted call - do some default behaviour */
  467.     if ((callid & IPC_CALLID_NOTIFICATION)) {
  468.         in_interrupt_handler = 1;
  469.         (*interrupt_received)(callid,call);
  470.         in_interrupt_handler = 0;
  471.         return;
  472.     }      
  473.  
  474.     switch (IPC_GET_METHOD(*call)) {
  475.     case IPC_M_CONNECT_ME_TO:
  476.         /* Open new connection with fibril etc. */
  477.         async_new_connection(IPC_GET_ARG3(*call), callid, call,
  478.             client_connection);
  479.         return;
  480.     }
  481.  
  482.     /* Try to route call through connection tables */
  483.     if (route_call(callid, call))
  484.         return;
  485.  
  486.     /* Unknown call from unknown phone - hang it up */
  487.     ipc_answer_fast(callid, EHANGUP, 0, 0);
  488. }
  489.  
  490. /** Fire all timeouts that expired. */
  491. static void handle_expired_timeouts(void)
  492. {
  493.     struct timeval tv;
  494.     awaiter_t *waiter;
  495.     link_t *cur;
  496.  
  497.     gettimeofday(&tv,NULL);
  498.     futex_down(&async_futex);
  499.  
  500.     cur = timeout_list.next;
  501.     while (cur != &timeout_list) {
  502.         waiter = list_get_instance(cur, awaiter_t, link);
  503.         if (tv_gt(&waiter->expires, &tv))
  504.             break;
  505.         cur = cur->next;
  506.         list_remove(&waiter->link);
  507.         waiter->inlist = 0;
  508.         waiter->timedout = 1;
  509.         /* Redundant condition? The fibril should not
  510.          * be active when it gets here.
  511.          */
  512.         if (!waiter->active) {
  513.             waiter->active = 1;
  514.             fibril_add_ready(waiter->fid);
  515.         }
  516.     }
  517.  
  518.     futex_up(&async_futex);
  519. }
  520.  
  521. /** Endless loop dispatching incoming calls and answers */
  522. static int async_manager_worker(void)
  523. {
  524.     ipc_call_t call;
  525.     ipc_callid_t callid;
  526.     int timeout;
  527.     awaiter_t *waiter;
  528.     struct timeval tv;
  529.  
  530.     while (1) {
  531.         if (fibril_schedule_next_adv(FIBRIL_FROM_MANAGER)) {
  532.             futex_up(&async_futex);
  533.             /* async_futex is always held
  534.              * when entering manager fibril
  535.              */
  536.             continue;
  537.         }
  538.         futex_down(&async_futex);
  539.         if (!list_empty(&timeout_list)) {
  540.             waiter = list_get_instance(timeout_list.next, awaiter_t,
  541.                 link);
  542.             gettimeofday(&tv, NULL);
  543.             if (tv_gteq(&tv, &waiter->expires)) {
  544.                 futex_up(&async_futex);
  545.                 handle_expired_timeouts();
  546.                 continue;
  547.             } else
  548.                 timeout = tv_sub(&waiter->expires, &tv);
  549.         } else
  550.             timeout = SYNCH_NO_TIMEOUT;
  551.         futex_up(&async_futex);
  552.  
  553.         callid = ipc_wait_cycle(&call, timeout, SYNCH_FLAGS_NONE);
  554.  
  555.         if (!callid) {
  556.             handle_expired_timeouts();
  557.             continue;
  558.         }
  559.  
  560.         if (callid & IPC_CALLID_ANSWERED) {
  561.             continue;
  562.         }
  563.  
  564.         handle_call(callid, &call);
  565.     }
  566.    
  567.     return 0;
  568. }
  569.  
  570. /** Function to start async_manager as a standalone fibril.
  571.  *
  572.  * When more kernel threads are used, one async manager should
  573.  * exist per thread.
  574.  */
  575. static int async_manager_fibril(void *arg)
  576. {
  577.     futex_up(&async_futex);
  578.     /* async_futex is always locked when entering
  579.      * manager */
  580.     async_manager_worker();
  581.    
  582.     return 0;
  583. }
  584.  
  585. /** Add one manager to manager list */
  586. void async_create_manager(void)
  587. {
  588.     fid_t fid;
  589.  
  590.     fid = fibril_create(async_manager_fibril, NULL);
  591.     fibril_add_manager(fid);
  592. }
  593.  
  594. /** Remove one manager from manager list */
  595. void async_destroy_manager(void)
  596. {
  597.     fibril_remove_manager();
  598. }
  599.  
  600. /** Initialize internal structures needed for async manager */
  601. int _async_init(void)
  602. {
  603.     if (!hash_table_create(&conn_hash_table, CONN_HASH_TABLE_CHAINS, 1,
  604.         &conn_hash_table_ops)) {
  605.         printf("%s: cannot create hash table\n", "async");
  606.         return ENOMEM;
  607.     }
  608.    
  609.     return 0;
  610. }
  611.  
  612. /** IPC handler for messages in async framework
  613.  *
  614.  * Notify the fibril which is waiting for this message, that it arrived
  615.  */
  616. static void reply_received(void *private, int retval, ipc_call_t *data)
  617. {
  618.     amsg_t *msg = (amsg_t *) private;
  619.  
  620.     msg->retval = retval;
  621.  
  622.     futex_down(&async_futex);
  623.     /* Copy data after futex_down, just in case the
  624.      * call was detached
  625.      */
  626.     if (msg->dataptr)
  627.         *msg->dataptr = *data;
  628.  
  629.     write_barrier();
  630.     /* Remove message from timeout list */
  631.     if (msg->wdata.inlist)
  632.         list_remove(&msg->wdata.link);
  633.     msg->done = 1;
  634.     if (! msg->wdata.active) {
  635.         msg->wdata.active = 1;
  636.         fibril_add_ready(msg->wdata.fid);
  637.     }
  638.     futex_up(&async_futex);
  639. }
  640.  
  641. /** Send message and return id of the sent message
  642.  *
  643.  * The return value can be used as input for async_wait() to wait
  644.  * for completion.
  645.  */
  646. aid_t async_send_2(int phoneid, ipcarg_t method, ipcarg_t arg1, ipcarg_t arg2,
  647.     ipc_call_t *dataptr)
  648. {
  649.     amsg_t *msg;
  650.  
  651.     if (in_interrupt_handler) {
  652.         printf("Cannot send asynchronous request in interrupt "
  653.             "handler.\n");
  654.         _exit(1);
  655.     }
  656.  
  657.     msg = malloc(sizeof(*msg));
  658.     msg->done = 0;
  659.     msg->dataptr = dataptr;
  660.  
  661.     msg->wdata.active = 1; /* We may sleep in next method, but it
  662.                 * will use it's own mechanism */
  663.     ipc_call_async_2(phoneid, method, arg1, arg2, msg, reply_received, 1);
  664.  
  665.     return (aid_t) msg;
  666. }
  667.  
  668. /** Send message and return id of the sent message
  669.  *
  670.  * The return value can be used as input for async_wait() to wait
  671.  * for completion.
  672.  */
  673. aid_t async_send_3(int phoneid, ipcarg_t method, ipcarg_t arg1, ipcarg_t arg2,
  674.     ipcarg_t arg3, ipc_call_t *dataptr)
  675. {
  676.     amsg_t *msg;
  677.  
  678.     if (in_interrupt_handler) {
  679.         printf("Cannot send asynchronous request in interrupt handler.\n");
  680.         _exit(1);
  681.     }
  682.  
  683.     msg = malloc(sizeof(*msg));
  684.     msg->done = 0;
  685.     msg->dataptr = dataptr;
  686.  
  687.     msg->wdata.active = 1; /* We may sleep in next method, but it
  688.                 * will use it's own mechanism */
  689.     ipc_call_async_3(phoneid, method, arg1, arg2, arg3, msg, reply_received,
  690.         1);
  691.  
  692.     return (aid_t) msg;
  693. }
  694.  
  695. /** Wait for a message sent by async framework
  696.  *
  697.  * @param amsgid    Message ID to wait for
  698.  * @param retval    Pointer to variable where will be stored retval of the
  699.  *          answered message. If NULL, it is ignored.
  700.  */
  701. void async_wait_for(aid_t amsgid, ipcarg_t *retval)
  702. {
  703.     amsg_t *msg = (amsg_t *) amsgid;
  704.  
  705.     futex_down(&async_futex);
  706.     if (msg->done) {
  707.         futex_up(&async_futex);
  708.         goto done;
  709.     }
  710.  
  711.     msg->wdata.fid = fibril_get_id();
  712.     msg->wdata.active = 0;
  713.     msg->wdata.inlist = 0;
  714.     /* Leave locked async_futex when entering this function */
  715.     fibril_schedule_next_adv(FIBRIL_TO_MANAGER);
  716.     /* futex is up automatically after fibril_schedule_next...*/
  717. done:
  718.     if (retval)
  719.         *retval = msg->retval;
  720.     free(msg);
  721. }
  722.  
  723. /** Wait for a message sent by async framework with timeout
  724.  *
  725.  * @param amsgid Message ID to wait for
  726.  * @param retval Pointer to variable where will be stored retval
  727.  *               of the answered message. If NULL, it is ignored.
  728.  * @param timeout Timeout in usecs
  729.  * @return 0 on success, ETIMEOUT if timeout expired
  730.  *
  731.  */
  732. int async_wait_timeout(aid_t amsgid, ipcarg_t *retval, suseconds_t timeout)
  733. {
  734.     amsg_t *msg = (amsg_t *) amsgid;
  735.  
  736.     /* TODO: Let it go through the event read at least once */
  737.     if (timeout < 0)
  738.         return ETIMEOUT;
  739.  
  740.     futex_down(&async_futex);
  741.     if (msg->done) {
  742.         futex_up(&async_futex);
  743.         goto done;
  744.     }
  745.  
  746.     gettimeofday(&msg->wdata.expires, NULL);
  747.     tv_add(&msg->wdata.expires, timeout);
  748.  
  749.     msg->wdata.fid = fibril_get_id();
  750.     msg->wdata.active = 0;
  751.     insert_timeout(&msg->wdata);
  752.  
  753.     /* Leave locked async_futex when entering this function */
  754.     fibril_schedule_next_adv(FIBRIL_TO_MANAGER);
  755.     /* futex is up automatically after fibril_schedule_next...*/
  756.  
  757.     if (!msg->done)
  758.         return ETIMEOUT;
  759.  
  760. done:
  761.     if (retval)
  762.         *retval = msg->retval;
  763.     free(msg);
  764.  
  765.     return 0;
  766. }
  767.  
  768. /** Wait specified time, but in the meantime handle incoming events
  769.  *
  770.  * @param timeout Time in microseconds to wait
  771.  */
  772. void async_usleep(suseconds_t timeout)
  773. {
  774.     amsg_t *msg;
  775.    
  776.     if (in_interrupt_handler) {
  777.         printf("Cannot call async_usleep in interrupt handler.\n");
  778.         _exit(1);
  779.     }
  780.  
  781.     msg = malloc(sizeof(*msg));
  782.     if (!msg)
  783.         return;
  784.  
  785.     msg->wdata.fid = fibril_get_id();
  786.     msg->wdata.active = 0;
  787.  
  788.     gettimeofday(&msg->wdata.expires, NULL);
  789.     tv_add(&msg->wdata.expires, timeout);
  790.  
  791.     futex_down(&async_futex);
  792.     insert_timeout(&msg->wdata);
  793.     /* Leave locked the async_futex when entering this function */
  794.     fibril_schedule_next_adv(FIBRIL_TO_MANAGER);
  795.     /* futex is up automatically after fibril_schedule_next_adv()...*/
  796.     free(msg);
  797. }
  798.  
  799. /** Set function that is called when IPC_M_CONNECT_ME_TO is received.
  800.  *
  801.  * @param conn Function that will form a new fibril.
  802.  */
  803. void async_set_client_connection(async_client_conn_t conn)
  804. {
  805.     client_connection = conn;
  806. }
  807. void async_set_interrupt_received(async_client_conn_t conn)
  808. {
  809.     interrupt_received = conn;
  810. }
  811.  
  812. /* Primitive functions for simple communication */
  813. void async_msg_3(int phoneid, ipcarg_t method, ipcarg_t arg1,
  814.          ipcarg_t arg2, ipcarg_t arg3)
  815. {
  816.     ipc_call_async_3(phoneid, method, arg1, arg2, arg3, NULL, NULL,
  817.         !in_interrupt_handler);
  818. }
  819.  
  820. void async_msg_2(int phoneid, ipcarg_t method, ipcarg_t arg1, ipcarg_t arg2)
  821. {
  822.     ipc_call_async_2(phoneid, method, arg1, arg2, NULL, NULL,
  823.         !in_interrupt_handler);
  824. }
  825.  
  826. /** @}
  827.  */
  828.