Merge branch release-4-6 into master
[alexxy/gromacs.git] / src / gromacs / mdlib / pme.c
1 /* -*- mode: c; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4; c-file-style: "stroustrup"; -*-
2  *
3  *
4  *                This source code is part of
5  *
6  *                 G   R   O   M   A   C   S
7  *
8  *          GROningen MAchine for Chemical Simulations
9  *
10  *                        VERSION 3.2.0
11  * Written by David van der Spoel, Erik Lindahl, Berk Hess, and others.
12  * Copyright (c) 1991-2000, University of Groningen, The Netherlands.
13  * Copyright (c) 2001-2004, The GROMACS development team,
14  * check out http://www.gromacs.org for more information.
15
16  * This program is free software; you can redistribute it and/or
17  * modify it under the terms of the GNU General Public License
18  * as published by the Free Software Foundation; either version 2
19  * of the License, or (at your option) any later version.
20  *
21  * If you want to redistribute modifications, please consider that
22  * scientific software is very special. Version control is crucial -
23  * bugs must be traceable. We will be happy to consider code for
24  * inclusion in the official distribution, but derived work must not
25  * be called official GROMACS. Details are found in the README & COPYING
26  * files - if they are missing, get the official version at www.gromacs.org.
27  *
28  * To help us fund GROMACS development, we humbly ask that you cite
29  * the papers on the package - you can find them in the top README file.
30  *
31  * For more info, check our website at http://www.gromacs.org
32  *
33  * And Hey:
34  * GROwing Monsters And Cloning Shrimps
35  */
36 /* IMPORTANT FOR DEVELOPERS:
37  *
38  * Triclinic pme stuff isn't entirely trivial, and we've experienced
39  * some bugs during development (many of them due to me). To avoid
40  * this in the future, please check the following things if you make
41  * changes in this file:
42  *
43  * 1. You should obtain identical (at least to the PME precision)
44  *    energies, forces, and virial for
45  *    a rectangular box and a triclinic one where the z (or y) axis is
46  *    tilted a whole box side. For instance you could use these boxes:
47  *
48  *    rectangular       triclinic
49  *     2  0  0           2  0  0
50  *     0  2  0           0  2  0
51  *     0  0  6           2  2  6
52  *
53  * 2. You should check the energy conservation in a triclinic box.
54  *
55  * It might seem an overkill, but better safe than sorry.
56  * /Erik 001109
57  */
58
59 #ifdef HAVE_CONFIG_H
60 #include <config.h>
61 #endif
62
63 #include "gromacs/fft/parallel_3dfft.h"
64 #include "gromacs/utility/gmxmpi.h"
65
66 #include <stdio.h>
67 #include <string.h>
68 #include <math.h>
69 #include <assert.h>
70 #include "typedefs.h"
71 #include "txtdump.h"
72 #include "vec.h"
73 #include "gmxcomplex.h"
74 #include "smalloc.h"
75 #include "futil.h"
76 #include "coulomb.h"
77 #include "gmx_fatal.h"
78 #include "pme.h"
79 #include "network.h"
80 #include "physics.h"
81 #include "nrnb.h"
82 #include "gmx_wallcycle.h"
83 #include "pdbio.h"
84 #include "gmx_cyclecounter.h"
85 #include "gmx_omp.h"
86 #include "macros.h"
87
88
89 /* Include the SIMD macro file and then check for support */
90 #include "gmx_simd_macros.h"
91 #if defined GMX_HAVE_SIMD_MACROS && defined GMX_SIMD_HAVE_EXP
92 /* Turn on arbitrary width SIMD intrinsics for PME solve */
93 #define PME_SIMD
94 #endif
95
96 /* Include the 4-wide SIMD macro file */
97 #include "gmx_simd4_macros.h"
98 /* Check if we have 4-wide SIMD macro support */
99 #ifdef GMX_HAVE_SIMD4_MACROS
100 /* Do PME spread and gather with 4-wide SIMD.
101  * NOTE: SIMD is only used with PME order 4 and 5 (which are the most common).
102  */
103 #define PME_SIMD4_SPREAD_GATHER
104
105 #ifdef GMX_SIMD4_HAVE_UNALIGNED
106 /* With PME-order=4 on x86, unaligned load+store is slightly faster
107  * than doubling all SIMD operations when using aligned load+store.
108  */
109 #define PME_SIMD4_UNALIGNED
110 #endif
111 #endif
112
113 #define DFT_TOL 1e-7
114 /* #define PRT_FORCE */
115 /* conditions for on the fly time-measurement */
116 /* #define TAKETIME (step > 1 && timesteps < 10) */
117 #define TAKETIME FALSE
118
119 /* #define PME_TIME_THREADS */
120
121 #ifdef GMX_DOUBLE
122 #define mpi_type MPI_DOUBLE
123 #else
124 #define mpi_type MPI_FLOAT
125 #endif
126
127 #ifdef PME_SIMD4_SPREAD_GATHER
128 #define SIMD4_ALIGNMENT  (GMX_SIMD4_WIDTH*sizeof(real))
129 #else
130 /* We can use any alignment, apart from 0, so we use 4 reals */
131 #define SIMD4_ALIGNMENT  (4*sizeof(real))
132 #endif
133
134 /* GMX_CACHE_SEP should be a multiple of the SIMD and SIMD4 register size
135  * to preserve alignment.
136  */
137 #define GMX_CACHE_SEP 64
138
139 /* We only define a maximum to be able to use local arrays without allocation.
140  * An order larger than 12 should never be needed, even for test cases.
141  * If needed it can be changed here.
142  */
143 #define PME_ORDER_MAX 12
144
145 /* Internal datastructures */
146 typedef struct {
147     int send_index0;
148     int send_nindex;
149     int recv_index0;
150     int recv_nindex;
151     int recv_size;   /* Receive buffer width, used with OpenMP */
152 } pme_grid_comm_t;
153
154 typedef struct {
155 #ifdef GMX_MPI
156     MPI_Comm         mpi_comm;
157 #endif
158     int              nnodes, nodeid;
159     int             *s2g0;
160     int             *s2g1;
161     int              noverlap_nodes;
162     int             *send_id, *recv_id;
163     int              send_size; /* Send buffer width, used with OpenMP */
164     pme_grid_comm_t *comm_data;
165     real            *sendbuf;
166     real            *recvbuf;
167 } pme_overlap_t;
168
169 typedef struct {
170     int *n;      /* Cumulative counts of the number of particles per thread */
171     int  nalloc; /* Allocation size of i */
172     int *i;      /* Particle indices ordered on thread index (n) */
173 } thread_plist_t;
174
175 typedef struct {
176     int      *thread_one;
177     int       n;
178     int      *ind;
179     splinevec theta;
180     real     *ptr_theta_z;
181     splinevec dtheta;
182     real     *ptr_dtheta_z;
183 } splinedata_t;
184
185 typedef struct {
186     int      dimind;        /* The index of the dimension, 0=x, 1=y */
187     int      nslab;
188     int      nodeid;
189 #ifdef GMX_MPI
190     MPI_Comm mpi_comm;
191 #endif
192
193     int     *node_dest;     /* The nodes to send x and q to with DD */
194     int     *node_src;      /* The nodes to receive x and q from with DD */
195     int     *buf_index;     /* Index for commnode into the buffers */
196
197     int      maxshift;
198
199     int      npd;
200     int      pd_nalloc;
201     int     *pd;
202     int     *count;         /* The number of atoms to send to each node */
203     int    **count_thread;
204     int     *rcount;        /* The number of atoms to receive */
205
206     int      n;
207     int      nalloc;
208     rvec    *x;
209     real    *q;
210     rvec    *f;
211     gmx_bool bSpread;       /* These coordinates are used for spreading */
212     int      pme_order;
213     ivec    *idx;
214     rvec    *fractx;            /* Fractional coordinate relative to the
215                                  * lower cell boundary
216                                  */
217     int             nthread;
218     int            *thread_idx; /* Which thread should spread which charge */
219     thread_plist_t *thread_plist;
220     splinedata_t   *spline;
221 } pme_atomcomm_t;
222
223 #define FLBS  3
224 #define FLBSZ 4
225
226 typedef struct {
227     ivec  ci;     /* The spatial location of this grid         */
228     ivec  n;      /* The used size of *grid, including order-1 */
229     ivec  offset; /* The grid offset from the full node grid   */
230     int   order;  /* PME spreading order                       */
231     ivec  s;      /* The allocated size of *grid, s >= n       */
232     real *grid;   /* The grid local thread, size n             */
233 } pmegrid_t;
234
235 typedef struct {
236     pmegrid_t  grid;         /* The full node grid (non thread-local)            */
237     int        nthread;      /* The number of threads operating on this grid     */
238     ivec       nc;           /* The local spatial decomposition over the threads */
239     pmegrid_t *grid_th;      /* Array of grids for each thread                   */
240     real      *grid_all;     /* Allocated array for the grids in *grid_th        */
241     int      **g2t;          /* The grid to thread index                         */
242     ivec       nthread_comm; /* The number of threads to communicate with        */
243 } pmegrids_t;
244
245
246 typedef struct {
247 #ifdef PME_SIMD4_SPREAD_GATHER
248     /* Masks for 4-wide SIMD aligned spreading and gathering */
249     gmx_simd4_pb mask_S0[6], mask_S1[6];
250 #else
251     int    dummy; /* C89 requires that struct has at least one member */
252 #endif
253 } pme_spline_work_t;
254
255 typedef struct {
256     /* work data for solve_pme */
257     int      nalloc;
258     real *   mhx;
259     real *   mhy;
260     real *   mhz;
261     real *   m2;
262     real *   denom;
263     real *   tmp1_alloc;
264     real *   tmp1;
265     real *   eterm;
266     real *   m2inv;
267
268     real     energy;
269     matrix   vir;
270 } pme_work_t;
271
272 typedef struct gmx_pme {
273     int           ndecompdim; /* The number of decomposition dimensions */
274     int           nodeid;     /* Our nodeid in mpi->mpi_comm */
275     int           nodeid_major;
276     int           nodeid_minor;
277     int           nnodes;    /* The number of nodes doing PME */
278     int           nnodes_major;
279     int           nnodes_minor;
280
281     MPI_Comm      mpi_comm;
282     MPI_Comm      mpi_comm_d[2]; /* Indexed on dimension, 0=x, 1=y */
283 #ifdef GMX_MPI
284     MPI_Datatype  rvec_mpi;      /* the pme vector's MPI type */
285 #endif
286
287     gmx_bool   bUseThreads;   /* Does any of the PME ranks have nthread>1 ?  */
288     int        nthread;       /* The number of threads doing PME on our rank */
289
290     gmx_bool   bPPnode;       /* Node also does particle-particle forces */
291     gmx_bool   bFEP;          /* Compute Free energy contribution */
292     int        nkx, nky, nkz; /* Grid dimensions */
293     gmx_bool   bP3M;          /* Do P3M: optimize the influence function */
294     int        pme_order;
295     real       epsilon_r;
296
297     pmegrids_t pmegridA;  /* Grids on which we do spreading/interpolation, includes overlap */
298     pmegrids_t pmegridB;
299     /* The PME charge spreading grid sizes/strides, includes pme_order-1 */
300     int        pmegrid_nx, pmegrid_ny, pmegrid_nz;
301     /* pmegrid_nz might be larger than strictly necessary to ensure
302      * memory alignment, pmegrid_nz_base gives the real base size.
303      */
304     int     pmegrid_nz_base;
305     /* The local PME grid starting indices */
306     int     pmegrid_start_ix, pmegrid_start_iy, pmegrid_start_iz;
307
308     /* Work data for spreading and gathering */
309     pme_spline_work_t    *spline_work;
310
311     real                 *fftgridA; /* Grids for FFT. With 1D FFT decomposition this can be a pointer */
312     real                 *fftgridB; /* inside the interpolation grid, but separate for 2D PME decomp. */
313     int                   fftgrid_nx, fftgrid_ny, fftgrid_nz;
314
315     t_complex            *cfftgridA;  /* Grids for complex FFT data */
316     t_complex            *cfftgridB;
317     int                   cfftgrid_nx, cfftgrid_ny, cfftgrid_nz;
318
319     gmx_parallel_3dfft_t  pfft_setupA;
320     gmx_parallel_3dfft_t  pfft_setupB;
321
322     int                  *nnx, *nny, *nnz;
323     real                 *fshx, *fshy, *fshz;
324
325     pme_atomcomm_t        atc[2]; /* Indexed on decomposition index */
326     matrix                recipbox;
327     splinevec             bsp_mod;
328
329     pme_overlap_t         overlap[2]; /* Indexed on dimension, 0=x, 1=y */
330
331     pme_atomcomm_t        atc_energy; /* Only for gmx_pme_calc_energy */
332
333     rvec                 *bufv;       /* Communication buffer */
334     real                 *bufr;       /* Communication buffer */
335     int                   buf_nalloc; /* The communication buffer size */
336
337     /* thread local work data for solve_pme */
338     pme_work_t *work;
339
340     /* Work data for PME_redist */
341     gmx_bool redist_init;
342     int *    scounts;
343     int *    rcounts;
344     int *    sdispls;
345     int *    rdispls;
346     int *    sidx;
347     int *    idxa;
348     real *   redist_buf;
349     int      redist_buf_nalloc;
350
351     /* Work data for sum_qgrid */
352     real *   sum_qgrid_tmp;
353     real *   sum_qgrid_dd_tmp;
354 } t_gmx_pme;
355
356
357 static void calc_interpolation_idx(gmx_pme_t pme, pme_atomcomm_t *atc,
358                                    int start, int end, int thread)
359 {
360     int             i;
361     int            *idxptr, tix, tiy, tiz;
362     real           *xptr, *fptr, tx, ty, tz;
363     real            rxx, ryx, ryy, rzx, rzy, rzz;
364     int             nx, ny, nz;
365     int             start_ix, start_iy, start_iz;
366     int            *g2tx, *g2ty, *g2tz;
367     gmx_bool        bThreads;
368     int            *thread_idx = NULL;
369     thread_plist_t *tpl        = NULL;
370     int            *tpl_n      = NULL;
371     int             thread_i;
372
373     nx  = pme->nkx;
374     ny  = pme->nky;
375     nz  = pme->nkz;
376
377     start_ix = pme->pmegrid_start_ix;
378     start_iy = pme->pmegrid_start_iy;
379     start_iz = pme->pmegrid_start_iz;
380
381     rxx = pme->recipbox[XX][XX];
382     ryx = pme->recipbox[YY][XX];
383     ryy = pme->recipbox[YY][YY];
384     rzx = pme->recipbox[ZZ][XX];
385     rzy = pme->recipbox[ZZ][YY];
386     rzz = pme->recipbox[ZZ][ZZ];
387
388     g2tx = pme->pmegridA.g2t[XX];
389     g2ty = pme->pmegridA.g2t[YY];
390     g2tz = pme->pmegridA.g2t[ZZ];
391
392     bThreads = (atc->nthread > 1);
393     if (bThreads)
394     {
395         thread_idx = atc->thread_idx;
396
397         tpl   = &atc->thread_plist[thread];
398         tpl_n = tpl->n;
399         for (i = 0; i < atc->nthread; i++)
400         {
401             tpl_n[i] = 0;
402         }
403     }
404
405     for (i = start; i < end; i++)
406     {
407         xptr   = atc->x[i];
408         idxptr = atc->idx[i];
409         fptr   = atc->fractx[i];
410
411         /* Fractional coordinates along box vectors, add 2.0 to make 100% sure we are positive for triclinic boxes */
412         tx = nx * ( xptr[XX] * rxx + xptr[YY] * ryx + xptr[ZZ] * rzx + 2.0 );
413         ty = ny * (                  xptr[YY] * ryy + xptr[ZZ] * rzy + 2.0 );
414         tz = nz * (                                   xptr[ZZ] * rzz + 2.0 );
415
416         tix = (int)(tx);
417         tiy = (int)(ty);
418         tiz = (int)(tz);
419
420         /* Because decomposition only occurs in x and y,
421          * we never have a fraction correction in z.
422          */
423         fptr[XX] = tx - tix + pme->fshx[tix];
424         fptr[YY] = ty - tiy + pme->fshy[tiy];
425         fptr[ZZ] = tz - tiz;
426
427         idxptr[XX] = pme->nnx[tix];
428         idxptr[YY] = pme->nny[tiy];
429         idxptr[ZZ] = pme->nnz[tiz];
430
431 #ifdef DEBUG
432         range_check(idxptr[XX], 0, pme->pmegrid_nx);
433         range_check(idxptr[YY], 0, pme->pmegrid_ny);
434         range_check(idxptr[ZZ], 0, pme->pmegrid_nz);
435 #endif
436
437         if (bThreads)
438         {
439             thread_i      = g2tx[idxptr[XX]] + g2ty[idxptr[YY]] + g2tz[idxptr[ZZ]];
440             thread_idx[i] = thread_i;
441             tpl_n[thread_i]++;
442         }
443     }
444
445     if (bThreads)
446     {
447         /* Make a list of particle indices sorted on thread */
448
449         /* Get the cumulative count */
450         for (i = 1; i < atc->nthread; i++)
451         {
452             tpl_n[i] += tpl_n[i-1];
453         }
454         /* The current implementation distributes particles equally
455          * over the threads, so we could actually allocate for that
456          * in pme_realloc_atomcomm_things.
457          */
458         if (tpl_n[atc->nthread-1] > tpl->nalloc)
459         {
460             tpl->nalloc = over_alloc_large(tpl_n[atc->nthread-1]);
461             srenew(tpl->i, tpl->nalloc);
462         }
463         /* Set tpl_n to the cumulative start */
464         for (i = atc->nthread-1; i >= 1; i--)
465         {
466             tpl_n[i] = tpl_n[i-1];
467         }
468         tpl_n[0] = 0;
469
470         /* Fill our thread local array with indices sorted on thread */
471         for (i = start; i < end; i++)
472         {
473             tpl->i[tpl_n[atc->thread_idx[i]]++] = i;
474         }
475         /* Now tpl_n contains the cummulative count again */
476     }
477 }
478
479 static void make_thread_local_ind(pme_atomcomm_t *atc,
480                                   int thread, splinedata_t *spline)
481 {
482     int             n, t, i, start, end;
483     thread_plist_t *tpl;
484
485     /* Combine the indices made by each thread into one index */
486
487     n     = 0;
488     start = 0;
489     for (t = 0; t < atc->nthread; t++)
490     {
491         tpl = &atc->thread_plist[t];
492         /* Copy our part (start - end) from the list of thread t */
493         if (thread > 0)
494         {
495             start = tpl->n[thread-1];
496         }
497         end = tpl->n[thread];
498         for (i = start; i < end; i++)
499         {
500             spline->ind[n++] = tpl->i[i];
501         }
502     }
503
504     spline->n = n;
505 }
506
507
508 static void pme_calc_pidx(int start, int end,
509                           matrix recipbox, rvec x[],
510                           pme_atomcomm_t *atc, int *count)
511 {
512     int   nslab, i;
513     int   si;
514     real *xptr, s;
515     real  rxx, ryx, rzx, ryy, rzy;
516     int  *pd;
517
518     /* Calculate PME task index (pidx) for each grid index.
519      * Here we always assign equally sized slabs to each node
520      * for load balancing reasons (the PME grid spacing is not used).
521      */
522
523     nslab = atc->nslab;
524     pd    = atc->pd;
525
526     /* Reset the count */
527     for (i = 0; i < nslab; i++)
528     {
529         count[i] = 0;
530     }
531
532     if (atc->dimind == 0)
533     {
534         rxx = recipbox[XX][XX];
535         ryx = recipbox[YY][XX];
536         rzx = recipbox[ZZ][XX];
537         /* Calculate the node index in x-dimension */
538         for (i = start; i < end; i++)
539         {
540             xptr   = x[i];
541             /* Fractional coordinates along box vectors */
542             s     = nslab*(xptr[XX]*rxx + xptr[YY]*ryx + xptr[ZZ]*rzx);
543             si    = (int)(s + 2*nslab) % nslab;
544             pd[i] = si;
545             count[si]++;
546         }
547     }
548     else
549     {
550         ryy = recipbox[YY][YY];
551         rzy = recipbox[ZZ][YY];
552         /* Calculate the node index in y-dimension */
553         for (i = start; i < end; i++)
554         {
555             xptr   = x[i];
556             /* Fractional coordinates along box vectors */
557             s     = nslab*(xptr[YY]*ryy + xptr[ZZ]*rzy);
558             si    = (int)(s + 2*nslab) % nslab;
559             pd[i] = si;
560             count[si]++;
561         }
562     }
563 }
564
565 static void pme_calc_pidx_wrapper(int natoms, matrix recipbox, rvec x[],
566                                   pme_atomcomm_t *atc)
567 {
568     int nthread, thread, slab;
569
570     nthread = atc->nthread;
571
572 #pragma omp parallel for num_threads(nthread) schedule(static)
573     for (thread = 0; thread < nthread; thread++)
574     {
575         pme_calc_pidx(natoms* thread   /nthread,
576                       natoms*(thread+1)/nthread,
577                       recipbox, x, atc, atc->count_thread[thread]);
578     }
579     /* Non-parallel reduction, since nslab is small */
580
581     for (thread = 1; thread < nthread; thread++)
582     {
583         for (slab = 0; slab < atc->nslab; slab++)
584         {
585             atc->count_thread[0][slab] += atc->count_thread[thread][slab];
586         }
587     }
588 }
589
590 static void realloc_splinevec(splinevec th, real **ptr_z, int nalloc)
591 {
592     const int padding = 4;
593     int       i;
594
595     srenew(th[XX], nalloc);
596     srenew(th[YY], nalloc);
597     /* In z we add padding, this is only required for the aligned SIMD code */
598     sfree_aligned(*ptr_z);
599     snew_aligned(*ptr_z, nalloc+2*padding, SIMD4_ALIGNMENT);
600     th[ZZ] = *ptr_z + padding;
601
602     for (i = 0; i < padding; i++)
603     {
604         (*ptr_z)[               i] = 0;
605         (*ptr_z)[padding+nalloc+i] = 0;
606     }
607 }
608
609 static void pme_realloc_splinedata(splinedata_t *spline, pme_atomcomm_t *atc)
610 {
611     int i, d;
612
613     srenew(spline->ind, atc->nalloc);
614     /* Initialize the index to identity so it works without threads */
615     for (i = 0; i < atc->nalloc; i++)
616     {
617         spline->ind[i] = i;
618     }
619
620     realloc_splinevec(spline->theta, &spline->ptr_theta_z,
621                       atc->pme_order*atc->nalloc);
622     realloc_splinevec(spline->dtheta, &spline->ptr_dtheta_z,
623                       atc->pme_order*atc->nalloc);
624 }
625
626 static void pme_realloc_atomcomm_things(pme_atomcomm_t *atc)
627 {
628     int nalloc_old, i, j, nalloc_tpl;
629
630     /* We have to avoid a NULL pointer for atc->x to avoid
631      * possible fatal errors in MPI routines.
632      */
633     if (atc->n > atc->nalloc || atc->nalloc == 0)
634     {
635         nalloc_old  = atc->nalloc;
636         atc->nalloc = over_alloc_dd(max(atc->n, 1));
637
638         if (atc->nslab > 1)
639         {
640             srenew(atc->x, atc->nalloc);
641             srenew(atc->q, atc->nalloc);
642             srenew(atc->f, atc->nalloc);
643             for (i = nalloc_old; i < atc->nalloc; i++)
644             {
645                 clear_rvec(atc->f[i]);
646             }
647         }
648         if (atc->bSpread)
649         {
650             srenew(atc->fractx, atc->nalloc);
651             srenew(atc->idx, atc->nalloc);
652
653             if (atc->nthread > 1)
654             {
655                 srenew(atc->thread_idx, atc->nalloc);
656             }
657
658             for (i = 0; i < atc->nthread; i++)
659             {
660                 pme_realloc_splinedata(&atc->spline[i], atc);
661             }
662         }
663     }
664 }
665
666 static void pmeredist_pd(gmx_pme_t pme, gmx_bool forw,
667                          int n, gmx_bool bXF, rvec *x_f, real *charge,
668                          pme_atomcomm_t *atc)
669 /* Redistribute particle data for PME calculation */
670 /* domain decomposition by x coordinate           */
671 {
672     int *idxa;
673     int  i, ii;
674
675     if (FALSE == pme->redist_init)
676     {
677         snew(pme->scounts, atc->nslab);
678         snew(pme->rcounts, atc->nslab);
679         snew(pme->sdispls, atc->nslab);
680         snew(pme->rdispls, atc->nslab);
681         snew(pme->sidx, atc->nslab);
682         pme->redist_init = TRUE;
683     }
684     if (n > pme->redist_buf_nalloc)
685     {
686         pme->redist_buf_nalloc = over_alloc_dd(n);
687         srenew(pme->redist_buf, pme->redist_buf_nalloc*DIM);
688     }
689
690     pme->idxa = atc->pd;
691
692 #ifdef GMX_MPI
693     if (forw && bXF)
694     {
695         /* forward, redistribution from pp to pme */
696
697         /* Calculate send counts and exchange them with other nodes */
698         for (i = 0; (i < atc->nslab); i++)
699         {
700             pme->scounts[i] = 0;
701         }
702         for (i = 0; (i < n); i++)
703         {
704             pme->scounts[pme->idxa[i]]++;
705         }
706         MPI_Alltoall( pme->scounts, 1, MPI_INT, pme->rcounts, 1, MPI_INT, atc->mpi_comm);
707
708         /* Calculate send and receive displacements and index into send
709            buffer */
710         pme->sdispls[0] = 0;
711         pme->rdispls[0] = 0;
712         pme->sidx[0]    = 0;
713         for (i = 1; i < atc->nslab; i++)
714         {
715             pme->sdispls[i] = pme->sdispls[i-1]+pme->scounts[i-1];
716             pme->rdispls[i] = pme->rdispls[i-1]+pme->rcounts[i-1];
717             pme->sidx[i]    = pme->sdispls[i];
718         }
719         /* Total # of particles to be received */
720         atc->n = pme->rdispls[atc->nslab-1] + pme->rcounts[atc->nslab-1];
721
722         pme_realloc_atomcomm_things(atc);
723
724         /* Copy particle coordinates into send buffer and exchange*/
725         for (i = 0; (i < n); i++)
726         {
727             ii = DIM*pme->sidx[pme->idxa[i]];
728             pme->sidx[pme->idxa[i]]++;
729             pme->redist_buf[ii+XX] = x_f[i][XX];
730             pme->redist_buf[ii+YY] = x_f[i][YY];
731             pme->redist_buf[ii+ZZ] = x_f[i][ZZ];
732         }
733         MPI_Alltoallv(pme->redist_buf, pme->scounts, pme->sdispls,
734                       pme->rvec_mpi, atc->x, pme->rcounts, pme->rdispls,
735                       pme->rvec_mpi, atc->mpi_comm);
736     }
737     if (forw)
738     {
739         /* Copy charge into send buffer and exchange*/
740         for (i = 0; i < atc->nslab; i++)
741         {
742             pme->sidx[i] = pme->sdispls[i];
743         }
744         for (i = 0; (i < n); i++)
745         {
746             ii = pme->sidx[pme->idxa[i]];
747             pme->sidx[pme->idxa[i]]++;
748             pme->redist_buf[ii] = charge[i];
749         }
750         MPI_Alltoallv(pme->redist_buf, pme->scounts, pme->sdispls, mpi_type,
751                       atc->q, pme->rcounts, pme->rdispls, mpi_type,
752                       atc->mpi_comm);
753     }
754     else   /* backward, redistribution from pme to pp */
755     {
756         MPI_Alltoallv(atc->f, pme->rcounts, pme->rdispls, pme->rvec_mpi,
757                       pme->redist_buf, pme->scounts, pme->sdispls,
758                       pme->rvec_mpi, atc->mpi_comm);
759
760         /* Copy data from receive buffer */
761         for (i = 0; i < atc->nslab; i++)
762         {
763             pme->sidx[i] = pme->sdispls[i];
764         }
765         for (i = 0; (i < n); i++)
766         {
767             ii          = DIM*pme->sidx[pme->idxa[i]];
768             x_f[i][XX] += pme->redist_buf[ii+XX];
769             x_f[i][YY] += pme->redist_buf[ii+YY];
770             x_f[i][ZZ] += pme->redist_buf[ii+ZZ];
771             pme->sidx[pme->idxa[i]]++;
772         }
773     }
774 #endif
775 }
776
777 static void pme_dd_sendrecv(pme_atomcomm_t *atc,
778                             gmx_bool bBackward, int shift,
779                             void *buf_s, int nbyte_s,
780                             void *buf_r, int nbyte_r)
781 {
782 #ifdef GMX_MPI
783     int        dest, src;
784     MPI_Status stat;
785
786     if (bBackward == FALSE)
787     {
788         dest = atc->node_dest[shift];
789         src  = atc->node_src[shift];
790     }
791     else
792     {
793         dest = atc->node_src[shift];
794         src  = atc->node_dest[shift];
795     }
796
797     if (nbyte_s > 0 && nbyte_r > 0)
798     {
799         MPI_Sendrecv(buf_s, nbyte_s, MPI_BYTE,
800                      dest, shift,
801                      buf_r, nbyte_r, MPI_BYTE,
802                      src, shift,
803                      atc->mpi_comm, &stat);
804     }
805     else if (nbyte_s > 0)
806     {
807         MPI_Send(buf_s, nbyte_s, MPI_BYTE,
808                  dest, shift,
809                  atc->mpi_comm);
810     }
811     else if (nbyte_r > 0)
812     {
813         MPI_Recv(buf_r, nbyte_r, MPI_BYTE,
814                  src, shift,
815                  atc->mpi_comm, &stat);
816     }
817 #endif
818 }
819
820 static void dd_pmeredist_x_q(gmx_pme_t pme,
821                              int n, gmx_bool bX, rvec *x, real *charge,
822                              pme_atomcomm_t *atc)
823 {
824     int *commnode, *buf_index;
825     int  nnodes_comm, i, nsend, local_pos, buf_pos, node, scount, rcount;
826
827     commnode  = atc->node_dest;
828     buf_index = atc->buf_index;
829
830     nnodes_comm = min(2*atc->maxshift, atc->nslab-1);
831
832     nsend = 0;
833     for (i = 0; i < nnodes_comm; i++)
834     {
835         buf_index[commnode[i]] = nsend;
836         nsend                 += atc->count[commnode[i]];
837     }
838     if (bX)
839     {
840         if (atc->count[atc->nodeid] + nsend != n)
841         {
842             gmx_fatal(FARGS, "%d particles communicated to PME node %d are more than 2/3 times the cut-off out of the domain decomposition cell of their charge group in dimension %c.\n"
843                       "This usually means that your system is not well equilibrated.",
844                       n - (atc->count[atc->nodeid] + nsend),
845                       pme->nodeid, 'x'+atc->dimind);
846         }
847
848         if (nsend > pme->buf_nalloc)
849         {
850             pme->buf_nalloc = over_alloc_dd(nsend);
851             srenew(pme->bufv, pme->buf_nalloc);
852             srenew(pme->bufr, pme->buf_nalloc);
853         }
854
855         atc->n = atc->count[atc->nodeid];
856         for (i = 0; i < nnodes_comm; i++)
857         {
858             scount = atc->count[commnode[i]];
859             /* Communicate the count */
860             if (debug)
861             {
862                 fprintf(debug, "dimind %d PME node %d send to node %d: %d\n",
863                         atc->dimind, atc->nodeid, commnode[i], scount);
864             }
865             pme_dd_sendrecv(atc, FALSE, i,
866                             &scount, sizeof(int),
867                             &atc->rcount[i], sizeof(int));
868             atc->n += atc->rcount[i];
869         }
870
871         pme_realloc_atomcomm_things(atc);
872     }
873
874     local_pos = 0;
875     for (i = 0; i < n; i++)
876     {
877         node = atc->pd[i];
878         if (node == atc->nodeid)
879         {
880             /* Copy direct to the receive buffer */
881             if (bX)
882             {
883                 copy_rvec(x[i], atc->x[local_pos]);
884             }
885             atc->q[local_pos] = charge[i];
886             local_pos++;
887         }
888         else
889         {
890             /* Copy to the send buffer */
891             if (bX)
892             {
893                 copy_rvec(x[i], pme->bufv[buf_index[node]]);
894             }
895             pme->bufr[buf_index[node]] = charge[i];
896             buf_index[node]++;
897         }
898     }
899
900     buf_pos = 0;
901     for (i = 0; i < nnodes_comm; i++)
902     {
903         scount = atc->count[commnode[i]];
904         rcount = atc->rcount[i];
905         if (scount > 0 || rcount > 0)
906         {
907             if (bX)
908             {
909                 /* Communicate the coordinates */
910                 pme_dd_sendrecv(atc, FALSE, i,
911                                 pme->bufv[buf_pos], scount*sizeof(rvec),
912                                 atc->x[local_pos], rcount*sizeof(rvec));
913             }
914             /* Communicate the charges */
915             pme_dd_sendrecv(atc, FALSE, i,
916                             pme->bufr+buf_pos, scount*sizeof(real),
917                             atc->q+local_pos, rcount*sizeof(real));
918             buf_pos   += scount;
919             local_pos += atc->rcount[i];
920         }
921     }
922 }
923
924 static void dd_pmeredist_f(gmx_pme_t pme, pme_atomcomm_t *atc,
925                            int n, rvec *f,
926                            gmx_bool bAddF)
927 {
928     int *commnode, *buf_index;
929     int  nnodes_comm, local_pos, buf_pos, i, scount, rcount, node;
930
931     commnode  = atc->node_dest;
932     buf_index = atc->buf_index;
933
934     nnodes_comm = min(2*atc->maxshift, atc->nslab-1);
935
936     local_pos = atc->count[atc->nodeid];
937     buf_pos   = 0;
938     for (i = 0; i < nnodes_comm; i++)
939     {
940         scount = atc->rcount[i];
941         rcount = atc->count[commnode[i]];
942         if (scount > 0 || rcount > 0)
943         {
944             /* Communicate the forces */
945             pme_dd_sendrecv(atc, TRUE, i,
946                             atc->f[local_pos], scount*sizeof(rvec),
947                             pme->bufv[buf_pos], rcount*sizeof(rvec));
948             local_pos += scount;
949         }
950         buf_index[commnode[i]] = buf_pos;
951         buf_pos               += rcount;
952     }
953
954     local_pos = 0;
955     if (bAddF)
956     {
957         for (i = 0; i < n; i++)
958         {
959             node = atc->pd[i];
960             if (node == atc->nodeid)
961             {
962                 /* Add from the local force array */
963                 rvec_inc(f[i], atc->f[local_pos]);
964                 local_pos++;
965             }
966             else
967             {
968                 /* Add from the receive buffer */
969                 rvec_inc(f[i], pme->bufv[buf_index[node]]);
970                 buf_index[node]++;
971             }
972         }
973     }
974     else
975     {
976         for (i = 0; i < n; i++)
977         {
978             node = atc->pd[i];
979             if (node == atc->nodeid)
980             {
981                 /* Copy from the local force array */
982                 copy_rvec(atc->f[local_pos], f[i]);
983                 local_pos++;
984             }
985             else
986             {
987                 /* Copy from the receive buffer */
988                 copy_rvec(pme->bufv[buf_index[node]], f[i]);
989                 buf_index[node]++;
990             }
991         }
992     }
993 }
994
995 #ifdef GMX_MPI
996 static void
997 gmx_sum_qgrid_dd(gmx_pme_t pme, real *grid, int direction)
998 {
999     pme_overlap_t *overlap;
1000     int            send_index0, send_nindex;
1001     int            recv_index0, recv_nindex;
1002     MPI_Status     stat;
1003     int            i, j, k, ix, iy, iz, icnt;
1004     int            ipulse, send_id, recv_id, datasize;
1005     real          *p;
1006     real          *sendptr, *recvptr;
1007
1008     /* Start with minor-rank communication. This is a bit of a pain since it is not contiguous */
1009     overlap = &pme->overlap[1];
1010
1011     for (ipulse = 0; ipulse < overlap->noverlap_nodes; ipulse++)
1012     {
1013         /* Since we have already (un)wrapped the overlap in the z-dimension,
1014          * we only have to communicate 0 to nkz (not pmegrid_nz).
1015          */
1016         if (direction == GMX_SUM_QGRID_FORWARD)
1017         {
1018             send_id       = overlap->send_id[ipulse];
1019             recv_id       = overlap->recv_id[ipulse];
1020             send_index0   = overlap->comm_data[ipulse].send_index0;
1021             send_nindex   = overlap->comm_data[ipulse].send_nindex;
1022             recv_index0   = overlap->comm_data[ipulse].recv_index0;
1023             recv_nindex   = overlap->comm_data[ipulse].recv_nindex;
1024         }
1025         else
1026         {
1027             send_id       = overlap->recv_id[ipulse];
1028             recv_id       = overlap->send_id[ipulse];
1029             send_index0   = overlap->comm_data[ipulse].recv_index0;
1030             send_nindex   = overlap->comm_data[ipulse].recv_nindex;
1031             recv_index0   = overlap->comm_data[ipulse].send_index0;
1032             recv_nindex   = overlap->comm_data[ipulse].send_nindex;
1033         }
1034
1035         /* Copy data to contiguous send buffer */
1036         if (debug)
1037         {
1038             fprintf(debug, "PME send node %d %d -> %d grid start %d Communicating %d to %d\n",
1039                     pme->nodeid, overlap->nodeid, send_id,
1040                     pme->pmegrid_start_iy,
1041                     send_index0-pme->pmegrid_start_iy,
1042                     send_index0-pme->pmegrid_start_iy+send_nindex);
1043         }
1044         icnt = 0;
1045         for (i = 0; i < pme->pmegrid_nx; i++)
1046         {
1047             ix = i;
1048             for (j = 0; j < send_nindex; j++)
1049             {
1050                 iy = j + send_index0 - pme->pmegrid_start_iy;
1051                 for (k = 0; k < pme->nkz; k++)
1052                 {
1053                     iz = k;
1054                     overlap->sendbuf[icnt++] = grid[ix*(pme->pmegrid_ny*pme->pmegrid_nz)+iy*(pme->pmegrid_nz)+iz];
1055                 }
1056             }
1057         }
1058
1059         datasize      = pme->pmegrid_nx * pme->nkz;
1060
1061         MPI_Sendrecv(overlap->sendbuf, send_nindex*datasize, GMX_MPI_REAL,
1062                      send_id, ipulse,
1063                      overlap->recvbuf, recv_nindex*datasize, GMX_MPI_REAL,
1064                      recv_id, ipulse,
1065                      overlap->mpi_comm, &stat);
1066
1067         /* Get data from contiguous recv buffer */
1068         if (debug)
1069         {
1070             fprintf(debug, "PME recv node %d %d <- %d grid start %d Communicating %d to %d\n",
1071                     pme->nodeid, overlap->nodeid, recv_id,
1072                     pme->pmegrid_start_iy,
1073                     recv_index0-pme->pmegrid_start_iy,
1074                     recv_index0-pme->pmegrid_start_iy+recv_nindex);
1075         }
1076         icnt = 0;
1077         for (i = 0; i < pme->pmegrid_nx; i++)
1078         {
1079             ix = i;
1080             for (j = 0; j < recv_nindex; j++)
1081             {
1082                 iy = j + recv_index0 - pme->pmegrid_start_iy;
1083                 for (k = 0; k < pme->nkz; k++)
1084                 {
1085                     iz = k;
1086                     if (direction == GMX_SUM_QGRID_FORWARD)
1087                     {
1088                         grid[ix*(pme->pmegrid_ny*pme->pmegrid_nz)+iy*(pme->pmegrid_nz)+iz] += overlap->recvbuf[icnt++];
1089                     }
1090                     else
1091                     {
1092                         grid[ix*(pme->pmegrid_ny*pme->pmegrid_nz)+iy*(pme->pmegrid_nz)+iz]  = overlap->recvbuf[icnt++];
1093                     }
1094                 }
1095             }
1096         }
1097     }
1098
1099     /* Major dimension is easier, no copying required,
1100      * but we might have to sum to separate array.
1101      * Since we don't copy, we have to communicate up to pmegrid_nz,
1102      * not nkz as for the minor direction.
1103      */
1104     overlap = &pme->overlap[0];
1105
1106     for (ipulse = 0; ipulse < overlap->noverlap_nodes; ipulse++)
1107     {
1108         if (direction == GMX_SUM_QGRID_FORWARD)
1109         {
1110             send_id       = overlap->send_id[ipulse];
1111             recv_id       = overlap->recv_id[ipulse];
1112             send_index0   = overlap->comm_data[ipulse].send_index0;
1113             send_nindex   = overlap->comm_data[ipulse].send_nindex;
1114             recv_index0   = overlap->comm_data[ipulse].recv_index0;
1115             recv_nindex   = overlap->comm_data[ipulse].recv_nindex;
1116             recvptr       = overlap->recvbuf;
1117         }
1118         else
1119         {
1120             send_id       = overlap->recv_id[ipulse];
1121             recv_id       = overlap->send_id[ipulse];
1122             send_index0   = overlap->comm_data[ipulse].recv_index0;
1123             send_nindex   = overlap->comm_data[ipulse].recv_nindex;
1124             recv_index0   = overlap->comm_data[ipulse].send_index0;
1125             recv_nindex   = overlap->comm_data[ipulse].send_nindex;
1126             recvptr       = grid + (recv_index0-pme->pmegrid_start_ix)*(pme->pmegrid_ny*pme->pmegrid_nz);
1127         }
1128
1129         sendptr       = grid + (send_index0-pme->pmegrid_start_ix)*(pme->pmegrid_ny*pme->pmegrid_nz);
1130         datasize      = pme->pmegrid_ny * pme->pmegrid_nz;
1131
1132         if (debug)
1133         {
1134             fprintf(debug, "PME send node %d %d -> %d grid start %d Communicating %d to %d\n",
1135                     pme->nodeid, overlap->nodeid, send_id,
1136                     pme->pmegrid_start_ix,
1137                     send_index0-pme->pmegrid_start_ix,
1138                     send_index0-pme->pmegrid_start_ix+send_nindex);
1139             fprintf(debug, "PME recv node %d %d <- %d grid start %d Communicating %d to %d\n",
1140                     pme->nodeid, overlap->nodeid, recv_id,
1141                     pme->pmegrid_start_ix,
1142                     recv_index0-pme->pmegrid_start_ix,
1143                     recv_index0-pme->pmegrid_start_ix+recv_nindex);
1144         }
1145
1146         MPI_Sendrecv(sendptr, send_nindex*datasize, GMX_MPI_REAL,
1147                      send_id, ipulse,
1148                      recvptr, recv_nindex*datasize, GMX_MPI_REAL,
1149                      recv_id, ipulse,
1150                      overlap->mpi_comm, &stat);
1151
1152         /* ADD data from contiguous recv buffer */
1153         if (direction == GMX_SUM_QGRID_FORWARD)
1154         {
1155             p = grid + (recv_index0-pme->pmegrid_start_ix)*(pme->pmegrid_ny*pme->pmegrid_nz);
1156             for (i = 0; i < recv_nindex*datasize; i++)
1157             {
1158                 p[i] += overlap->recvbuf[i];
1159             }
1160         }
1161     }
1162 }
1163 #endif
1164
1165
1166 static int
1167 copy_pmegrid_to_fftgrid(gmx_pme_t pme, real *pmegrid, real *fftgrid)
1168 {
1169     ivec    local_fft_ndata, local_fft_offset, local_fft_size;
1170     ivec    local_pme_size;
1171     int     i, ix, iy, iz;
1172     int     pmeidx, fftidx;
1173
1174     /* Dimensions should be identical for A/B grid, so we just use A here */
1175     gmx_parallel_3dfft_real_limits(pme->pfft_setupA,
1176                                    local_fft_ndata,
1177                                    local_fft_offset,
1178                                    local_fft_size);
1179
1180     local_pme_size[0] = pme->pmegrid_nx;
1181     local_pme_size[1] = pme->pmegrid_ny;
1182     local_pme_size[2] = pme->pmegrid_nz;
1183
1184     /* The fftgrid is always 'justified' to the lower-left corner of the PME grid,
1185        the offset is identical, and the PME grid always has more data (due to overlap)
1186      */
1187     {
1188 #ifdef DEBUG_PME
1189         FILE *fp, *fp2;
1190         char  fn[STRLEN], format[STRLEN];
1191         real  val;
1192         sprintf(fn, "pmegrid%d.pdb", pme->nodeid);
1193         fp = ffopen(fn, "w");
1194         sprintf(fn, "pmegrid%d.txt", pme->nodeid);
1195         fp2 = ffopen(fn, "w");
1196         sprintf(format, "%s%s\n", pdbformat, "%6.2f%6.2f");
1197 #endif
1198
1199         for (ix = 0; ix < local_fft_ndata[XX]; ix++)
1200         {
1201             for (iy = 0; iy < local_fft_ndata[YY]; iy++)
1202             {
1203                 for (iz = 0; iz < local_fft_ndata[ZZ]; iz++)
1204                 {
1205                     pmeidx          = ix*(local_pme_size[YY]*local_pme_size[ZZ])+iy*(local_pme_size[ZZ])+iz;
1206                     fftidx          = ix*(local_fft_size[YY]*local_fft_size[ZZ])+iy*(local_fft_size[ZZ])+iz;
1207                     fftgrid[fftidx] = pmegrid[pmeidx];
1208 #ifdef DEBUG_PME
1209                     val = 100*pmegrid[pmeidx];
1210                     if (pmegrid[pmeidx] != 0)
1211                     {
1212                         fprintf(fp, format, "ATOM", pmeidx, "CA", "GLY", ' ', pmeidx, ' ',
1213                                 5.0*ix, 5.0*iy, 5.0*iz, 1.0, val);
1214                     }
1215                     if (pmegrid[pmeidx] != 0)
1216                     {
1217                         fprintf(fp2, "%-12s  %5d  %5d  %5d  %12.5e\n",
1218                                 "qgrid",
1219                                 pme->pmegrid_start_ix + ix,
1220                                 pme->pmegrid_start_iy + iy,
1221                                 pme->pmegrid_start_iz + iz,
1222                                 pmegrid[pmeidx]);
1223                     }
1224 #endif
1225                 }
1226             }
1227         }
1228 #ifdef DEBUG_PME
1229         ffclose(fp);
1230         ffclose(fp2);
1231 #endif
1232     }
1233     return 0;
1234 }
1235
1236
1237 static gmx_cycles_t omp_cyc_start()
1238 {
1239     return gmx_cycles_read();
1240 }
1241
1242 static gmx_cycles_t omp_cyc_end(gmx_cycles_t c)
1243 {
1244     return gmx_cycles_read() - c;
1245 }
1246
1247
1248 static int
1249 copy_fftgrid_to_pmegrid(gmx_pme_t pme, const real *fftgrid, real *pmegrid,
1250                         int nthread, int thread)
1251 {
1252     ivec          local_fft_ndata, local_fft_offset, local_fft_size;
1253     ivec          local_pme_size;
1254     int           ixy0, ixy1, ixy, ix, iy, iz;
1255     int           pmeidx, fftidx;
1256 #ifdef PME_TIME_THREADS
1257     gmx_cycles_t  c1;
1258     static double cs1 = 0;
1259     static int    cnt = 0;
1260 #endif
1261
1262 #ifdef PME_TIME_THREADS
1263     c1 = omp_cyc_start();
1264 #endif
1265     /* Dimensions should be identical for A/B grid, so we just use A here */
1266     gmx_parallel_3dfft_real_limits(pme->pfft_setupA,
1267                                    local_fft_ndata,
1268                                    local_fft_offset,
1269                                    local_fft_size);
1270
1271     local_pme_size[0] = pme->pmegrid_nx;
1272     local_pme_size[1] = pme->pmegrid_ny;
1273     local_pme_size[2] = pme->pmegrid_nz;
1274
1275     /* The fftgrid is always 'justified' to the lower-left corner of the PME grid,
1276        the offset is identical, and the PME grid always has more data (due to overlap)
1277      */
1278     ixy0 = ((thread  )*local_fft_ndata[XX]*local_fft_ndata[YY])/nthread;
1279     ixy1 = ((thread+1)*local_fft_ndata[XX]*local_fft_ndata[YY])/nthread;
1280
1281     for (ixy = ixy0; ixy < ixy1; ixy++)
1282     {
1283         ix = ixy/local_fft_ndata[YY];
1284         iy = ixy - ix*local_fft_ndata[YY];
1285
1286         pmeidx = (ix*local_pme_size[YY] + iy)*local_pme_size[ZZ];
1287         fftidx = (ix*local_fft_size[YY] + iy)*local_fft_size[ZZ];
1288         for (iz = 0; iz < local_fft_ndata[ZZ]; iz++)
1289         {
1290             pmegrid[pmeidx+iz] = fftgrid[fftidx+iz];
1291         }
1292     }
1293
1294 #ifdef PME_TIME_THREADS
1295     c1   = omp_cyc_end(c1);
1296     cs1 += (double)c1;
1297     cnt++;
1298     if (cnt % 20 == 0)
1299     {
1300         printf("copy %.2f\n", cs1*1e-9);
1301     }
1302 #endif
1303
1304     return 0;
1305 }
1306
1307
1308 static void
1309 wrap_periodic_pmegrid(gmx_pme_t pme, real *pmegrid)
1310 {
1311     int     nx, ny, nz, pnx, pny, pnz, ny_x, overlap, ix, iy, iz;
1312
1313     nx = pme->nkx;
1314     ny = pme->nky;
1315     nz = pme->nkz;
1316
1317     pnx = pme->pmegrid_nx;
1318     pny = pme->pmegrid_ny;
1319     pnz = pme->pmegrid_nz;
1320
1321     overlap = pme->pme_order - 1;
1322
1323     /* Add periodic overlap in z */
1324     for (ix = 0; ix < pme->pmegrid_nx; ix++)
1325     {
1326         for (iy = 0; iy < pme->pmegrid_ny; iy++)
1327         {
1328             for (iz = 0; iz < overlap; iz++)
1329             {
1330                 pmegrid[(ix*pny+iy)*pnz+iz] +=
1331                     pmegrid[(ix*pny+iy)*pnz+nz+iz];
1332             }
1333         }
1334     }
1335
1336     if (pme->nnodes_minor == 1)
1337     {
1338         for (ix = 0; ix < pme->pmegrid_nx; ix++)
1339         {
1340             for (iy = 0; iy < overlap; iy++)
1341             {
1342                 for (iz = 0; iz < nz; iz++)
1343                 {
1344                     pmegrid[(ix*pny+iy)*pnz+iz] +=
1345                         pmegrid[(ix*pny+ny+iy)*pnz+iz];
1346                 }
1347             }
1348         }
1349     }
1350
1351     if (pme->nnodes_major == 1)
1352     {
1353         ny_x = (pme->nnodes_minor == 1 ? ny : pme->pmegrid_ny);
1354
1355         for (ix = 0; ix < overlap; ix++)
1356         {
1357             for (iy = 0; iy < ny_x; iy++)
1358             {
1359                 for (iz = 0; iz < nz; iz++)
1360                 {
1361                     pmegrid[(ix*pny+iy)*pnz+iz] +=
1362                         pmegrid[((nx+ix)*pny+iy)*pnz+iz];
1363                 }
1364             }
1365         }
1366     }
1367 }
1368
1369
1370 static void
1371 unwrap_periodic_pmegrid(gmx_pme_t pme, real *pmegrid)
1372 {
1373     int     nx, ny, nz, pnx, pny, pnz, ny_x, overlap, ix;
1374
1375     nx = pme->nkx;
1376     ny = pme->nky;
1377     nz = pme->nkz;
1378
1379     pnx = pme->pmegrid_nx;
1380     pny = pme->pmegrid_ny;
1381     pnz = pme->pmegrid_nz;
1382
1383     overlap = pme->pme_order - 1;
1384
1385     if (pme->nnodes_major == 1)
1386     {
1387         ny_x = (pme->nnodes_minor == 1 ? ny : pme->pmegrid_ny);
1388
1389         for (ix = 0; ix < overlap; ix++)
1390         {
1391             int iy, iz;
1392
1393             for (iy = 0; iy < ny_x; iy++)
1394             {
1395                 for (iz = 0; iz < nz; iz++)
1396                 {
1397                     pmegrid[((nx+ix)*pny+iy)*pnz+iz] =
1398                         pmegrid[(ix*pny+iy)*pnz+iz];
1399                 }
1400             }
1401         }
1402     }
1403
1404     if (pme->nnodes_minor == 1)
1405     {
1406 #pragma omp parallel for num_threads(pme->nthread) schedule(static)
1407         for (ix = 0; ix < pme->pmegrid_nx; ix++)
1408         {
1409             int iy, iz;
1410
1411             for (iy = 0; iy < overlap; iy++)
1412             {
1413                 for (iz = 0; iz < nz; iz++)
1414                 {
1415                     pmegrid[(ix*pny+ny+iy)*pnz+iz] =
1416                         pmegrid[(ix*pny+iy)*pnz+iz];
1417                 }
1418             }
1419         }
1420     }
1421
1422     /* Copy periodic overlap in z */
1423 #pragma omp parallel for num_threads(pme->nthread) schedule(static)
1424     for (ix = 0; ix < pme->pmegrid_nx; ix++)
1425     {
1426         int iy, iz;
1427
1428         for (iy = 0; iy < pme->pmegrid_ny; iy++)
1429         {
1430             for (iz = 0; iz < overlap; iz++)
1431             {
1432                 pmegrid[(ix*pny+iy)*pnz+nz+iz] =
1433                     pmegrid[(ix*pny+iy)*pnz+iz];
1434             }
1435         }
1436     }
1437 }
1438
1439
1440 /* This has to be a macro to enable full compiler optimization with xlC (and probably others too) */
1441 #define DO_BSPLINE(order)                            \
1442     for (ithx = 0; (ithx < order); ithx++)                    \
1443     {                                                    \
1444         index_x = (i0+ithx)*pny*pnz;                     \
1445         valx    = qn*thx[ithx];                          \
1446                                                      \
1447         for (ithy = 0; (ithy < order); ithy++)                \
1448         {                                                \
1449             valxy    = valx*thy[ithy];                   \
1450             index_xy = index_x+(j0+ithy)*pnz;            \
1451                                                      \
1452             for (ithz = 0; (ithz < order); ithz++)            \
1453             {                                            \
1454                 index_xyz        = index_xy+(k0+ithz);   \
1455                 grid[index_xyz] += valxy*thz[ithz];      \
1456             }                                            \
1457         }                                                \
1458     }
1459
1460
1461 static void spread_q_bsplines_thread(pmegrid_t *pmegrid,
1462                                      pme_atomcomm_t *atc, splinedata_t *spline,
1463                                      pme_spline_work_t *work)
1464 {
1465
1466     /* spread charges from home atoms to local grid */
1467     real          *grid;
1468     pme_overlap_t *ol;
1469     int            b, i, nn, n, ithx, ithy, ithz, i0, j0, k0;
1470     int       *    idxptr;
1471     int            order, norder, index_x, index_xy, index_xyz;
1472     real           valx, valxy, qn;
1473     real          *thx, *thy, *thz;
1474     int            localsize, bndsize;
1475     int            pnx, pny, pnz, ndatatot;
1476     int            offx, offy, offz;
1477
1478 #if defined PME_SIMD4_SPREAD_GATHER && !defined PME_SIMD4_UNALIGNED
1479     real           thz_buffer[12], *thz_aligned;
1480
1481     thz_aligned = gmx_simd4_align_real(thz_buffer);
1482 #endif
1483
1484     pnx = pmegrid->s[XX];
1485     pny = pmegrid->s[YY];
1486     pnz = pmegrid->s[ZZ];
1487
1488     offx = pmegrid->offset[XX];
1489     offy = pmegrid->offset[YY];
1490     offz = pmegrid->offset[ZZ];
1491
1492     ndatatot = pnx*pny*pnz;
1493     grid     = pmegrid->grid;
1494     for (i = 0; i < ndatatot; i++)
1495     {
1496         grid[i] = 0;
1497     }
1498
1499     order = pmegrid->order;
1500
1501     for (nn = 0; nn < spline->n; nn++)
1502     {
1503         n  = spline->ind[nn];
1504         qn = atc->q[n];
1505
1506         if (qn != 0)
1507         {
1508             idxptr = atc->idx[n];
1509             norder = nn*order;
1510
1511             i0   = idxptr[XX] - offx;
1512             j0   = idxptr[YY] - offy;
1513             k0   = idxptr[ZZ] - offz;
1514
1515             thx = spline->theta[XX] + norder;
1516             thy = spline->theta[YY] + norder;
1517             thz = spline->theta[ZZ] + norder;
1518
1519             switch (order)
1520             {
1521                 case 4:
1522 #ifdef PME_SIMD4_SPREAD_GATHER
1523 #ifdef PME_SIMD4_UNALIGNED
1524 #define PME_SPREAD_SIMD4_ORDER4
1525 #else
1526 #define PME_SPREAD_SIMD4_ALIGNED
1527 #define PME_ORDER 4
1528 #endif
1529 #include "pme_simd4.h"
1530 #else
1531                     DO_BSPLINE(4);
1532 #endif
1533                     break;
1534                 case 5:
1535 #ifdef PME_SIMD4_SPREAD_GATHER
1536 #define PME_SPREAD_SIMD4_ALIGNED
1537 #define PME_ORDER 5
1538 #include "pme_simd4.h"
1539 #else
1540                     DO_BSPLINE(5);
1541 #endif
1542                     break;
1543                 default:
1544                     DO_BSPLINE(order);
1545                     break;
1546             }
1547         }
1548     }
1549 }
1550
1551 static void set_grid_alignment(int *pmegrid_nz, int pme_order)
1552 {
1553 #ifdef PME_SIMD4_SPREAD_GATHER
1554     if (pme_order == 5
1555 #ifndef PME_SIMD4_UNALIGNED
1556         || pme_order == 4
1557 #endif
1558         )
1559     {
1560         /* Round nz up to a multiple of 4 to ensure alignment */
1561         *pmegrid_nz = ((*pmegrid_nz + 3) & ~3);
1562     }
1563 #endif
1564 }
1565
1566 static void set_gridsize_alignment(int gmx_unused *gridsize, int gmx_unused pme_order)
1567 {
1568 #ifdef PME_SIMD4_SPREAD_GATHER
1569 #ifndef PME_SIMD4_UNALIGNED
1570     if (pme_order == 4)
1571     {
1572         /* Add extra elements to ensured aligned operations do not go
1573          * beyond the allocated grid size.
1574          * Note that for pme_order=5, the pme grid z-size alignment
1575          * ensures that we will not go beyond the grid size.
1576          */
1577         *gridsize += 4;
1578     }
1579 #endif
1580 #endif
1581 }
1582
1583 static void pmegrid_init(pmegrid_t *grid,
1584                          int cx, int cy, int cz,
1585                          int x0, int y0, int z0,
1586                          int x1, int y1, int z1,
1587                          gmx_bool set_alignment,
1588                          int pme_order,
1589                          real *ptr)
1590 {
1591     int nz, gridsize;
1592
1593     grid->ci[XX]     = cx;
1594     grid->ci[YY]     = cy;
1595     grid->ci[ZZ]     = cz;
1596     grid->offset[XX] = x0;
1597     grid->offset[YY] = y0;
1598     grid->offset[ZZ] = z0;
1599     grid->n[XX]      = x1 - x0 + pme_order - 1;
1600     grid->n[YY]      = y1 - y0 + pme_order - 1;
1601     grid->n[ZZ]      = z1 - z0 + pme_order - 1;
1602     copy_ivec(grid->n, grid->s);
1603
1604     nz = grid->s[ZZ];
1605     set_grid_alignment(&nz, pme_order);
1606     if (set_alignment)
1607     {
1608         grid->s[ZZ] = nz;
1609     }
1610     else if (nz != grid->s[ZZ])
1611     {
1612         gmx_incons("pmegrid_init call with an unaligned z size");
1613     }
1614
1615     grid->order = pme_order;
1616     if (ptr == NULL)
1617     {
1618         gridsize = grid->s[XX]*grid->s[YY]*grid->s[ZZ];
1619         set_gridsize_alignment(&gridsize, pme_order);
1620         snew_aligned(grid->grid, gridsize, SIMD4_ALIGNMENT);
1621     }
1622     else
1623     {
1624         grid->grid = ptr;
1625     }
1626 }
1627
1628 static int div_round_up(int enumerator, int denominator)
1629 {
1630     return (enumerator + denominator - 1)/denominator;
1631 }
1632
1633 static void make_subgrid_division(const ivec n, int ovl, int nthread,
1634                                   ivec nsub)
1635 {
1636     int gsize_opt, gsize;
1637     int nsx, nsy, nsz;
1638     char *env;
1639
1640     gsize_opt = -1;
1641     for (nsx = 1; nsx <= nthread; nsx++)
1642     {
1643         if (nthread % nsx == 0)
1644         {
1645             for (nsy = 1; nsy <= nthread; nsy++)
1646             {
1647                 if (nsx*nsy <= nthread && nthread % (nsx*nsy) == 0)
1648                 {
1649                     nsz = nthread/(nsx*nsy);
1650
1651                     /* Determine the number of grid points per thread */
1652                     gsize =
1653                         (div_round_up(n[XX], nsx) + ovl)*
1654                         (div_round_up(n[YY], nsy) + ovl)*
1655                         (div_round_up(n[ZZ], nsz) + ovl);
1656
1657                     /* Minimize the number of grids points per thread
1658                      * and, secondarily, the number of cuts in minor dimensions.
1659                      */
1660                     if (gsize_opt == -1 ||
1661                         gsize < gsize_opt ||
1662                         (gsize == gsize_opt &&
1663                          (nsz < nsub[ZZ] || (nsz == nsub[ZZ] && nsy < nsub[YY]))))
1664                     {
1665                         nsub[XX]  = nsx;
1666                         nsub[YY]  = nsy;
1667                         nsub[ZZ]  = nsz;
1668                         gsize_opt = gsize;
1669                     }
1670                 }
1671             }
1672         }
1673     }
1674
1675     env = getenv("GMX_PME_THREAD_DIVISION");
1676     if (env != NULL)
1677     {
1678         sscanf(env, "%d %d %d", &nsub[XX], &nsub[YY], &nsub[ZZ]);
1679     }
1680
1681     if (nsub[XX]*nsub[YY]*nsub[ZZ] != nthread)
1682     {
1683         gmx_fatal(FARGS, "PME grid thread division (%d x %d x %d) does not match the total number of threads (%d)", nsub[XX], nsub[YY], nsub[ZZ], nthread);
1684     }
1685 }
1686
1687 static void pmegrids_init(pmegrids_t *grids,
1688                           int nx, int ny, int nz, int nz_base,
1689                           int pme_order,
1690                           gmx_bool bUseThreads,
1691                           int nthread,
1692                           int overlap_x,
1693                           int overlap_y)
1694 {
1695     ivec n, n_base, g0, g1;
1696     int t, x, y, z, d, i, tfac;
1697     int max_comm_lines = -1;
1698
1699     n[XX] = nx - (pme_order - 1);
1700     n[YY] = ny - (pme_order - 1);
1701     n[ZZ] = nz - (pme_order - 1);
1702
1703     copy_ivec(n, n_base);
1704     n_base[ZZ] = nz_base;
1705
1706     pmegrid_init(&grids->grid, 0, 0, 0, 0, 0, 0, n[XX], n[YY], n[ZZ], FALSE, pme_order,
1707                  NULL);
1708
1709     grids->nthread = nthread;
1710
1711     make_subgrid_division(n_base, pme_order-1, grids->nthread, grids->nc);
1712
1713     if (bUseThreads)
1714     {
1715         ivec nst;
1716         int gridsize;
1717
1718         for (d = 0; d < DIM; d++)
1719         {
1720             nst[d] = div_round_up(n[d], grids->nc[d]) + pme_order - 1;
1721         }
1722         set_grid_alignment(&nst[ZZ], pme_order);
1723
1724         if (debug)
1725         {
1726             fprintf(debug, "pmegrid thread local division: %d x %d x %d\n",
1727                     grids->nc[XX], grids->nc[YY], grids->nc[ZZ]);
1728             fprintf(debug, "pmegrid %d %d %d max thread pmegrid %d %d %d\n",
1729                     nx, ny, nz,
1730                     nst[XX], nst[YY], nst[ZZ]);
1731         }
1732
1733         snew(grids->grid_th, grids->nthread);
1734         t        = 0;
1735         gridsize = nst[XX]*nst[YY]*nst[ZZ];
1736         set_gridsize_alignment(&gridsize, pme_order);
1737         snew_aligned(grids->grid_all,
1738                      grids->nthread*gridsize+(grids->nthread+1)*GMX_CACHE_SEP,
1739                      SIMD4_ALIGNMENT);
1740
1741         for (x = 0; x < grids->nc[XX]; x++)
1742         {
1743             for (y = 0; y < grids->nc[YY]; y++)
1744             {
1745                 for (z = 0; z < grids->nc[ZZ]; z++)
1746                 {
1747                     pmegrid_init(&grids->grid_th[t],
1748                                  x, y, z,
1749                                  (n[XX]*(x  ))/grids->nc[XX],
1750                                  (n[YY]*(y  ))/grids->nc[YY],
1751                                  (n[ZZ]*(z  ))/grids->nc[ZZ],
1752                                  (n[XX]*(x+1))/grids->nc[XX],
1753                                  (n[YY]*(y+1))/grids->nc[YY],
1754                                  (n[ZZ]*(z+1))/grids->nc[ZZ],
1755                                  TRUE,
1756                                  pme_order,
1757                                  grids->grid_all+GMX_CACHE_SEP+t*(gridsize+GMX_CACHE_SEP));
1758                     t++;
1759                 }
1760             }
1761         }
1762     }
1763     else
1764     {
1765         grids->grid_th = NULL;
1766     }
1767
1768     snew(grids->g2t, DIM);
1769     tfac = 1;
1770     for (d = DIM-1; d >= 0; d--)
1771     {
1772         snew(grids->g2t[d], n[d]);
1773         t = 0;
1774         for (i = 0; i < n[d]; i++)
1775         {
1776             /* The second check should match the parameters
1777              * of the pmegrid_init call above.
1778              */
1779             while (t + 1 < grids->nc[d] && i >= (n[d]*(t+1))/grids->nc[d])
1780             {
1781                 t++;
1782             }
1783             grids->g2t[d][i] = t*tfac;
1784         }
1785
1786         tfac *= grids->nc[d];
1787
1788         switch (d)
1789         {
1790             case XX: max_comm_lines = overlap_x;     break;
1791             case YY: max_comm_lines = overlap_y;     break;
1792             case ZZ: max_comm_lines = pme_order - 1; break;
1793         }
1794         grids->nthread_comm[d] = 0;
1795         while ((n[d]*grids->nthread_comm[d])/grids->nc[d] < max_comm_lines &&
1796                grids->nthread_comm[d] < grids->nc[d])
1797         {
1798             grids->nthread_comm[d]++;
1799         }
1800         if (debug != NULL)
1801         {
1802             fprintf(debug, "pmegrid thread grid communication range in %c: %d\n",
1803                     'x'+d, grids->nthread_comm[d]);
1804         }
1805         /* It should be possible to make grids->nthread_comm[d]==grids->nc[d]
1806          * work, but this is not a problematic restriction.
1807          */
1808         if (grids->nc[d] > 1 && grids->nthread_comm[d] > grids->nc[d])
1809         {
1810             gmx_fatal(FARGS, "Too many threads for PME (%d) compared to the number of grid lines, reduce the number of threads doing PME", grids->nthread);
1811         }
1812     }
1813 }
1814
1815
1816 static void pmegrids_destroy(pmegrids_t *grids)
1817 {
1818     int t;
1819
1820     if (grids->grid.grid != NULL)
1821     {
1822         sfree(grids->grid.grid);
1823
1824         if (grids->nthread > 0)
1825         {
1826             for (t = 0; t < grids->nthread; t++)
1827             {
1828                 sfree(grids->grid_th[t].grid);
1829             }
1830             sfree(grids->grid_th);
1831         }
1832     }
1833 }
1834
1835
1836 static void realloc_work(pme_work_t *work, int nkx)
1837 {
1838     int simd_width;
1839
1840     if (nkx > work->nalloc)
1841     {
1842         work->nalloc = nkx;
1843         srenew(work->mhx, work->nalloc);
1844         srenew(work->mhy, work->nalloc);
1845         srenew(work->mhz, work->nalloc);
1846         srenew(work->m2, work->nalloc);
1847         /* Allocate an aligned pointer for SIMD operations, including extra
1848          * elements at the end for padding.
1849          */
1850 #ifdef PME_SIMD
1851         simd_width = GMX_SIMD_WIDTH_HERE;
1852 #else
1853         /* We can use any alignment, apart from 0, so we use 4 */
1854         simd_width = 4;
1855 #endif
1856         sfree_aligned(work->denom);
1857         sfree_aligned(work->tmp1);
1858         sfree_aligned(work->eterm);
1859         snew_aligned(work->denom, work->nalloc+simd_width, simd_width*sizeof(real));
1860         snew_aligned(work->tmp1,  work->nalloc+simd_width, simd_width*sizeof(real));
1861         snew_aligned(work->eterm, work->nalloc+simd_width, simd_width*sizeof(real));
1862         srenew(work->m2inv, work->nalloc);
1863     }
1864 }
1865
1866
1867 static void free_work(pme_work_t *work)
1868 {
1869     sfree(work->mhx);
1870     sfree(work->mhy);
1871     sfree(work->mhz);
1872     sfree(work->m2);
1873     sfree_aligned(work->denom);
1874     sfree_aligned(work->tmp1);
1875     sfree_aligned(work->eterm);
1876     sfree(work->m2inv);
1877 }
1878
1879
1880 #ifdef PME_SIMD
1881 /* Calculate exponentials through SIMD */
1882 inline static void calc_exponentials(int start, int end, real f, real *d_aligned, real *r_aligned, real *e_aligned)
1883 {
1884     {
1885         const gmx_mm_pr two = gmx_set1_pr(2.0);
1886         gmx_mm_pr f_simd;
1887         gmx_mm_pr lu;
1888         gmx_mm_pr tmp_d1, d_inv, tmp_r, tmp_e;
1889         int kx;
1890         f_simd = gmx_set1_pr(f);
1891         for (kx = 0; kx < end; kx += GMX_SIMD_WIDTH_HERE)
1892         {
1893             tmp_d1   = gmx_load_pr(d_aligned+kx);
1894             d_inv    = gmx_inv_pr(tmp_d1);
1895             tmp_r    = gmx_load_pr(r_aligned+kx);
1896             tmp_r    = gmx_exp_pr(tmp_r);
1897             tmp_e    = gmx_mul_pr(f_simd, d_inv);
1898             tmp_e    = gmx_mul_pr(tmp_e, tmp_r);
1899             gmx_store_pr(e_aligned+kx, tmp_e);
1900         }
1901     }
1902 }
1903 #else
1904 inline static void calc_exponentials(int start, int end, real f, real *d, real *r, real *e)
1905 {
1906     int kx;
1907     for (kx = start; kx < end; kx++)
1908     {
1909         d[kx] = 1.0/d[kx];
1910     }
1911     for (kx = start; kx < end; kx++)
1912     {
1913         r[kx] = exp(r[kx]);
1914     }
1915     for (kx = start; kx < end; kx++)
1916     {
1917         e[kx] = f*r[kx]*d[kx];
1918     }
1919 }
1920 #endif
1921
1922
1923 static int solve_pme_yzx(gmx_pme_t pme, t_complex *grid,
1924                          real ewaldcoeff, real vol,
1925                          gmx_bool bEnerVir,
1926                          int nthread, int thread)
1927 {
1928     /* do recip sum over local cells in grid */
1929     /* y major, z middle, x minor or continuous */
1930     t_complex *p0;
1931     int     kx, ky, kz, maxkx, maxky, maxkz;
1932     int     nx, ny, nz, iyz0, iyz1, iyz, iy, iz, kxstart, kxend;
1933     real    mx, my, mz;
1934     real    factor = M_PI*M_PI/(ewaldcoeff*ewaldcoeff);
1935     real    ets2, struct2, vfactor, ets2vf;
1936     real    d1, d2, energy = 0;
1937     real    by, bz;
1938     real    virxx = 0, virxy = 0, virxz = 0, viryy = 0, viryz = 0, virzz = 0;
1939     real    rxx, ryx, ryy, rzx, rzy, rzz;
1940     pme_work_t *work;
1941     real    *mhx, *mhy, *mhz, *m2, *denom, *tmp1, *eterm, *m2inv;
1942     real    mhxk, mhyk, mhzk, m2k;
1943     real    corner_fac;
1944     ivec    complex_order;
1945     ivec    local_ndata, local_offset, local_size;
1946     real    elfac;
1947
1948     elfac = ONE_4PI_EPS0/pme->epsilon_r;
1949
1950     nx = pme->nkx;
1951     ny = pme->nky;
1952     nz = pme->nkz;
1953
1954     /* Dimensions should be identical for A/B grid, so we just use A here */
1955     gmx_parallel_3dfft_complex_limits(pme->pfft_setupA,
1956                                       complex_order,
1957                                       local_ndata,
1958                                       local_offset,
1959                                       local_size);
1960
1961     rxx = pme->recipbox[XX][XX];
1962     ryx = pme->recipbox[YY][XX];
1963     ryy = pme->recipbox[YY][YY];
1964     rzx = pme->recipbox[ZZ][XX];
1965     rzy = pme->recipbox[ZZ][YY];
1966     rzz = pme->recipbox[ZZ][ZZ];
1967
1968     maxkx = (nx+1)/2;
1969     maxky = (ny+1)/2;
1970     maxkz = nz/2+1;
1971
1972     work  = &pme->work[thread];
1973     mhx   = work->mhx;
1974     mhy   = work->mhy;
1975     mhz   = work->mhz;
1976     m2    = work->m2;
1977     denom = work->denom;
1978     tmp1  = work->tmp1;
1979     eterm = work->eterm;
1980     m2inv = work->m2inv;
1981
1982     iyz0 = local_ndata[YY]*local_ndata[ZZ]* thread   /nthread;
1983     iyz1 = local_ndata[YY]*local_ndata[ZZ]*(thread+1)/nthread;
1984
1985     for (iyz = iyz0; iyz < iyz1; iyz++)
1986     {
1987         iy = iyz/local_ndata[ZZ];
1988         iz = iyz - iy*local_ndata[ZZ];
1989
1990         ky = iy + local_offset[YY];
1991
1992         if (ky < maxky)
1993         {
1994             my = ky;
1995         }
1996         else
1997         {
1998             my = (ky - ny);
1999         }
2000
2001         by = M_PI*vol*pme->bsp_mod[YY][ky];
2002
2003         kz = iz + local_offset[ZZ];
2004
2005         mz = kz;
2006
2007         bz = pme->bsp_mod[ZZ][kz];
2008
2009         /* 0.5 correction for corner points */
2010         corner_fac = 1;
2011         if (kz == 0 || kz == (nz+1)/2)
2012         {
2013             corner_fac = 0.5;
2014         }
2015
2016         p0 = grid + iy*local_size[ZZ]*local_size[XX] + iz*local_size[XX];
2017
2018         /* We should skip the k-space point (0,0,0) */
2019         if (local_offset[XX] > 0 || ky > 0 || kz > 0)
2020         {
2021             kxstart = local_offset[XX];
2022         }
2023         else
2024         {
2025             kxstart = local_offset[XX] + 1;
2026             p0++;
2027         }
2028         kxend = local_offset[XX] + local_ndata[XX];
2029
2030         if (bEnerVir)
2031         {
2032             /* More expensive inner loop, especially because of the storage
2033              * of the mh elements in array's.
2034              * Because x is the minor grid index, all mh elements
2035              * depend on kx for triclinic unit cells.
2036              */
2037
2038             /* Two explicit loops to avoid a conditional inside the loop */
2039             for (kx = kxstart; kx < maxkx; kx++)
2040             {
2041                 mx = kx;
2042
2043                 mhxk      = mx * rxx;
2044                 mhyk      = mx * ryx + my * ryy;
2045                 mhzk      = mx * rzx + my * rzy + mz * rzz;
2046                 m2k       = mhxk*mhxk + mhyk*mhyk + mhzk*mhzk;
2047                 mhx[kx]   = mhxk;
2048                 mhy[kx]   = mhyk;
2049                 mhz[kx]   = mhzk;
2050                 m2[kx]    = m2k;
2051                 denom[kx] = m2k*bz*by*pme->bsp_mod[XX][kx];
2052                 tmp1[kx]  = -factor*m2k;
2053             }
2054
2055             for (kx = maxkx; kx < kxend; kx++)
2056             {
2057                 mx = (kx - nx);
2058
2059                 mhxk      = mx * rxx;
2060                 mhyk      = mx * ryx + my * ryy;
2061                 mhzk      = mx * rzx + my * rzy + mz * rzz;
2062                 m2k       = mhxk*mhxk + mhyk*mhyk + mhzk*mhzk;
2063                 mhx[kx]   = mhxk;
2064                 mhy[kx]   = mhyk;
2065                 mhz[kx]   = mhzk;
2066                 m2[kx]    = m2k;
2067                 denom[kx] = m2k*bz*by*pme->bsp_mod[XX][kx];
2068                 tmp1[kx]  = -factor*m2k;
2069             }
2070
2071             for (kx = kxstart; kx < kxend; kx++)
2072             {
2073                 m2inv[kx] = 1.0/m2[kx];
2074             }
2075
2076             calc_exponentials(kxstart, kxend, elfac, denom, tmp1, eterm);
2077
2078             for (kx = kxstart; kx < kxend; kx++, p0++)
2079             {
2080                 d1      = p0->re;
2081                 d2      = p0->im;
2082
2083                 p0->re  = d1*eterm[kx];
2084                 p0->im  = d2*eterm[kx];
2085
2086                 struct2 = 2.0*(d1*d1+d2*d2);
2087
2088                 tmp1[kx] = eterm[kx]*struct2;
2089             }
2090
2091             for (kx = kxstart; kx < kxend; kx++)
2092             {
2093                 ets2     = corner_fac*tmp1[kx];
2094                 vfactor  = (factor*m2[kx] + 1.0)*2.0*m2inv[kx];
2095                 energy  += ets2;
2096
2097                 ets2vf   = ets2*vfactor;
2098                 virxx   += ets2vf*mhx[kx]*mhx[kx] - ets2;
2099                 virxy   += ets2vf*mhx[kx]*mhy[kx];
2100                 virxz   += ets2vf*mhx[kx]*mhz[kx];
2101                 viryy   += ets2vf*mhy[kx]*mhy[kx] - ets2;
2102                 viryz   += ets2vf*mhy[kx]*mhz[kx];
2103                 virzz   += ets2vf*mhz[kx]*mhz[kx] - ets2;
2104             }
2105         }
2106         else
2107         {
2108             /* We don't need to calculate the energy and the virial.
2109              * In this case the triclinic overhead is small.
2110              */
2111
2112             /* Two explicit loops to avoid a conditional inside the loop */
2113
2114             for (kx = kxstart; kx < maxkx; kx++)
2115             {
2116                 mx = kx;
2117
2118                 mhxk      = mx * rxx;
2119                 mhyk      = mx * ryx + my * ryy;
2120                 mhzk      = mx * rzx + my * rzy + mz * rzz;
2121                 m2k       = mhxk*mhxk + mhyk*mhyk + mhzk*mhzk;
2122                 denom[kx] = m2k*bz*by*pme->bsp_mod[XX][kx];
2123                 tmp1[kx]  = -factor*m2k;
2124             }
2125
2126             for (kx = maxkx; kx < kxend; kx++)
2127             {
2128                 mx = (kx - nx);
2129
2130                 mhxk      = mx * rxx;
2131                 mhyk      = mx * ryx + my * ryy;
2132                 mhzk      = mx * rzx + my * rzy + mz * rzz;
2133                 m2k       = mhxk*mhxk + mhyk*mhyk + mhzk*mhzk;
2134                 denom[kx] = m2k*bz*by*pme->bsp_mod[XX][kx];
2135                 tmp1[kx]  = -factor*m2k;
2136             }
2137
2138             calc_exponentials(kxstart, kxend, elfac, denom, tmp1, eterm);
2139
2140             for (kx = kxstart; kx < kxend; kx++, p0++)
2141             {
2142                 d1      = p0->re;
2143                 d2      = p0->im;
2144
2145                 p0->re  = d1*eterm[kx];
2146                 p0->im  = d2*eterm[kx];
2147             }
2148         }
2149     }
2150
2151     if (bEnerVir)
2152     {
2153         /* Update virial with local values.
2154          * The virial is symmetric by definition.
2155          * this virial seems ok for isotropic scaling, but I'm
2156          * experiencing problems on semiisotropic membranes.
2157          * IS THAT COMMENT STILL VALID??? (DvdS, 2001/02/07).
2158          */
2159         work->vir[XX][XX] = 0.25*virxx;
2160         work->vir[YY][YY] = 0.25*viryy;
2161         work->vir[ZZ][ZZ] = 0.25*virzz;
2162         work->vir[XX][YY] = work->vir[YY][XX] = 0.25*virxy;
2163         work->vir[XX][ZZ] = work->vir[ZZ][XX] = 0.25*virxz;
2164         work->vir[YY][ZZ] = work->vir[ZZ][YY] = 0.25*viryz;
2165
2166         /* This energy should be corrected for a charged system */
2167         work->energy = 0.5*energy;
2168     }
2169
2170     /* Return the loop count */
2171     return local_ndata[YY]*local_ndata[XX];
2172 }
2173
2174 static void get_pme_ener_vir(const gmx_pme_t pme, int nthread,
2175                              real *mesh_energy, matrix vir)
2176 {
2177     /* This function sums output over threads
2178      * and should therefore only be called after thread synchronization.
2179      */
2180     int thread;
2181
2182     *mesh_energy = pme->work[0].energy;
2183     copy_mat(pme->work[0].vir, vir);
2184
2185     for (thread = 1; thread < nthread; thread++)
2186     {
2187         *mesh_energy += pme->work[thread].energy;
2188         m_add(vir, pme->work[thread].vir, vir);
2189     }
2190 }
2191
2192 #define DO_FSPLINE(order)                      \
2193     for (ithx = 0; (ithx < order); ithx++)              \
2194     {                                              \
2195         index_x = (i0+ithx)*pny*pnz;               \
2196         tx      = thx[ithx];                       \
2197         dx      = dthx[ithx];                      \
2198                                                \
2199         for (ithy = 0; (ithy < order); ithy++)          \
2200         {                                          \
2201             index_xy = index_x+(j0+ithy)*pnz;      \
2202             ty       = thy[ithy];                  \
2203             dy       = dthy[ithy];                 \
2204             fxy1     = fz1 = 0;                    \
2205                                                \
2206             for (ithz = 0; (ithz < order); ithz++)      \
2207             {                                      \
2208                 gval  = grid[index_xy+(k0+ithz)];  \
2209                 fxy1 += thz[ithz]*gval;            \
2210                 fz1  += dthz[ithz]*gval;           \
2211             }                                      \
2212             fx += dx*ty*fxy1;                      \
2213             fy += tx*dy*fxy1;                      \
2214             fz += tx*ty*fz1;                       \
2215         }                                          \
2216     }
2217
2218
2219 static void gather_f_bsplines(gmx_pme_t pme, real *grid,
2220                               gmx_bool bClearF, pme_atomcomm_t *atc,
2221                               splinedata_t *spline,
2222                               real scale)
2223 {
2224     /* sum forces for local particles */
2225     int     nn, n, ithx, ithy, ithz, i0, j0, k0;
2226     int     index_x, index_xy;
2227     int     nx, ny, nz, pnx, pny, pnz;
2228     int *   idxptr;
2229     real    tx, ty, dx, dy, qn;
2230     real    fx, fy, fz, gval;
2231     real    fxy1, fz1;
2232     real    *thx, *thy, *thz, *dthx, *dthy, *dthz;
2233     int     norder;
2234     real    rxx, ryx, ryy, rzx, rzy, rzz;
2235     int     order;
2236
2237     pme_spline_work_t *work;
2238
2239 #if defined PME_SIMD4_SPREAD_GATHER && !defined PME_SIMD4_UNALIGNED
2240     real           thz_buffer[12],  *thz_aligned;
2241     real           dthz_buffer[12], *dthz_aligned;
2242
2243     thz_aligned  = gmx_simd4_align_real(thz_buffer);
2244     dthz_aligned = gmx_simd4_align_real(dthz_buffer);
2245 #endif
2246
2247     work = pme->spline_work;
2248
2249     order = pme->pme_order;
2250     thx   = spline->theta[XX];
2251     thy   = spline->theta[YY];
2252     thz   = spline->theta[ZZ];
2253     dthx  = spline->dtheta[XX];
2254     dthy  = spline->dtheta[YY];
2255     dthz  = spline->dtheta[ZZ];
2256     nx    = pme->nkx;
2257     ny    = pme->nky;
2258     nz    = pme->nkz;
2259     pnx   = pme->pmegrid_nx;
2260     pny   = pme->pmegrid_ny;
2261     pnz   = pme->pmegrid_nz;
2262
2263     rxx   = pme->recipbox[XX][XX];
2264     ryx   = pme->recipbox[YY][XX];
2265     ryy   = pme->recipbox[YY][YY];
2266     rzx   = pme->recipbox[ZZ][XX];
2267     rzy   = pme->recipbox[ZZ][YY];
2268     rzz   = pme->recipbox[ZZ][ZZ];
2269
2270     for (nn = 0; nn < spline->n; nn++)
2271     {
2272         n  = spline->ind[nn];
2273         qn = scale*atc->q[n];
2274
2275         if (bClearF)
2276         {
2277             atc->f[n][XX] = 0;
2278             atc->f[n][YY] = 0;
2279             atc->f[n][ZZ] = 0;
2280         }
2281         if (qn != 0)
2282         {
2283             fx     = 0;
2284             fy     = 0;
2285             fz     = 0;
2286             idxptr = atc->idx[n];
2287             norder = nn*order;
2288
2289             i0   = idxptr[XX];
2290             j0   = idxptr[YY];
2291             k0   = idxptr[ZZ];
2292
2293             /* Pointer arithmetic alert, next six statements */
2294             thx  = spline->theta[XX] + norder;
2295             thy  = spline->theta[YY] + norder;
2296             thz  = spline->theta[ZZ] + norder;
2297             dthx = spline->dtheta[XX] + norder;
2298             dthy = spline->dtheta[YY] + norder;
2299             dthz = spline->dtheta[ZZ] + norder;
2300
2301             switch (order)
2302             {
2303                 case 4:
2304 #ifdef PME_SIMD4_SPREAD_GATHER
2305 #ifdef PME_SIMD4_UNALIGNED
2306 #define PME_GATHER_F_SIMD4_ORDER4
2307 #else
2308 #define PME_GATHER_F_SIMD4_ALIGNED
2309 #define PME_ORDER 4
2310 #endif
2311 #include "pme_simd4.h"
2312 #else
2313                     DO_FSPLINE(4);
2314 #endif
2315                     break;
2316                 case 5:
2317 #ifdef PME_SIMD4_SPREAD_GATHER
2318 #define PME_GATHER_F_SIMD4_ALIGNED
2319 #define PME_ORDER 5
2320 #include "pme_simd4.h"
2321 #else
2322                     DO_FSPLINE(5);
2323 #endif
2324                     break;
2325                 default:
2326                     DO_FSPLINE(order);
2327                     break;
2328             }
2329
2330             atc->f[n][XX] += -qn*( fx*nx*rxx );
2331             atc->f[n][YY] += -qn*( fx*nx*ryx + fy*ny*ryy );
2332             atc->f[n][ZZ] += -qn*( fx*nx*rzx + fy*ny*rzy + fz*nz*rzz );
2333         }
2334     }
2335     /* Since the energy and not forces are interpolated
2336      * the net force might not be exactly zero.
2337      * This can be solved by also interpolating F, but
2338      * that comes at a cost.
2339      * A better hack is to remove the net force every
2340      * step, but that must be done at a higher level
2341      * since this routine doesn't see all atoms if running
2342      * in parallel. Don't know how important it is?  EL 990726
2343      */
2344 }
2345
2346
2347 static real gather_energy_bsplines(gmx_pme_t pme, real *grid,
2348                                    pme_atomcomm_t *atc)
2349 {
2350     splinedata_t *spline;
2351     int     n, ithx, ithy, ithz, i0, j0, k0;
2352     int     index_x, index_xy;
2353     int *   idxptr;
2354     real    energy, pot, tx, ty, qn, gval;
2355     real    *thx, *thy, *thz;
2356     int     norder;
2357     int     order;
2358
2359     spline = &atc->spline[0];
2360
2361     order = pme->pme_order;
2362
2363     energy = 0;
2364     for (n = 0; (n < atc->n); n++)
2365     {
2366         qn      = atc->q[n];
2367
2368         if (qn != 0)
2369         {
2370             idxptr = atc->idx[n];
2371             norder = n*order;
2372
2373             i0   = idxptr[XX];
2374             j0   = idxptr[YY];
2375             k0   = idxptr[ZZ];
2376
2377             /* Pointer arithmetic alert, next three statements */
2378             thx  = spline->theta[XX] + norder;
2379             thy  = spline->theta[YY] + norder;
2380             thz  = spline->theta[ZZ] + norder;
2381
2382             pot = 0;
2383             for (ithx = 0; (ithx < order); ithx++)
2384             {
2385                 index_x = (i0+ithx)*pme->pmegrid_ny*pme->pmegrid_nz;
2386                 tx      = thx[ithx];
2387
2388                 for (ithy = 0; (ithy < order); ithy++)
2389                 {
2390                     index_xy = index_x+(j0+ithy)*pme->pmegrid_nz;
2391                     ty       = thy[ithy];
2392
2393                     for (ithz = 0; (ithz < order); ithz++)
2394                     {
2395                         gval  = grid[index_xy+(k0+ithz)];
2396                         pot  += tx*ty*thz[ithz]*gval;
2397                     }
2398
2399                 }
2400             }
2401
2402             energy += pot*qn;
2403         }
2404     }
2405
2406     return energy;
2407 }
2408
2409 /* Macro to force loop unrolling by fixing order.
2410  * This gives a significant performance gain.
2411  */
2412 #define CALC_SPLINE(order)                     \
2413     {                                              \
2414         int j, k, l;                                 \
2415         real dr, div;                               \
2416         real data[PME_ORDER_MAX];                  \
2417         real ddata[PME_ORDER_MAX];                 \
2418                                                \
2419         for (j = 0; (j < DIM); j++)                     \
2420         {                                          \
2421             dr  = xptr[j];                         \
2422                                                \
2423             /* dr is relative offset from lower cell limit */ \
2424             data[order-1] = 0;                     \
2425             data[1]       = dr;                          \
2426             data[0]       = 1 - dr;                      \
2427                                                \
2428             for (k = 3; (k < order); k++)               \
2429             {                                      \
2430                 div       = 1.0/(k - 1.0);               \
2431                 data[k-1] = div*dr*data[k-2];      \
2432                 for (l = 1; (l < (k-1)); l++)           \
2433                 {                                  \
2434                     data[k-l-1] = div*((dr+l)*data[k-l-2]+(k-l-dr)* \
2435                                        data[k-l-1]);                \
2436                 }                                  \
2437                 data[0] = div*(1-dr)*data[0];      \
2438             }                                      \
2439             /* differentiate */                    \
2440             ddata[0] = -data[0];                   \
2441             for (k = 1; (k < order); k++)               \
2442             {                                      \
2443                 ddata[k] = data[k-1] - data[k];    \
2444             }                                      \
2445                                                \
2446             div           = 1.0/(order - 1);                 \
2447             data[order-1] = div*dr*data[order-2];  \
2448             for (l = 1; (l < (order-1)); l++)           \
2449             {                                      \
2450                 data[order-l-1] = div*((dr+l)*data[order-l-2]+    \
2451                                        (order-l-dr)*data[order-l-1]); \
2452             }                                      \
2453             data[0] = div*(1 - dr)*data[0];        \
2454                                                \
2455             for (k = 0; k < order; k++)                 \
2456             {                                      \
2457                 theta[j][i*order+k]  = data[k];    \
2458                 dtheta[j][i*order+k] = ddata[k];   \
2459             }                                      \
2460         }                                          \
2461     }
2462
2463 void make_bsplines(splinevec theta, splinevec dtheta, int order,
2464                    rvec fractx[], int nr, int ind[], real charge[],
2465                    gmx_bool bFreeEnergy)
2466 {
2467     /* construct splines for local atoms */
2468     int  i, ii;
2469     real *xptr;
2470
2471     for (i = 0; i < nr; i++)
2472     {
2473         /* With free energy we do not use the charge check.
2474          * In most cases this will be more efficient than calling make_bsplines
2475          * twice, since usually more than half the particles have charges.
2476          */
2477         ii = ind[i];
2478         if (bFreeEnergy || charge[ii] != 0.0)
2479         {
2480             xptr = fractx[ii];
2481             switch (order)
2482             {
2483                 case 4:  CALC_SPLINE(4);     break;
2484                 case 5:  CALC_SPLINE(5);     break;
2485                 default: CALC_SPLINE(order); break;
2486             }
2487         }
2488     }
2489 }
2490
2491
2492 void make_dft_mod(real *mod, real *data, int ndata)
2493 {
2494     int i, j;
2495     real sc, ss, arg;
2496
2497     for (i = 0; i < ndata; i++)
2498     {
2499         sc = ss = 0;
2500         for (j = 0; j < ndata; j++)
2501         {
2502             arg = (2.0*M_PI*i*j)/ndata;
2503             sc += data[j]*cos(arg);
2504             ss += data[j]*sin(arg);
2505         }
2506         mod[i] = sc*sc+ss*ss;
2507     }
2508     for (i = 0; i < ndata; i++)
2509     {
2510         if (mod[i] < 1e-7)
2511         {
2512             mod[i] = (mod[i-1]+mod[i+1])*0.5;
2513         }
2514     }
2515 }
2516
2517
2518 static void make_bspline_moduli(splinevec bsp_mod,
2519                                 int nx, int ny, int nz, int order)
2520 {
2521     int nmax = max(nx, max(ny, nz));
2522     real *data, *ddata, *bsp_data;
2523     int i, k, l;
2524     real div;
2525
2526     snew(data, order);
2527     snew(ddata, order);
2528     snew(bsp_data, nmax);
2529
2530     data[order-1] = 0;
2531     data[1]       = 0;
2532     data[0]       = 1;
2533
2534     for (k = 3; k < order; k++)
2535     {
2536         div       = 1.0/(k-1.0);
2537         data[k-1] = 0;
2538         for (l = 1; l < (k-1); l++)
2539         {
2540             data[k-l-1] = div*(l*data[k-l-2]+(k-l)*data[k-l-1]);
2541         }
2542         data[0] = div*data[0];
2543     }
2544     /* differentiate */
2545     ddata[0] = -data[0];
2546     for (k = 1; k < order; k++)
2547     {
2548         ddata[k] = data[k-1]-data[k];
2549     }
2550     div           = 1.0/(order-1);
2551     data[order-1] = 0;
2552     for (l = 1; l < (order-1); l++)
2553     {
2554         data[order-l-1] = div*(l*data[order-l-2]+(order-l)*data[order-l-1]);
2555     }
2556     data[0] = div*data[0];
2557
2558     for (i = 0; i < nmax; i++)
2559     {
2560         bsp_data[i] = 0;
2561     }
2562     for (i = 1; i <= order; i++)
2563     {
2564         bsp_data[i] = data[i-1];
2565     }
2566
2567     make_dft_mod(bsp_mod[XX], bsp_data, nx);
2568     make_dft_mod(bsp_mod[YY], bsp_data, ny);
2569     make_dft_mod(bsp_mod[ZZ], bsp_data, nz);
2570
2571     sfree(data);
2572     sfree(ddata);
2573     sfree(bsp_data);
2574 }
2575
2576
2577 /* Return the P3M optimal influence function */
2578 static double do_p3m_influence(double z, int order)
2579 {
2580     double z2, z4;
2581
2582     z2 = z*z;
2583     z4 = z2*z2;
2584
2585     /* The formula and most constants can be found in:
2586      * Ballenegger et al., JCTC 8, 936 (2012)
2587      */
2588     switch (order)
2589     {
2590         case 2:
2591             return 1.0 - 2.0*z2/3.0;
2592             break;
2593         case 3:
2594             return 1.0 - z2 + 2.0*z4/15.0;
2595             break;
2596         case 4:
2597             return 1.0 - 4.0*z2/3.0 + 2.0*z4/5.0 + 4.0*z2*z4/315.0;
2598             break;
2599         case 5:
2600             return 1.0 - 5.0*z2/3.0 + 7.0*z4/9.0 - 17.0*z2*z4/189.0 + 2.0*z4*z4/2835.0;
2601             break;
2602         case 6:
2603             return 1.0 - 2.0*z2 + 19.0*z4/15.0 - 256.0*z2*z4/945.0 + 62.0*z4*z4/4725.0 + 4.0*z2*z4*z4/155925.0;
2604             break;
2605         case 7:
2606             return 1.0 - 7.0*z2/3.0 + 28.0*z4/15.0 - 16.0*z2*z4/27.0 + 26.0*z4*z4/405.0 - 2.0*z2*z4*z4/1485.0 + 4.0*z4*z4*z4/6081075.0;
2607         case 8:
2608             return 1.0 - 8.0*z2/3.0 + 116.0*z4/45.0 - 344.0*z2*z4/315.0 + 914.0*z4*z4/4725.0 - 248.0*z4*z4*z2/22275.0 + 21844.0*z4*z4*z4/212837625.0 - 8.0*z4*z4*z4*z2/638512875.0;
2609             break;
2610     }
2611
2612     return 0.0;
2613 }
2614
2615 /* Calculate the P3M B-spline moduli for one dimension */
2616 static void make_p3m_bspline_moduli_dim(real *bsp_mod, int n, int order)
2617 {
2618     double zarg, zai, sinzai, infl;
2619     int    maxk, i;
2620
2621     if (order > 8)
2622     {
2623         gmx_fatal(FARGS, "The current P3M code only supports orders up to 8");
2624     }
2625
2626     zarg = M_PI/n;
2627
2628     maxk = (n + 1)/2;
2629
2630     for (i = -maxk; i < 0; i++)
2631     {
2632         zai          = zarg*i;
2633         sinzai       = sin(zai);
2634         infl         = do_p3m_influence(sinzai, order);
2635         bsp_mod[n+i] = infl*infl*pow(sinzai/zai, -2.0*order);
2636     }
2637     bsp_mod[0] = 1.0;
2638     for (i = 1; i < maxk; i++)
2639     {
2640         zai        = zarg*i;
2641         sinzai     = sin(zai);
2642         infl       = do_p3m_influence(sinzai, order);
2643         bsp_mod[i] = infl*infl*pow(sinzai/zai, -2.0*order);
2644     }
2645 }
2646
2647 /* Calculate the P3M B-spline moduli */
2648 static void make_p3m_bspline_moduli(splinevec bsp_mod,
2649                                     int nx, int ny, int nz, int order)
2650 {
2651     make_p3m_bspline_moduli_dim(bsp_mod[XX], nx, order);
2652     make_p3m_bspline_moduli_dim(bsp_mod[YY], ny, order);
2653     make_p3m_bspline_moduli_dim(bsp_mod[ZZ], nz, order);
2654 }
2655
2656
2657 static void setup_coordinate_communication(pme_atomcomm_t *atc)
2658 {
2659     int nslab, n, i;
2660     int fw, bw;
2661
2662     nslab = atc->nslab;
2663
2664     n = 0;
2665     for (i = 1; i <= nslab/2; i++)
2666     {
2667         fw = (atc->nodeid + i) % nslab;
2668         bw = (atc->nodeid - i + nslab) % nslab;
2669         if (n < nslab - 1)
2670         {
2671             atc->node_dest[n] = fw;
2672             atc->node_src[n]  = bw;
2673             n++;
2674         }
2675         if (n < nslab - 1)
2676         {
2677             atc->node_dest[n] = bw;
2678             atc->node_src[n]  = fw;
2679             n++;
2680         }
2681     }
2682 }
2683
2684 int gmx_pme_destroy(FILE *log, gmx_pme_t *pmedata)
2685 {
2686     int thread;
2687
2688     if (NULL != log)
2689     {
2690         fprintf(log, "Destroying PME data structures.\n");
2691     }
2692
2693     sfree((*pmedata)->nnx);
2694     sfree((*pmedata)->nny);
2695     sfree((*pmedata)->nnz);
2696
2697     pmegrids_destroy(&(*pmedata)->pmegridA);
2698
2699     sfree((*pmedata)->fftgridA);
2700     sfree((*pmedata)->cfftgridA);
2701     gmx_parallel_3dfft_destroy((*pmedata)->pfft_setupA);
2702
2703     if ((*pmedata)->pmegridB.grid.grid != NULL)
2704     {
2705         pmegrids_destroy(&(*pmedata)->pmegridB);
2706         sfree((*pmedata)->fftgridB);
2707         sfree((*pmedata)->cfftgridB);
2708         gmx_parallel_3dfft_destroy((*pmedata)->pfft_setupB);
2709     }
2710     for (thread = 0; thread < (*pmedata)->nthread; thread++)
2711     {
2712         free_work(&(*pmedata)->work[thread]);
2713     }
2714     sfree((*pmedata)->work);
2715
2716     sfree(*pmedata);
2717     *pmedata = NULL;
2718
2719     return 0;
2720 }
2721
2722 static int mult_up(int n, int f)
2723 {
2724     return ((n + f - 1)/f)*f;
2725 }
2726
2727
2728 static double pme_load_imbalance(gmx_pme_t pme)
2729 {
2730     int    nma, nmi;
2731     double n1, n2, n3;
2732
2733     nma = pme->nnodes_major;
2734     nmi = pme->nnodes_minor;
2735
2736     n1 = mult_up(pme->nkx, nma)*mult_up(pme->nky, nmi)*pme->nkz;
2737     n2 = mult_up(pme->nkx, nma)*mult_up(pme->nkz, nmi)*pme->nky;
2738     n3 = mult_up(pme->nky, nma)*mult_up(pme->nkz, nmi)*pme->nkx;
2739
2740     /* pme_solve is roughly double the cost of an fft */
2741
2742     return (n1 + n2 + 3*n3)/(double)(6*pme->nkx*pme->nky*pme->nkz);
2743 }
2744
2745 static void init_atomcomm(gmx_pme_t pme, pme_atomcomm_t *atc,
2746                           int dimind, gmx_bool bSpread)
2747 {
2748     int nk, k, s, thread;
2749
2750     atc->dimind    = dimind;
2751     atc->nslab     = 1;
2752     atc->nodeid    = 0;
2753     atc->pd_nalloc = 0;
2754 #ifdef GMX_MPI
2755     if (pme->nnodes > 1)
2756     {
2757         atc->mpi_comm = pme->mpi_comm_d[dimind];
2758         MPI_Comm_size(atc->mpi_comm, &atc->nslab);
2759         MPI_Comm_rank(atc->mpi_comm, &atc->nodeid);
2760     }
2761     if (debug)
2762     {
2763         fprintf(debug, "For PME atom communication in dimind %d: nslab %d rank %d\n", atc->dimind, atc->nslab, atc->nodeid);
2764     }
2765 #endif
2766
2767     atc->bSpread   = bSpread;
2768     atc->pme_order = pme->pme_order;
2769
2770     if (atc->nslab > 1)
2771     {
2772         /* These three allocations are not required for particle decomp. */
2773         snew(atc->node_dest, atc->nslab);
2774         snew(atc->node_src, atc->nslab);
2775         setup_coordinate_communication(atc);
2776
2777         snew(atc->count_thread, pme->nthread);
2778         for (thread = 0; thread < pme->nthread; thread++)
2779         {
2780             snew(atc->count_thread[thread], atc->nslab);
2781         }
2782         atc->count = atc->count_thread[0];
2783         snew(atc->rcount, atc->nslab);
2784         snew(atc->buf_index, atc->nslab);
2785     }
2786
2787     atc->nthread = pme->nthread;
2788     if (atc->nthread > 1)
2789     {
2790         snew(atc->thread_plist, atc->nthread);
2791     }
2792     snew(atc->spline, atc->nthread);
2793     for (thread = 0; thread < atc->nthread; thread++)
2794     {
2795         if (atc->nthread > 1)
2796         {
2797             snew(atc->thread_plist[thread].n, atc->nthread+2*GMX_CACHE_SEP);
2798             atc->thread_plist[thread].n += GMX_CACHE_SEP;
2799         }
2800         snew(atc->spline[thread].thread_one, pme->nthread);
2801         atc->spline[thread].thread_one[thread] = 1;
2802     }
2803 }
2804
2805 static void
2806 init_overlap_comm(pme_overlap_t *  ol,
2807                   int              norder,
2808 #ifdef GMX_MPI
2809                   MPI_Comm         comm,
2810 #endif
2811                   int              nnodes,
2812                   int              nodeid,
2813                   int              ndata,
2814                   int              commplainsize)
2815 {
2816     int lbnd, rbnd, maxlr, b, i;
2817     int exten;
2818     int nn, nk;
2819     pme_grid_comm_t *pgc;
2820     gmx_bool bCont;
2821     int fft_start, fft_end, send_index1, recv_index1;
2822 #ifdef GMX_MPI
2823     MPI_Status stat;
2824
2825     ol->mpi_comm = comm;
2826 #endif
2827
2828     ol->nnodes = nnodes;
2829     ol->nodeid = nodeid;
2830
2831     /* Linear translation of the PME grid won't affect reciprocal space
2832      * calculations, so to optimize we only interpolate "upwards",
2833      * which also means we only have to consider overlap in one direction.
2834      * I.e., particles on this node might also be spread to grid indices
2835      * that belong to higher nodes (modulo nnodes)
2836      */
2837
2838     snew(ol->s2g0, ol->nnodes+1);
2839     snew(ol->s2g1, ol->nnodes);
2840     if (debug)
2841     {
2842         fprintf(debug, "PME slab boundaries:");
2843     }
2844     for (i = 0; i < nnodes; i++)
2845     {
2846         /* s2g0 the local interpolation grid start.
2847          * s2g1 the local interpolation grid end.
2848          * Because grid overlap communication only goes forward,
2849          * the grid the slabs for fft's should be rounded down.
2850          */
2851         ol->s2g0[i] = ( i   *ndata + 0       )/nnodes;
2852         ol->s2g1[i] = ((i+1)*ndata + nnodes-1)/nnodes + norder - 1;
2853
2854         if (debug)
2855         {
2856             fprintf(debug, "  %3d %3d", ol->s2g0[i], ol->s2g1[i]);
2857         }
2858     }
2859     ol->s2g0[nnodes] = ndata;
2860     if (debug)
2861     {
2862         fprintf(debug, "\n");
2863     }
2864
2865     /* Determine with how many nodes we need to communicate the grid overlap */
2866     b = 0;
2867     do
2868     {
2869         b++;
2870         bCont = FALSE;
2871         for (i = 0; i < nnodes; i++)
2872         {
2873             if ((i+b <  nnodes && ol->s2g1[i] > ol->s2g0[i+b]) ||
2874                 (i+b >= nnodes && ol->s2g1[i] > ol->s2g0[i+b-nnodes] + ndata))
2875             {
2876                 bCont = TRUE;
2877             }
2878         }
2879     }
2880     while (bCont && b < nnodes);
2881     ol->noverlap_nodes = b - 1;
2882
2883     snew(ol->send_id, ol->noverlap_nodes);
2884     snew(ol->recv_id, ol->noverlap_nodes);
2885     for (b = 0; b < ol->noverlap_nodes; b++)
2886     {
2887         ol->send_id[b] = (ol->nodeid + (b + 1)) % ol->nnodes;
2888         ol->recv_id[b] = (ol->nodeid - (b + 1) + ol->nnodes) % ol->nnodes;
2889     }
2890     snew(ol->comm_data, ol->noverlap_nodes);
2891
2892     ol->send_size = 0;
2893     for (b = 0; b < ol->noverlap_nodes; b++)
2894     {
2895         pgc = &ol->comm_data[b];
2896         /* Send */
2897         fft_start        = ol->s2g0[ol->send_id[b]];
2898         fft_end          = ol->s2g0[ol->send_id[b]+1];
2899         if (ol->send_id[b] < nodeid)
2900         {
2901             fft_start += ndata;
2902             fft_end   += ndata;
2903         }
2904         send_index1       = ol->s2g1[nodeid];
2905         send_index1       = min(send_index1, fft_end);
2906         pgc->send_index0  = fft_start;
2907         pgc->send_nindex  = max(0, send_index1 - pgc->send_index0);
2908         ol->send_size    += pgc->send_nindex;
2909
2910         /* We always start receiving to the first index of our slab */
2911         fft_start        = ol->s2g0[ol->nodeid];
2912         fft_end          = ol->s2g0[ol->nodeid+1];
2913         recv_index1      = ol->s2g1[ol->recv_id[b]];
2914         if (ol->recv_id[b] > nodeid)
2915         {
2916             recv_index1 -= ndata;
2917         }
2918         recv_index1      = min(recv_index1, fft_end);
2919         pgc->recv_index0 = fft_start;
2920         pgc->recv_nindex = max(0, recv_index1 - pgc->recv_index0);
2921     }
2922
2923 #ifdef GMX_MPI
2924     /* Communicate the buffer sizes to receive */
2925     for (b = 0; b < ol->noverlap_nodes; b++)
2926     {
2927         MPI_Sendrecv(&ol->send_size, 1, MPI_INT, ol->send_id[b], b,
2928                      &ol->comm_data[b].recv_size, 1, MPI_INT, ol->recv_id[b], b,
2929                      ol->mpi_comm, &stat);
2930     }
2931 #endif
2932
2933     /* For non-divisible grid we need pme_order iso pme_order-1 */
2934     snew(ol->sendbuf, norder*commplainsize);
2935     snew(ol->recvbuf, norder*commplainsize);
2936 }
2937
2938 static void
2939 make_gridindex5_to_localindex(int n, int local_start, int local_range,
2940                               int **global_to_local,
2941                               real **fraction_shift)
2942 {
2943     int i;
2944     int * gtl;
2945     real * fsh;
2946
2947     snew(gtl, 5*n);
2948     snew(fsh, 5*n);
2949     for (i = 0; (i < 5*n); i++)
2950     {
2951         /* Determine the global to local grid index */
2952         gtl[i] = (i - local_start + n) % n;
2953         /* For coordinates that fall within the local grid the fraction
2954          * is correct, we don't need to shift it.
2955          */
2956         fsh[i] = 0;
2957         if (local_range < n)
2958         {
2959             /* Due to rounding issues i could be 1 beyond the lower or
2960              * upper boundary of the local grid. Correct the index for this.
2961              * If we shift the index, we need to shift the fraction by
2962              * the same amount in the other direction to not affect
2963              * the weights.
2964              * Note that due to this shifting the weights at the end of
2965              * the spline might change, but that will only involve values
2966              * between zero and values close to the precision of a real,
2967              * which is anyhow the accuracy of the whole mesh calculation.
2968              */
2969             /* With local_range=0 we should not change i=local_start */
2970             if (i % n != local_start)
2971             {
2972                 if (gtl[i] == n-1)
2973                 {
2974                     gtl[i] = 0;
2975                     fsh[i] = -1;
2976                 }
2977                 else if (gtl[i] == local_range)
2978                 {
2979                     gtl[i] = local_range - 1;
2980                     fsh[i] = 1;
2981                 }
2982             }
2983         }
2984     }
2985
2986     *global_to_local = gtl;
2987     *fraction_shift  = fsh;
2988 }
2989
2990 static pme_spline_work_t *make_pme_spline_work(int order)
2991 {
2992     pme_spline_work_t *work;
2993
2994 #ifdef PME_SIMD4_SPREAD_GATHER
2995     real         tmp[12], *tmp_aligned;
2996     gmx_simd4_pr zero_S;
2997     gmx_simd4_pr real_mask_S0, real_mask_S1;
2998     int          of, i;
2999
3000     snew_aligned(work, 1, SIMD4_ALIGNMENT);
3001
3002     tmp_aligned = gmx_simd4_align_real(tmp);
3003
3004     zero_S = gmx_simd4_setzero_pr();
3005
3006     /* Generate bit masks to mask out the unused grid entries,
3007      * as we only operate on order of the 8 grid entries that are
3008      * load into 2 SIMD registers.
3009      */
3010     for (of = 0; of < 8-(order-1); of++)
3011     {
3012         for (i = 0; i < 8; i++)
3013         {
3014             tmp_aligned[i] = (i >= of && i < of+order ? -1.0 : 1.0);
3015         }
3016         real_mask_S0      = gmx_simd4_load_pr(tmp_aligned);
3017         real_mask_S1      = gmx_simd4_load_pr(tmp_aligned+4);
3018         work->mask_S0[of] = gmx_simd4_cmplt_pr(real_mask_S0, zero_S);
3019         work->mask_S1[of] = gmx_simd4_cmplt_pr(real_mask_S1, zero_S);
3020     }
3021 #else
3022     work = NULL;
3023 #endif
3024
3025     return work;
3026 }
3027
3028 void gmx_pme_check_restrictions(int pme_order,
3029                                 int nkx, int nky, int nkz,
3030                                 int nnodes_major,
3031                                 int nnodes_minor,
3032                                 gmx_bool bUseThreads,
3033                                 gmx_bool bFatal,
3034                                 gmx_bool *bValidSettings)
3035 {
3036     if (pme_order > PME_ORDER_MAX)
3037     {
3038         if (!bFatal)
3039         {
3040             *bValidSettings = FALSE;
3041             return;
3042         }
3043         gmx_fatal(FARGS, "pme_order (%d) is larger than the maximum allowed value (%d). Modify and recompile the code if you really need such a high order.",
3044                   pme_order, PME_ORDER_MAX);
3045     }
3046
3047     if (nkx <= pme_order*(nnodes_major > 1 ? 2 : 1) ||
3048         nky <= pme_order*(nnodes_minor > 1 ? 2 : 1) ||
3049         nkz <= pme_order)
3050     {
3051         if (!bFatal)
3052         {
3053             *bValidSettings = FALSE;
3054             return;
3055         }
3056         gmx_fatal(FARGS, "The PME grid sizes need to be larger than pme_order (%d) and for dimensions with domain decomposition larger than 2*pme_order",
3057                   pme_order);
3058     }
3059
3060     /* Check for a limitation of the (current) sum_fftgrid_dd code.
3061      * We only allow multiple communication pulses in dim 1, not in dim 0.
3062      */
3063     if (bUseThreads && (nkx < nnodes_major*pme_order &&
3064                         nkx != nnodes_major*(pme_order - 1)))
3065     {
3066         if (!bFatal)
3067         {
3068             *bValidSettings = FALSE;
3069             return;
3070         }
3071         gmx_fatal(FARGS, "The number of PME grid lines per node along x is %g. But when using OpenMP threads, the number of grid lines per node along x should be >= pme_order (%d) or = pmeorder-1. To resolve this issue, use less nodes along x (and possibly more along y and/or z) by specifying -dd manually.",
3072                   nkx/(double)nnodes_major, pme_order);
3073     }
3074
3075     if (bValidSettings != NULL)
3076     {
3077         *bValidSettings = TRUE;
3078     }
3079
3080     return;
3081 }
3082
3083 int gmx_pme_init(gmx_pme_t *         pmedata,
3084                  t_commrec *         cr,
3085                  int                 nnodes_major,
3086                  int                 nnodes_minor,
3087                  t_inputrec *        ir,
3088                  int                 homenr,
3089                  gmx_bool            bFreeEnergy,
3090                  gmx_bool            bReproducible,
3091                  int                 nthread)
3092 {
3093     gmx_pme_t pme = NULL;
3094
3095     int  use_threads, sum_use_threads;
3096     ivec ndata;
3097
3098     if (debug)
3099     {
3100         fprintf(debug, "Creating PME data structures.\n");
3101     }
3102     snew(pme, 1);
3103
3104     pme->redist_init         = FALSE;
3105     pme->sum_qgrid_tmp       = NULL;
3106     pme->sum_qgrid_dd_tmp    = NULL;
3107     pme->buf_nalloc          = 0;
3108     pme->redist_buf_nalloc   = 0;
3109
3110     pme->nnodes              = 1;
3111     pme->bPPnode             = TRUE;
3112
3113     pme->nnodes_major        = nnodes_major;
3114     pme->nnodes_minor        = nnodes_minor;
3115
3116 #ifdef GMX_MPI
3117     if (nnodes_major*nnodes_minor > 1)
3118     {
3119         pme->mpi_comm = cr->mpi_comm_mygroup;
3120
3121         MPI_Comm_rank(pme->mpi_comm, &pme->nodeid);
3122         MPI_Comm_size(pme->mpi_comm, &pme->nnodes);
3123         if (pme->nnodes != nnodes_major*nnodes_minor)
3124         {
3125             gmx_incons("PME node count mismatch");
3126         }
3127     }
3128     else
3129     {
3130         pme->mpi_comm = MPI_COMM_NULL;
3131     }
3132 #endif
3133
3134     if (pme->nnodes == 1)
3135     {
3136 #ifdef GMX_MPI
3137         pme->mpi_comm_d[0] = MPI_COMM_NULL;
3138         pme->mpi_comm_d[1] = MPI_COMM_NULL;
3139 #endif
3140         pme->ndecompdim   = 0;
3141         pme->nodeid_major = 0;
3142         pme->nodeid_minor = 0;
3143 #ifdef GMX_MPI
3144         pme->mpi_comm_d[0] = pme->mpi_comm_d[1] = MPI_COMM_NULL;
3145 #endif
3146     }
3147     else
3148     {
3149         if (nnodes_minor == 1)
3150         {
3151 #ifdef GMX_MPI
3152             pme->mpi_comm_d[0] = pme->mpi_comm;
3153             pme->mpi_comm_d[1] = MPI_COMM_NULL;
3154 #endif
3155             pme->ndecompdim   = 1;
3156             pme->nodeid_major = pme->nodeid;
3157             pme->nodeid_minor = 0;
3158
3159         }
3160         else if (nnodes_major == 1)
3161         {
3162 #ifdef GMX_MPI
3163             pme->mpi_comm_d[0] = MPI_COMM_NULL;
3164             pme->mpi_comm_d[1] = pme->mpi_comm;
3165 #endif
3166             pme->ndecompdim   = 1;
3167             pme->nodeid_major = 0;
3168             pme->nodeid_minor = pme->nodeid;
3169         }
3170         else
3171         {
3172             if (pme->nnodes % nnodes_major != 0)
3173             {
3174                 gmx_incons("For 2D PME decomposition, #PME nodes must be divisible by the number of nodes in the major dimension");
3175             }
3176             pme->ndecompdim = 2;
3177
3178 #ifdef GMX_MPI
3179             MPI_Comm_split(pme->mpi_comm, pme->nodeid % nnodes_minor,
3180                            pme->nodeid, &pme->mpi_comm_d[0]);  /* My communicator along major dimension */
3181             MPI_Comm_split(pme->mpi_comm, pme->nodeid/nnodes_minor,
3182                            pme->nodeid, &pme->mpi_comm_d[1]);  /* My communicator along minor dimension */
3183
3184             MPI_Comm_rank(pme->mpi_comm_d[0], &pme->nodeid_major);
3185             MPI_Comm_size(pme->mpi_comm_d[0], &pme->nnodes_major);
3186             MPI_Comm_rank(pme->mpi_comm_d[1], &pme->nodeid_minor);
3187             MPI_Comm_size(pme->mpi_comm_d[1], &pme->nnodes_minor);
3188 #endif
3189         }
3190         pme->bPPnode = (cr->duty & DUTY_PP);
3191     }
3192
3193     pme->nthread = nthread;
3194
3195     /* Check if any of the PME MPI ranks uses threads */
3196     use_threads = (pme->nthread > 1 ? 1 : 0);
3197 #ifdef GMX_MPI
3198     if (pme->nnodes > 1)
3199     {
3200         MPI_Allreduce(&use_threads, &sum_use_threads, 1, MPI_INT,
3201                       MPI_SUM, pme->mpi_comm);
3202     }
3203     else
3204 #endif
3205     {
3206         sum_use_threads = use_threads;
3207     }
3208     pme->bUseThreads = (sum_use_threads > 0);
3209
3210     if (ir->ePBC == epbcSCREW)
3211     {
3212         gmx_fatal(FARGS, "pme does not (yet) work with pbc = screw");
3213     }
3214
3215     pme->bFEP        = ((ir->efep != efepNO) && bFreeEnergy);
3216     pme->nkx         = ir->nkx;
3217     pme->nky         = ir->nky;
3218     pme->nkz         = ir->nkz;
3219     pme->bP3M        = (ir->coulombtype == eelP3M_AD || getenv("GMX_PME_P3M") != NULL);
3220     pme->pme_order   = ir->pme_order;
3221     pme->epsilon_r   = ir->epsilon_r;
3222
3223     /* If we violate restrictions, generate a fatal error here */
3224     gmx_pme_check_restrictions(pme->pme_order,
3225                                pme->nkx, pme->nky, pme->nkz,
3226                                pme->nnodes_major,
3227                                pme->nnodes_minor,
3228                                pme->bUseThreads,
3229                                TRUE,
3230                                NULL);
3231
3232     if (pme->nnodes > 1)
3233     {
3234         double imbal;
3235
3236 #ifdef GMX_MPI
3237         MPI_Type_contiguous(DIM, mpi_type, &(pme->rvec_mpi));
3238         MPI_Type_commit(&(pme->rvec_mpi));
3239 #endif
3240
3241         /* Note that the charge spreading and force gathering, which usually
3242          * takes about the same amount of time as FFT+solve_pme,
3243          * is always fully load balanced
3244          * (unless the charge distribution is inhomogeneous).
3245          */
3246
3247         imbal = pme_load_imbalance(pme);
3248         if (imbal >= 1.2 && pme->nodeid_major == 0 && pme->nodeid_minor == 0)
3249         {
3250             fprintf(stderr,
3251                     "\n"
3252                     "NOTE: The load imbalance in PME FFT and solve is %d%%.\n"
3253                     "      For optimal PME load balancing\n"
3254                     "      PME grid_x (%d) and grid_y (%d) should be divisible by #PME_nodes_x (%d)\n"
3255                     "      and PME grid_y (%d) and grid_z (%d) should be divisible by #PME_nodes_y (%d)\n"
3256                     "\n",
3257                     (int)((imbal-1)*100 + 0.5),
3258                     pme->nkx, pme->nky, pme->nnodes_major,
3259                     pme->nky, pme->nkz, pme->nnodes_minor);
3260         }
3261     }
3262
3263     /* For non-divisible grid we need pme_order iso pme_order-1 */
3264     /* In sum_qgrid_dd x overlap is copied in place: take padding into account.
3265      * y is always copied through a buffer: we don't need padding in z,
3266      * but we do need the overlap in x because of the communication order.
3267      */
3268     init_overlap_comm(&pme->overlap[0], pme->pme_order,
3269 #ifdef GMX_MPI
3270                       pme->mpi_comm_d[0],
3271 #endif
3272                       pme->nnodes_major, pme->nodeid_major,
3273                       pme->nkx,
3274                       (div_round_up(pme->nky, pme->nnodes_minor)+pme->pme_order)*(pme->nkz+pme->pme_order-1));
3275
3276     /* Along overlap dim 1 we can send in multiple pulses in sum_fftgrid_dd.
3277      * We do this with an offset buffer of equal size, so we need to allocate
3278      * extra for the offset. That's what the (+1)*pme->nkz is for.
3279      */
3280     init_overlap_comm(&pme->overlap[1], pme->pme_order,
3281 #ifdef GMX_MPI
3282                       pme->mpi_comm_d[1],
3283 #endif
3284                       pme->nnodes_minor, pme->nodeid_minor,
3285                       pme->nky,
3286                       (div_round_up(pme->nkx, pme->nnodes_major)+pme->pme_order+1)*pme->nkz);
3287
3288     /* Double-check for a limitation of the (current) sum_fftgrid_dd code.
3289      * Note that gmx_pme_check_restrictions checked for this already.
3290      */
3291     if (pme->bUseThreads && pme->overlap[0].noverlap_nodes > 1)
3292     {
3293         gmx_incons("More than one communication pulse required for grid overlap communication along the major dimension while using threads");
3294     }
3295
3296     snew(pme->bsp_mod[XX], pme->nkx);
3297     snew(pme->bsp_mod[YY], pme->nky);
3298     snew(pme->bsp_mod[ZZ], pme->nkz);
3299
3300     /* The required size of the interpolation grid, including overlap.
3301      * The allocated size (pmegrid_n?) might be slightly larger.
3302      */
3303     pme->pmegrid_nx = pme->overlap[0].s2g1[pme->nodeid_major] -
3304         pme->overlap[0].s2g0[pme->nodeid_major];
3305     pme->pmegrid_ny = pme->overlap[1].s2g1[pme->nodeid_minor] -
3306         pme->overlap[1].s2g0[pme->nodeid_minor];
3307     pme->pmegrid_nz_base = pme->nkz;
3308     pme->pmegrid_nz      = pme->pmegrid_nz_base + pme->pme_order - 1;
3309     set_grid_alignment(&pme->pmegrid_nz, pme->pme_order);
3310
3311     pme->pmegrid_start_ix = pme->overlap[0].s2g0[pme->nodeid_major];
3312     pme->pmegrid_start_iy = pme->overlap[1].s2g0[pme->nodeid_minor];
3313     pme->pmegrid_start_iz = 0;
3314
3315     make_gridindex5_to_localindex(pme->nkx,
3316                                   pme->pmegrid_start_ix,
3317                                   pme->pmegrid_nx - (pme->pme_order-1),
3318                                   &pme->nnx, &pme->fshx);
3319     make_gridindex5_to_localindex(pme->nky,
3320                                   pme->pmegrid_start_iy,
3321                                   pme->pmegrid_ny - (pme->pme_order-1),
3322                                   &pme->nny, &pme->fshy);
3323     make_gridindex5_to_localindex(pme->nkz,
3324                                   pme->pmegrid_start_iz,
3325                                   pme->pmegrid_nz_base,
3326                                   &pme->nnz, &pme->fshz);
3327
3328     pmegrids_init(&pme->pmegridA,
3329                   pme->pmegrid_nx, pme->pmegrid_ny, pme->pmegrid_nz,
3330                   pme->pmegrid_nz_base,
3331                   pme->pme_order,
3332                   pme->bUseThreads,
3333                   pme->nthread,
3334                   pme->overlap[0].s2g1[pme->nodeid_major]-pme->overlap[0].s2g0[pme->nodeid_major+1],
3335                   pme->overlap[1].s2g1[pme->nodeid_minor]-pme->overlap[1].s2g0[pme->nodeid_minor+1]);
3336
3337     pme->spline_work = make_pme_spline_work(pme->pme_order);
3338
3339     ndata[0] = pme->nkx;
3340     ndata[1] = pme->nky;
3341     ndata[2] = pme->nkz;
3342
3343     /* This routine will allocate the grid data to fit the FFTs */
3344     gmx_parallel_3dfft_init(&pme->pfft_setupA, ndata,
3345                             &pme->fftgridA, &pme->cfftgridA,
3346                             pme->mpi_comm_d,
3347                             bReproducible, pme->nthread);
3348
3349     if (bFreeEnergy)
3350     {
3351         pmegrids_init(&pme->pmegridB,
3352                       pme->pmegrid_nx, pme->pmegrid_ny, pme->pmegrid_nz,
3353                       pme->pmegrid_nz_base,
3354                       pme->pme_order,
3355                       pme->bUseThreads,
3356                       pme->nthread,
3357                       pme->nkx % pme->nnodes_major != 0,
3358                       pme->nky % pme->nnodes_minor != 0);
3359
3360         gmx_parallel_3dfft_init(&pme->pfft_setupB, ndata,
3361                                 &pme->fftgridB, &pme->cfftgridB,
3362                                 pme->mpi_comm_d,
3363                                 bReproducible, pme->nthread);
3364     }
3365     else
3366     {
3367         pme->pmegridB.grid.grid = NULL;
3368         pme->fftgridB           = NULL;
3369         pme->cfftgridB          = NULL;
3370     }
3371
3372     if (!pme->bP3M)
3373     {
3374         /* Use plain SPME B-spline interpolation */
3375         make_bspline_moduli(pme->bsp_mod, pme->nkx, pme->nky, pme->nkz, pme->pme_order);
3376     }
3377     else
3378     {
3379         /* Use the P3M grid-optimized influence function */
3380         make_p3m_bspline_moduli(pme->bsp_mod, pme->nkx, pme->nky, pme->nkz, pme->pme_order);
3381     }
3382
3383     /* Use atc[0] for spreading */
3384     init_atomcomm(pme, &pme->atc[0], nnodes_major > 1 ? 0 : 1, TRUE);
3385     if (pme->ndecompdim >= 2)
3386     {
3387         init_atomcomm(pme, &pme->atc[1], 1, FALSE);
3388     }
3389
3390     if (pme->nnodes == 1)
3391     {
3392         pme->atc[0].n = homenr;
3393         pme_realloc_atomcomm_things(&pme->atc[0]);
3394     }
3395
3396     {
3397         int thread;
3398
3399         /* Use fft5d, order after FFT is y major, z, x minor */
3400
3401         snew(pme->work, pme->nthread);
3402         for (thread = 0; thread < pme->nthread; thread++)
3403         {
3404             realloc_work(&pme->work[thread], pme->nkx);
3405         }
3406     }
3407
3408     *pmedata = pme;
3409
3410     return 0;
3411 }
3412
3413 static void reuse_pmegrids(const pmegrids_t *old, pmegrids_t *new)
3414 {
3415     int d, t;
3416
3417     for (d = 0; d < DIM; d++)
3418     {
3419         if (new->grid.n[d] > old->grid.n[d])
3420         {
3421             return;
3422         }
3423     }
3424
3425     sfree_aligned(new->grid.grid);
3426     new->grid.grid = old->grid.grid;
3427
3428     if (new->grid_th != NULL && new->nthread == old->nthread)
3429     {
3430         sfree_aligned(new->grid_all);
3431         for (t = 0; t < new->nthread; t++)
3432         {
3433             new->grid_th[t].grid = old->grid_th[t].grid;
3434         }
3435     }
3436 }
3437
3438 int gmx_pme_reinit(gmx_pme_t *         pmedata,
3439                    t_commrec *         cr,
3440                    gmx_pme_t           pme_src,
3441                    const t_inputrec *  ir,
3442                    ivec                grid_size)
3443 {
3444     t_inputrec irc;
3445     int homenr;
3446     int ret;
3447
3448     irc     = *ir;
3449     irc.nkx = grid_size[XX];
3450     irc.nky = grid_size[YY];
3451     irc.nkz = grid_size[ZZ];
3452
3453     if (pme_src->nnodes == 1)
3454     {
3455         homenr = pme_src->atc[0].n;
3456     }
3457     else
3458     {
3459         homenr = -1;
3460     }
3461
3462     ret = gmx_pme_init(pmedata, cr, pme_src->nnodes_major, pme_src->nnodes_minor,
3463                        &irc, homenr, pme_src->bFEP, FALSE, pme_src->nthread);
3464
3465     if (ret == 0)
3466     {
3467         /* We can easily reuse the allocated pme grids in pme_src */
3468         reuse_pmegrids(&pme_src->pmegridA, &(*pmedata)->pmegridA);
3469         /* We would like to reuse the fft grids, but that's harder */
3470     }
3471
3472     return ret;
3473 }
3474
3475
3476 static void copy_local_grid(gmx_pme_t pme,
3477                             pmegrids_t *pmegrids, int thread, real *fftgrid)
3478 {
3479     ivec local_fft_ndata, local_fft_offset, local_fft_size;
3480     int  fft_my, fft_mz;
3481     int  nsx, nsy, nsz;
3482     ivec nf;
3483     int  offx, offy, offz, x, y, z, i0, i0t;
3484     int  d;
3485     pmegrid_t *pmegrid;
3486     real *grid_th;
3487
3488     gmx_parallel_3dfft_real_limits(pme->pfft_setupA,
3489                                    local_fft_ndata,
3490                                    local_fft_offset,
3491                                    local_fft_size);
3492     fft_my = local_fft_size[YY];
3493     fft_mz = local_fft_size[ZZ];
3494
3495     pmegrid = &pmegrids->grid_th[thread];
3496
3497     nsx = pmegrid->s[XX];
3498     nsy = pmegrid->s[YY];
3499     nsz = pmegrid->s[ZZ];
3500
3501     for (d = 0; d < DIM; d++)
3502     {
3503         nf[d] = min(pmegrid->n[d] - (pmegrid->order - 1),
3504                     local_fft_ndata[d] - pmegrid->offset[d]);
3505     }
3506
3507     offx = pmegrid->offset[XX];
3508     offy = pmegrid->offset[YY];
3509     offz = pmegrid->offset[ZZ];
3510
3511     /* Directly copy the non-overlapping parts of the local grids.
3512      * This also initializes the full grid.
3513      */
3514     grid_th = pmegrid->grid;
3515     for (x = 0; x < nf[XX]; x++)
3516     {
3517         for (y = 0; y < nf[YY]; y++)
3518         {
3519             i0  = ((offx + x)*fft_my + (offy + y))*fft_mz + offz;
3520             i0t = (x*nsy + y)*nsz;
3521             for (z = 0; z < nf[ZZ]; z++)
3522             {
3523                 fftgrid[i0+z] = grid_th[i0t+z];
3524             }
3525         }
3526     }
3527 }
3528
3529 static void
3530 reduce_threadgrid_overlap(gmx_pme_t pme,
3531                           const pmegrids_t *pmegrids, int thread,
3532                           real *fftgrid, real *commbuf_x, real *commbuf_y)
3533 {
3534     ivec local_fft_ndata, local_fft_offset, local_fft_size;
3535     int  fft_nx, fft_ny, fft_nz;
3536     int  fft_my, fft_mz;
3537     int  buf_my = -1;
3538     int  nsx, nsy, nsz;
3539     ivec ne;
3540     int  offx, offy, offz, x, y, z, i0, i0t;
3541     int  sx, sy, sz, fx, fy, fz, tx1, ty1, tz1, ox, oy, oz;
3542     gmx_bool bClearBufX, bClearBufY, bClearBufXY, bClearBuf;
3543     gmx_bool bCommX, bCommY;
3544     int  d;
3545     int  thread_f;
3546     const pmegrid_t *pmegrid, *pmegrid_g, *pmegrid_f;
3547     const real *grid_th;
3548     real *commbuf = NULL;
3549
3550     gmx_parallel_3dfft_real_limits(pme->pfft_setupA,
3551                                    local_fft_ndata,
3552                                    local_fft_offset,
3553                                    local_fft_size);
3554     fft_nx = local_fft_ndata[XX];
3555     fft_ny = local_fft_ndata[YY];
3556     fft_nz = local_fft_ndata[ZZ];
3557
3558     fft_my = local_fft_size[YY];
3559     fft_mz = local_fft_size[ZZ];
3560
3561     /* This routine is called when all thread have finished spreading.
3562      * Here each thread sums grid contributions calculated by other threads
3563      * to the thread local grid volume.
3564      * To minimize the number of grid copying operations,
3565      * this routines sums immediately from the pmegrid to the fftgrid.
3566      */
3567
3568     /* Determine which part of the full node grid we should operate on,
3569      * this is our thread local part of the full grid.
3570      */
3571     pmegrid = &pmegrids->grid_th[thread];
3572
3573     for (d = 0; d < DIM; d++)
3574     {
3575         ne[d] = min(pmegrid->offset[d]+pmegrid->n[d]-(pmegrid->order-1),
3576                     local_fft_ndata[d]);
3577     }
3578
3579     offx = pmegrid->offset[XX];
3580     offy = pmegrid->offset[YY];
3581     offz = pmegrid->offset[ZZ];
3582
3583
3584     bClearBufX  = TRUE;
3585     bClearBufY  = TRUE;
3586     bClearBufXY = TRUE;
3587
3588     /* Now loop over all the thread data blocks that contribute
3589      * to the grid region we (our thread) are operating on.
3590      */
3591     /* Note that ffy_nx/y is equal to the number of grid points
3592      * between the first point of our node grid and the one of the next node.
3593      */
3594     for (sx = 0; sx >= -pmegrids->nthread_comm[XX]; sx--)
3595     {
3596         fx     = pmegrid->ci[XX] + sx;
3597         ox     = 0;
3598         bCommX = FALSE;
3599         if (fx < 0)
3600         {
3601             fx    += pmegrids->nc[XX];
3602             ox    -= fft_nx;
3603             bCommX = (pme->nnodes_major > 1);
3604         }
3605         pmegrid_g = &pmegrids->grid_th[fx*pmegrids->nc[YY]*pmegrids->nc[ZZ]];
3606         ox       += pmegrid_g->offset[XX];
3607         if (!bCommX)
3608         {
3609             tx1 = min(ox + pmegrid_g->n[XX], ne[XX]);
3610         }
3611         else
3612         {
3613             tx1 = min(ox + pmegrid_g->n[XX], pme->pme_order);
3614         }
3615
3616         for (sy = 0; sy >= -pmegrids->nthread_comm[YY]; sy--)
3617         {
3618             fy     = pmegrid->ci[YY] + sy;
3619             oy     = 0;
3620             bCommY = FALSE;
3621             if (fy < 0)
3622             {
3623                 fy    += pmegrids->nc[YY];
3624                 oy    -= fft_ny;
3625                 bCommY = (pme->nnodes_minor > 1);
3626             }
3627             pmegrid_g = &pmegrids->grid_th[fy*pmegrids->nc[ZZ]];
3628             oy       += pmegrid_g->offset[YY];
3629             if (!bCommY)
3630             {
3631                 ty1 = min(oy + pmegrid_g->n[YY], ne[YY]);
3632             }
3633             else
3634             {
3635                 ty1 = min(oy + pmegrid_g->n[YY], pme->pme_order);
3636             }
3637
3638             for (sz = 0; sz >= -pmegrids->nthread_comm[ZZ]; sz--)
3639             {
3640                 fz = pmegrid->ci[ZZ] + sz;
3641                 oz = 0;
3642                 if (fz < 0)
3643                 {
3644                     fz += pmegrids->nc[ZZ];
3645                     oz -= fft_nz;
3646                 }
3647                 pmegrid_g = &pmegrids->grid_th[fz];
3648                 oz       += pmegrid_g->offset[ZZ];
3649                 tz1       = min(oz + pmegrid_g->n[ZZ], ne[ZZ]);
3650
3651                 if (sx == 0 && sy == 0 && sz == 0)
3652                 {
3653                     /* We have already added our local contribution
3654                      * before calling this routine, so skip it here.
3655                      */
3656                     continue;
3657                 }
3658
3659                 thread_f = (fx*pmegrids->nc[YY] + fy)*pmegrids->nc[ZZ] + fz;
3660
3661                 pmegrid_f = &pmegrids->grid_th[thread_f];
3662
3663                 grid_th = pmegrid_f->grid;
3664
3665                 nsx = pmegrid_f->s[XX];
3666                 nsy = pmegrid_f->s[YY];
3667                 nsz = pmegrid_f->s[ZZ];
3668
3669 #ifdef DEBUG_PME_REDUCE
3670                 printf("n%d t%d add %d  %2d %2d %2d  %2d %2d %2d  %2d-%2d %2d-%2d, %2d-%2d %2d-%2d, %2d-%2d %2d-%2d\n",
3671                        pme->nodeid, thread, thread_f,
3672                        pme->pmegrid_start_ix,
3673                        pme->pmegrid_start_iy,
3674                        pme->pmegrid_start_iz,
3675                        sx, sy, sz,
3676                        offx-ox, tx1-ox, offx, tx1,
3677                        offy-oy, ty1-oy, offy, ty1,
3678                        offz-oz, tz1-oz, offz, tz1);
3679 #endif
3680
3681                 if (!(bCommX || bCommY))
3682                 {
3683                     /* Copy from the thread local grid to the node grid */
3684                     for (x = offx; x < tx1; x++)
3685                     {
3686                         for (y = offy; y < ty1; y++)
3687                         {
3688                             i0  = (x*fft_my + y)*fft_mz;
3689                             i0t = ((x - ox)*nsy + (y - oy))*nsz - oz;
3690                             for (z = offz; z < tz1; z++)
3691                             {
3692                                 fftgrid[i0+z] += grid_th[i0t+z];
3693                             }
3694                         }
3695                     }
3696                 }
3697                 else
3698                 {
3699                     /* The order of this conditional decides
3700                      * where the corner volume gets stored with x+y decomp.
3701                      */
3702                     if (bCommY)
3703                     {
3704                         commbuf = commbuf_y;
3705                         buf_my  = ty1 - offy;
3706                         if (bCommX)
3707                         {
3708                             /* We index commbuf modulo the local grid size */
3709                             commbuf += buf_my*fft_nx*fft_nz;
3710
3711                             bClearBuf   = bClearBufXY;
3712                             bClearBufXY = FALSE;
3713                         }
3714                         else
3715                         {
3716                             bClearBuf  = bClearBufY;
3717                             bClearBufY = FALSE;
3718                         }
3719                     }
3720                     else
3721                     {
3722                         commbuf    = commbuf_x;
3723                         buf_my     = fft_ny;
3724                         bClearBuf  = bClearBufX;
3725                         bClearBufX = FALSE;
3726                     }
3727
3728                     /* Copy to the communication buffer */
3729                     for (x = offx; x < tx1; x++)
3730                     {
3731                         for (y = offy; y < ty1; y++)
3732                         {
3733                             i0  = (x*buf_my + y)*fft_nz;
3734                             i0t = ((x - ox)*nsy + (y - oy))*nsz - oz;
3735
3736                             if (bClearBuf)
3737                             {
3738                                 /* First access of commbuf, initialize it */
3739                                 for (z = offz; z < tz1; z++)
3740                                 {
3741                                     commbuf[i0+z]  = grid_th[i0t+z];
3742                                 }
3743                             }
3744                             else
3745                             {
3746                                 for (z = offz; z < tz1; z++)
3747                                 {
3748                                     commbuf[i0+z] += grid_th[i0t+z];
3749                                 }
3750                             }
3751                         }
3752                     }
3753                 }
3754             }
3755         }
3756     }
3757 }
3758
3759
3760 static void sum_fftgrid_dd(gmx_pme_t pme, real *fftgrid)
3761 {
3762     ivec local_fft_ndata, local_fft_offset, local_fft_size;
3763     pme_overlap_t *overlap;
3764     int  send_index0, send_nindex;
3765     int  recv_nindex;
3766 #ifdef GMX_MPI
3767     MPI_Status stat;
3768 #endif
3769     int  send_size_y, recv_size_y;
3770     int  ipulse, send_id, recv_id, datasize, gridsize, size_yx;
3771     real *sendptr, *recvptr;
3772     int  x, y, z, indg, indb;
3773
3774     /* Note that this routine is only used for forward communication.
3775      * Since the force gathering, unlike the charge spreading,
3776      * can be trivially parallelized over the particles,
3777      * the backwards process is much simpler and can use the "old"
3778      * communication setup.
3779      */
3780
3781     gmx_parallel_3dfft_real_limits(pme->pfft_setupA,
3782                                    local_fft_ndata,
3783                                    local_fft_offset,
3784                                    local_fft_size);
3785
3786     if (pme->nnodes_minor > 1)
3787     {
3788         /* Major dimension */
3789         overlap = &pme->overlap[1];
3790
3791         if (pme->nnodes_major > 1)
3792         {
3793             size_yx = pme->overlap[0].comm_data[0].send_nindex;
3794         }
3795         else
3796         {
3797             size_yx = 0;
3798         }
3799         datasize = (local_fft_ndata[XX] + size_yx)*local_fft_ndata[ZZ];
3800
3801         send_size_y = overlap->send_size;
3802
3803         for (ipulse = 0; ipulse < overlap->noverlap_nodes; ipulse++)
3804         {
3805             send_id       = overlap->send_id[ipulse];
3806             recv_id       = overlap->recv_id[ipulse];
3807             send_index0   =
3808                 overlap->comm_data[ipulse].send_index0 -
3809                 overlap->comm_data[0].send_index0;
3810             send_nindex   = overlap->comm_data[ipulse].send_nindex;
3811             /* We don't use recv_index0, as we always receive starting at 0 */
3812             recv_nindex   = overlap->comm_data[ipulse].recv_nindex;
3813             recv_size_y   = overlap->comm_data[ipulse].recv_size;
3814
3815             sendptr = overlap->sendbuf + send_index0*local_fft_ndata[ZZ];
3816             recvptr = overlap->recvbuf;
3817
3818 #ifdef GMX_MPI
3819             MPI_Sendrecv(sendptr, send_size_y*datasize, GMX_MPI_REAL,
3820                          send_id, ipulse,
3821                          recvptr, recv_size_y*datasize, GMX_MPI_REAL,
3822                          recv_id, ipulse,
3823                          overlap->mpi_comm, &stat);
3824 #endif
3825
3826             for (x = 0; x < local_fft_ndata[XX]; x++)
3827             {
3828                 for (y = 0; y < recv_nindex; y++)
3829                 {
3830                     indg = (x*local_fft_size[YY] + y)*local_fft_size[ZZ];
3831                     indb = (x*recv_size_y        + y)*local_fft_ndata[ZZ];
3832                     for (z = 0; z < local_fft_ndata[ZZ]; z++)
3833                     {
3834                         fftgrid[indg+z] += recvptr[indb+z];
3835                     }
3836                 }
3837             }
3838
3839             if (pme->nnodes_major > 1)
3840             {
3841                 /* Copy from the received buffer to the send buffer for dim 0 */
3842                 sendptr = pme->overlap[0].sendbuf;
3843                 for (x = 0; x < size_yx; x++)
3844                 {
3845                     for (y = 0; y < recv_nindex; y++)
3846                     {
3847                         indg = (x*local_fft_ndata[YY] + y)*local_fft_ndata[ZZ];
3848                         indb = ((local_fft_ndata[XX] + x)*recv_size_y + y)*local_fft_ndata[ZZ];
3849                         for (z = 0; z < local_fft_ndata[ZZ]; z++)
3850                         {
3851                             sendptr[indg+z] += recvptr[indb+z];
3852                         }
3853                     }
3854                 }
3855             }
3856         }
3857     }
3858
3859     /* We only support a single pulse here.
3860      * This is not a severe limitation, as this code is only used
3861      * with OpenMP and with OpenMP the (PME) domains can be larger.
3862      */
3863     if (pme->nnodes_major > 1)
3864     {
3865         /* Major dimension */
3866         overlap = &pme->overlap[0];
3867
3868         datasize = local_fft_ndata[YY]*local_fft_ndata[ZZ];
3869         gridsize = local_fft_size[YY] *local_fft_size[ZZ];
3870
3871         ipulse = 0;
3872
3873         send_id       = overlap->send_id[ipulse];
3874         recv_id       = overlap->recv_id[ipulse];
3875         send_nindex   = overlap->comm_data[ipulse].send_nindex;
3876         /* We don't use recv_index0, as we always receive starting at 0 */
3877         recv_nindex   = overlap->comm_data[ipulse].recv_nindex;
3878
3879         sendptr = overlap->sendbuf;
3880         recvptr = overlap->recvbuf;
3881
3882         if (debug != NULL)
3883         {
3884             fprintf(debug, "PME fftgrid comm %2d x %2d x %2d\n",
3885                     send_nindex, local_fft_ndata[YY], local_fft_ndata[ZZ]);
3886         }
3887
3888 #ifdef GMX_MPI
3889         MPI_Sendrecv(sendptr, send_nindex*datasize, GMX_MPI_REAL,
3890                      send_id, ipulse,
3891                      recvptr, recv_nindex*datasize, GMX_MPI_REAL,
3892                      recv_id, ipulse,
3893                      overlap->mpi_comm, &stat);
3894 #endif
3895
3896         for (x = 0; x < recv_nindex; x++)
3897         {
3898             for (y = 0; y < local_fft_ndata[YY]; y++)
3899             {
3900                 indg = (x*local_fft_size[YY]  + y)*local_fft_size[ZZ];
3901                 indb = (x*local_fft_ndata[YY] + y)*local_fft_ndata[ZZ];
3902                 for (z = 0; z < local_fft_ndata[ZZ]; z++)
3903                 {
3904                     fftgrid[indg+z] += recvptr[indb+z];
3905                 }
3906             }
3907         }
3908     }
3909 }
3910
3911
3912 static void spread_on_grid(gmx_pme_t pme,
3913                            pme_atomcomm_t *atc, pmegrids_t *grids,
3914                            gmx_bool bCalcSplines, gmx_bool bSpread,
3915                            real *fftgrid)
3916 {
3917     int nthread, thread;
3918 #ifdef PME_TIME_THREADS
3919     gmx_cycles_t c1, c2, c3, ct1a, ct1b, ct1c;
3920     static double cs1     = 0, cs2 = 0, cs3 = 0;
3921     static double cs1a[6] = {0, 0, 0, 0, 0, 0};
3922     static int cnt        = 0;
3923 #endif
3924
3925     nthread = pme->nthread;
3926     assert(nthread > 0);
3927
3928 #ifdef PME_TIME_THREADS
3929     c1 = omp_cyc_start();
3930 #endif
3931     if (bCalcSplines)
3932     {
3933 #pragma omp parallel for num_threads(nthread) schedule(static)
3934         for (thread = 0; thread < nthread; thread++)
3935         {
3936             int start, end;
3937
3938             start = atc->n* thread   /nthread;
3939             end   = atc->n*(thread+1)/nthread;
3940
3941             /* Compute fftgrid index for all atoms,
3942              * with help of some extra variables.
3943              */
3944             calc_interpolation_idx(pme, atc, start, end, thread);
3945         }
3946     }
3947 #ifdef PME_TIME_THREADS
3948     c1   = omp_cyc_end(c1);
3949     cs1 += (double)c1;
3950 #endif
3951
3952 #ifdef PME_TIME_THREADS
3953     c2 = omp_cyc_start();
3954 #endif
3955 #pragma omp parallel for num_threads(nthread) schedule(static)
3956     for (thread = 0; thread < nthread; thread++)
3957     {
3958         splinedata_t *spline;
3959         pmegrid_t *grid = NULL;
3960
3961         /* make local bsplines  */
3962         if (grids == NULL || !pme->bUseThreads)
3963         {
3964             spline = &atc->spline[0];
3965
3966             spline->n = atc->n;
3967
3968             if (bSpread)
3969             {
3970                 grid = &grids->grid;
3971             }
3972         }
3973         else
3974         {
3975             spline = &atc->spline[thread];
3976
3977             if (grids->nthread == 1)
3978             {
3979                 /* One thread, we operate on all charges */
3980                 spline->n = atc->n;
3981             }
3982             else
3983             {
3984                 /* Get the indices our thread should operate on */
3985                 make_thread_local_ind(atc, thread, spline);
3986             }
3987
3988             grid = &grids->grid_th[thread];
3989         }
3990
3991         if (bCalcSplines)
3992         {
3993             make_bsplines(spline->theta, spline->dtheta, pme->pme_order,
3994                           atc->fractx, spline->n, spline->ind, atc->q, pme->bFEP);
3995         }
3996
3997         if (bSpread)
3998         {
3999             /* put local atoms on grid. */
4000 #ifdef PME_TIME_SPREAD
4001             ct1a = omp_cyc_start();
4002 #endif
4003             spread_q_bsplines_thread(grid, atc, spline, pme->spline_work);
4004
4005             if (pme->bUseThreads)
4006             {
4007                 copy_local_grid(pme, grids, thread, fftgrid);
4008             }
4009 #ifdef PME_TIME_SPREAD
4010             ct1a          = omp_cyc_end(ct1a);
4011             cs1a[thread] += (double)ct1a;
4012 #endif
4013         }
4014     }
4015 #ifdef PME_TIME_THREADS
4016     c2   = omp_cyc_end(c2);
4017     cs2 += (double)c2;
4018 #endif
4019
4020     if (bSpread && pme->bUseThreads)
4021     {
4022 #ifdef PME_TIME_THREADS
4023         c3 = omp_cyc_start();
4024 #endif
4025 #pragma omp parallel for num_threads(grids->nthread) schedule(static)
4026         for (thread = 0; thread < grids->nthread; thread++)
4027         {
4028             reduce_threadgrid_overlap(pme, grids, thread,
4029                                       fftgrid,
4030                                       pme->overlap[0].sendbuf,
4031                                       pme->overlap[1].sendbuf);
4032         }
4033 #ifdef PME_TIME_THREADS
4034         c3   = omp_cyc_end(c3);
4035         cs3 += (double)c3;
4036 #endif
4037
4038         if (pme->nnodes > 1)
4039         {
4040             /* Communicate the overlapping part of the fftgrid.
4041              * For this communication call we need to check pme->bUseThreads
4042              * to have all ranks communicate here, regardless of pme->nthread.
4043              */
4044             sum_fftgrid_dd(pme, fftgrid);
4045         }
4046     }
4047
4048 #ifdef PME_TIME_THREADS
4049     cnt++;
4050     if (cnt % 20 == 0)
4051     {
4052         printf("idx %.2f spread %.2f red %.2f",
4053                cs1*1e-9, cs2*1e-9, cs3*1e-9);
4054 #ifdef PME_TIME_SPREAD
4055         for (thread = 0; thread < nthread; thread++)
4056         {
4057             printf(" %.2f", cs1a[thread]*1e-9);
4058         }
4059 #endif
4060         printf("\n");
4061     }
4062 #endif
4063 }
4064
4065
4066 static void dump_grid(FILE *fp,
4067                       int sx, int sy, int sz, int nx, int ny, int nz,
4068                       int my, int mz, const real *g)
4069 {
4070     int x, y, z;
4071
4072     for (x = 0; x < nx; x++)
4073     {
4074         for (y = 0; y < ny; y++)
4075         {
4076             for (z = 0; z < nz; z++)
4077             {
4078                 fprintf(fp, "%2d %2d %2d %6.3f\n",
4079                         sx+x, sy+y, sz+z, g[(x*my + y)*mz + z]);
4080             }
4081         }
4082     }
4083 }
4084
4085 static void dump_local_fftgrid(gmx_pme_t pme, const real *fftgrid)
4086 {
4087     ivec local_fft_ndata, local_fft_offset, local_fft_size;
4088
4089     gmx_parallel_3dfft_real_limits(pme->pfft_setupA,
4090                                    local_fft_ndata,
4091                                    local_fft_offset,
4092                                    local_fft_size);
4093
4094     dump_grid(stderr,
4095               pme->pmegrid_start_ix,
4096               pme->pmegrid_start_iy,
4097               pme->pmegrid_start_iz,
4098               pme->pmegrid_nx-pme->pme_order+1,
4099               pme->pmegrid_ny-pme->pme_order+1,
4100               pme->pmegrid_nz-pme->pme_order+1,
4101               local_fft_size[YY],
4102               local_fft_size[ZZ],
4103               fftgrid);
4104 }
4105
4106
4107 void gmx_pme_calc_energy(gmx_pme_t pme, int n, rvec *x, real *q, real *V)
4108 {
4109     pme_atomcomm_t *atc;
4110     pmegrids_t *grid;
4111
4112     if (pme->nnodes > 1)
4113     {
4114         gmx_incons("gmx_pme_calc_energy called in parallel");
4115     }
4116     if (pme->bFEP > 1)
4117     {
4118         gmx_incons("gmx_pme_calc_energy with free energy");
4119     }
4120
4121     atc            = &pme->atc_energy;
4122     atc->nthread   = 1;
4123     if (atc->spline == NULL)
4124     {
4125         snew(atc->spline, atc->nthread);
4126     }
4127     atc->nslab     = 1;
4128     atc->bSpread   = TRUE;
4129     atc->pme_order = pme->pme_order;
4130     atc->n         = n;
4131     pme_realloc_atomcomm_things(atc);
4132     atc->x         = x;
4133     atc->q         = q;
4134
4135     /* We only use the A-charges grid */
4136     grid = &pme->pmegridA;
4137
4138     /* Only calculate the spline coefficients, don't actually spread */
4139     spread_on_grid(pme, atc, NULL, TRUE, FALSE, pme->fftgridA);
4140
4141     *V = gather_energy_bsplines(pme, grid->grid.grid, atc);
4142 }
4143
4144
4145 static void reset_pmeonly_counters(gmx_wallcycle_t wcycle,
4146                                    gmx_runtime_t *runtime,
4147                                    t_nrnb *nrnb, t_inputrec *ir,
4148                                    gmx_large_int_t step)
4149 {
4150     /* Reset all the counters related to performance over the run */
4151     wallcycle_stop(wcycle, ewcRUN);
4152     wallcycle_reset_all(wcycle);
4153     init_nrnb(nrnb);
4154     if (ir->nsteps >= 0)
4155     {
4156         /* ir->nsteps is not used here, but we update it for consistency */
4157         ir->nsteps -= step - ir->init_step;
4158     }
4159     ir->init_step = step;
4160     wallcycle_start(wcycle, ewcRUN);
4161     runtime_start(runtime);
4162 }
4163
4164
4165 static void gmx_pmeonly_switch(int *npmedata, gmx_pme_t **pmedata,
4166                                ivec grid_size,
4167                                t_commrec *cr, t_inputrec *ir,
4168                                gmx_pme_t *pme_ret)
4169 {
4170     int ind;
4171     gmx_pme_t pme = NULL;
4172
4173     ind = 0;
4174     while (ind < *npmedata)
4175     {
4176         pme = (*pmedata)[ind];
4177         if (pme->nkx == grid_size[XX] &&
4178             pme->nky == grid_size[YY] &&
4179             pme->nkz == grid_size[ZZ])
4180         {
4181             *pme_ret = pme;
4182
4183             return;
4184         }
4185
4186         ind++;
4187     }
4188
4189     (*npmedata)++;
4190     srenew(*pmedata, *npmedata);
4191
4192     /* Generate a new PME data structure, copying part of the old pointers */
4193     gmx_pme_reinit(&((*pmedata)[ind]), cr, pme, ir, grid_size);
4194
4195     *pme_ret = (*pmedata)[ind];
4196 }
4197
4198
4199 int gmx_pmeonly(gmx_pme_t pme,
4200                 t_commrec *cr,    t_nrnb *nrnb,
4201                 gmx_wallcycle_t wcycle,
4202                 gmx_runtime_t *runtime,
4203                 real ewaldcoeff,
4204                 t_inputrec *ir)
4205 {
4206     int npmedata;
4207     gmx_pme_t *pmedata;
4208     gmx_pme_pp_t pme_pp;
4209     int  ret;
4210     int  natoms;
4211     matrix box;
4212     rvec *x_pp      = NULL, *f_pp = NULL;
4213     real *chargeA   = NULL, *chargeB = NULL;
4214     real lambda     = 0;
4215     int  maxshift_x = 0, maxshift_y = 0;
4216     real energy, dvdlambda;
4217     matrix vir;
4218     float cycles;
4219     int  count;
4220     gmx_bool bEnerVir;
4221     gmx_large_int_t step, step_rel;
4222     ivec grid_switch;
4223
4224     /* This data will only use with PME tuning, i.e. switching PME grids */
4225     npmedata = 1;
4226     snew(pmedata, npmedata);
4227     pmedata[0] = pme;
4228
4229     pme_pp = gmx_pme_pp_init(cr);
4230
4231     init_nrnb(nrnb);
4232
4233     count = 0;
4234     do /****** this is a quasi-loop over time steps! */
4235     {
4236         /* The reason for having a loop here is PME grid tuning/switching */
4237         do
4238         {
4239             /* Domain decomposition */
4240             ret = gmx_pme_recv_q_x(pme_pp,
4241                                    &natoms,
4242                                    &chargeA, &chargeB, box, &x_pp, &f_pp,
4243                                    &maxshift_x, &maxshift_y,
4244                                    &pme->bFEP, &lambda,
4245                                    &bEnerVir,
4246                                    &step,
4247                                    grid_switch, &ewaldcoeff);
4248
4249             if (ret == pmerecvqxSWITCHGRID)
4250             {
4251                 /* Switch the PME grid to grid_switch */
4252                 gmx_pmeonly_switch(&npmedata, &pmedata, grid_switch, cr, ir, &pme);
4253             }
4254
4255             if (ret == pmerecvqxRESETCOUNTERS)
4256             {
4257                 /* Reset the cycle and flop counters */
4258                 reset_pmeonly_counters(wcycle, runtime, nrnb, ir, step);
4259             }
4260         }
4261         while (ret == pmerecvqxSWITCHGRID || ret == pmerecvqxRESETCOUNTERS);
4262
4263         if (ret == pmerecvqxFINISH)
4264         {
4265             /* We should stop: break out of the loop */
4266             break;
4267         }
4268
4269         step_rel = step - ir->init_step;
4270
4271         if (count == 0)
4272         {
4273             wallcycle_start(wcycle, ewcRUN);
4274             runtime_start(runtime);
4275         }
4276
4277         wallcycle_start(wcycle, ewcPMEMESH);
4278
4279         dvdlambda = 0;
4280         clear_mat(vir);
4281         gmx_pme_do(pme, 0, natoms, x_pp, f_pp, chargeA, chargeB, box,
4282                    cr, maxshift_x, maxshift_y, nrnb, wcycle, vir, ewaldcoeff,
4283                    &energy, lambda, &dvdlambda,
4284                    GMX_PME_DO_ALL_F | (bEnerVir ? GMX_PME_CALC_ENER_VIR : 0));
4285
4286         cycles = wallcycle_stop(wcycle, ewcPMEMESH);
4287
4288         gmx_pme_send_force_vir_ener(pme_pp,
4289                                     f_pp, vir, energy, dvdlambda,
4290                                     cycles);
4291
4292         count++;
4293     } /***** end of quasi-loop, we stop with the break above */
4294     while (TRUE);
4295
4296     runtime_end(runtime);
4297
4298     return 0;
4299 }
4300
4301 int gmx_pme_do(gmx_pme_t pme,
4302                int start,       int homenr,
4303                rvec x[],        rvec f[],
4304                real *chargeA,   real *chargeB,
4305                matrix box, t_commrec *cr,
4306                int  maxshift_x, int maxshift_y,
4307                t_nrnb *nrnb,    gmx_wallcycle_t wcycle,
4308                matrix vir,      real ewaldcoeff,
4309                real *energy,    real lambda,
4310                real *dvdlambda, int flags)
4311 {
4312     int     q, d, i, j, ntot, npme;
4313     int     nx, ny, nz;
4314     int     n_d, local_ny;
4315     pme_atomcomm_t *atc = NULL;
4316     pmegrids_t *pmegrid = NULL;
4317     real    *grid       = NULL;
4318     real    *ptr;
4319     rvec    *x_d, *f_d;
4320     real    *charge = NULL, *q_d;
4321     real    energy_AB[2];
4322     matrix  vir_AB[2];
4323     gmx_bool bClearF;
4324     gmx_parallel_3dfft_t pfft_setup;
4325     real *  fftgrid;
4326     t_complex * cfftgrid;
4327     int     thread;
4328     const gmx_bool bCalcEnerVir = flags & GMX_PME_CALC_ENER_VIR;
4329     const gmx_bool bCalcF       = flags & GMX_PME_CALC_F;
4330
4331     assert(pme->nnodes > 0);
4332     assert(pme->nnodes == 1 || pme->ndecompdim > 0);
4333
4334     if (pme->nnodes > 1)
4335     {
4336         atc      = &pme->atc[0];
4337         atc->npd = homenr;
4338         if (atc->npd > atc->pd_nalloc)
4339         {
4340             atc->pd_nalloc = over_alloc_dd(atc->npd);
4341             srenew(atc->pd, atc->pd_nalloc);
4342         }
4343         atc->maxshift = (atc->dimind == 0 ? maxshift_x : maxshift_y);
4344     }
4345     else
4346     {
4347         /* This could be necessary for TPI */
4348         pme->atc[0].n = homenr;
4349     }
4350
4351     for (q = 0; q < (pme->bFEP ? 2 : 1); q++)
4352     {
4353         if (q == 0)
4354         {
4355             pmegrid    = &pme->pmegridA;
4356             fftgrid    = pme->fftgridA;
4357             cfftgrid   = pme->cfftgridA;
4358             pfft_setup = pme->pfft_setupA;
4359             charge     = chargeA+start;
4360         }
4361         else
4362         {
4363             pmegrid    = &pme->pmegridB;
4364             fftgrid    = pme->fftgridB;
4365             cfftgrid   = pme->cfftgridB;
4366             pfft_setup = pme->pfft_setupB;
4367             charge     = chargeB+start;
4368         }
4369         grid = pmegrid->grid.grid;
4370         /* Unpack structure */
4371         if (debug)
4372         {
4373             fprintf(debug, "PME: nnodes = %d, nodeid = %d\n",
4374                     cr->nnodes, cr->nodeid);
4375             fprintf(debug, "Grid = %p\n", (void*)grid);
4376             if (grid == NULL)
4377             {
4378                 gmx_fatal(FARGS, "No grid!");
4379             }
4380         }
4381         where();
4382
4383         m_inv_ur0(box, pme->recipbox);
4384
4385         if (pme->nnodes == 1)
4386         {
4387             atc = &pme->atc[0];
4388             if (DOMAINDECOMP(cr))
4389             {
4390                 atc->n = homenr;
4391                 pme_realloc_atomcomm_things(atc);
4392             }
4393             atc->x = x;
4394             atc->q = charge;
4395             atc->f = f;
4396         }
4397         else
4398         {
4399             wallcycle_start(wcycle, ewcPME_REDISTXF);
4400             for (d = pme->ndecompdim-1; d >= 0; d--)
4401             {
4402                 if (d == pme->ndecompdim-1)
4403                 {
4404                     n_d = homenr;
4405                     x_d = x + start;
4406                     q_d = charge;
4407                 }
4408                 else
4409                 {
4410                     n_d = pme->atc[d+1].n;
4411                     x_d = atc->x;
4412                     q_d = atc->q;
4413                 }
4414                 atc      = &pme->atc[d];
4415                 atc->npd = n_d;
4416                 if (atc->npd > atc->pd_nalloc)
4417                 {
4418                     atc->pd_nalloc = over_alloc_dd(atc->npd);
4419                     srenew(atc->pd, atc->pd_nalloc);
4420                 }
4421                 atc->maxshift = (atc->dimind == 0 ? maxshift_x : maxshift_y);
4422                 pme_calc_pidx_wrapper(n_d, pme->recipbox, x_d, atc);
4423                 where();
4424
4425                 /* Redistribute x (only once) and qA or qB */
4426                 if (DOMAINDECOMP(cr))
4427                 {
4428                     dd_pmeredist_x_q(pme, n_d, q == 0, x_d, q_d, atc);
4429                 }
4430                 else
4431                 {
4432                     pmeredist_pd(pme, TRUE, n_d, q == 0, x_d, q_d, atc);
4433                 }
4434             }
4435             where();
4436
4437             wallcycle_stop(wcycle, ewcPME_REDISTXF);
4438         }
4439
4440         if (debug)
4441         {
4442             fprintf(debug, "Node= %6d, pme local particles=%6d\n",
4443                     cr->nodeid, atc->n);
4444         }
4445
4446         if (flags & GMX_PME_SPREAD_Q)
4447         {
4448             wallcycle_start(wcycle, ewcPME_SPREADGATHER);
4449
4450             /* Spread the charges on a grid */
4451             spread_on_grid(pme, &pme->atc[0], pmegrid, q == 0, TRUE, fftgrid);
4452
4453             if (q == 0)
4454             {
4455                 inc_nrnb(nrnb, eNR_WEIGHTS, DIM*atc->n);
4456             }
4457             inc_nrnb(nrnb, eNR_SPREADQBSP,
4458                      pme->pme_order*pme->pme_order*pme->pme_order*atc->n);
4459
4460             if (!pme->bUseThreads)
4461             {
4462                 wrap_periodic_pmegrid(pme, grid);
4463
4464                 /* sum contributions to local grid from other nodes */
4465 #ifdef GMX_MPI
4466                 if (pme->nnodes > 1)
4467                 {
4468                     gmx_sum_qgrid_dd(pme, grid, GMX_SUM_QGRID_FORWARD);
4469                     where();
4470                 }
4471 #endif
4472
4473                 copy_pmegrid_to_fftgrid(pme, grid, fftgrid);
4474             }
4475
4476             wallcycle_stop(wcycle, ewcPME_SPREADGATHER);
4477
4478             /*
4479                dump_local_fftgrid(pme,fftgrid);
4480                exit(0);
4481              */
4482         }
4483
4484         /* Here we start a large thread parallel region */
4485 #pragma omp parallel num_threads(pme->nthread) private(thread)
4486         {
4487             thread = gmx_omp_get_thread_num();
4488             if (flags & GMX_PME_SOLVE)
4489             {
4490                 int loop_count;
4491
4492                 /* do 3d-fft */
4493                 if (thread == 0)
4494                 {
4495                     wallcycle_start(wcycle, ewcPME_FFT);
4496                 }
4497                 gmx_parallel_3dfft_execute(pfft_setup, GMX_FFT_REAL_TO_COMPLEX,
4498                                            thread, wcycle);
4499                 if (thread == 0)
4500                 {
4501                     wallcycle_stop(wcycle, ewcPME_FFT);
4502                 }
4503                 where();
4504
4505                 /* solve in k-space for our local cells */
4506                 if (thread == 0)
4507                 {
4508                     wallcycle_start(wcycle, ewcPME_SOLVE);
4509                 }
4510                 loop_count =
4511                     solve_pme_yzx(pme, cfftgrid, ewaldcoeff,
4512                                   box[XX][XX]*box[YY][YY]*box[ZZ][ZZ],
4513                                   bCalcEnerVir,
4514                                   pme->nthread, thread);
4515                 if (thread == 0)
4516                 {
4517                     wallcycle_stop(wcycle, ewcPME_SOLVE);
4518                     where();
4519                     inc_nrnb(nrnb, eNR_SOLVEPME, loop_count);
4520                 }
4521             }
4522
4523             if (bCalcF)
4524             {
4525                 /* do 3d-invfft */
4526                 if (thread == 0)
4527                 {
4528                     where();
4529                     wallcycle_start(wcycle, ewcPME_FFT);
4530                 }
4531                 gmx_parallel_3dfft_execute(pfft_setup, GMX_FFT_COMPLEX_TO_REAL,
4532                                            thread, wcycle);
4533                 if (thread == 0)
4534                 {
4535                     wallcycle_stop(wcycle, ewcPME_FFT);
4536
4537                     where();
4538
4539                     if (pme->nodeid == 0)
4540                     {
4541                         ntot  = pme->nkx*pme->nky*pme->nkz;
4542                         npme  = ntot*log((real)ntot)/log(2.0);
4543                         inc_nrnb(nrnb, eNR_FFT, 2*npme);
4544                     }
4545
4546                     wallcycle_start(wcycle, ewcPME_SPREADGATHER);
4547                 }
4548
4549                 copy_fftgrid_to_pmegrid(pme, fftgrid, grid, pme->nthread, thread);
4550             }
4551         }
4552         /* End of thread parallel section.
4553          * With MPI we have to synchronize here before gmx_sum_qgrid_dd.
4554          */
4555
4556         if (bCalcF)
4557         {
4558             /* distribute local grid to all nodes */
4559 #ifdef GMX_MPI
4560             if (pme->nnodes > 1)
4561             {
4562                 gmx_sum_qgrid_dd(pme, grid, GMX_SUM_QGRID_BACKWARD);
4563             }
4564 #endif
4565             where();
4566
4567             unwrap_periodic_pmegrid(pme, grid);
4568
4569             /* interpolate forces for our local atoms */
4570
4571             where();
4572
4573             /* If we are running without parallelization,
4574              * atc->f is the actual force array, not a buffer,
4575              * therefore we should not clear it.
4576              */
4577             bClearF = (q == 0 && PAR(cr));
4578 #pragma omp parallel for num_threads(pme->nthread) schedule(static)
4579             for (thread = 0; thread < pme->nthread; thread++)
4580             {
4581                 gather_f_bsplines(pme, grid, bClearF, atc,
4582                                   &atc->spline[thread],
4583                                   pme->bFEP ? (q == 0 ? 1.0-lambda : lambda) : 1.0);
4584             }
4585
4586             where();
4587
4588             inc_nrnb(nrnb, eNR_GATHERFBSP,
4589                      pme->pme_order*pme->pme_order*pme->pme_order*pme->atc[0].n);
4590             wallcycle_stop(wcycle, ewcPME_SPREADGATHER);
4591         }
4592
4593         if (bCalcEnerVir)
4594         {
4595             /* This should only be called on the master thread
4596              * and after the threads have synchronized.
4597              */
4598             get_pme_ener_vir(pme, pme->nthread, &energy_AB[q], vir_AB[q]);
4599         }
4600     } /* of q-loop */
4601
4602     if (bCalcF && pme->nnodes > 1)
4603     {
4604         wallcycle_start(wcycle, ewcPME_REDISTXF);
4605         for (d = 0; d < pme->ndecompdim; d++)
4606         {
4607             atc = &pme->atc[d];
4608             if (d == pme->ndecompdim - 1)
4609             {
4610                 n_d = homenr;
4611                 f_d = f + start;
4612             }
4613             else
4614             {
4615                 n_d = pme->atc[d+1].n;
4616                 f_d = pme->atc[d+1].f;
4617             }
4618             if (DOMAINDECOMP(cr))
4619             {
4620                 dd_pmeredist_f(pme, atc, n_d, f_d,
4621                                d == pme->ndecompdim-1 && pme->bPPnode);
4622             }
4623             else
4624             {
4625                 pmeredist_pd(pme, FALSE, n_d, TRUE, f_d, NULL, atc);
4626             }
4627         }
4628
4629         wallcycle_stop(wcycle, ewcPME_REDISTXF);
4630     }
4631     where();
4632
4633     if (bCalcEnerVir)
4634     {
4635         if (!pme->bFEP)
4636         {
4637             *energy = energy_AB[0];
4638             m_add(vir, vir_AB[0], vir);
4639         }
4640         else
4641         {
4642             *energy     = (1.0-lambda)*energy_AB[0] + lambda*energy_AB[1];
4643             *dvdlambda += energy_AB[1] - energy_AB[0];
4644             for (i = 0; i < DIM; i++)
4645             {
4646                 for (j = 0; j < DIM; j++)
4647                 {
4648                     vir[i][j] += (1.0-lambda)*vir_AB[0][i][j] +
4649                         lambda*vir_AB[1][i][j];
4650                 }
4651             }
4652         }
4653     }
4654     else
4655     {
4656         *energy = 0;
4657     }
4658
4659     if (debug)
4660     {
4661         fprintf(debug, "PME mesh energy: %g\n", *energy);
4662     }
4663
4664     return 0;
4665 }