(__getline): Define.
[glibc/history.git] / sysdeps / pthread / aio_misc.c
blob3e1dbe9c63f2e45edbfdcaa81859c14fd46113ed
1 /* Handle general operations.
2 Copyright (C) 1997, 1998, 1999, 2000, 2001, 2003, 2004, 2006
3 Free Software Foundation, Inc.
4 This file is part of the GNU C Library.
5 Contributed by Ulrich Drepper <drepper@cygnus.com>, 1997.
7 The GNU C Library is free software; you can redistribute it and/or
8 modify it under the terms of the GNU Lesser General Public
9 License as published by the Free Software Foundation; either
10 version 2.1 of the License, or (at your option) any later version.
12 The GNU C Library is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 Lesser General Public License for more details.
17 You should have received a copy of the GNU Lesser General Public
18 License along with the GNU C Library; if not, write to the Free
19 Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
20 02111-1307 USA. */
22 #include <aio.h>
23 #include <assert.h>
24 #include <errno.h>
25 #include <limits.h>
26 #include <pthread.h>
27 #include <stdlib.h>
28 #include <unistd.h>
29 #include <sys/stat.h>
30 #include <sys/time.h>
31 #include <aio_misc.h>
33 #ifndef aio_create_helper_thread
34 # define aio_create_helper_thread __aio_create_helper_thread
36 extern inline int
37 __aio_create_helper_thread (pthread_t *threadp, void *(*tf) (void *), void *arg)
39 pthread_attr_t attr;
41 /* Make sure the thread is created detached. */
42 pthread_attr_init (&attr);
43 pthread_attr_setdetachstate (&attr, PTHREAD_CREATE_DETACHED);
45 int ret = pthread_create (threadp, &attr, tf, arg);
47 (void) pthread_attr_destroy (&attr);
48 return ret;
50 #endif
52 static void add_request_to_runlist (struct requestlist *newrequest);
54 /* Pool of request list entries. */
55 static struct requestlist **pool;
57 /* Number of total and allocated pool entries. */
58 static size_t pool_max_size;
59 static size_t pool_size;
61 /* We implement a two dimensional array but allocate each row separately.
62 The macro below determines how many entries should be used per row.
63 It should better be a power of two. */
64 #define ENTRIES_PER_ROW 32
66 /* How many rows we allocate at once. */
67 #define ROWS_STEP 8
69 /* List of available entries. */
70 static struct requestlist *freelist;
72 /* List of request waiting to be processed. */
73 static struct requestlist *runlist;
75 /* Structure list of all currently processed requests. */
76 static struct requestlist *requests;
78 /* Number of threads currently running. */
79 static int nthreads;
81 /* Number of threads waiting for work to arrive. */
82 static int idle_thread_count;
85 /* These are the values used to optimize the use of AIO. The user can
86 overwrite them by using the `aio_init' function. */
87 static struct aioinit optim =
89 20, /* int aio_threads; Maximal number of threads. */
90 64, /* int aio_num; Number of expected simultanious requests. */
100 /* Since the list is global we need a mutex protecting it. */
101 pthread_mutex_t __aio_requests_mutex = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP;
103 /* When you add a request to the list and there are idle threads present,
104 you signal this condition variable. When a thread finishes work, it waits
105 on this condition variable for a time before it actually exits. */
106 pthread_cond_t __aio_new_request_notification = PTHREAD_COND_INITIALIZER;
109 /* Functions to handle request list pool. */
110 static struct requestlist *
111 get_elem (void)
113 struct requestlist *result;
115 if (freelist == NULL)
117 struct requestlist *new_row;
118 int cnt;
120 assert (sizeof (struct aiocb) == sizeof (struct aiocb64));
122 if (pool_size + 1 >= pool_max_size)
124 size_t new_max_size = pool_max_size + ROWS_STEP;
125 struct requestlist **new_tab;
127 new_tab = (struct requestlist **)
128 realloc (pool, new_max_size * sizeof (struct requestlist *));
130 if (new_tab == NULL)
131 return NULL;
133 pool_max_size = new_max_size;
134 pool = new_tab;
137 /* Allocate the new row. */
138 cnt = pool_size == 0 ? optim.aio_num : ENTRIES_PER_ROW;
139 new_row = (struct requestlist *) calloc (cnt,
140 sizeof (struct requestlist));
141 if (new_row == NULL)
142 return NULL;
144 pool[pool_size++] = new_row;
146 /* Put all the new entries in the freelist. */
149 new_row->next_prio = freelist;
150 freelist = new_row++;
152 while (--cnt > 0);
155 result = freelist;
156 freelist = freelist->next_prio;
158 return result;
162 void
163 internal_function
164 __aio_free_request (struct requestlist *elem)
166 elem->running = no;
167 elem->next_prio = freelist;
168 freelist = elem;
172 struct requestlist *
173 internal_function
174 __aio_find_req (aiocb_union *elem)
176 struct requestlist *runp = requests;
177 int fildes = elem->aiocb.aio_fildes;
179 while (runp != NULL && runp->aiocbp->aiocb.aio_fildes < fildes)
180 runp = runp->next_fd;
182 if (runp != NULL)
184 if (runp->aiocbp->aiocb.aio_fildes != fildes)
185 runp = NULL;
186 else
187 while (runp != NULL && runp->aiocbp != elem)
188 runp = runp->next_prio;
191 return runp;
195 struct requestlist *
196 internal_function
197 __aio_find_req_fd (int fildes)
199 struct requestlist *runp = requests;
201 while (runp != NULL && runp->aiocbp->aiocb.aio_fildes < fildes)
202 runp = runp->next_fd;
204 return (runp != NULL && runp->aiocbp->aiocb.aio_fildes == fildes
205 ? runp : NULL);
209 void
210 internal_function
211 __aio_remove_request (struct requestlist *last, struct requestlist *req,
212 int all)
214 assert (req->running == yes || req->running == queued
215 || req->running == done);
217 if (last != NULL)
218 last->next_prio = all ? NULL : req->next_prio;
219 else
221 if (all || req->next_prio == NULL)
223 if (req->last_fd != NULL)
224 req->last_fd->next_fd = req->next_fd;
225 else
226 requests = req->next_fd;
227 if (req->next_fd != NULL)
228 req->next_fd->last_fd = req->last_fd;
230 else
232 if (req->last_fd != NULL)
233 req->last_fd->next_fd = req->next_prio;
234 else
235 requests = req->next_prio;
237 if (req->next_fd != NULL)
238 req->next_fd->last_fd = req->next_prio;
240 req->next_prio->last_fd = req->last_fd;
241 req->next_prio->next_fd = req->next_fd;
243 /* Mark this entry as runnable. */
244 req->next_prio->running = yes;
247 if (req->running == yes)
249 struct requestlist *runp = runlist;
251 last = NULL;
252 while (runp != NULL)
254 if (runp == req)
256 if (last == NULL)
257 runlist = runp->next_run;
258 else
259 last->next_run = runp->next_run;
260 break;
262 last = runp;
263 runp = runp->next_run;
270 /* The thread handler. */
271 static void *handle_fildes_io (void *arg);
274 /* User optimization. */
275 void
276 __aio_init (const struct aioinit *init)
278 /* Get the mutex. */
279 pthread_mutex_lock (&__aio_requests_mutex);
281 /* Only allow writing new values if the table is not yet allocated. */
282 if (pool == NULL)
284 optim.aio_threads = init->aio_threads < 1 ? 1 : init->aio_threads;
285 optim.aio_num = (init->aio_num < ENTRIES_PER_ROW
286 ? ENTRIES_PER_ROW
287 : init->aio_num & ~ENTRIES_PER_ROW);
290 if (init->aio_idle_time != 0)
291 optim.aio_idle_time = init->aio_idle_time;
293 /* Release the mutex. */
294 pthread_mutex_unlock (&__aio_requests_mutex);
296 weak_alias (__aio_init, aio_init)
299 /* The main function of the async I/O handling. It enqueues requests
300 and if necessary starts and handles threads. */
301 struct requestlist *
302 internal_function
303 __aio_enqueue_request (aiocb_union *aiocbp, int operation)
305 int result = 0;
306 int policy, prio;
307 struct sched_param param;
308 struct requestlist *last, *runp, *newp;
309 int running = no;
311 if (operation == LIO_SYNC || operation == LIO_DSYNC)
312 aiocbp->aiocb.aio_reqprio = 0;
313 else if (aiocbp->aiocb.aio_reqprio < 0
314 || aiocbp->aiocb.aio_reqprio > AIO_PRIO_DELTA_MAX)
316 /* Invalid priority value. */
317 __set_errno (EINVAL);
318 aiocbp->aiocb.__error_code = EINVAL;
319 aiocbp->aiocb.__return_value = -1;
320 return NULL;
323 /* Compute priority for this request. */
324 pthread_getschedparam (pthread_self (), &policy, &param);
325 prio = param.sched_priority - aiocbp->aiocb.aio_reqprio;
327 /* Get the mutex. */
328 pthread_mutex_lock (&__aio_requests_mutex);
330 last = NULL;
331 runp = requests;
332 /* First look whether the current file descriptor is currently
333 worked with. */
334 while (runp != NULL
335 && runp->aiocbp->aiocb.aio_fildes < aiocbp->aiocb.aio_fildes)
337 last = runp;
338 runp = runp->next_fd;
341 /* Get a new element for the waiting list. */
342 newp = get_elem ();
343 if (newp == NULL)
345 pthread_mutex_unlock (&__aio_requests_mutex);
346 __set_errno (EAGAIN);
347 return NULL;
349 newp->aiocbp = aiocbp;
350 #ifdef BROKEN_THREAD_SIGNALS
351 newp->caller_pid = (aiocbp->aiocb.aio_sigevent.sigev_notify == SIGEV_SIGNAL
352 ? getpid () : 0);
353 #endif
354 newp->waiting = NULL;
356 aiocbp->aiocb.__abs_prio = prio;
357 aiocbp->aiocb.__policy = policy;
358 aiocbp->aiocb.aio_lio_opcode = operation;
359 aiocbp->aiocb.__error_code = EINPROGRESS;
360 aiocbp->aiocb.__return_value = 0;
362 if (runp != NULL
363 && runp->aiocbp->aiocb.aio_fildes == aiocbp->aiocb.aio_fildes)
365 /* The current file descriptor is worked on. It makes no sense
366 to start another thread since this new thread would fight
367 with the running thread for the resources. But we also cannot
368 say that the thread processing this desriptor shall immediately
369 after finishing the current job process this request if there
370 are other threads in the running queue which have a higher
371 priority. */
373 /* Simply enqueue it after the running one according to the
374 priority. */
375 while (runp->next_prio != NULL
376 && runp->next_prio->aiocbp->aiocb.__abs_prio >= prio)
377 runp = runp->next_prio;
379 newp->next_prio = runp->next_prio;
380 runp->next_prio = newp;
382 running = queued;
384 else
386 running = yes;
387 /* Enqueue this request for a new descriptor. */
388 if (last == NULL)
390 newp->last_fd = NULL;
391 newp->next_fd = requests;
392 if (requests != NULL)
393 requests->last_fd = newp;
394 requests = newp;
396 else
398 newp->next_fd = last->next_fd;
399 newp->last_fd = last;
400 last->next_fd = newp;
401 if (newp->next_fd != NULL)
402 newp->next_fd->last_fd = newp;
405 newp->next_prio = NULL;
408 if (running == yes)
410 /* We try to create a new thread for this file descriptor. The
411 function which gets called will handle all available requests
412 for this descriptor and when all are processed it will
413 terminate.
415 If no new thread can be created or if the specified limit of
416 threads for AIO is reached we queue the request. */
418 /* See if we need to and are able to create a thread. */
419 if (nthreads < optim.aio_threads && idle_thread_count == 0)
421 pthread_t thid;
423 running = newp->running = allocated;
425 /* Now try to start a thread. */
426 if (aio_create_helper_thread (&thid, handle_fildes_io, newp) == 0)
427 /* We managed to enqueue the request. All errors which can
428 happen now can be recognized by calls to `aio_return' and
429 `aio_error'. */
430 ++nthreads;
431 else
433 /* Reset the running flag. The new request is not running. */
434 running = newp->running = yes;
436 if (nthreads == 0)
437 /* We cannot create a thread in the moment and there is
438 also no thread running. This is a problem. `errno' is
439 set to EAGAIN if this is only a temporary problem. */
440 result = -1;
445 /* Enqueue the request in the run queue if it is not yet running. */
446 if (running == yes && result == 0)
448 add_request_to_runlist (newp);
450 /* If there is a thread waiting for work, then let it know that we
451 have just given it something to do. */
452 if (idle_thread_count > 0)
453 pthread_cond_signal (&__aio_new_request_notification);
456 if (result == 0)
457 newp->running = running;
458 else
460 /* Something went wrong. */
461 __aio_free_request (newp);
462 newp = NULL;
465 /* Release the mutex. */
466 pthread_mutex_unlock (&__aio_requests_mutex);
468 return newp;
472 static void *
473 handle_fildes_io (void *arg)
475 pthread_t self = pthread_self ();
476 struct sched_param param;
477 struct requestlist *runp = (struct requestlist *) arg;
478 aiocb_union *aiocbp;
479 int policy;
480 int fildes;
482 pthread_getschedparam (self, &policy, &param);
486 /* If runp is NULL, then we were created to service the work queue
487 in general, not to handle any particular request. In that case we
488 skip the "do work" stuff on the first pass, and go directly to the
489 "get work off the work queue" part of this loop, which is near the
490 end. */
491 if (runp == NULL)
492 pthread_mutex_lock (&__aio_requests_mutex);
493 else
495 /* Hopefully this request is marked as running. */
496 assert (runp->running == allocated);
498 /* Update our variables. */
499 aiocbp = runp->aiocbp;
500 fildes = aiocbp->aiocb.aio_fildes;
502 /* Change the priority to the requested value (if necessary). */
503 if (aiocbp->aiocb.__abs_prio != param.sched_priority
504 || aiocbp->aiocb.__policy != policy)
506 param.sched_priority = aiocbp->aiocb.__abs_prio;
507 policy = aiocbp->aiocb.__policy;
508 pthread_setschedparam (self, policy, &param);
511 /* Process request pointed to by RUNP. We must not be disturbed
512 by signals. */
513 if ((aiocbp->aiocb.aio_lio_opcode & 127) == LIO_READ)
515 if (aiocbp->aiocb.aio_lio_opcode & 128)
516 aiocbp->aiocb.__return_value =
517 TEMP_FAILURE_RETRY (__pread64 (fildes, (void *)
518 aiocbp->aiocb64.aio_buf,
519 aiocbp->aiocb64.aio_nbytes,
520 aiocbp->aiocb64.aio_offset));
521 else
522 aiocbp->aiocb.__return_value =
523 TEMP_FAILURE_RETRY (pread (fildes,
524 (void *) aiocbp->aiocb.aio_buf,
525 aiocbp->aiocb.aio_nbytes,
526 aiocbp->aiocb.aio_offset));
528 if (aiocbp->aiocb.__return_value == -1 && errno == ESPIPE)
529 /* The Linux kernel is different from others. It returns
530 ESPIPE if using pread on a socket. Other platforms
531 simply ignore the offset parameter and behave like
532 read. */
533 aiocbp->aiocb.__return_value =
534 TEMP_FAILURE_RETRY (read (fildes,
535 (void *) aiocbp->aiocb64.aio_buf,
536 aiocbp->aiocb64.aio_nbytes));
538 else if ((aiocbp->aiocb.aio_lio_opcode & 127) == LIO_WRITE)
540 if (aiocbp->aiocb.aio_lio_opcode & 128)
541 aiocbp->aiocb.__return_value =
542 TEMP_FAILURE_RETRY (__pwrite64 (fildes, (const void *)
543 aiocbp->aiocb64.aio_buf,
544 aiocbp->aiocb64.aio_nbytes,
545 aiocbp->aiocb64.aio_offset));
546 else
547 aiocbp->aiocb.__return_value =
548 TEMP_FAILURE_RETRY (__libc_pwrite (fildes, (const void *)
549 aiocbp->aiocb.aio_buf,
550 aiocbp->aiocb.aio_nbytes,
551 aiocbp->aiocb.aio_offset));
553 if (aiocbp->aiocb.__return_value == -1 && errno == ESPIPE)
554 /* The Linux kernel is different from others. It returns
555 ESPIPE if using pwrite on a socket. Other platforms
556 simply ignore the offset parameter and behave like
557 write. */
558 aiocbp->aiocb.__return_value =
559 TEMP_FAILURE_RETRY (write (fildes,
560 (void *) aiocbp->aiocb64.aio_buf,
561 aiocbp->aiocb64.aio_nbytes));
563 else if (aiocbp->aiocb.aio_lio_opcode == LIO_DSYNC)
564 aiocbp->aiocb.__return_value =
565 TEMP_FAILURE_RETRY (fdatasync (fildes));
566 else if (aiocbp->aiocb.aio_lio_opcode == LIO_SYNC)
567 aiocbp->aiocb.__return_value =
568 TEMP_FAILURE_RETRY (fsync (fildes));
569 else
571 /* This is an invalid opcode. */
572 aiocbp->aiocb.__return_value = -1;
573 __set_errno (EINVAL);
576 /* Get the mutex. */
577 pthread_mutex_lock (&__aio_requests_mutex);
579 /* In theory we would need here a write memory barrier since the
580 callers test using aio_error() whether the request finished
581 and once this value != EINPROGRESS the field __return_value
582 must be committed to memory.
584 But since the pthread_mutex_lock call involves write memory
585 barriers as well it is not necessary. */
587 if (aiocbp->aiocb.__return_value == -1)
588 aiocbp->aiocb.__error_code = errno;
589 else
590 aiocbp->aiocb.__error_code = 0;
592 /* Send the signal to notify about finished processing of the
593 request. */
594 __aio_notify (runp);
596 /* For debugging purposes we reset the running flag of the
597 finished request. */
598 assert (runp->running == allocated);
599 runp->running = done;
601 /* Now dequeue the current request. */
602 __aio_remove_request (NULL, runp, 0);
603 if (runp->next_prio != NULL)
604 add_request_to_runlist (runp->next_prio);
606 /* Free the old element. */
607 __aio_free_request (runp);
610 runp = runlist;
612 /* If the runlist is empty, then we sleep for a while, waiting for
613 something to arrive in it. */
614 if (runp == NULL && optim.aio_idle_time >= 0)
616 struct timeval now;
617 struct timespec wakeup_time;
619 ++idle_thread_count;
620 gettimeofday (&now, NULL);
621 wakeup_time.tv_sec = now.tv_sec + optim.aio_idle_time;
622 wakeup_time.tv_nsec = now.tv_usec * 1000;
623 if (wakeup_time.tv_nsec > 1000000000)
625 wakeup_time.tv_nsec -= 1000000000;
626 ++wakeup_time.tv_sec;
628 pthread_cond_timedwait (&__aio_new_request_notification,
629 &__aio_requests_mutex,
630 &wakeup_time);
631 --idle_thread_count;
632 runp = runlist;
635 if (runp == NULL)
636 --nthreads;
637 else
639 assert (runp->running == yes);
640 runp->running = allocated;
641 runlist = runp->next_run;
643 /* If we have a request to process, and there's still another in
644 the run list, then we need to either wake up or create a new
645 thread to service the request that is still in the run list. */
646 if (runlist != NULL)
648 /* There are at least two items in the work queue to work on.
649 If there are other idle threads, then we should wake them
650 up for these other work elements; otherwise, we should try
651 to create a new thread. */
652 if (idle_thread_count > 0)
653 pthread_cond_signal (&__aio_new_request_notification);
654 else if (nthreads < optim.aio_threads)
656 pthread_t thid;
657 pthread_attr_t attr;
659 /* Make sure the thread is created detached. */
660 pthread_attr_init (&attr);
661 pthread_attr_setdetachstate (&attr, PTHREAD_CREATE_DETACHED);
663 /* Now try to start a thread. If we fail, no big deal,
664 because we know that there is at least one thread (us)
665 that is working on AIO operations. */
666 if (pthread_create (&thid, &attr, handle_fildes_io, NULL)
667 == 0)
668 ++nthreads;
673 /* Release the mutex. */
674 pthread_mutex_unlock (&__aio_requests_mutex);
676 while (runp != NULL);
678 return NULL;
682 /* Free allocated resources. */
683 libc_freeres_fn (free_res)
685 size_t row;
687 for (row = 0; row < pool_max_size; ++row)
688 free (pool[row]);
690 free (pool);
694 /* Add newrequest to the runlist. The __abs_prio flag of newrequest must
695 be correctly set to do this. Also, you had better set newrequest's
696 "running" flag to "yes" before you release your lock or you'll throw an
697 assertion. */
698 static void
699 add_request_to_runlist (struct requestlist *newrequest)
701 int prio = newrequest->aiocbp->aiocb.__abs_prio;
702 struct requestlist *runp;
704 if (runlist == NULL || runlist->aiocbp->aiocb.__abs_prio < prio)
706 newrequest->next_run = runlist;
707 runlist = newrequest;
709 else
711 runp = runlist;
713 while (runp->next_run != NULL
714 && runp->next_run->aiocbp->aiocb.__abs_prio >= prio)
715 runp = runp->next_run;
717 newrequest->next_run = runp->next_run;
718 runp->next_run = newrequest;