Back to index

glibc  2.9
sockperf.c
Go to the documentation of this file.
00001 #define _GNU_SOURCE
00002 #include <argp.h>
00003 #include <complex.h>
00004 #include <errno.h>
00005 #include <error.h>
00006 #include <fcntl.h>
00007 #include <gd.h>
00008 #include <inttypes.h>
00009 #include <pthread.h>
00010 #include <signal.h>
00011 #include <stdbool.h>
00012 #include <stddef.h>
00013 #include <stdio.h>
00014 #include <stdlib.h>
00015 #include <string.h>
00016 #include <time.h>
00017 #include <unistd.h>
00018 #include <sys/param.h>
00019 #include <sys/poll.h>
00020 #include <sys/socket.h>
00021 #include <sys/un.h>
00022 
00023 
00024 #define size_x 320
00025 #define size_y 240
00026 
00027 
00028 #define PATH "/tmp/s.sockperf"
00029 
00030 
00031 struct thread_param
00032 {
00033   unsigned int from;
00034   unsigned int to;
00035   unsigned int nserv;
00036 };
00037 
00038 struct coord
00039 {
00040   unsigned int x;
00041   unsigned int y;
00042   complex double z;
00043 };
00044 
00045 
00046 /* We use 64bit values for the times.  */
00047 typedef unsigned long long int hp_timing_t;
00048 
00049 
00050 static unsigned int nclients = 2;
00051 static unsigned int nservers = 2;
00052 
00053 static bool timing;
00054 static int points;
00055 
00056 
00057 static complex double top_left = -0.7 + 0.2i;
00058 static complex double bottom_right = -0.5 - 0.0i;
00059 
00060 
00061 static int colors[256];
00062 static gdImagePtr image;
00063 static pthread_mutex_t image_lock;
00064 
00065 static int sock;
00066 
00067 
00068 static void *
00069 client (void *arg)
00070 {
00071   struct thread_param *param = arg;
00072   unsigned int cnt;
00073   unsigned int nserv = param->nserv;
00074   int clisock[nserv];
00075   struct pollfd servpoll[nserv];
00076   struct sockaddr_un servaddr;
00077   socklen_t servlen;
00078   struct coord c;
00079 
00080   bool new_coord (void)
00081     {
00082       if (cnt >= param->to)
00083        return false;
00084 
00085       unsigned int row = cnt / size_x;
00086       unsigned int col = cnt % size_x;
00087 
00088       c.x = col;
00089       c.y = row;
00090       c.z = (top_left
00091             + ((col
00092                * (creal (bottom_right) - creal (top_left))) / size_x)
00093             + (_Complex_I * (row * (cimag (bottom_right) - cimag (top_left)))
00094               / size_y));
00095 
00096       ++cnt;
00097 
00098       return true;
00099     }
00100 
00101 
00102   for (cnt = 0; cnt < nserv; ++cnt)
00103     {
00104       servpoll[cnt].fd = socket (AF_UNIX, SOCK_STREAM, 0);
00105       if (clisock < 0)
00106        {
00107          puts ("cannot create socket in client");
00108          return NULL;
00109        }
00110 
00111       memset (&servaddr, '\0', sizeof (servaddr));
00112       servaddr.sun_family = AF_UNIX;
00113       strncpy (servaddr.sun_path, PATH, sizeof (servaddr.sun_path));
00114       servlen = offsetof (struct sockaddr_un, sun_path) + strlen (PATH) + 1;
00115 
00116 
00117       int err;
00118       while (1)
00119        {
00120          err = TEMP_FAILURE_RETRY (connect (servpoll[cnt].fd, &servaddr,
00121                                         servlen));
00122          if (err != -1 || errno != ECONNREFUSED)
00123            break;
00124 
00125          pthread_yield ();
00126        }
00127 
00128       if (err == -1)
00129        {
00130          printf ("cannot connect: %m (%d)\n", errno);
00131          exit (1);
00132        }
00133 
00134       servpoll[cnt].events = POLLOUT;
00135       servpoll[cnt].revents = 0;
00136     }
00137 
00138   cnt = param->from;
00139 
00140   new_coord ();
00141   bool z_valid = true;
00142 
00143   while (1)
00144     {
00145       int i;
00146       int n = poll (servpoll, nserv, -1);
00147       if (n == -1)
00148        {
00149          puts ("poll returned error");
00150          break;
00151        }
00152 
00153       bool cont = false;
00154       for (i = 0; i < nserv && n > 0; ++i)
00155        if (servpoll[i].revents != 0)
00156          {
00157            if (servpoll[i].revents == POLLIN)
00158              {
00159               unsigned int vals[3];
00160               if (TEMP_FAILURE_RETRY (read (servpoll[i].fd, &vals,
00161                                          sizeof (vals)))
00162                   != sizeof (vals))
00163                 {
00164                   puts ("read error in client");
00165                   return NULL;
00166                 }
00167 
00168               pthread_mutex_lock (&image_lock);
00169 
00170               gdImageSetPixel (image, vals[0], vals[1], vals[2]);
00171               ++points;
00172 
00173               pthread_mutex_unlock (&image_lock);
00174 
00175               servpoll[i].events = POLLOUT;
00176              }
00177            else
00178              {
00179               if (servpoll[i].revents != POLLOUT)
00180                 printf ("revents: %hd != POLLOUT ???\n",
00181                        servpoll[i].revents);
00182 
00183               if (z_valid)
00184                 {
00185                   if (TEMP_FAILURE_RETRY (write (servpoll[i].fd, &c,
00186                                              sizeof (c))) != sizeof (c))
00187                     {
00188                      puts ("write error in client");
00189                      return NULL;
00190                     }
00191                   cont = true;
00192                   servpoll[i].events = POLLIN;
00193 
00194                   z_valid = new_coord ();
00195                   if (! z_valid)
00196                     /* No more to do.  Clear the event fields.  */
00197                     for (i = 0; i < nserv; ++i)
00198                      if (servpoll[i].events == POLLOUT)
00199                        servpoll[i].events = servpoll[i].revents = 0;
00200                 }
00201               else
00202                 servpoll[i].events = servpoll[i].revents = 0;
00203              }
00204 
00205            --n;
00206          }
00207        else if (servpoll[i].events != 0)
00208          cont = true;
00209 
00210       if (! cont && ! z_valid)
00211        break;
00212     }
00213 
00214   c.x = 0xffffffff;
00215   c.y = 0xffffffff;
00216   for (cnt = 0; cnt < nserv; ++cnt)
00217     {
00218       TEMP_FAILURE_RETRY (write (servpoll[cnt].fd, &c, sizeof (c)));
00219       close (servpoll[cnt].fd);
00220     }
00221 
00222   return NULL;
00223 }
00224 
00225 
00226 static void *
00227 server (void *arg)
00228 {
00229   struct sockaddr_un cliaddr;
00230   socklen_t clilen;
00231   int clisock = TEMP_FAILURE_RETRY (accept (sock, &cliaddr, &clilen));
00232 
00233   if (clisock == -1)
00234     {
00235       puts ("accept failed");
00236       return NULL;
00237     }
00238 
00239   while (1)
00240     {
00241       struct coord c;
00242 
00243       if (TEMP_FAILURE_RETRY (read (clisock, &c, sizeof (c))) != sizeof (c))
00244        {
00245          printf ("server read failed: %m (%d)\n", errno);
00246          break;
00247        }
00248 
00249       if (c.x == 0xffffffff && c.y == 0xffffffff)
00250        break;
00251 
00252       unsigned int rnds = 0;
00253       complex double z = c.z;
00254       while (cabs (z) < 4.0)
00255        {
00256          z = z * z - 1;
00257          if (++rnds == 255)
00258            break;
00259        }
00260 
00261       unsigned int vals[3] = { c.x, c.y, rnds };
00262       if (TEMP_FAILURE_RETRY (write (clisock, vals, sizeof (vals)))
00263          != sizeof (vals))
00264        {
00265          puts ("server write error");
00266          return NULL;
00267        }
00268     }
00269 
00270   close (clisock);
00271 
00272   return NULL;
00273 }
00274 
00275 
00276 static const char *outfilename = "test.png";
00277 
00278 
00279 static const struct argp_option options[] =
00280   {
00281     { "clients", 'c', "NUMBER", 0, "Number of client threads" },
00282     { "servers", 's', "NUMBER", 0, "Number of server threads per client" },
00283     { "timing", 'T', NULL, 0,
00284       "Measure time from startup to the last thread finishing" },
00285     { NULL, 0, NULL, 0, NULL }
00286   };
00287 
00288 /* Prototype for option handler.  */
00289 static error_t parse_opt (int key, char *arg, struct argp_state *state);
00290 
00291 /* Data structure to communicate with argp functions.  */
00292 static struct argp argp =
00293 {
00294   options, parse_opt
00295 };
00296 
00297 
00298 int
00299 main (int argc, char *argv[])
00300 {
00301   int cnt;
00302   FILE *outfile;
00303   struct sockaddr_un servaddr;
00304   socklen_t servlen;
00305   int remaining;
00306 
00307   /* Parse and process arguments.  */
00308   argp_parse (&argp, argc, argv, 0, &remaining, NULL);
00309 
00310 
00311   pthread_t servth[nservers * nclients];
00312   pthread_t clntth[nclients];
00313   struct thread_param clntparam[nclients];
00314 
00315 
00316   image = gdImageCreate (size_x, size_y);
00317   if (image == NULL)
00318     {
00319       puts ("gdImageCreate failed");
00320       return 1;
00321     }
00322 
00323   for (cnt = 0; cnt < 255; ++cnt)
00324     colors[cnt] = gdImageColorAllocate (image, 256 - cnt, 256 - cnt,
00325                                    256 - cnt);
00326   /* Black.  */
00327   colors[cnt] = gdImageColorAllocate (image, 0, 0, 0);
00328 
00329 
00330   sock = socket (AF_UNIX, SOCK_STREAM, 0);
00331   if (sock < 0)
00332     error (EXIT_FAILURE, errno, "cannot create socket");
00333 
00334   memset (&servaddr, '\0', sizeof (servaddr));
00335   servaddr.sun_family = AF_UNIX;
00336   strncpy (servaddr.sun_path, PATH, sizeof (servaddr.sun_path));
00337   servlen = offsetof (struct sockaddr_un, sun_path) + strlen (PATH) + 1;
00338 
00339   if (bind (sock, &servaddr, servlen) == -1)
00340     error (EXIT_FAILURE, errno, "bind failed");
00341 
00342   listen (sock, SOMAXCONN);
00343 
00344   pthread_mutex_init (&image_lock, NULL);
00345 
00346 
00347   struct sigaction sa;
00348   sa.sa_handler = SIG_IGN;
00349   sigemptyset (&sa.sa_mask);
00350   sa.sa_flags = 0;
00351 
00352   clockid_t cl;
00353   struct timespec start_time;
00354   if (timing)
00355     {
00356       if (clock_getcpuclockid (0, &cl) != 0
00357          || clock_gettime (cl, &start_time) != 0)
00358        timing = false;
00359     }
00360 
00361   /* Start the servers.  */
00362   for (cnt = 0; cnt < nservers * nclients; ++cnt)
00363     {
00364       if (pthread_create (&servth[cnt], NULL, server, NULL) != 0)
00365        {
00366          puts ("pthread_create for server failed");
00367          exit (1);
00368        }
00369     }
00370 
00371   for (cnt = 0; cnt < nclients; ++cnt)
00372     {
00373       clntparam[cnt].from = cnt * (size_x * size_y) / nclients;
00374       clntparam[cnt].to = MIN ((cnt + 1) * (size_x * size_y) / nclients,
00375                             size_x * size_y);
00376       clntparam[cnt].nserv = nservers;
00377 
00378       if (pthread_create (&clntth[cnt], NULL, client, &clntparam[cnt]) != 0)
00379        {
00380          puts ("pthread_create for client failed");
00381          exit (1);
00382        }
00383     }
00384 
00385 
00386   /* Wait for the clients.  */
00387   for (cnt = 0; cnt < nclients; ++cnt)
00388     if (pthread_join (clntth[cnt], NULL) != 0)
00389       {
00390        puts ("client pthread_join failed");
00391        exit (1);
00392       }
00393 
00394   /* Wait for the servers.  */
00395   for (cnt = 0; cnt < nclients * nservers; ++cnt)
00396     if (pthread_join (servth[cnt], NULL) != 0)
00397       {
00398        puts ("server pthread_join failed");
00399        exit (1);
00400       }
00401 
00402 
00403   if (timing)
00404     {
00405       struct timespec end_time;
00406 
00407       if (clock_gettime (cl, &end_time) == 0)
00408        {
00409          end_time.tv_sec -= start_time.tv_sec;
00410          end_time.tv_nsec -= start_time.tv_nsec;
00411          if (end_time.tv_nsec < 0)
00412            {
00413              end_time.tv_nsec += 1000000000;
00414              --end_time.tv_sec;
00415            }
00416 
00417          printf ("\nRuntime: %lu.%09lu seconds\n%d points computed\n",
00418                 (unsigned long int) end_time.tv_sec,
00419                 (unsigned long int) end_time.tv_nsec,
00420                 points);
00421        }
00422     }
00423 
00424 
00425   outfile = fopen (outfilename, "w");
00426   if (outfile == NULL)
00427     error (EXIT_FAILURE, errno, "cannot open output file '%s'", outfilename);
00428 
00429   gdImagePng (image, outfile);
00430 
00431   fclose (outfile);
00432 
00433   unlink (PATH);
00434 
00435   return 0;
00436 }
00437 
00438 
00439 /* Handle program arguments.  */
00440 static error_t
00441 parse_opt (int key, char *arg, struct argp_state *state)
00442 {
00443   switch (key)
00444     {
00445     case 'c':
00446       nclients = strtoul (arg, NULL, 0);
00447       break;
00448 
00449     case 's':
00450       nservers = strtoul (arg, NULL, 0);
00451       break;
00452 
00453     case 'T':
00454       timing = true;
00455       break;
00456 
00457     default:
00458       return ARGP_ERR_UNKNOWN;
00459     }
00460 
00461   return 0;
00462 }
00463 
00464 
00465 static hp_timing_t
00466 get_clockfreq (void)
00467 {
00468   /* We read the information from the /proc filesystem.  It contains at
00469      least one line like
00470        cpu MHz         : 497.840237
00471      or also
00472        cpu MHz         : 497.841
00473      We search for this line and convert the number in an integer.  */
00474   static hp_timing_t result;
00475   int fd;
00476 
00477   /* If this function was called before, we know the result.  */
00478   if (result != 0)
00479     return result;
00480 
00481   fd = open ("/proc/cpuinfo", O_RDONLY);
00482   if (__builtin_expect (fd != -1, 1))
00483     {
00484       /* XXX AFAIK the /proc filesystem can generate "files" only up
00485          to a size of 4096 bytes.  */
00486       char buf[4096];
00487       ssize_t n;
00488 
00489       n = read (fd, buf, sizeof buf);
00490       if (__builtin_expect (n, 1) > 0)
00491        {
00492          char *mhz = memmem (buf, n, "cpu MHz", 7);
00493 
00494          if (__builtin_expect (mhz != NULL, 1))
00495            {
00496              char *endp = buf + n;
00497              int seen_decpoint = 0;
00498              int ndigits = 0;
00499 
00500              /* Search for the beginning of the string.  */
00501              while (mhz < endp && (*mhz < '0' || *mhz > '9') && *mhz != '\n')
00502               ++mhz;
00503 
00504              while (mhz < endp && *mhz != '\n')
00505               {
00506                 if (*mhz >= '0' && *mhz <= '9')
00507                   {
00508                     result *= 10;
00509                     result += *mhz - '0';
00510                     if (seen_decpoint)
00511                      ++ndigits;
00512                   }
00513                 else if (*mhz == '.')
00514                   seen_decpoint = 1;
00515 
00516                 ++mhz;
00517               }
00518 
00519              /* Compensate for missing digits at the end.  */
00520              while (ndigits++ < 6)
00521               result *= 10;
00522            }
00523        }
00524 
00525       close (fd);
00526     }
00527 
00528   return result;
00529 }
00530 
00531 
00532 int
00533 clock_getcpuclockid (pid_t pid, clockid_t *clock_id)
00534 {
00535   /* We don't allow any process ID but our own.  */
00536   if (pid != 0 && pid != getpid ())
00537     return EPERM;
00538 
00539 #ifdef CLOCK_PROCESS_CPUTIME_ID
00540   /* Store the number.  */
00541   *clock_id = CLOCK_PROCESS_CPUTIME_ID;
00542 
00543   return 0;
00544 #else
00545   /* We don't have a timer for that.  */
00546   return ENOENT;
00547 #endif
00548 }
00549 
00550 
00551 #define HP_TIMING_NOW(Var)  __asm__ __volatile__ ("rdtsc" : "=A" (Var))
00552 
00553 /* Get current value of CLOCK and store it in TP.  */
00554 int
00555 clock_gettime (clockid_t clock_id, struct timespec *tp)
00556 {
00557   int retval = -1;
00558 
00559   switch (clock_id)
00560     {
00561     case CLOCK_PROCESS_CPUTIME_ID:
00562       {
00563 
00564        static hp_timing_t freq;
00565        hp_timing_t tsc;
00566 
00567        /* Get the current counter.  */
00568        HP_TIMING_NOW (tsc);
00569 
00570        if (freq == 0)
00571          {
00572            freq = get_clockfreq ();
00573            if (freq == 0)
00574              return EINVAL;
00575          }
00576 
00577        /* Compute the seconds.  */
00578        tp->tv_sec = tsc / freq;
00579 
00580        /* And the nanoseconds.  This computation should be stable until
00581           we get machines with about 16GHz frequency.  */
00582        tp->tv_nsec = ((tsc % freq) * UINT64_C (1000000000)) / freq;
00583 
00584        retval = 0;
00585       }
00586     break;
00587 
00588     default:
00589       errno = EINVAL;
00590       break;
00591     }
00592 
00593   return retval;
00594 }