Merge release-5-0 into master
[alexxy/gromacs.git] / src / gromacs / mdlib / nbnxn_search.c
1 /*
2  * This file is part of the GROMACS molecular simulation package.
3  *
4  * Copyright (c) 2012,2013,2014, by the GROMACS development team, led by
5  * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
6  * and including many others, as listed in the AUTHORS file in the
7  * top-level source directory and at http://www.gromacs.org.
8  *
9  * GROMACS is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public License
11  * as published by the Free Software Foundation; either version 2.1
12  * of the License, or (at your option) any later version.
13  *
14  * GROMACS is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public
20  * License along with GROMACS; if not, see
21  * http://www.gnu.org/licenses, or write to the Free Software Foundation,
22  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA.
23  *
24  * If you want to redistribute modifications to GROMACS, please
25  * consider that scientific software is very special. Version
26  * control is crucial - bugs must be traceable. We will be happy to
27  * consider code for inclusion in the official distribution, but
28  * derived work must not be called official GROMACS. Details are found
29  * in the README & COPYING files - if they are missing, get the
30  * official version at http://www.gromacs.org.
31  *
32  * To help us fund GROMACS development, we humbly ask that you cite
33  * the research papers on the package. Check out http://www.gromacs.org.
34  */
35
36 #ifdef HAVE_CONFIG_H
37 #include <config.h>
38 #endif
39
40 #include <math.h>
41 #include <string.h>
42 #include <assert.h>
43
44 #include "types/commrec.h"
45 #include "macros.h"
46 #include "gromacs/math/utilities.h"
47 #include "gromacs/math/vec.h"
48 #include "nbnxn_consts.h"
49 /* nbnxn_internal.h included gromacs/simd/macros.h */
50 #include "nbnxn_internal.h"
51 #ifdef GMX_NBNXN_SIMD
52 #include "gromacs/simd/vector_operations.h"
53 #endif
54 #include "nbnxn_atomdata.h"
55 #include "nbnxn_search.h"
56 #include "gmx_omp_nthreads.h"
57 #include "nrnb.h"
58 #include "ns.h"
59
60 #include "gromacs/pbcutil/ishift.h"
61 #include "gromacs/pbcutil/pbc.h"
62 #include "gromacs/utility/smalloc.h"
63
64 #ifdef NBNXN_SEARCH_BB_SIMD4
65 /* Always use 4-wide SIMD for bounding box calculations */
66
67 #    ifndef GMX_DOUBLE
68 /* Single precision BBs + coordinates, we can also load coordinates with SIMD */
69 #        define NBNXN_SEARCH_SIMD4_FLOAT_X_BB
70 #    endif
71
72 #    if defined NBNXN_SEARCH_SIMD4_FLOAT_X_BB && (GPU_NSUBCELL == 4 || GPU_NSUBCELL == 8)
73 /* Store bounding boxes with x, y and z coordinates in packs of 4 */
74 #        define NBNXN_PBB_SIMD4
75 #    endif
76
77 /* The packed bounding box coordinate stride is always set to 4.
78  * With AVX we could use 8, but that turns out not to be faster.
79  */
80 #    define STRIDE_PBB        4
81 #    define STRIDE_PBB_2LOG   2
82
83 #endif /* NBNXN_SEARCH_BB_SIMD4 */
84
85 #ifdef GMX_NBNXN_SIMD
86
87 /* The functions below are macros as they are performance sensitive */
88
89 /* 4x4 list, pack=4: no complex conversion required */
90 /* i-cluster to j-cluster conversion */
91 #define CI_TO_CJ_J4(ci)   (ci)
92 /* cluster index to coordinate array index conversion */
93 #define X_IND_CI_J4(ci)  ((ci)*STRIDE_P4)
94 #define X_IND_CJ_J4(cj)  ((cj)*STRIDE_P4)
95
96 /* 4x2 list, pack=4: j-cluster size is half the packing width */
97 /* i-cluster to j-cluster conversion */
98 #define CI_TO_CJ_J2(ci)  ((ci)<<1)
99 /* cluster index to coordinate array index conversion */
100 #define X_IND_CI_J2(ci)  ((ci)*STRIDE_P4)
101 #define X_IND_CJ_J2(cj)  (((cj)>>1)*STRIDE_P4 + ((cj) & 1)*(PACK_X4>>1))
102
103 /* 4x8 list, pack=8: i-cluster size is half the packing width */
104 /* i-cluster to j-cluster conversion */
105 #define CI_TO_CJ_J8(ci)  ((ci)>>1)
106 /* cluster index to coordinate array index conversion */
107 #define X_IND_CI_J8(ci)  (((ci)>>1)*STRIDE_P8 + ((ci) & 1)*(PACK_X8>>1))
108 #define X_IND_CJ_J8(cj)  ((cj)*STRIDE_P8)
109
110 /* The j-cluster size is matched to the SIMD width */
111 #if GMX_SIMD_REAL_WIDTH == 2
112 #define CI_TO_CJ_SIMD_4XN(ci)  CI_TO_CJ_J2(ci)
113 #define X_IND_CI_SIMD_4XN(ci)  X_IND_CI_J2(ci)
114 #define X_IND_CJ_SIMD_4XN(cj)  X_IND_CJ_J2(cj)
115 #else
116 #if GMX_SIMD_REAL_WIDTH == 4
117 #define CI_TO_CJ_SIMD_4XN(ci)  CI_TO_CJ_J4(ci)
118 #define X_IND_CI_SIMD_4XN(ci)  X_IND_CI_J4(ci)
119 #define X_IND_CJ_SIMD_4XN(cj)  X_IND_CJ_J4(cj)
120 #else
121 #if GMX_SIMD_REAL_WIDTH == 8
122 #define CI_TO_CJ_SIMD_4XN(ci)  CI_TO_CJ_J8(ci)
123 #define X_IND_CI_SIMD_4XN(ci)  X_IND_CI_J8(ci)
124 #define X_IND_CJ_SIMD_4XN(cj)  X_IND_CJ_J8(cj)
125 /* Half SIMD with j-cluster size */
126 #define CI_TO_CJ_SIMD_2XNN(ci) CI_TO_CJ_J4(ci)
127 #define X_IND_CI_SIMD_2XNN(ci) X_IND_CI_J4(ci)
128 #define X_IND_CJ_SIMD_2XNN(cj) X_IND_CJ_J4(cj)
129 #else
130 #if GMX_SIMD_REAL_WIDTH == 16
131 #define CI_TO_CJ_SIMD_2XNN(ci) CI_TO_CJ_J8(ci)
132 #define X_IND_CI_SIMD_2XNN(ci) X_IND_CI_J8(ci)
133 #define X_IND_CJ_SIMD_2XNN(cj) X_IND_CJ_J8(cj)
134 #else
135 #error "unsupported GMX_SIMD_REAL_WIDTH"
136 #endif
137 #endif
138 #endif
139 #endif
140
141 #endif /* GMX_NBNXN_SIMD */
142
143
144 #ifdef NBNXN_SEARCH_BB_SIMD4
145 /* Store bounding boxes corners as quadruplets: xxxxyyyyzzzz */
146 #define NBNXN_BBXXXX
147 /* Size of bounding box corners quadruplet */
148 #define NNBSBB_XXXX      (NNBSBB_D*DIM*STRIDE_PBB)
149 #endif
150
151 /* We shift the i-particles backward for PBC.
152  * This leads to more conditionals than shifting forward.
153  * We do this to get more balanced pair lists.
154  */
155 #define NBNXN_SHIFT_BACKWARD
156
157
158 /* This define is a lazy way to avoid interdependence of the grid
159  * and searching data structures.
160  */
161 #define NBNXN_NA_SC_MAX (GPU_NSUBCELL*NBNXN_GPU_CLUSTER_SIZE)
162
163
164 static void nbs_cycle_clear(nbnxn_cycle_t *cc)
165 {
166     int i;
167
168     for (i = 0; i < enbsCCnr; i++)
169     {
170         cc[i].count = 0;
171         cc[i].c     = 0;
172     }
173 }
174
175 static double Mcyc_av(const nbnxn_cycle_t *cc)
176 {
177     return (double)cc->c*1e-6/cc->count;
178 }
179
180 static void nbs_cycle_print(FILE *fp, const nbnxn_search_t nbs)
181 {
182     int n;
183     int t;
184
185     fprintf(fp, "\n");
186     fprintf(fp, "ns %4d grid %4.1f search %4.1f red.f %5.3f",
187             nbs->cc[enbsCCgrid].count,
188             Mcyc_av(&nbs->cc[enbsCCgrid]),
189             Mcyc_av(&nbs->cc[enbsCCsearch]),
190             Mcyc_av(&nbs->cc[enbsCCreducef]));
191
192     if (nbs->nthread_max > 1)
193     {
194         if (nbs->cc[enbsCCcombine].count > 0)
195         {
196             fprintf(fp, " comb %5.2f",
197                     Mcyc_av(&nbs->cc[enbsCCcombine]));
198         }
199         fprintf(fp, " s. th");
200         for (t = 0; t < nbs->nthread_max; t++)
201         {
202             fprintf(fp, " %4.1f",
203                     Mcyc_av(&nbs->work[t].cc[enbsCCsearch]));
204         }
205     }
206     fprintf(fp, "\n");
207 }
208
209 static void nbnxn_grid_init(nbnxn_grid_t * grid)
210 {
211     grid->cxy_na      = NULL;
212     grid->cxy_ind     = NULL;
213     grid->cxy_nalloc  = 0;
214     grid->bb          = NULL;
215     grid->bbj         = NULL;
216     grid->nc_nalloc   = 0;
217 }
218
219 static int get_2log(int n)
220 {
221     int log2;
222
223     log2 = 0;
224     while ((1<<log2) < n)
225     {
226         log2++;
227     }
228     if ((1<<log2) != n)
229     {
230         gmx_fatal(FARGS, "nbnxn na_c (%d) is not a power of 2", n);
231     }
232
233     return log2;
234 }
235
236 static int nbnxn_kernel_to_ci_size(int nb_kernel_type)
237 {
238     switch (nb_kernel_type)
239     {
240         case nbnxnk4x4_PlainC:
241         case nbnxnk4xN_SIMD_4xN:
242         case nbnxnk4xN_SIMD_2xNN:
243             return NBNXN_CPU_CLUSTER_I_SIZE;
244         case nbnxnk8x8x8_CUDA:
245         case nbnxnk8x8x8_PlainC:
246             /* The cluster size for super/sub lists is only set here.
247              * Any value should work for the pair-search and atomdata code.
248              * The kernels, of course, might require a particular value.
249              */
250             return NBNXN_GPU_CLUSTER_SIZE;
251         default:
252             gmx_incons("unknown kernel type");
253     }
254
255     return 0;
256 }
257
258 int nbnxn_kernel_to_cj_size(int nb_kernel_type)
259 {
260     int nbnxn_simd_width = 0;
261     int cj_size          = 0;
262
263 #ifdef GMX_NBNXN_SIMD
264     nbnxn_simd_width = GMX_SIMD_REAL_WIDTH;
265 #endif
266
267     switch (nb_kernel_type)
268     {
269         case nbnxnk4x4_PlainC:
270             cj_size = NBNXN_CPU_CLUSTER_I_SIZE;
271             break;
272         case nbnxnk4xN_SIMD_4xN:
273             cj_size = nbnxn_simd_width;
274             break;
275         case nbnxnk4xN_SIMD_2xNN:
276             cj_size = nbnxn_simd_width/2;
277             break;
278         case nbnxnk8x8x8_CUDA:
279         case nbnxnk8x8x8_PlainC:
280             cj_size = nbnxn_kernel_to_ci_size(nb_kernel_type);
281             break;
282         default:
283             gmx_incons("unknown kernel type");
284     }
285
286     return cj_size;
287 }
288
289 static int ci_to_cj(int na_cj_2log, int ci)
290 {
291     switch (na_cj_2log)
292     {
293         case 2: return ci;     break;
294         case 1: return (ci<<1); break;
295         case 3: return (ci>>1); break;
296     }
297
298     return 0;
299 }
300
301 gmx_bool nbnxn_kernel_pairlist_simple(int nb_kernel_type)
302 {
303     if (nb_kernel_type == nbnxnkNotSet)
304     {
305         gmx_fatal(FARGS, "Non-bonded kernel type not set for Verlet-style pair-list.");
306     }
307
308     switch (nb_kernel_type)
309     {
310         case nbnxnk8x8x8_CUDA:
311         case nbnxnk8x8x8_PlainC:
312             return FALSE;
313
314         case nbnxnk4x4_PlainC:
315         case nbnxnk4xN_SIMD_4xN:
316         case nbnxnk4xN_SIMD_2xNN:
317             return TRUE;
318
319         default:
320             gmx_incons("Invalid nonbonded kernel type passed!");
321             return FALSE;
322     }
323 }
324
325 /* Initializes a single nbnxn_pairlist_t data structure */
326 static void nbnxn_init_pairlist_fep(t_nblist *nl)
327 {
328     nl->type        = GMX_NBLIST_INTERACTION_FREE_ENERGY;
329     nl->igeometry   = GMX_NBLIST_GEOMETRY_PARTICLE_PARTICLE;
330     /* The interaction functions are set in the free energy kernel fuction */
331     nl->ivdw        = -1;
332     nl->ivdwmod     = -1;
333     nl->ielec       = -1;
334     nl->ielecmod    = -1;
335
336     nl->maxnri      = 0;
337     nl->maxnrj      = 0;
338     nl->nri         = 0;
339     nl->nrj         = 0;
340     nl->iinr        = NULL;
341     nl->gid         = NULL;
342     nl->shift       = NULL;
343     nl->jindex      = NULL;
344     nl->jjnr        = NULL;
345     nl->excl_fep    = NULL;
346
347 }
348
349 void nbnxn_init_search(nbnxn_search_t    * nbs_ptr,
350                        ivec               *n_dd_cells,
351                        gmx_domdec_zones_t *zones,
352                        gmx_bool            bFEP,
353                        int                 nthread_max)
354 {
355     nbnxn_search_t nbs;
356     int            d, g, t;
357
358     snew(nbs, 1);
359     *nbs_ptr = nbs;
360
361     nbs->bFEP   = bFEP;
362
363     nbs->DomDec = (n_dd_cells != NULL);
364
365     clear_ivec(nbs->dd_dim);
366     nbs->ngrid = 1;
367     if (nbs->DomDec)
368     {
369         nbs->zones = zones;
370
371         for (d = 0; d < DIM; d++)
372         {
373             if ((*n_dd_cells)[d] > 1)
374             {
375                 nbs->dd_dim[d] = 1;
376                 /* Each grid matches a DD zone */
377                 nbs->ngrid *= 2;
378             }
379         }
380     }
381
382     snew(nbs->grid, nbs->ngrid);
383     for (g = 0; g < nbs->ngrid; g++)
384     {
385         nbnxn_grid_init(&nbs->grid[g]);
386     }
387     nbs->cell        = NULL;
388     nbs->cell_nalloc = 0;
389     nbs->a           = NULL;
390     nbs->a_nalloc    = 0;
391
392     nbs->nthread_max = nthread_max;
393
394     /* Initialize the work data structures for each thread */
395     snew(nbs->work, nbs->nthread_max);
396     for (t = 0; t < nbs->nthread_max; t++)
397     {
398         nbs->work[t].cxy_na           = NULL;
399         nbs->work[t].cxy_na_nalloc    = 0;
400         nbs->work[t].sort_work        = NULL;
401         nbs->work[t].sort_work_nalloc = 0;
402
403         snew(nbs->work[t].nbl_fep, 1);
404         nbnxn_init_pairlist_fep(nbs->work[t].nbl_fep);
405     }
406
407     /* Initialize detailed nbsearch cycle counting */
408     nbs->print_cycles = (getenv("GMX_NBNXN_CYCLE") != 0);
409     nbs->search_count = 0;
410     nbs_cycle_clear(nbs->cc);
411     for (t = 0; t < nbs->nthread_max; t++)
412     {
413         nbs_cycle_clear(nbs->work[t].cc);
414     }
415 }
416
417 static real grid_atom_density(int n, rvec corner0, rvec corner1)
418 {
419     rvec size;
420
421     rvec_sub(corner1, corner0, size);
422
423     return n/(size[XX]*size[YY]*size[ZZ]);
424 }
425
426 static int set_grid_size_xy(const nbnxn_search_t nbs,
427                             nbnxn_grid_t *grid,
428                             int dd_zone,
429                             int n, rvec corner0, rvec corner1,
430                             real atom_density)
431 {
432     rvec size;
433     int  na_c;
434     real adens, tlen, tlen_x, tlen_y, nc_max;
435     int  t;
436
437     rvec_sub(corner1, corner0, size);
438
439     if (n > grid->na_sc)
440     {
441         /* target cell length */
442         if (grid->bSimple)
443         {
444             /* To minimize the zero interactions, we should make
445              * the largest of the i/j cell cubic.
446              */
447             na_c = max(grid->na_c, grid->na_cj);
448
449             /* Approximately cubic cells */
450             tlen   = pow(na_c/atom_density, 1.0/3.0);
451             tlen_x = tlen;
452             tlen_y = tlen;
453         }
454         else
455         {
456             /* Approximately cubic sub cells */
457             tlen   = pow(grid->na_c/atom_density, 1.0/3.0);
458             tlen_x = tlen*GPU_NSUBCELL_X;
459             tlen_y = tlen*GPU_NSUBCELL_Y;
460         }
461         /* We round ncx and ncy down, because we get less cell pairs
462          * in the nbsist when the fixed cell dimensions (x,y) are
463          * larger than the variable one (z) than the other way around.
464          */
465         grid->ncx = max(1, (int)(size[XX]/tlen_x));
466         grid->ncy = max(1, (int)(size[YY]/tlen_y));
467     }
468     else
469     {
470         grid->ncx = 1;
471         grid->ncy = 1;
472     }
473
474     grid->sx     = size[XX]/grid->ncx;
475     grid->sy     = size[YY]/grid->ncy;
476     grid->inv_sx = 1/grid->sx;
477     grid->inv_sy = 1/grid->sy;
478
479     if (dd_zone > 0)
480     {
481         /* This is a non-home zone, add an extra row of cells
482          * for particles communicated for bonded interactions.
483          * These can be beyond the cut-off. It doesn't matter where
484          * they end up on the grid, but for performance it's better
485          * if they don't end up in cells that can be within cut-off range.
486          */
487         grid->ncx++;
488         grid->ncy++;
489     }
490
491     /* We need one additional cell entry for particles moved by DD */
492     if (grid->ncx*grid->ncy+1 > grid->cxy_nalloc)
493     {
494         grid->cxy_nalloc = over_alloc_large(grid->ncx*grid->ncy+1);
495         srenew(grid->cxy_na, grid->cxy_nalloc);
496         srenew(grid->cxy_ind, grid->cxy_nalloc+1);
497     }
498     for (t = 0; t < nbs->nthread_max; t++)
499     {
500         if (grid->ncx*grid->ncy+1 > nbs->work[t].cxy_na_nalloc)
501         {
502             nbs->work[t].cxy_na_nalloc = over_alloc_large(grid->ncx*grid->ncy+1);
503             srenew(nbs->work[t].cxy_na, nbs->work[t].cxy_na_nalloc);
504         }
505     }
506
507     /* Worst case scenario of 1 atom in each last cell */
508     if (grid->na_cj <= grid->na_c)
509     {
510         nc_max = n/grid->na_sc + grid->ncx*grid->ncy;
511     }
512     else
513     {
514         nc_max = n/grid->na_sc + grid->ncx*grid->ncy*grid->na_cj/grid->na_c;
515     }
516
517     if (nc_max > grid->nc_nalloc)
518     {
519         grid->nc_nalloc = over_alloc_large(nc_max);
520         srenew(grid->nsubc, grid->nc_nalloc);
521         srenew(grid->bbcz, grid->nc_nalloc*NNBSBB_D);
522
523         sfree_aligned(grid->bb);
524         /* This snew also zeros the contents, this avoid possible
525          * floating exceptions in SIMD with the unused bb elements.
526          */
527         if (grid->bSimple)
528         {
529             snew_aligned(grid->bb, grid->nc_nalloc, 16);
530         }
531         else
532         {
533 #ifdef NBNXN_BBXXXX
534             int pbb_nalloc;
535
536             pbb_nalloc = grid->nc_nalloc*GPU_NSUBCELL/STRIDE_PBB*NNBSBB_XXXX;
537             snew_aligned(grid->pbb, pbb_nalloc, 16);
538 #else
539             snew_aligned(grid->bb, grid->nc_nalloc*GPU_NSUBCELL, 16);
540 #endif
541         }
542
543         if (grid->bSimple)
544         {
545             if (grid->na_cj == grid->na_c)
546             {
547                 grid->bbj = grid->bb;
548             }
549             else
550             {
551                 sfree_aligned(grid->bbj);
552                 snew_aligned(grid->bbj, grid->nc_nalloc*grid->na_c/grid->na_cj, 16);
553             }
554         }
555
556         srenew(grid->flags, grid->nc_nalloc);
557         if (nbs->bFEP)
558         {
559             srenew(grid->fep, grid->nc_nalloc*grid->na_sc/grid->na_c);
560         }
561     }
562
563     copy_rvec(corner0, grid->c0);
564     copy_rvec(corner1, grid->c1);
565
566     return nc_max;
567 }
568
569 /* We need to sort paricles in grid columns on z-coordinate.
570  * As particle are very often distributed homogeneously, we a sorting
571  * algorithm similar to pigeonhole sort. We multiply the z-coordinate
572  * by a factor, cast to an int and try to store in that hole. If the hole
573  * is full, we move this or another particle. A second pass is needed to make
574  * contiguous elements. SORT_GRID_OVERSIZE is the ratio of holes to particles.
575  * 4 is the optimal value for homogeneous particle distribution and allows
576  * for an O(#particles) sort up till distributions were all particles are
577  * concentrated in 1/4 of the space. No NlogN fallback is implemented,
578  * as it can be expensive to detect imhomogeneous particle distributions.
579  * SGSF is the maximum ratio of holes used, in the worst case all particles
580  * end up in the last hole and we need #particles extra holes at the end.
581  */
582 #define SORT_GRID_OVERSIZE 4
583 #define SGSF (SORT_GRID_OVERSIZE + 1)
584
585 /* Sort particle index a on coordinates x along dim.
586  * Backwards tells if we want decreasing iso increasing coordinates.
587  * h0 is the minimum of the coordinate range.
588  * invh is the 1/length of the sorting range.
589  * n_per_h (>=n) is the expected average number of particles per 1/invh
590  * sort is the sorting work array.
591  * sort should have a size of at least n_per_h*SORT_GRID_OVERSIZE + n,
592  * or easier, allocate at least n*SGSF elements.
593  */
594 static void sort_atoms(int dim, gmx_bool Backwards,
595                        int gmx_unused dd_zone,
596                        int *a, int n, rvec *x,
597                        real h0, real invh, int n_per_h,
598                        int *sort)
599 {
600     int nsort, i, c;
601     int zi, zim, zi_min, zi_max;
602     int cp, tmp;
603
604     if (n <= 1)
605     {
606         /* Nothing to do */
607         return;
608     }
609
610 #ifndef NDEBUG
611     if (n > n_per_h)
612     {
613         gmx_incons("n > n_per_h");
614     }
615 #endif
616
617     /* Transform the inverse range height into the inverse hole height */
618     invh *= n_per_h*SORT_GRID_OVERSIZE;
619
620     /* Set nsort to the maximum possible number of holes used.
621      * In worst case all n elements end up in the last bin.
622      */
623     nsort = n_per_h*SORT_GRID_OVERSIZE + n;
624
625     /* Determine the index range used, so we can limit it for the second pass */
626     zi_min = INT_MAX;
627     zi_max = -1;
628
629     /* Sort the particles using a simple index sort */
630     for (i = 0; i < n; i++)
631     {
632         /* The cast takes care of float-point rounding effects below zero.
633          * This code assumes particles are less than 1/SORT_GRID_OVERSIZE
634          * times the box height out of the box.
635          */
636         zi = (int)((x[a[i]][dim] - h0)*invh);
637
638 #ifndef NDEBUG
639         /* As we can have rounding effect, we use > iso >= here */
640         if (zi < 0 || (dd_zone == 0 && zi > n_per_h*SORT_GRID_OVERSIZE))
641         {
642             gmx_fatal(FARGS, "(int)((x[%d][%c]=%f - %f)*%f) = %d, not in 0 - %d*%d\n",
643                       a[i], 'x'+dim, x[a[i]][dim], h0, invh, zi,
644                       n_per_h, SORT_GRID_OVERSIZE);
645         }
646 #endif
647
648         /* In a non-local domain, particles communcated for bonded interactions
649          * can be far beyond the grid size, which is set by the non-bonded
650          * cut-off distance. We sort such particles into the last cell.
651          */
652         if (zi > n_per_h*SORT_GRID_OVERSIZE)
653         {
654             zi = n_per_h*SORT_GRID_OVERSIZE;
655         }
656
657         /* Ideally this particle should go in sort cell zi,
658          * but that might already be in use,
659          * in that case find the first empty cell higher up
660          */
661         if (sort[zi] < 0)
662         {
663             sort[zi] = a[i];
664             zi_min   = min(zi_min, zi);
665             zi_max   = max(zi_max, zi);
666         }
667         else
668         {
669             /* We have multiple atoms in the same sorting slot.
670              * Sort on real z for minimal bounding box size.
671              * There is an extra check for identical z to ensure
672              * well-defined output order, independent of input order
673              * to ensure binary reproducibility after restarts.
674              */
675             while (sort[zi] >= 0 && ( x[a[i]][dim] >  x[sort[zi]][dim] ||
676                                       (x[a[i]][dim] == x[sort[zi]][dim] &&
677                                        a[i] > sort[zi])))
678             {
679                 zi++;
680             }
681
682             if (sort[zi] >= 0)
683             {
684                 /* Shift all elements by one slot until we find an empty slot */
685                 cp  = sort[zi];
686                 zim = zi + 1;
687                 while (sort[zim] >= 0)
688                 {
689                     tmp       = sort[zim];
690                     sort[zim] = cp;
691                     cp        = tmp;
692                     zim++;
693                 }
694                 sort[zim] = cp;
695                 zi_max    = max(zi_max, zim);
696             }
697             sort[zi] = a[i];
698             zi_max   = max(zi_max, zi);
699         }
700     }
701
702     c = 0;
703     if (!Backwards)
704     {
705         for (zi = 0; zi < nsort; zi++)
706         {
707             if (sort[zi] >= 0)
708             {
709                 a[c++]   = sort[zi];
710                 sort[zi] = -1;
711             }
712         }
713     }
714     else
715     {
716         for (zi = zi_max; zi >= zi_min; zi--)
717         {
718             if (sort[zi] >= 0)
719             {
720                 a[c++]   = sort[zi];
721                 sort[zi] = -1;
722             }
723         }
724     }
725     if (c < n)
726     {
727         gmx_incons("Lost particles while sorting");
728     }
729 }
730
731 #ifdef GMX_DOUBLE
732 #define R2F_D(x) ((float)((x) >= 0 ? ((1-GMX_FLOAT_EPS)*(x)) : ((1+GMX_FLOAT_EPS)*(x))))
733 #define R2F_U(x) ((float)((x) >= 0 ? ((1+GMX_FLOAT_EPS)*(x)) : ((1-GMX_FLOAT_EPS)*(x))))
734 #else
735 #define R2F_D(x) (x)
736 #define R2F_U(x) (x)
737 #endif
738
739 /* Coordinate order x,y,z, bb order xyz0 */
740 static void calc_bounding_box(int na, int stride, const real *x, nbnxn_bb_t *bb)
741 {
742     int  i, j;
743     real xl, xh, yl, yh, zl, zh;
744
745     i  = 0;
746     xl = x[i+XX];
747     xh = x[i+XX];
748     yl = x[i+YY];
749     yh = x[i+YY];
750     zl = x[i+ZZ];
751     zh = x[i+ZZ];
752     i += stride;
753     for (j = 1; j < na; j++)
754     {
755         xl = min(xl, x[i+XX]);
756         xh = max(xh, x[i+XX]);
757         yl = min(yl, x[i+YY]);
758         yh = max(yh, x[i+YY]);
759         zl = min(zl, x[i+ZZ]);
760         zh = max(zh, x[i+ZZ]);
761         i += stride;
762     }
763     /* Note: possible double to float conversion here */
764     bb->lower[BB_X] = R2F_D(xl);
765     bb->lower[BB_Y] = R2F_D(yl);
766     bb->lower[BB_Z] = R2F_D(zl);
767     bb->upper[BB_X] = R2F_U(xh);
768     bb->upper[BB_Y] = R2F_U(yh);
769     bb->upper[BB_Z] = R2F_U(zh);
770 }
771
772 /* Packed coordinates, bb order xyz0 */
773 static void calc_bounding_box_x_x4(int na, const real *x, nbnxn_bb_t *bb)
774 {
775     int  j;
776     real xl, xh, yl, yh, zl, zh;
777
778     xl = x[XX*PACK_X4];
779     xh = x[XX*PACK_X4];
780     yl = x[YY*PACK_X4];
781     yh = x[YY*PACK_X4];
782     zl = x[ZZ*PACK_X4];
783     zh = x[ZZ*PACK_X4];
784     for (j = 1; j < na; j++)
785     {
786         xl = min(xl, x[j+XX*PACK_X4]);
787         xh = max(xh, x[j+XX*PACK_X4]);
788         yl = min(yl, x[j+YY*PACK_X4]);
789         yh = max(yh, x[j+YY*PACK_X4]);
790         zl = min(zl, x[j+ZZ*PACK_X4]);
791         zh = max(zh, x[j+ZZ*PACK_X4]);
792     }
793     /* Note: possible double to float conversion here */
794     bb->lower[BB_X] = R2F_D(xl);
795     bb->lower[BB_Y] = R2F_D(yl);
796     bb->lower[BB_Z] = R2F_D(zl);
797     bb->upper[BB_X] = R2F_U(xh);
798     bb->upper[BB_Y] = R2F_U(yh);
799     bb->upper[BB_Z] = R2F_U(zh);
800 }
801
802 /* Packed coordinates, bb order xyz0 */
803 static void calc_bounding_box_x_x8(int na, const real *x, nbnxn_bb_t *bb)
804 {
805     int  j;
806     real xl, xh, yl, yh, zl, zh;
807
808     xl = x[XX*PACK_X8];
809     xh = x[XX*PACK_X8];
810     yl = x[YY*PACK_X8];
811     yh = x[YY*PACK_X8];
812     zl = x[ZZ*PACK_X8];
813     zh = x[ZZ*PACK_X8];
814     for (j = 1; j < na; j++)
815     {
816         xl = min(xl, x[j+XX*PACK_X8]);
817         xh = max(xh, x[j+XX*PACK_X8]);
818         yl = min(yl, x[j+YY*PACK_X8]);
819         yh = max(yh, x[j+YY*PACK_X8]);
820         zl = min(zl, x[j+ZZ*PACK_X8]);
821         zh = max(zh, x[j+ZZ*PACK_X8]);
822     }
823     /* Note: possible double to float conversion here */
824     bb->lower[BB_X] = R2F_D(xl);
825     bb->lower[BB_Y] = R2F_D(yl);
826     bb->lower[BB_Z] = R2F_D(zl);
827     bb->upper[BB_X] = R2F_U(xh);
828     bb->upper[BB_Y] = R2F_U(yh);
829     bb->upper[BB_Z] = R2F_U(zh);
830 }
831
832 /* Packed coordinates, bb order xyz0 */
833 static void calc_bounding_box_x_x4_halves(int na, const real *x,
834                                           nbnxn_bb_t *bb, nbnxn_bb_t *bbj)
835 {
836     calc_bounding_box_x_x4(min(na, 2), x, bbj);
837
838     if (na > 2)
839     {
840         calc_bounding_box_x_x4(min(na-2, 2), x+(PACK_X4>>1), bbj+1);
841     }
842     else
843     {
844         /* Set the "empty" bounding box to the same as the first one,
845          * so we don't need to treat special cases in the rest of the code.
846          */
847 #ifdef NBNXN_SEARCH_BB_SIMD4
848         gmx_simd4_store_f(&bbj[1].lower[0], gmx_simd4_load_f(&bbj[0].lower[0]));
849         gmx_simd4_store_f(&bbj[1].upper[0], gmx_simd4_load_f(&bbj[0].upper[0]));
850 #else
851         bbj[1] = bbj[0];
852 #endif
853     }
854
855 #ifdef NBNXN_SEARCH_BB_SIMD4
856     gmx_simd4_store_f(&bb->lower[0],
857                       gmx_simd4_min_f(gmx_simd4_load_f(&bbj[0].lower[0]),
858                                       gmx_simd4_load_f(&bbj[1].lower[0])));
859     gmx_simd4_store_f(&bb->upper[0],
860                       gmx_simd4_max_f(gmx_simd4_load_f(&bbj[0].upper[0]),
861                                       gmx_simd4_load_f(&bbj[1].upper[0])));
862 #else
863     {
864         int i;
865
866         for (i = 0; i < NNBSBB_C; i++)
867         {
868             bb->lower[i] = min(bbj[0].lower[i], bbj[1].lower[i]);
869             bb->upper[i] = max(bbj[0].upper[i], bbj[1].upper[i]);
870         }
871     }
872 #endif
873 }
874
875 #ifdef NBNXN_SEARCH_BB_SIMD4
876
877 /* Coordinate order xyz, bb order xxxxyyyyzzzz */
878 static void calc_bounding_box_xxxx(int na, int stride, const real *x, float *bb)
879 {
880     int  i, j;
881     real xl, xh, yl, yh, zl, zh;
882
883     i  = 0;
884     xl = x[i+XX];
885     xh = x[i+XX];
886     yl = x[i+YY];
887     yh = x[i+YY];
888     zl = x[i+ZZ];
889     zh = x[i+ZZ];
890     i += stride;
891     for (j = 1; j < na; j++)
892     {
893         xl = min(xl, x[i+XX]);
894         xh = max(xh, x[i+XX]);
895         yl = min(yl, x[i+YY]);
896         yh = max(yh, x[i+YY]);
897         zl = min(zl, x[i+ZZ]);
898         zh = max(zh, x[i+ZZ]);
899         i += stride;
900     }
901     /* Note: possible double to float conversion here */
902     bb[0*STRIDE_PBB] = R2F_D(xl);
903     bb[1*STRIDE_PBB] = R2F_D(yl);
904     bb[2*STRIDE_PBB] = R2F_D(zl);
905     bb[3*STRIDE_PBB] = R2F_U(xh);
906     bb[4*STRIDE_PBB] = R2F_U(yh);
907     bb[5*STRIDE_PBB] = R2F_U(zh);
908 }
909
910 #endif /* NBNXN_SEARCH_BB_SIMD4 */
911
912 #ifdef NBNXN_SEARCH_SIMD4_FLOAT_X_BB
913
914 /* Coordinate order xyz?, bb order xyz0 */
915 static void calc_bounding_box_simd4(int na, const float *x, nbnxn_bb_t *bb)
916 {
917     gmx_simd4_float_t bb_0_S, bb_1_S;
918     gmx_simd4_float_t x_S;
919
920     int               i;
921
922     bb_0_S = gmx_simd4_load_f(x);
923     bb_1_S = bb_0_S;
924
925     for (i = 1; i < na; i++)
926     {
927         x_S    = gmx_simd4_load_f(x+i*NNBSBB_C);
928         bb_0_S = gmx_simd4_min_f(bb_0_S, x_S);
929         bb_1_S = gmx_simd4_max_f(bb_1_S, x_S);
930     }
931
932     gmx_simd4_store_f(&bb->lower[0], bb_0_S);
933     gmx_simd4_store_f(&bb->upper[0], bb_1_S);
934 }
935
936 /* Coordinate order xyz?, bb order xxxxyyyyzzzz */
937 static void calc_bounding_box_xxxx_simd4(int na, const float *x,
938                                          nbnxn_bb_t *bb_work_aligned,
939                                          real *bb)
940 {
941     calc_bounding_box_simd4(na, x, bb_work_aligned);
942
943     bb[0*STRIDE_PBB] = bb_work_aligned->lower[BB_X];
944     bb[1*STRIDE_PBB] = bb_work_aligned->lower[BB_Y];
945     bb[2*STRIDE_PBB] = bb_work_aligned->lower[BB_Z];
946     bb[3*STRIDE_PBB] = bb_work_aligned->upper[BB_X];
947     bb[4*STRIDE_PBB] = bb_work_aligned->upper[BB_Y];
948     bb[5*STRIDE_PBB] = bb_work_aligned->upper[BB_Z];
949 }
950
951 #endif /* NBNXN_SEARCH_SIMD4_FLOAT_X_BB */
952
953
954 /* Combines pairs of consecutive bounding boxes */
955 static void combine_bounding_box_pairs(nbnxn_grid_t *grid, const nbnxn_bb_t *bb)
956 {
957     int    i, j, sc2, nc2, c2;
958
959     for (i = 0; i < grid->ncx*grid->ncy; i++)
960     {
961         /* Starting bb in a column is expected to be 2-aligned */
962         sc2 = grid->cxy_ind[i]>>1;
963         /* For odd numbers skip the last bb here */
964         nc2 = (grid->cxy_na[i]+3)>>(2+1);
965         for (c2 = sc2; c2 < sc2+nc2; c2++)
966         {
967 #ifdef NBNXN_SEARCH_BB_SIMD4
968             gmx_simd4_float_t min_S, max_S;
969
970             min_S = gmx_simd4_min_f(gmx_simd4_load_f(&bb[c2*2+0].lower[0]),
971                                     gmx_simd4_load_f(&bb[c2*2+1].lower[0]));
972             max_S = gmx_simd4_max_f(gmx_simd4_load_f(&bb[c2*2+0].upper[0]),
973                                     gmx_simd4_load_f(&bb[c2*2+1].upper[0]));
974             gmx_simd4_store_f(&grid->bbj[c2].lower[0], min_S);
975             gmx_simd4_store_f(&grid->bbj[c2].upper[0], max_S);
976 #else
977             for (j = 0; j < NNBSBB_C; j++)
978             {
979                 grid->bbj[c2].lower[j] = min(bb[c2*2+0].lower[j],
980                                              bb[c2*2+1].lower[j]);
981                 grid->bbj[c2].upper[j] = max(bb[c2*2+0].upper[j],
982                                              bb[c2*2+1].upper[j]);
983             }
984 #endif
985         }
986         if (((grid->cxy_na[i]+3)>>2) & 1)
987         {
988             /* The bb count in this column is odd: duplicate the last bb */
989             for (j = 0; j < NNBSBB_C; j++)
990             {
991                 grid->bbj[c2].lower[j] = bb[c2*2].lower[j];
992                 grid->bbj[c2].upper[j] = bb[c2*2].upper[j];
993             }
994         }
995     }
996 }
997
998
999 /* Prints the average bb size, used for debug output */
1000 static void print_bbsizes_simple(FILE                *fp,
1001                                  const nbnxn_search_t nbs,
1002                                  const nbnxn_grid_t  *grid)
1003 {
1004     int  c, d;
1005     dvec ba;
1006
1007     clear_dvec(ba);
1008     for (c = 0; c < grid->nc; c++)
1009     {
1010         for (d = 0; d < DIM; d++)
1011         {
1012             ba[d] += grid->bb[c].upper[d] - grid->bb[c].lower[d];
1013         }
1014     }
1015     dsvmul(1.0/grid->nc, ba, ba);
1016
1017     fprintf(fp, "ns bb: %4.2f %4.2f %4.2f  %4.2f %4.2f %4.2f rel %4.2f %4.2f %4.2f\n",
1018             nbs->box[XX][XX]/grid->ncx,
1019             nbs->box[YY][YY]/grid->ncy,
1020             nbs->box[ZZ][ZZ]*grid->ncx*grid->ncy/grid->nc,
1021             ba[XX], ba[YY], ba[ZZ],
1022             ba[XX]*grid->ncx/nbs->box[XX][XX],
1023             ba[YY]*grid->ncy/nbs->box[YY][YY],
1024             ba[ZZ]*grid->nc/(grid->ncx*grid->ncy*nbs->box[ZZ][ZZ]));
1025 }
1026
1027 /* Prints the average bb size, used for debug output */
1028 static void print_bbsizes_supersub(FILE                *fp,
1029                                    const nbnxn_search_t nbs,
1030                                    const nbnxn_grid_t  *grid)
1031 {
1032     int  ns, c, s;
1033     dvec ba;
1034
1035     clear_dvec(ba);
1036     ns = 0;
1037     for (c = 0; c < grid->nc; c++)
1038     {
1039 #ifdef NBNXN_BBXXXX
1040         for (s = 0; s < grid->nsubc[c]; s += STRIDE_PBB)
1041         {
1042             int cs_w, i, d;
1043
1044             cs_w = (c*GPU_NSUBCELL + s)/STRIDE_PBB;
1045             for (i = 0; i < STRIDE_PBB; i++)
1046             {
1047                 for (d = 0; d < DIM; d++)
1048                 {
1049                     ba[d] +=
1050                         grid->pbb[cs_w*NNBSBB_XXXX+(DIM+d)*STRIDE_PBB+i] -
1051                         grid->pbb[cs_w*NNBSBB_XXXX+     d *STRIDE_PBB+i];
1052                 }
1053             }
1054         }
1055 #else
1056         for (s = 0; s < grid->nsubc[c]; s++)
1057         {
1058             int cs, d;
1059
1060             cs = c*GPU_NSUBCELL + s;
1061             for (d = 0; d < DIM; d++)
1062             {
1063                 ba[d] += grid->bb[cs].upper[d] - grid->bb[cs].lower[d];
1064             }
1065         }
1066 #endif
1067         ns += grid->nsubc[c];
1068     }
1069     dsvmul(1.0/ns, ba, ba);
1070
1071     fprintf(fp, "ns bb: %4.2f %4.2f %4.2f  %4.2f %4.2f %4.2f rel %4.2f %4.2f %4.2f\n",
1072             nbs->box[XX][XX]/(grid->ncx*GPU_NSUBCELL_X),
1073             nbs->box[YY][YY]/(grid->ncy*GPU_NSUBCELL_Y),
1074             nbs->box[ZZ][ZZ]*grid->ncx*grid->ncy/(grid->nc*GPU_NSUBCELL_Z),
1075             ba[XX], ba[YY], ba[ZZ],
1076             ba[XX]*grid->ncx*GPU_NSUBCELL_X/nbs->box[XX][XX],
1077             ba[YY]*grid->ncy*GPU_NSUBCELL_Y/nbs->box[YY][YY],
1078             ba[ZZ]*grid->nc*GPU_NSUBCELL_Z/(grid->ncx*grid->ncy*nbs->box[ZZ][ZZ]));
1079 }
1080
1081 /* Potentially sorts atoms on LJ coefficients !=0 and ==0.
1082  * Also sets interaction flags.
1083  */
1084 void sort_on_lj(int na_c,
1085                 int a0, int a1, const int *atinfo,
1086                 int *order,
1087                 int *flags)
1088 {
1089     int      subc, s, a, n1, n2, a_lj_max, i, j;
1090     int      sort1[NBNXN_NA_SC_MAX/GPU_NSUBCELL];
1091     int      sort2[NBNXN_NA_SC_MAX/GPU_NSUBCELL];
1092     gmx_bool haveQ, bFEP;
1093
1094     *flags = 0;
1095
1096     subc = 0;
1097     for (s = a0; s < a1; s += na_c)
1098     {
1099         /* Make lists for this (sub-)cell on atoms with and without LJ */
1100         n1       = 0;
1101         n2       = 0;
1102         haveQ    = FALSE;
1103         a_lj_max = -1;
1104         for (a = s; a < min(s+na_c, a1); a++)
1105         {
1106             haveQ = haveQ || GET_CGINFO_HAS_Q(atinfo[order[a]]);
1107
1108             if (GET_CGINFO_HAS_VDW(atinfo[order[a]]))
1109             {
1110                 sort1[n1++] = order[a];
1111                 a_lj_max    = a;
1112             }
1113             else
1114             {
1115                 sort2[n2++] = order[a];
1116             }
1117         }
1118
1119         /* If we don't have atoms with LJ, there's nothing to sort */
1120         if (n1 > 0)
1121         {
1122             *flags |= NBNXN_CI_DO_LJ(subc);
1123
1124             if (2*n1 <= na_c)
1125             {
1126                 /* Only sort when strictly necessary. Ordering particles
1127                  * Ordering particles can lead to less accurate summation
1128                  * due to rounding, both for LJ and Coulomb interactions.
1129                  */
1130                 if (2*(a_lj_max - s) >= na_c)
1131                 {
1132                     for (i = 0; i < n1; i++)
1133                     {
1134                         order[a0+i] = sort1[i];
1135                     }
1136                     for (j = 0; j < n2; j++)
1137                     {
1138                         order[a0+n1+j] = sort2[j];
1139                     }
1140                 }
1141
1142                 *flags |= NBNXN_CI_HALF_LJ(subc);
1143             }
1144         }
1145         if (haveQ)
1146         {
1147             *flags |= NBNXN_CI_DO_COUL(subc);
1148         }
1149         subc++;
1150     }
1151 }
1152
1153 /* Fill a pair search cell with atoms.
1154  * Potentially sorts atoms and sets the interaction flags.
1155  */
1156 void fill_cell(const nbnxn_search_t nbs,
1157                nbnxn_grid_t *grid,
1158                nbnxn_atomdata_t *nbat,
1159                int a0, int a1,
1160                const int *atinfo,
1161                rvec *x,
1162                int sx, int sy, int sz,
1163                nbnxn_bb_t gmx_unused *bb_work_aligned)
1164 {
1165     int         na, a;
1166     size_t      offset;
1167     nbnxn_bb_t *bb_ptr;
1168 #ifdef NBNXN_BBXXXX
1169     float      *pbb_ptr;
1170 #endif
1171
1172     na = a1 - a0;
1173
1174     if (grid->bSimple)
1175     {
1176         sort_on_lj(grid->na_c, a0, a1, atinfo, nbs->a,
1177                    grid->flags+(a0>>grid->na_c_2log)-grid->cell0);
1178     }
1179
1180     if (nbs->bFEP)
1181     {
1182         /* Set the fep flag for perturbed atoms in this (sub-)cell */
1183         int c, at;
1184
1185         /* The grid-local cluster/(sub-)cell index */
1186         c            = (a0 >> grid->na_c_2log) - grid->cell0*(grid->bSimple ? 1 : GPU_NSUBCELL);
1187         grid->fep[c] = 0;
1188         for (at = a0; at < a1; at++)
1189         {
1190             if (nbs->a[at] >= 0 && GET_CGINFO_FEP(atinfo[nbs->a[at]]))
1191             {
1192                 grid->fep[c] |= (1 << (at - a0));
1193             }
1194         }
1195     }
1196
1197     /* Now we have sorted the atoms, set the cell indices */
1198     for (a = a0; a < a1; a++)
1199     {
1200         nbs->cell[nbs->a[a]] = a;
1201     }
1202
1203     copy_rvec_to_nbat_real(nbs->a+a0, a1-a0, grid->na_c, x,
1204                            nbat->XFormat, nbat->x, a0,
1205                            sx, sy, sz);
1206
1207     if (nbat->XFormat == nbatX4)
1208     {
1209         /* Store the bounding boxes as xyz.xyz. */
1210         offset = (a0 - grid->cell0*grid->na_sc) >> grid->na_c_2log;
1211         bb_ptr = grid->bb + offset;
1212
1213 #if defined GMX_NBNXN_SIMD && GMX_SIMD_REAL_WIDTH == 2
1214         if (2*grid->na_cj == grid->na_c)
1215         {
1216             calc_bounding_box_x_x4_halves(na, nbat->x+X4_IND_A(a0), bb_ptr,
1217                                           grid->bbj+offset*2);
1218         }
1219         else
1220 #endif
1221         {
1222             calc_bounding_box_x_x4(na, nbat->x+X4_IND_A(a0), bb_ptr);
1223         }
1224     }
1225     else if (nbat->XFormat == nbatX8)
1226     {
1227         /* Store the bounding boxes as xyz.xyz. */
1228         offset = (a0 - grid->cell0*grid->na_sc) >> grid->na_c_2log;
1229         bb_ptr = grid->bb + offset;
1230
1231         calc_bounding_box_x_x8(na, nbat->x+X8_IND_A(a0), bb_ptr);
1232     }
1233 #ifdef NBNXN_BBXXXX
1234     else if (!grid->bSimple)
1235     {
1236         /* Store the bounding boxes in a format convenient
1237          * for SIMD4 calculations: xxxxyyyyzzzz...
1238          */
1239         pbb_ptr =
1240             grid->pbb +
1241             ((a0-grid->cell0*grid->na_sc)>>(grid->na_c_2log+STRIDE_PBB_2LOG))*NNBSBB_XXXX +
1242             (((a0-grid->cell0*grid->na_sc)>>grid->na_c_2log) & (STRIDE_PBB-1));
1243
1244 #ifdef NBNXN_SEARCH_SIMD4_FLOAT_X_BB
1245         if (nbat->XFormat == nbatXYZQ)
1246         {
1247             calc_bounding_box_xxxx_simd4(na, nbat->x+a0*nbat->xstride,
1248                                          bb_work_aligned, pbb_ptr);
1249         }
1250         else
1251 #endif
1252         {
1253             calc_bounding_box_xxxx(na, nbat->xstride, nbat->x+a0*nbat->xstride,
1254                                    pbb_ptr);
1255         }
1256         if (gmx_debug_at)
1257         {
1258             fprintf(debug, "%2d %2d %2d bb %5.2f %5.2f %5.2f %5.2f %5.2f %5.2f\n",
1259                     sx, sy, sz,
1260                     pbb_ptr[0*STRIDE_PBB], pbb_ptr[3*STRIDE_PBB],
1261                     pbb_ptr[1*STRIDE_PBB], pbb_ptr[4*STRIDE_PBB],
1262                     pbb_ptr[2*STRIDE_PBB], pbb_ptr[5*STRIDE_PBB]);
1263         }
1264     }
1265 #endif
1266     else
1267     {
1268         /* Store the bounding boxes as xyz.xyz. */
1269         bb_ptr = grid->bb+((a0-grid->cell0*grid->na_sc)>>grid->na_c_2log);
1270
1271         calc_bounding_box(na, nbat->xstride, nbat->x+a0*nbat->xstride,
1272                           bb_ptr);
1273
1274         if (gmx_debug_at)
1275         {
1276             int bbo;
1277             bbo = (a0 - grid->cell0*grid->na_sc)/grid->na_c;
1278             fprintf(debug, "%2d %2d %2d bb %5.2f %5.2f %5.2f %5.2f %5.2f %5.2f\n",
1279                     sx, sy, sz,
1280                     grid->bb[bbo].lower[BB_X],
1281                     grid->bb[bbo].lower[BB_Y],
1282                     grid->bb[bbo].lower[BB_Z],
1283                     grid->bb[bbo].upper[BB_X],
1284                     grid->bb[bbo].upper[BB_Y],
1285                     grid->bb[bbo].upper[BB_Z]);
1286         }
1287     }
1288 }
1289
1290 /* Spatially sort the atoms within one grid column */
1291 static void sort_columns_simple(const nbnxn_search_t nbs,
1292                                 int dd_zone,
1293                                 nbnxn_grid_t *grid,
1294                                 int a0, int a1,
1295                                 const int *atinfo,
1296                                 rvec *x,
1297                                 nbnxn_atomdata_t *nbat,
1298                                 int cxy_start, int cxy_end,
1299                                 int *sort_work)
1300 {
1301     int  cxy;
1302     int  cx, cy, cz, ncz, cfilled, c;
1303     int  na, ash, ind, a;
1304     int  na_c, ash_c;
1305
1306     if (debug)
1307     {
1308         fprintf(debug, "cell0 %d sorting columns %d - %d, atoms %d - %d\n",
1309                 grid->cell0, cxy_start, cxy_end, a0, a1);
1310     }
1311
1312     /* Sort the atoms within each x,y column in 3 dimensions */
1313     for (cxy = cxy_start; cxy < cxy_end; cxy++)
1314     {
1315         cx = cxy/grid->ncy;
1316         cy = cxy - cx*grid->ncy;
1317
1318         na  = grid->cxy_na[cxy];
1319         ncz = grid->cxy_ind[cxy+1] - grid->cxy_ind[cxy];
1320         ash = (grid->cell0 + grid->cxy_ind[cxy])*grid->na_sc;
1321
1322         /* Sort the atoms within each x,y column on z coordinate */
1323         sort_atoms(ZZ, FALSE, dd_zone,
1324                    nbs->a+ash, na, x,
1325                    grid->c0[ZZ],
1326                    1.0/nbs->box[ZZ][ZZ], ncz*grid->na_sc,
1327                    sort_work);
1328
1329         /* Fill the ncz cells in this column */
1330         cfilled = grid->cxy_ind[cxy];
1331         for (cz = 0; cz < ncz; cz++)
1332         {
1333             c  = grid->cxy_ind[cxy] + cz;
1334
1335             ash_c = ash + cz*grid->na_sc;
1336             na_c  = min(grid->na_sc, na-(ash_c-ash));
1337
1338             fill_cell(nbs, grid, nbat,
1339                       ash_c, ash_c+na_c, atinfo, x,
1340                       grid->na_sc*cx + (dd_zone >> 2),
1341                       grid->na_sc*cy + (dd_zone & 3),
1342                       grid->na_sc*cz,
1343                       NULL);
1344
1345             /* This copy to bbcz is not really necessary.
1346              * But it allows to use the same grid search code
1347              * for the simple and supersub cell setups.
1348              */
1349             if (na_c > 0)
1350             {
1351                 cfilled = c;
1352             }
1353             grid->bbcz[c*NNBSBB_D  ] = grid->bb[cfilled].lower[BB_Z];
1354             grid->bbcz[c*NNBSBB_D+1] = grid->bb[cfilled].upper[BB_Z];
1355         }
1356
1357         /* Set the unused atom indices to -1 */
1358         for (ind = na; ind < ncz*grid->na_sc; ind++)
1359         {
1360             nbs->a[ash+ind] = -1;
1361         }
1362     }
1363 }
1364
1365 /* Spatially sort the atoms within one grid column */
1366 static void sort_columns_supersub(const nbnxn_search_t nbs,
1367                                   int dd_zone,
1368                                   nbnxn_grid_t *grid,
1369                                   int a0, int a1,
1370                                   const int *atinfo,
1371                                   rvec *x,
1372                                   nbnxn_atomdata_t *nbat,
1373                                   int cxy_start, int cxy_end,
1374                                   int *sort_work)
1375 {
1376     int        cxy;
1377     int        cx, cy, cz = -1, c = -1, ncz;
1378     int        na, ash, na_c, ind, a;
1379     int        subdiv_z, sub_z, na_z, ash_z;
1380     int        subdiv_y, sub_y, na_y, ash_y;
1381     int        subdiv_x, sub_x, na_x, ash_x;
1382
1383     nbnxn_bb_t bb_work_array[2], *bb_work_aligned;
1384
1385     bb_work_aligned = (nbnxn_bb_t *)(((size_t)(bb_work_array+1)) & (~((size_t)15)));
1386
1387     if (debug)
1388     {
1389         fprintf(debug, "cell0 %d sorting columns %d - %d, atoms %d - %d\n",
1390                 grid->cell0, cxy_start, cxy_end, a0, a1);
1391     }
1392
1393     subdiv_x = grid->na_c;
1394     subdiv_y = GPU_NSUBCELL_X*subdiv_x;
1395     subdiv_z = GPU_NSUBCELL_Y*subdiv_y;
1396
1397     /* Sort the atoms within each x,y column in 3 dimensions */
1398     for (cxy = cxy_start; cxy < cxy_end; cxy++)
1399     {
1400         cx = cxy/grid->ncy;
1401         cy = cxy - cx*grid->ncy;
1402
1403         na  = grid->cxy_na[cxy];
1404         ncz = grid->cxy_ind[cxy+1] - grid->cxy_ind[cxy];
1405         ash = (grid->cell0 + grid->cxy_ind[cxy])*grid->na_sc;
1406
1407         /* Sort the atoms within each x,y column on z coordinate */
1408         sort_atoms(ZZ, FALSE, dd_zone,
1409                    nbs->a+ash, na, x,
1410                    grid->c0[ZZ],
1411                    1.0/nbs->box[ZZ][ZZ], ncz*grid->na_sc,
1412                    sort_work);
1413
1414         /* This loop goes over the supercells and subcells along z at once */
1415         for (sub_z = 0; sub_z < ncz*GPU_NSUBCELL_Z; sub_z++)
1416         {
1417             ash_z = ash + sub_z*subdiv_z;
1418             na_z  = min(subdiv_z, na-(ash_z-ash));
1419
1420             /* We have already sorted on z */
1421
1422             if (sub_z % GPU_NSUBCELL_Z == 0)
1423             {
1424                 cz = sub_z/GPU_NSUBCELL_Z;
1425                 c  = grid->cxy_ind[cxy] + cz;
1426
1427                 /* The number of atoms in this supercell */
1428                 na_c = min(grid->na_sc, na-(ash_z-ash));
1429
1430                 grid->nsubc[c] = min(GPU_NSUBCELL, (na_c+grid->na_c-1)/grid->na_c);
1431
1432                 /* Store the z-boundaries of the super cell */
1433                 grid->bbcz[c*NNBSBB_D  ] = x[nbs->a[ash_z]][ZZ];
1434                 grid->bbcz[c*NNBSBB_D+1] = x[nbs->a[ash_z+na_c-1]][ZZ];
1435             }
1436
1437 #if GPU_NSUBCELL_Y > 1
1438             /* Sort the atoms along y */
1439             sort_atoms(YY, (sub_z & 1), dd_zone,
1440                        nbs->a+ash_z, na_z, x,
1441                        grid->c0[YY]+cy*grid->sy,
1442                        grid->inv_sy, subdiv_z,
1443                        sort_work);
1444 #endif
1445
1446             for (sub_y = 0; sub_y < GPU_NSUBCELL_Y; sub_y++)
1447             {
1448                 ash_y = ash_z + sub_y*subdiv_y;
1449                 na_y  = min(subdiv_y, na-(ash_y-ash));
1450
1451 #if GPU_NSUBCELL_X > 1
1452                 /* Sort the atoms along x */
1453                 sort_atoms(XX, ((cz*GPU_NSUBCELL_Y + sub_y) & 1), dd_zone,
1454                            nbs->a+ash_y, na_y, x,
1455                            grid->c0[XX]+cx*grid->sx,
1456                            grid->inv_sx, subdiv_y,
1457                            sort_work);
1458 #endif
1459
1460                 for (sub_x = 0; sub_x < GPU_NSUBCELL_X; sub_x++)
1461                 {
1462                     ash_x = ash_y + sub_x*subdiv_x;
1463                     na_x  = min(subdiv_x, na-(ash_x-ash));
1464
1465                     fill_cell(nbs, grid, nbat,
1466                               ash_x, ash_x+na_x, atinfo, x,
1467                               grid->na_c*(cx*GPU_NSUBCELL_X+sub_x) + (dd_zone >> 2),
1468                               grid->na_c*(cy*GPU_NSUBCELL_Y+sub_y) + (dd_zone & 3),
1469                               grid->na_c*sub_z,
1470                               bb_work_aligned);
1471                 }
1472             }
1473         }
1474
1475         /* Set the unused atom indices to -1 */
1476         for (ind = na; ind < ncz*grid->na_sc; ind++)
1477         {
1478             nbs->a[ash+ind] = -1;
1479         }
1480     }
1481 }
1482
1483 /* Determine in which grid column atoms should go */
1484 static void calc_column_indices(nbnxn_grid_t *grid,
1485                                 int a0, int a1,
1486                                 rvec *x,
1487                                 int dd_zone, const int *move,
1488                                 int thread, int nthread,
1489                                 int *cell,
1490                                 int *cxy_na)
1491 {
1492     int  n0, n1, i;
1493     int  cx, cy;
1494
1495     /* We add one extra cell for particles which moved during DD */
1496     for (i = 0; i < grid->ncx*grid->ncy+1; i++)
1497     {
1498         cxy_na[i] = 0;
1499     }
1500
1501     n0 = a0 + (int)((thread+0)*(a1 - a0))/nthread;
1502     n1 = a0 + (int)((thread+1)*(a1 - a0))/nthread;
1503     if (dd_zone == 0)
1504     {
1505         /* Home zone */
1506         for (i = n0; i < n1; i++)
1507         {
1508             if (move == NULL || move[i] >= 0)
1509             {
1510                 /* We need to be careful with rounding,
1511                  * particles might be a few bits outside the local zone.
1512                  * The int cast takes care of the lower bound,
1513                  * we will explicitly take care of the upper bound.
1514                  */
1515                 cx = (int)((x[i][XX] - grid->c0[XX])*grid->inv_sx);
1516                 cy = (int)((x[i][YY] - grid->c0[YY])*grid->inv_sy);
1517
1518 #ifndef NDEBUG
1519                 if (cx < 0 || cx > grid->ncx ||
1520                     cy < 0 || cy > grid->ncy)
1521                 {
1522                     gmx_fatal(FARGS,
1523                               "grid cell cx %d cy %d out of range (max %d %d)\n"
1524                               "atom %f %f %f, grid->c0 %f %f",
1525                               cx, cy, grid->ncx, grid->ncy,
1526                               x[i][XX], x[i][YY], x[i][ZZ], grid->c0[XX], grid->c0[YY]);
1527                 }
1528 #endif
1529                 /* Take care of potential rouding issues */
1530                 cx = min(cx, grid->ncx - 1);
1531                 cy = min(cy, grid->ncy - 1);
1532
1533                 /* For the moment cell will contain only the, grid local,
1534                  * x and y indices, not z.
1535                  */
1536                 cell[i] = cx*grid->ncy + cy;
1537             }
1538             else
1539             {
1540                 /* Put this moved particle after the end of the grid,
1541                  * so we can process it later without using conditionals.
1542                  */
1543                 cell[i] = grid->ncx*grid->ncy;
1544             }
1545
1546             cxy_na[cell[i]]++;
1547         }
1548     }
1549     else
1550     {
1551         /* Non-home zone */
1552         for (i = n0; i < n1; i++)
1553         {
1554             cx = (int)((x[i][XX] - grid->c0[XX])*grid->inv_sx);
1555             cy = (int)((x[i][YY] - grid->c0[YY])*grid->inv_sy);
1556
1557             /* For non-home zones there could be particles outside
1558              * the non-bonded cut-off range, which have been communicated
1559              * for bonded interactions only. For the result it doesn't
1560              * matter where these end up on the grid. For performance
1561              * we put them in an extra row at the border.
1562              */
1563             cx = max(cx, 0);
1564             cx = min(cx, grid->ncx - 1);
1565             cy = max(cy, 0);
1566             cy = min(cy, grid->ncy - 1);
1567
1568             /* For the moment cell will contain only the, grid local,
1569              * x and y indices, not z.
1570              */
1571             cell[i] = cx*grid->ncy + cy;
1572
1573             cxy_na[cell[i]]++;
1574         }
1575     }
1576 }
1577
1578 /* Determine in which grid cells the atoms should go */
1579 static void calc_cell_indices(const nbnxn_search_t nbs,
1580                               int dd_zone,
1581                               nbnxn_grid_t *grid,
1582                               int a0, int a1,
1583                               const int *atinfo,
1584                               rvec *x,
1585                               const int *move,
1586                               nbnxn_atomdata_t *nbat)
1587 {
1588     int   n0, n1, i;
1589     int   cx, cy, cxy, ncz_max, ncz;
1590     int   nthread, thread;
1591     int  *cxy_na, cxy_na_i;
1592
1593     nthread = gmx_omp_nthreads_get(emntPairsearch);
1594
1595 #pragma omp parallel for num_threads(nthread) schedule(static)
1596     for (thread = 0; thread < nthread; thread++)
1597     {
1598         calc_column_indices(grid, a0, a1, x, dd_zone, move, thread, nthread,
1599                             nbs->cell, nbs->work[thread].cxy_na);
1600     }
1601
1602     /* Make the cell index as a function of x and y */
1603     ncz_max          = 0;
1604     ncz              = 0;
1605     grid->cxy_ind[0] = 0;
1606     for (i = 0; i < grid->ncx*grid->ncy+1; i++)
1607     {
1608         /* We set ncz_max at the beginning of the loop iso at the end
1609          * to skip i=grid->ncx*grid->ncy which are moved particles
1610          * that do not need to be ordered on the grid.
1611          */
1612         if (ncz > ncz_max)
1613         {
1614             ncz_max = ncz;
1615         }
1616         cxy_na_i = nbs->work[0].cxy_na[i];
1617         for (thread = 1; thread < nthread; thread++)
1618         {
1619             cxy_na_i += nbs->work[thread].cxy_na[i];
1620         }
1621         ncz = (cxy_na_i + grid->na_sc - 1)/grid->na_sc;
1622         if (nbat->XFormat == nbatX8)
1623         {
1624             /* Make the number of cell a multiple of 2 */
1625             ncz = (ncz + 1) & ~1;
1626         }
1627         grid->cxy_ind[i+1] = grid->cxy_ind[i] + ncz;
1628         /* Clear cxy_na, so we can reuse the array below */
1629         grid->cxy_na[i] = 0;
1630     }
1631     grid->nc = grid->cxy_ind[grid->ncx*grid->ncy] - grid->cxy_ind[0];
1632
1633     nbat->natoms = (grid->cell0 + grid->nc)*grid->na_sc;
1634
1635     if (debug)
1636     {
1637         fprintf(debug, "ns na_sc %d na_c %d super-cells: %d x %d y %d z %.1f maxz %d\n",
1638                 grid->na_sc, grid->na_c, grid->nc,
1639                 grid->ncx, grid->ncy, grid->nc/((double)(grid->ncx*grid->ncy)),
1640                 ncz_max);
1641         if (gmx_debug_at)
1642         {
1643             i = 0;
1644             for (cy = 0; cy < grid->ncy; cy++)
1645             {
1646                 for (cx = 0; cx < grid->ncx; cx++)
1647                 {
1648                     fprintf(debug, " %2d", grid->cxy_ind[i+1]-grid->cxy_ind[i]);
1649                     i++;
1650                 }
1651                 fprintf(debug, "\n");
1652             }
1653         }
1654     }
1655
1656     /* Make sure the work array for sorting is large enough */
1657     if (ncz_max*grid->na_sc*SGSF > nbs->work[0].sort_work_nalloc)
1658     {
1659         for (thread = 0; thread < nbs->nthread_max; thread++)
1660         {
1661             nbs->work[thread].sort_work_nalloc =
1662                 over_alloc_large(ncz_max*grid->na_sc*SGSF);
1663             srenew(nbs->work[thread].sort_work,
1664                    nbs->work[thread].sort_work_nalloc);
1665             /* When not in use, all elements should be -1 */
1666             for (i = 0; i < nbs->work[thread].sort_work_nalloc; i++)
1667             {
1668                 nbs->work[thread].sort_work[i] = -1;
1669             }
1670         }
1671     }
1672
1673     /* Now we know the dimensions we can fill the grid.
1674      * This is the first, unsorted fill. We sort the columns after this.
1675      */
1676     for (i = a0; i < a1; i++)
1677     {
1678         /* At this point nbs->cell contains the local grid x,y indices */
1679         cxy = nbs->cell[i];
1680         nbs->a[(grid->cell0 + grid->cxy_ind[cxy])*grid->na_sc + grid->cxy_na[cxy]++] = i;
1681     }
1682
1683     if (dd_zone == 0)
1684     {
1685         /* Set the cell indices for the moved particles */
1686         n0 = grid->nc*grid->na_sc;
1687         n1 = grid->nc*grid->na_sc+grid->cxy_na[grid->ncx*grid->ncy];
1688         if (dd_zone == 0)
1689         {
1690             for (i = n0; i < n1; i++)
1691             {
1692                 nbs->cell[nbs->a[i]] = i;
1693             }
1694         }
1695     }
1696
1697     /* Sort the super-cell columns along z into the sub-cells. */
1698 #pragma omp parallel for num_threads(nbs->nthread_max) schedule(static)
1699     for (thread = 0; thread < nbs->nthread_max; thread++)
1700     {
1701         if (grid->bSimple)
1702         {
1703             sort_columns_simple(nbs, dd_zone, grid, a0, a1, atinfo, x, nbat,
1704                                 ((thread+0)*grid->ncx*grid->ncy)/nthread,
1705                                 ((thread+1)*grid->ncx*grid->ncy)/nthread,
1706                                 nbs->work[thread].sort_work);
1707         }
1708         else
1709         {
1710             sort_columns_supersub(nbs, dd_zone, grid, a0, a1, atinfo, x, nbat,
1711                                   ((thread+0)*grid->ncx*grid->ncy)/nthread,
1712                                   ((thread+1)*grid->ncx*grid->ncy)/nthread,
1713                                   nbs->work[thread].sort_work);
1714         }
1715     }
1716
1717     if (grid->bSimple && nbat->XFormat == nbatX8)
1718     {
1719         combine_bounding_box_pairs(grid, grid->bb);
1720     }
1721
1722     if (!grid->bSimple)
1723     {
1724         grid->nsubc_tot = 0;
1725         for (i = 0; i < grid->nc; i++)
1726         {
1727             grid->nsubc_tot += grid->nsubc[i];
1728         }
1729     }
1730
1731     if (debug)
1732     {
1733         if (grid->bSimple)
1734         {
1735             print_bbsizes_simple(debug, nbs, grid);
1736         }
1737         else
1738         {
1739             fprintf(debug, "ns non-zero sub-cells: %d average atoms %.2f\n",
1740                     grid->nsubc_tot, (a1-a0)/(double)grid->nsubc_tot);
1741
1742             print_bbsizes_supersub(debug, nbs, grid);
1743         }
1744     }
1745 }
1746
1747 static void init_buffer_flags(nbnxn_buffer_flags_t *flags,
1748                               int                   natoms)
1749 {
1750     int b;
1751
1752     flags->nflag = (natoms + NBNXN_BUFFERFLAG_SIZE - 1)/NBNXN_BUFFERFLAG_SIZE;
1753     if (flags->nflag > flags->flag_nalloc)
1754     {
1755         flags->flag_nalloc = over_alloc_large(flags->nflag);
1756         srenew(flags->flag, flags->flag_nalloc);
1757     }
1758     for (b = 0; b < flags->nflag; b++)
1759     {
1760         flags->flag[b] = 0;
1761     }
1762 }
1763
1764 /* Sets up a grid and puts the atoms on the grid.
1765  * This function only operates on one domain of the domain decompostion.
1766  * Note that without domain decomposition there is only one domain.
1767  */
1768 void nbnxn_put_on_grid(nbnxn_search_t nbs,
1769                        int ePBC, matrix box,
1770                        int dd_zone,
1771                        rvec corner0, rvec corner1,
1772                        int a0, int a1,
1773                        real atom_density,
1774                        const int *atinfo,
1775                        rvec *x,
1776                        int nmoved, int *move,
1777                        int nb_kernel_type,
1778                        nbnxn_atomdata_t *nbat)
1779 {
1780     nbnxn_grid_t *grid;
1781     int           n;
1782     int           nc_max_grid, nc_max;
1783
1784     grid = &nbs->grid[dd_zone];
1785
1786     nbs_cycle_start(&nbs->cc[enbsCCgrid]);
1787
1788     grid->bSimple = nbnxn_kernel_pairlist_simple(nb_kernel_type);
1789
1790     grid->na_c      = nbnxn_kernel_to_ci_size(nb_kernel_type);
1791     grid->na_cj     = nbnxn_kernel_to_cj_size(nb_kernel_type);
1792     grid->na_sc     = (grid->bSimple ? 1 : GPU_NSUBCELL)*grid->na_c;
1793     grid->na_c_2log = get_2log(grid->na_c);
1794
1795     nbat->na_c = grid->na_c;
1796
1797     if (dd_zone == 0)
1798     {
1799         grid->cell0 = 0;
1800     }
1801     else
1802     {
1803         grid->cell0 =
1804             (nbs->grid[dd_zone-1].cell0 + nbs->grid[dd_zone-1].nc)*
1805             nbs->grid[dd_zone-1].na_sc/grid->na_sc;
1806     }
1807
1808     n = a1 - a0;
1809
1810     if (dd_zone == 0)
1811     {
1812         nbs->ePBC = ePBC;
1813         copy_mat(box, nbs->box);
1814
1815         if (atom_density >= 0)
1816         {
1817             grid->atom_density = atom_density;
1818         }
1819         else
1820         {
1821             grid->atom_density = grid_atom_density(n-nmoved, corner0, corner1);
1822         }
1823
1824         grid->cell0 = 0;
1825
1826         nbs->natoms_local    = a1 - nmoved;
1827         /* We assume that nbnxn_put_on_grid is called first
1828          * for the local atoms (dd_zone=0).
1829          */
1830         nbs->natoms_nonlocal = a1 - nmoved;
1831     }
1832     else
1833     {
1834         nbs->natoms_nonlocal = max(nbs->natoms_nonlocal, a1);
1835     }
1836
1837     nc_max_grid = set_grid_size_xy(nbs, grid,
1838                                    dd_zone, n-nmoved, corner0, corner1,
1839                                    nbs->grid[0].atom_density);
1840
1841     nc_max = grid->cell0 + nc_max_grid;
1842
1843     if (a1 > nbs->cell_nalloc)
1844     {
1845         nbs->cell_nalloc = over_alloc_large(a1);
1846         srenew(nbs->cell, nbs->cell_nalloc);
1847     }
1848
1849     /* To avoid conditionals we store the moved particles at the end of a,
1850      * make sure we have enough space.
1851      */
1852     if (nc_max*grid->na_sc + nmoved > nbs->a_nalloc)
1853     {
1854         nbs->a_nalloc = over_alloc_large(nc_max*grid->na_sc + nmoved);
1855         srenew(nbs->a, nbs->a_nalloc);
1856     }
1857
1858     /* We need padding up to a multiple of the buffer flag size: simply add */
1859     if (nc_max*grid->na_sc + NBNXN_BUFFERFLAG_SIZE > nbat->nalloc)
1860     {
1861         nbnxn_atomdata_realloc(nbat, nc_max*grid->na_sc+NBNXN_BUFFERFLAG_SIZE);
1862     }
1863
1864     calc_cell_indices(nbs, dd_zone, grid, a0, a1, atinfo, x, move, nbat);
1865
1866     if (dd_zone == 0)
1867     {
1868         nbat->natoms_local = nbat->natoms;
1869     }
1870
1871     nbs_cycle_stop(&nbs->cc[enbsCCgrid]);
1872 }
1873
1874 /* Calls nbnxn_put_on_grid for all non-local domains */
1875 void nbnxn_put_on_grid_nonlocal(nbnxn_search_t            nbs,
1876                                 const gmx_domdec_zones_t *zones,
1877                                 const int                *atinfo,
1878                                 rvec                     *x,
1879                                 int                       nb_kernel_type,
1880                                 nbnxn_atomdata_t         *nbat)
1881 {
1882     int  zone, d;
1883     rvec c0, c1;
1884
1885     for (zone = 1; zone < zones->n; zone++)
1886     {
1887         for (d = 0; d < DIM; d++)
1888         {
1889             c0[d] = zones->size[zone].bb_x0[d];
1890             c1[d] = zones->size[zone].bb_x1[d];
1891         }
1892
1893         nbnxn_put_on_grid(nbs, nbs->ePBC, NULL,
1894                           zone, c0, c1,
1895                           zones->cg_range[zone],
1896                           zones->cg_range[zone+1],
1897                           -1,
1898                           atinfo,
1899                           x,
1900                           0, NULL,
1901                           nb_kernel_type,
1902                           nbat);
1903     }
1904 }
1905
1906 /* Add simple grid type information to the local super/sub grid */
1907 void nbnxn_grid_add_simple(nbnxn_search_t    nbs,
1908                            nbnxn_atomdata_t *nbat)
1909 {
1910     nbnxn_grid_t *grid;
1911     float        *bbcz;
1912     nbnxn_bb_t   *bb;
1913     int           ncd, sc;
1914
1915     grid = &nbs->grid[0];
1916
1917     if (grid->bSimple)
1918     {
1919         gmx_incons("nbnxn_grid_simple called with a simple grid");
1920     }
1921
1922     ncd = grid->na_sc/NBNXN_CPU_CLUSTER_I_SIZE;
1923
1924     if (grid->nc*ncd > grid->nc_nalloc_simple)
1925     {
1926         grid->nc_nalloc_simple = over_alloc_large(grid->nc*ncd);
1927         srenew(grid->bbcz_simple, grid->nc_nalloc_simple*NNBSBB_D);
1928         srenew(grid->bb_simple, grid->nc_nalloc_simple);
1929         srenew(grid->flags_simple, grid->nc_nalloc_simple);
1930         if (nbat->XFormat)
1931         {
1932             sfree_aligned(grid->bbj);
1933             snew_aligned(grid->bbj, grid->nc_nalloc_simple/2, 16);
1934         }
1935     }
1936
1937     bbcz = grid->bbcz_simple;
1938     bb   = grid->bb_simple;
1939
1940 #pragma omp parallel for num_threads(gmx_omp_nthreads_get(emntPairsearch)) schedule(static)
1941     for (sc = 0; sc < grid->nc; sc++)
1942     {
1943         int c, tx, na;
1944
1945         for (c = 0; c < ncd; c++)
1946         {
1947             tx = sc*ncd + c;
1948
1949             na = NBNXN_CPU_CLUSTER_I_SIZE;
1950             while (na > 0 &&
1951                    nbat->type[tx*NBNXN_CPU_CLUSTER_I_SIZE+na-1] == nbat->ntype-1)
1952             {
1953                 na--;
1954             }
1955
1956             if (na > 0)
1957             {
1958                 switch (nbat->XFormat)
1959                 {
1960                     case nbatX4:
1961                         /* PACK_X4==NBNXN_CPU_CLUSTER_I_SIZE, so this is simple */
1962                         calc_bounding_box_x_x4(na, nbat->x+tx*STRIDE_P4,
1963                                                bb+tx);
1964                         break;
1965                     case nbatX8:
1966                         /* PACK_X8>NBNXN_CPU_CLUSTER_I_SIZE, more complicated */
1967                         calc_bounding_box_x_x8(na, nbat->x+X8_IND_A(tx*NBNXN_CPU_CLUSTER_I_SIZE),
1968                                                bb+tx);
1969                         break;
1970                     default:
1971                         calc_bounding_box(na, nbat->xstride,
1972                                           nbat->x+tx*NBNXN_CPU_CLUSTER_I_SIZE*nbat->xstride,
1973                                           bb+tx);
1974                         break;
1975                 }
1976                 bbcz[tx*NNBSBB_D+0] = bb[tx].lower[BB_Z];
1977                 bbcz[tx*NNBSBB_D+1] = bb[tx].upper[BB_Z];
1978
1979                 /* No interaction optimization yet here */
1980                 grid->flags_simple[tx] = NBNXN_CI_DO_LJ(0) | NBNXN_CI_DO_COUL(0);
1981             }
1982             else
1983             {
1984                 grid->flags_simple[tx] = 0;
1985             }
1986         }
1987     }
1988
1989     if (grid->bSimple && nbat->XFormat == nbatX8)
1990     {
1991         combine_bounding_box_pairs(grid, grid->bb_simple);
1992     }
1993 }
1994
1995 void nbnxn_get_ncells(nbnxn_search_t nbs, int *ncx, int *ncy)
1996 {
1997     *ncx = nbs->grid[0].ncx;
1998     *ncy = nbs->grid[0].ncy;
1999 }
2000
2001 void nbnxn_get_atomorder(nbnxn_search_t nbs, int **a, int *n)
2002 {
2003     const nbnxn_grid_t *grid;
2004
2005     grid = &nbs->grid[0];
2006
2007     /* Return the atom order for the home cell (index 0) */
2008     *a  = nbs->a;
2009
2010     *n = grid->cxy_ind[grid->ncx*grid->ncy]*grid->na_sc;
2011 }
2012
2013 void nbnxn_set_atomorder(nbnxn_search_t nbs)
2014 {
2015     nbnxn_grid_t *grid;
2016     int           ao, cx, cy, cxy, cz, j;
2017
2018     /* Set the atom order for the home cell (index 0) */
2019     grid = &nbs->grid[0];
2020
2021     ao = 0;
2022     for (cx = 0; cx < grid->ncx; cx++)
2023     {
2024         for (cy = 0; cy < grid->ncy; cy++)
2025         {
2026             cxy = cx*grid->ncy + cy;
2027             j   = grid->cxy_ind[cxy]*grid->na_sc;
2028             for (cz = 0; cz < grid->cxy_na[cxy]; cz++)
2029             {
2030                 nbs->a[j]     = ao;
2031                 nbs->cell[ao] = j;
2032                 ao++;
2033                 j++;
2034             }
2035         }
2036     }
2037 }
2038
2039 /* Determines the cell range along one dimension that
2040  * the bounding box b0 - b1 sees.
2041  */
2042 static void get_cell_range(real b0, real b1,
2043                            int nc, real c0, real s, real invs,
2044                            real d2, real r2, int *cf, int *cl)
2045 {
2046     *cf = max((int)((b0 - c0)*invs), 0);
2047
2048     while (*cf > 0 && d2 + sqr((b0 - c0) - (*cf-1+1)*s) < r2)
2049     {
2050         (*cf)--;
2051     }
2052
2053     *cl = min((int)((b1 - c0)*invs), nc-1);
2054     while (*cl < nc-1 && d2 + sqr((*cl+1)*s - (b1 - c0)) < r2)
2055     {
2056         (*cl)++;
2057     }
2058 }
2059
2060 /* Reference code calculating the distance^2 between two bounding boxes */
2061 static float box_dist2(float bx0, float bx1, float by0,
2062                        float by1, float bz0, float bz1,
2063                        const nbnxn_bb_t *bb)
2064 {
2065     float d2;
2066     float dl, dh, dm, dm0;
2067
2068     d2 = 0;
2069
2070     dl  = bx0 - bb->upper[BB_X];
2071     dh  = bb->lower[BB_X] - bx1;
2072     dm  = max(dl, dh);
2073     dm0 = max(dm, 0);
2074     d2 += dm0*dm0;
2075
2076     dl  = by0 - bb->upper[BB_Y];
2077     dh  = bb->lower[BB_Y] - by1;
2078     dm  = max(dl, dh);
2079     dm0 = max(dm, 0);
2080     d2 += dm0*dm0;
2081
2082     dl  = bz0 - bb->upper[BB_Z];
2083     dh  = bb->lower[BB_Z] - bz1;
2084     dm  = max(dl, dh);
2085     dm0 = max(dm, 0);
2086     d2 += dm0*dm0;
2087
2088     return d2;
2089 }
2090
2091 /* Plain C code calculating the distance^2 between two bounding boxes */
2092 static float subc_bb_dist2(int si, const nbnxn_bb_t *bb_i_ci,
2093                            int csj, const nbnxn_bb_t *bb_j_all)
2094 {
2095     const nbnxn_bb_t *bb_i, *bb_j;
2096     float             d2;
2097     float             dl, dh, dm, dm0;
2098
2099     bb_i = bb_i_ci  +  si;
2100     bb_j = bb_j_all + csj;
2101
2102     d2 = 0;
2103
2104     dl  = bb_i->lower[BB_X] - bb_j->upper[BB_X];
2105     dh  = bb_j->lower[BB_X] - bb_i->upper[BB_X];
2106     dm  = max(dl, dh);
2107     dm0 = max(dm, 0);
2108     d2 += dm0*dm0;
2109
2110     dl  = bb_i->lower[BB_Y] - bb_j->upper[BB_Y];
2111     dh  = bb_j->lower[BB_Y] - bb_i->upper[BB_Y];
2112     dm  = max(dl, dh);
2113     dm0 = max(dm, 0);
2114     d2 += dm0*dm0;
2115
2116     dl  = bb_i->lower[BB_Z] - bb_j->upper[BB_Z];
2117     dh  = bb_j->lower[BB_Z] - bb_i->upper[BB_Z];
2118     dm  = max(dl, dh);
2119     dm0 = max(dm, 0);
2120     d2 += dm0*dm0;
2121
2122     return d2;
2123 }
2124
2125 #ifdef NBNXN_SEARCH_BB_SIMD4
2126
2127 /* 4-wide SIMD code for bb distance for bb format xyz0 */
2128 static float subc_bb_dist2_simd4(int si, const nbnxn_bb_t *bb_i_ci,
2129                                  int csj, const nbnxn_bb_t *bb_j_all)
2130 {
2131     gmx_simd4_float_t bb_i_S0, bb_i_S1;
2132     gmx_simd4_float_t bb_j_S0, bb_j_S1;
2133     gmx_simd4_float_t dl_S;
2134     gmx_simd4_float_t dh_S;
2135     gmx_simd4_float_t dm_S;
2136     gmx_simd4_float_t dm0_S;
2137
2138     bb_i_S0 = gmx_simd4_load_f(&bb_i_ci[si].lower[0]);
2139     bb_i_S1 = gmx_simd4_load_f(&bb_i_ci[si].upper[0]);
2140     bb_j_S0 = gmx_simd4_load_f(&bb_j_all[csj].lower[0]);
2141     bb_j_S1 = gmx_simd4_load_f(&bb_j_all[csj].upper[0]);
2142
2143     dl_S    = gmx_simd4_sub_f(bb_i_S0, bb_j_S1);
2144     dh_S    = gmx_simd4_sub_f(bb_j_S0, bb_i_S1);
2145
2146     dm_S    = gmx_simd4_max_f(dl_S, dh_S);
2147     dm0_S   = gmx_simd4_max_f(dm_S, gmx_simd4_setzero_f());
2148
2149     return gmx_simd4_dotproduct3_f(dm0_S, dm0_S);
2150 }
2151
2152 /* Calculate bb bounding distances of bb_i[si,...,si+3] and store them in d2 */
2153 #define SUBC_BB_DIST2_SIMD4_XXXX_INNER(si, bb_i, d2) \
2154     {                                                \
2155         int               shi;                                  \
2156                                                  \
2157         gmx_simd4_float_t dx_0, dy_0, dz_0;                    \
2158         gmx_simd4_float_t dx_1, dy_1, dz_1;                    \
2159                                                  \
2160         gmx_simd4_float_t mx, my, mz;                          \
2161         gmx_simd4_float_t m0x, m0y, m0z;                       \
2162                                                  \
2163         gmx_simd4_float_t d2x, d2y, d2z;                       \
2164         gmx_simd4_float_t d2s, d2t;                            \
2165                                                  \
2166         shi = si*NNBSBB_D*DIM;                       \
2167                                                  \
2168         xi_l = gmx_simd4_load_f(bb_i+shi+0*STRIDE_PBB);   \
2169         yi_l = gmx_simd4_load_f(bb_i+shi+1*STRIDE_PBB);   \
2170         zi_l = gmx_simd4_load_f(bb_i+shi+2*STRIDE_PBB);   \
2171         xi_h = gmx_simd4_load_f(bb_i+shi+3*STRIDE_PBB);   \
2172         yi_h = gmx_simd4_load_f(bb_i+shi+4*STRIDE_PBB);   \
2173         zi_h = gmx_simd4_load_f(bb_i+shi+5*STRIDE_PBB);   \
2174                                                  \
2175         dx_0 = gmx_simd4_sub_f(xi_l, xj_h);                 \
2176         dy_0 = gmx_simd4_sub_f(yi_l, yj_h);                 \
2177         dz_0 = gmx_simd4_sub_f(zi_l, zj_h);                 \
2178                                                  \
2179         dx_1 = gmx_simd4_sub_f(xj_l, xi_h);                 \
2180         dy_1 = gmx_simd4_sub_f(yj_l, yi_h);                 \
2181         dz_1 = gmx_simd4_sub_f(zj_l, zi_h);                 \
2182                                                  \
2183         mx   = gmx_simd4_max_f(dx_0, dx_1);                 \
2184         my   = gmx_simd4_max_f(dy_0, dy_1);                 \
2185         mz   = gmx_simd4_max_f(dz_0, dz_1);                 \
2186                                                  \
2187         m0x  = gmx_simd4_max_f(mx, zero);                   \
2188         m0y  = gmx_simd4_max_f(my, zero);                   \
2189         m0z  = gmx_simd4_max_f(mz, zero);                   \
2190                                                  \
2191         d2x  = gmx_simd4_mul_f(m0x, m0x);                   \
2192         d2y  = gmx_simd4_mul_f(m0y, m0y);                   \
2193         d2z  = gmx_simd4_mul_f(m0z, m0z);                   \
2194                                                  \
2195         d2s  = gmx_simd4_add_f(d2x, d2y);                   \
2196         d2t  = gmx_simd4_add_f(d2s, d2z);                   \
2197                                                  \
2198         gmx_simd4_store_f(d2+si, d2t);                      \
2199     }
2200
2201 /* 4-wide SIMD code for nsi bb distances for bb format xxxxyyyyzzzz */
2202 static void subc_bb_dist2_simd4_xxxx(const float *bb_j,
2203                                      int nsi, const float *bb_i,
2204                                      float *d2)
2205 {
2206     gmx_simd4_float_t xj_l, yj_l, zj_l;
2207     gmx_simd4_float_t xj_h, yj_h, zj_h;
2208     gmx_simd4_float_t xi_l, yi_l, zi_l;
2209     gmx_simd4_float_t xi_h, yi_h, zi_h;
2210
2211     gmx_simd4_float_t zero;
2212
2213     zero = gmx_simd4_setzero_f();
2214
2215     xj_l = gmx_simd4_set1_f(bb_j[0*STRIDE_PBB]);
2216     yj_l = gmx_simd4_set1_f(bb_j[1*STRIDE_PBB]);
2217     zj_l = gmx_simd4_set1_f(bb_j[2*STRIDE_PBB]);
2218     xj_h = gmx_simd4_set1_f(bb_j[3*STRIDE_PBB]);
2219     yj_h = gmx_simd4_set1_f(bb_j[4*STRIDE_PBB]);
2220     zj_h = gmx_simd4_set1_f(bb_j[5*STRIDE_PBB]);
2221
2222     /* Here we "loop" over si (0,STRIDE_PBB) from 0 to nsi with step STRIDE_PBB.
2223      * But as we know the number of iterations is 1 or 2, we unroll manually.
2224      */
2225     SUBC_BB_DIST2_SIMD4_XXXX_INNER(0, bb_i, d2);
2226     if (STRIDE_PBB < nsi)
2227     {
2228         SUBC_BB_DIST2_SIMD4_XXXX_INNER(STRIDE_PBB, bb_i, d2);
2229     }
2230 }
2231
2232 #endif /* NBNXN_SEARCH_BB_SIMD4 */
2233
2234 /* Plain C function which determines if any atom pair between two cells
2235  * is within distance sqrt(rl2).
2236  */
2237 static gmx_bool subc_in_range_x(int na_c,
2238                                 int si, const real *x_i,
2239                                 int csj, int stride, const real *x_j,
2240                                 real rl2)
2241 {
2242     int  i, j, i0, j0;
2243     real d2;
2244
2245     for (i = 0; i < na_c; i++)
2246     {
2247         i0 = (si*na_c + i)*DIM;
2248         for (j = 0; j < na_c; j++)
2249         {
2250             j0 = (csj*na_c + j)*stride;
2251
2252             d2 = sqr(x_i[i0  ] - x_j[j0  ]) +
2253                 sqr(x_i[i0+1] - x_j[j0+1]) +
2254                 sqr(x_i[i0+2] - x_j[j0+2]);
2255
2256             if (d2 < rl2)
2257             {
2258                 return TRUE;
2259             }
2260         }
2261     }
2262
2263     return FALSE;
2264 }
2265
2266 #ifdef NBNXN_SEARCH_SIMD4_FLOAT_X_BB
2267
2268 /* 4-wide SIMD function which determines if any atom pair between two cells,
2269  * both with 8 atoms, is within distance sqrt(rl2).
2270  * Using 8-wide AVX is not faster on Intel Sandy Bridge.
2271  */
2272 static gmx_bool subc_in_range_simd4(int na_c,
2273                                     int si, const real *x_i,
2274                                     int csj, int stride, const real *x_j,
2275                                     real rl2)
2276 {
2277     gmx_simd4_real_t ix_S0, iy_S0, iz_S0;
2278     gmx_simd4_real_t ix_S1, iy_S1, iz_S1;
2279
2280     gmx_simd4_real_t rc2_S;
2281
2282     int              dim_stride;
2283     int              j0, j1;
2284
2285     rc2_S   = gmx_simd4_set1_r(rl2);
2286
2287     dim_stride = NBNXN_GPU_CLUSTER_SIZE/STRIDE_PBB*DIM;
2288     ix_S0      = gmx_simd4_load_r(x_i+(si*dim_stride+0)*STRIDE_PBB);
2289     iy_S0      = gmx_simd4_load_r(x_i+(si*dim_stride+1)*STRIDE_PBB);
2290     iz_S0      = gmx_simd4_load_r(x_i+(si*dim_stride+2)*STRIDE_PBB);
2291     ix_S1      = gmx_simd4_load_r(x_i+(si*dim_stride+3)*STRIDE_PBB);
2292     iy_S1      = gmx_simd4_load_r(x_i+(si*dim_stride+4)*STRIDE_PBB);
2293     iz_S1      = gmx_simd4_load_r(x_i+(si*dim_stride+5)*STRIDE_PBB);
2294
2295     /* We loop from the outer to the inner particles to maximize
2296      * the chance that we find a pair in range quickly and return.
2297      */
2298     j0 = csj*na_c;
2299     j1 = j0 + na_c - 1;
2300     while (j0 < j1)
2301     {
2302         gmx_simd4_real_t jx0_S, jy0_S, jz0_S;
2303         gmx_simd4_real_t jx1_S, jy1_S, jz1_S;
2304
2305         gmx_simd4_real_t dx_S0, dy_S0, dz_S0;
2306         gmx_simd4_real_t dx_S1, dy_S1, dz_S1;
2307         gmx_simd4_real_t dx_S2, dy_S2, dz_S2;
2308         gmx_simd4_real_t dx_S3, dy_S3, dz_S3;
2309
2310         gmx_simd4_real_t rsq_S0;
2311         gmx_simd4_real_t rsq_S1;
2312         gmx_simd4_real_t rsq_S2;
2313         gmx_simd4_real_t rsq_S3;
2314
2315         gmx_simd4_bool_t wco_S0;
2316         gmx_simd4_bool_t wco_S1;
2317         gmx_simd4_bool_t wco_S2;
2318         gmx_simd4_bool_t wco_S3;
2319         gmx_simd4_bool_t wco_any_S01, wco_any_S23, wco_any_S;
2320
2321         jx0_S = gmx_simd4_set1_r(x_j[j0*stride+0]);
2322         jy0_S = gmx_simd4_set1_r(x_j[j0*stride+1]);
2323         jz0_S = gmx_simd4_set1_r(x_j[j0*stride+2]);
2324
2325         jx1_S = gmx_simd4_set1_r(x_j[j1*stride+0]);
2326         jy1_S = gmx_simd4_set1_r(x_j[j1*stride+1]);
2327         jz1_S = gmx_simd4_set1_r(x_j[j1*stride+2]);
2328
2329         /* Calculate distance */
2330         dx_S0            = gmx_simd4_sub_r(ix_S0, jx0_S);
2331         dy_S0            = gmx_simd4_sub_r(iy_S0, jy0_S);
2332         dz_S0            = gmx_simd4_sub_r(iz_S0, jz0_S);
2333         dx_S1            = gmx_simd4_sub_r(ix_S1, jx0_S);
2334         dy_S1            = gmx_simd4_sub_r(iy_S1, jy0_S);
2335         dz_S1            = gmx_simd4_sub_r(iz_S1, jz0_S);
2336         dx_S2            = gmx_simd4_sub_r(ix_S0, jx1_S);
2337         dy_S2            = gmx_simd4_sub_r(iy_S0, jy1_S);
2338         dz_S2            = gmx_simd4_sub_r(iz_S0, jz1_S);
2339         dx_S3            = gmx_simd4_sub_r(ix_S1, jx1_S);
2340         dy_S3            = gmx_simd4_sub_r(iy_S1, jy1_S);
2341         dz_S3            = gmx_simd4_sub_r(iz_S1, jz1_S);
2342
2343         /* rsq = dx*dx+dy*dy+dz*dz */
2344         rsq_S0           = gmx_simd4_calc_rsq_r(dx_S0, dy_S0, dz_S0);
2345         rsq_S1           = gmx_simd4_calc_rsq_r(dx_S1, dy_S1, dz_S1);
2346         rsq_S2           = gmx_simd4_calc_rsq_r(dx_S2, dy_S2, dz_S2);
2347         rsq_S3           = gmx_simd4_calc_rsq_r(dx_S3, dy_S3, dz_S3);
2348
2349         wco_S0           = gmx_simd4_cmplt_r(rsq_S0, rc2_S);
2350         wco_S1           = gmx_simd4_cmplt_r(rsq_S1, rc2_S);
2351         wco_S2           = gmx_simd4_cmplt_r(rsq_S2, rc2_S);
2352         wco_S3           = gmx_simd4_cmplt_r(rsq_S3, rc2_S);
2353
2354         wco_any_S01      = gmx_simd4_or_b(wco_S0, wco_S1);
2355         wco_any_S23      = gmx_simd4_or_b(wco_S2, wco_S3);
2356         wco_any_S        = gmx_simd4_or_b(wco_any_S01, wco_any_S23);
2357
2358         if (gmx_simd4_anytrue_b(wco_any_S))
2359         {
2360             return TRUE;
2361         }
2362
2363         j0++;
2364         j1--;
2365     }
2366     return FALSE;
2367
2368 }
2369 #endif
2370
2371
2372 /* Returns the j sub-cell for index cj_ind */
2373 static int nbl_cj(const nbnxn_pairlist_t *nbl, int cj_ind)
2374 {
2375     return nbl->cj4[cj_ind >> NBNXN_GPU_JGROUP_SIZE_2LOG].cj[cj_ind & (NBNXN_GPU_JGROUP_SIZE - 1)];
2376 }
2377
2378 /* Returns the i-interaction mask of the j sub-cell for index cj_ind */
2379 static unsigned int nbl_imask0(const nbnxn_pairlist_t *nbl, int cj_ind)
2380 {
2381     return nbl->cj4[cj_ind >> NBNXN_GPU_JGROUP_SIZE_2LOG].imei[0].imask;
2382 }
2383
2384 /* Ensures there is enough space for extra extra exclusion masks */
2385 static void check_excl_space(nbnxn_pairlist_t *nbl, int extra)
2386 {
2387     if (nbl->nexcl+extra > nbl->excl_nalloc)
2388     {
2389         nbl->excl_nalloc = over_alloc_small(nbl->nexcl+extra);
2390         nbnxn_realloc_void((void **)&nbl->excl,
2391                            nbl->nexcl*sizeof(*nbl->excl),
2392                            nbl->excl_nalloc*sizeof(*nbl->excl),
2393                            nbl->alloc, nbl->free);
2394     }
2395 }
2396
2397 /* Ensures there is enough space for ncell extra j-cells in the list */
2398 static void check_subcell_list_space_simple(nbnxn_pairlist_t *nbl,
2399                                             int               ncell)
2400 {
2401     int cj_max;
2402
2403     cj_max = nbl->ncj + ncell;
2404
2405     if (cj_max > nbl->cj_nalloc)
2406     {
2407         nbl->cj_nalloc = over_alloc_small(cj_max);
2408         nbnxn_realloc_void((void **)&nbl->cj,
2409                            nbl->ncj*sizeof(*nbl->cj),
2410                            nbl->cj_nalloc*sizeof(*nbl->cj),
2411                            nbl->alloc, nbl->free);
2412     }
2413 }
2414
2415 /* Ensures there is enough space for ncell extra j-subcells in the list */
2416 static void check_subcell_list_space_supersub(nbnxn_pairlist_t *nbl,
2417                                               int               nsupercell)
2418 {
2419     int ncj4_max, j4, j, w, t;
2420
2421 #define NWARP       2
2422 #define WARP_SIZE  32
2423
2424     /* We can have maximally nsupercell*GPU_NSUBCELL sj lists */
2425     /* We can store 4 j-subcell - i-supercell pairs in one struct.
2426      * since we round down, we need one extra entry.
2427      */
2428     ncj4_max = ((nbl->work->cj_ind + nsupercell*GPU_NSUBCELL + NBNXN_GPU_JGROUP_SIZE - 1) >> NBNXN_GPU_JGROUP_SIZE_2LOG);
2429
2430     if (ncj4_max > nbl->cj4_nalloc)
2431     {
2432         nbl->cj4_nalloc = over_alloc_small(ncj4_max);
2433         nbnxn_realloc_void((void **)&nbl->cj4,
2434                            nbl->work->cj4_init*sizeof(*nbl->cj4),
2435                            nbl->cj4_nalloc*sizeof(*nbl->cj4),
2436                            nbl->alloc, nbl->free);
2437     }
2438
2439     if (ncj4_max > nbl->work->cj4_init)
2440     {
2441         for (j4 = nbl->work->cj4_init; j4 < ncj4_max; j4++)
2442         {
2443             /* No i-subcells and no excl's in the list initially */
2444             for (w = 0; w < NWARP; w++)
2445             {
2446                 nbl->cj4[j4].imei[w].imask    = 0U;
2447                 nbl->cj4[j4].imei[w].excl_ind = 0;
2448
2449             }
2450         }
2451         nbl->work->cj4_init = ncj4_max;
2452     }
2453 }
2454
2455 /* Set all excl masks for one GPU warp no exclusions */
2456 static void set_no_excls(nbnxn_excl_t *excl)
2457 {
2458     int t;
2459
2460     for (t = 0; t < WARP_SIZE; t++)
2461     {
2462         /* Turn all interaction bits on */
2463         excl->pair[t] = NBNXN_INTERACTION_MASK_ALL;
2464     }
2465 }
2466
2467 /* Initializes a single nbnxn_pairlist_t data structure */
2468 static void nbnxn_init_pairlist(nbnxn_pairlist_t *nbl,
2469                                 gmx_bool          bSimple,
2470                                 nbnxn_alloc_t    *alloc,
2471                                 nbnxn_free_t     *free)
2472 {
2473     if (alloc == NULL)
2474     {
2475         nbl->alloc = nbnxn_alloc_aligned;
2476     }
2477     else
2478     {
2479         nbl->alloc = alloc;
2480     }
2481     if (free == NULL)
2482     {
2483         nbl->free = nbnxn_free_aligned;
2484     }
2485     else
2486     {
2487         nbl->free = free;
2488     }
2489
2490     nbl->bSimple     = bSimple;
2491     nbl->na_sc       = 0;
2492     nbl->na_ci       = 0;
2493     nbl->na_cj       = 0;
2494     nbl->nci         = 0;
2495     nbl->ci          = NULL;
2496     nbl->ci_nalloc   = 0;
2497     nbl->ncj         = 0;
2498     nbl->cj          = NULL;
2499     nbl->cj_nalloc   = 0;
2500     nbl->ncj4        = 0;
2501     /* We need one element extra in sj, so alloc initially with 1 */
2502     nbl->cj4_nalloc  = 0;
2503     nbl->cj4         = NULL;
2504     nbl->nci_tot     = 0;
2505
2506     if (!nbl->bSimple)
2507     {
2508         nbl->excl        = NULL;
2509         nbl->excl_nalloc = 0;
2510         nbl->nexcl       = 0;
2511         check_excl_space(nbl, 1);
2512         nbl->nexcl       = 1;
2513         set_no_excls(&nbl->excl[0]);
2514     }
2515
2516     snew(nbl->work, 1);
2517     if (nbl->bSimple)
2518     {
2519         snew_aligned(nbl->work->bb_ci, 1, NBNXN_SEARCH_BB_MEM_ALIGN);
2520     }
2521     else
2522     {
2523 #ifdef NBNXN_BBXXXX
2524         snew_aligned(nbl->work->pbb_ci, GPU_NSUBCELL/STRIDE_PBB*NNBSBB_XXXX, NBNXN_SEARCH_BB_MEM_ALIGN);
2525 #else
2526         snew_aligned(nbl->work->bb_ci, GPU_NSUBCELL, NBNXN_SEARCH_BB_MEM_ALIGN);
2527 #endif
2528     }
2529     snew_aligned(nbl->work->x_ci, NBNXN_NA_SC_MAX*DIM, NBNXN_SEARCH_BB_MEM_ALIGN);
2530 #ifdef GMX_NBNXN_SIMD
2531     snew_aligned(nbl->work->x_ci_simd_4xn, 1, NBNXN_MEM_ALIGN);
2532     snew_aligned(nbl->work->x_ci_simd_2xnn, 1, NBNXN_MEM_ALIGN);
2533 #endif
2534     snew_aligned(nbl->work->d2, GPU_NSUBCELL, NBNXN_SEARCH_BB_MEM_ALIGN);
2535
2536     nbl->work->sort            = NULL;
2537     nbl->work->sort_nalloc     = 0;
2538     nbl->work->sci_sort        = NULL;
2539     nbl->work->sci_sort_nalloc = 0;
2540 }
2541
2542 void nbnxn_init_pairlist_set(nbnxn_pairlist_set_t *nbl_list,
2543                              gmx_bool bSimple, gmx_bool bCombined,
2544                              nbnxn_alloc_t *alloc,
2545                              nbnxn_free_t  *free)
2546 {
2547     int i;
2548
2549     nbl_list->bSimple   = bSimple;
2550     nbl_list->bCombined = bCombined;
2551
2552     nbl_list->nnbl = gmx_omp_nthreads_get(emntNonbonded);
2553
2554     if (!nbl_list->bCombined &&
2555         nbl_list->nnbl > NBNXN_BUFFERFLAG_MAX_THREADS)
2556     {
2557         gmx_fatal(FARGS, "%d OpenMP threads were requested. Since the non-bonded force buffer reduction is prohibitively slow with more than %d threads, we do not allow this. Use %d or less OpenMP threads.",
2558                   nbl_list->nnbl, NBNXN_BUFFERFLAG_MAX_THREADS, NBNXN_BUFFERFLAG_MAX_THREADS);
2559     }
2560
2561     snew(nbl_list->nbl, nbl_list->nnbl);
2562     snew(nbl_list->nbl_fep, nbl_list->nnbl);
2563     /* Execute in order to avoid memory interleaving between threads */
2564 #pragma omp parallel for num_threads(nbl_list->nnbl) schedule(static)
2565     for (i = 0; i < nbl_list->nnbl; i++)
2566     {
2567         /* Allocate the nblist data structure locally on each thread
2568          * to optimize memory access for NUMA architectures.
2569          */
2570         snew(nbl_list->nbl[i], 1);
2571
2572         /* Only list 0 is used on the GPU, use normal allocation for i>0 */
2573         if (i == 0)
2574         {
2575             nbnxn_init_pairlist(nbl_list->nbl[i], nbl_list->bSimple, alloc, free);
2576         }
2577         else
2578         {
2579             nbnxn_init_pairlist(nbl_list->nbl[i], nbl_list->bSimple, NULL, NULL);
2580         }
2581
2582         snew(nbl_list->nbl_fep[i], 1);
2583         nbnxn_init_pairlist_fep(nbl_list->nbl_fep[i]);
2584     }
2585 }
2586
2587 /* Print statistics of a pair list, used for debug output */
2588 static void print_nblist_statistics_simple(FILE *fp, const nbnxn_pairlist_t *nbl,
2589                                            const nbnxn_search_t nbs, real rl)
2590 {
2591     const nbnxn_grid_t *grid;
2592     int                 cs[SHIFTS];
2593     int                 s, i, j;
2594     int                 npexcl;
2595
2596     /* This code only produces correct statistics with domain decomposition */
2597     grid = &nbs->grid[0];
2598
2599     fprintf(fp, "nbl nci %d ncj %d\n",
2600             nbl->nci, nbl->ncj);
2601     fprintf(fp, "nbl na_sc %d rl %g ncp %d per cell %.1f atoms %.1f ratio %.2f\n",
2602             nbl->na_sc, rl, nbl->ncj, nbl->ncj/(double)grid->nc,
2603             nbl->ncj/(double)grid->nc*grid->na_sc,
2604             nbl->ncj/(double)grid->nc*grid->na_sc/(0.5*4.0/3.0*M_PI*rl*rl*rl*grid->nc*grid->na_sc/det(nbs->box)));
2605
2606     fprintf(fp, "nbl average j cell list length %.1f\n",
2607             0.25*nbl->ncj/(double)nbl->nci);
2608
2609     for (s = 0; s < SHIFTS; s++)
2610     {
2611         cs[s] = 0;
2612     }
2613     npexcl = 0;
2614     for (i = 0; i < nbl->nci; i++)
2615     {
2616         cs[nbl->ci[i].shift & NBNXN_CI_SHIFT] +=
2617             nbl->ci[i].cj_ind_end - nbl->ci[i].cj_ind_start;
2618
2619         j = nbl->ci[i].cj_ind_start;
2620         while (j < nbl->ci[i].cj_ind_end &&
2621                nbl->cj[j].excl != NBNXN_INTERACTION_MASK_ALL)
2622         {
2623             npexcl++;
2624             j++;
2625         }
2626     }
2627     fprintf(fp, "nbl cell pairs, total: %d excl: %d %.1f%%\n",
2628             nbl->ncj, npexcl, 100*npexcl/(double)nbl->ncj);
2629     for (s = 0; s < SHIFTS; s++)
2630     {
2631         if (cs[s] > 0)
2632         {
2633             fprintf(fp, "nbl shift %2d ncj %3d\n", s, cs[s]);
2634         }
2635     }
2636 }
2637
2638 /* Print statistics of a pair lists, used for debug output */
2639 static void print_nblist_statistics_supersub(FILE *fp, const nbnxn_pairlist_t *nbl,
2640                                              const nbnxn_search_t nbs, real rl)
2641 {
2642     const nbnxn_grid_t *grid;
2643     int                 i, j4, j, si, b;
2644     int                 c[GPU_NSUBCELL+1];
2645
2646     /* This code only produces correct statistics with domain decomposition */
2647     grid = &nbs->grid[0];
2648
2649     fprintf(fp, "nbl nsci %d ncj4 %d nsi %d excl4 %d\n",
2650             nbl->nsci, nbl->ncj4, nbl->nci_tot, nbl->nexcl);
2651     fprintf(fp, "nbl na_c %d rl %g ncp %d per cell %.1f atoms %.1f ratio %.2f\n",
2652             nbl->na_ci, rl, nbl->nci_tot, nbl->nci_tot/(double)grid->nsubc_tot,
2653             nbl->nci_tot/(double)grid->nsubc_tot*grid->na_c,
2654             nbl->nci_tot/(double)grid->nsubc_tot*grid->na_c/(0.5*4.0/3.0*M_PI*rl*rl*rl*grid->nsubc_tot*grid->na_c/det(nbs->box)));
2655
2656     fprintf(fp, "nbl average j super cell list length %.1f\n",
2657             0.25*nbl->ncj4/(double)nbl->nsci);
2658     fprintf(fp, "nbl average i sub cell list length %.1f\n",
2659             nbl->nci_tot/((double)nbl->ncj4));
2660
2661     for (si = 0; si <= GPU_NSUBCELL; si++)
2662     {
2663         c[si] = 0;
2664     }
2665     for (i = 0; i < nbl->nsci; i++)
2666     {
2667         for (j4 = nbl->sci[i].cj4_ind_start; j4 < nbl->sci[i].cj4_ind_end; j4++)
2668         {
2669             for (j = 0; j < NBNXN_GPU_JGROUP_SIZE; j++)
2670             {
2671                 b = 0;
2672                 for (si = 0; si < GPU_NSUBCELL; si++)
2673                 {
2674                     if (nbl->cj4[j4].imei[0].imask & (1U << (j*GPU_NSUBCELL + si)))
2675                     {
2676                         b++;
2677                     }
2678                 }
2679                 c[b]++;
2680             }
2681         }
2682     }
2683     for (b = 0; b <= GPU_NSUBCELL; b++)
2684     {
2685         fprintf(fp, "nbl j-list #i-subcell %d %7d %4.1f\n",
2686                 b, c[b], 100.0*c[b]/(double)(nbl->ncj4*NBNXN_GPU_JGROUP_SIZE));
2687     }
2688 }
2689
2690 /* Returns a pointer to the exclusion mask for cj4-unit cj4, warp warp */
2691 static void low_get_nbl_exclusions(nbnxn_pairlist_t *nbl, int cj4,
2692                                    int warp, nbnxn_excl_t **excl)
2693 {
2694     if (nbl->cj4[cj4].imei[warp].excl_ind == 0)
2695     {
2696         /* No exclusions set, make a new list entry */
2697         nbl->cj4[cj4].imei[warp].excl_ind = nbl->nexcl;
2698         nbl->nexcl++;
2699         *excl = &nbl->excl[nbl->cj4[cj4].imei[warp].excl_ind];
2700         set_no_excls(*excl);
2701     }
2702     else
2703     {
2704         /* We already have some exclusions, new ones can be added to the list */
2705         *excl = &nbl->excl[nbl->cj4[cj4].imei[warp].excl_ind];
2706     }
2707 }
2708
2709 /* Returns a pointer to the exclusion mask for cj4-unit cj4, warp warp,
2710  * generates a new element and allocates extra memory, if necessary.
2711  */
2712 static void get_nbl_exclusions_1(nbnxn_pairlist_t *nbl, int cj4,
2713                                  int warp, nbnxn_excl_t **excl)
2714 {
2715     if (nbl->cj4[cj4].imei[warp].excl_ind == 0)
2716     {
2717         /* We need to make a new list entry, check if we have space */
2718         check_excl_space(nbl, 1);
2719     }
2720     low_get_nbl_exclusions(nbl, cj4, warp, excl);
2721 }
2722
2723 /* Returns pointers to the exclusion mask for cj4-unit cj4 for both warps,
2724  * generates a new element and allocates extra memory, if necessary.
2725  */
2726 static void get_nbl_exclusions_2(nbnxn_pairlist_t *nbl, int cj4,
2727                                  nbnxn_excl_t **excl_w0,
2728                                  nbnxn_excl_t **excl_w1)
2729 {
2730     /* Check for space we might need */
2731     check_excl_space(nbl, 2);
2732
2733     low_get_nbl_exclusions(nbl, cj4, 0, excl_w0);
2734     low_get_nbl_exclusions(nbl, cj4, 1, excl_w1);
2735 }
2736
2737 /* Sets the self exclusions i=j and pair exclusions i>j */
2738 static void set_self_and_newton_excls_supersub(nbnxn_pairlist_t *nbl,
2739                                                int cj4_ind, int sj_offset,
2740                                                int si)
2741 {
2742     nbnxn_excl_t *excl[2];
2743     int           ei, ej, w;
2744
2745     /* Here we only set the set self and double pair exclusions */
2746
2747     get_nbl_exclusions_2(nbl, cj4_ind, &excl[0], &excl[1]);
2748
2749     /* Only minor < major bits set */
2750     for (ej = 0; ej < nbl->na_ci; ej++)
2751     {
2752         w = (ej>>2);
2753         for (ei = ej; ei < nbl->na_ci; ei++)
2754         {
2755             excl[w]->pair[(ej & (NBNXN_GPU_JGROUP_SIZE-1))*nbl->na_ci + ei] &=
2756                 ~(1U << (sj_offset*GPU_NSUBCELL + si));
2757         }
2758     }
2759 }
2760
2761 /* Returns a diagonal or off-diagonal interaction mask for plain C lists */
2762 static unsigned int get_imask(gmx_bool rdiag, int ci, int cj)
2763 {
2764     return (rdiag && ci == cj ? NBNXN_INTERACTION_MASK_DIAG : NBNXN_INTERACTION_MASK_ALL);
2765 }
2766
2767 /* Returns a diagonal or off-diagonal interaction mask for cj-size=2 */
2768 static unsigned int get_imask_simd_j2(gmx_bool rdiag, int ci, int cj)
2769 {
2770     return (rdiag && ci*2 == cj ? NBNXN_INTERACTION_MASK_DIAG_J2_0 :
2771             (rdiag && ci*2+1 == cj ? NBNXN_INTERACTION_MASK_DIAG_J2_1 :
2772              NBNXN_INTERACTION_MASK_ALL));
2773 }
2774
2775 /* Returns a diagonal or off-diagonal interaction mask for cj-size=4 */
2776 static unsigned int get_imask_simd_j4(gmx_bool rdiag, int ci, int cj)
2777 {
2778     return (rdiag && ci == cj ? NBNXN_INTERACTION_MASK_DIAG : NBNXN_INTERACTION_MASK_ALL);
2779 }
2780
2781 /* Returns a diagonal or off-diagonal interaction mask for cj-size=8 */
2782 static unsigned int get_imask_simd_j8(gmx_bool rdiag, int ci, int cj)
2783 {
2784     return (rdiag && ci == cj*2 ? NBNXN_INTERACTION_MASK_DIAG_J8_0 :
2785             (rdiag && ci == cj*2+1 ? NBNXN_INTERACTION_MASK_DIAG_J8_1 :
2786              NBNXN_INTERACTION_MASK_ALL));
2787 }
2788
2789 #ifdef GMX_NBNXN_SIMD
2790 #if GMX_SIMD_REAL_WIDTH == 2
2791 #define get_imask_simd_4xn  get_imask_simd_j2
2792 #endif
2793 #if GMX_SIMD_REAL_WIDTH == 4
2794 #define get_imask_simd_4xn  get_imask_simd_j4
2795 #endif
2796 #if GMX_SIMD_REAL_WIDTH == 8
2797 #define get_imask_simd_4xn  get_imask_simd_j8
2798 #define get_imask_simd_2xnn get_imask_simd_j4
2799 #endif
2800 #if GMX_SIMD_REAL_WIDTH == 16
2801 #define get_imask_simd_2xnn get_imask_simd_j8
2802 #endif
2803 #endif
2804
2805 /* Plain C code for making a pair list of cell ci vs cell cjf-cjl.
2806  * Checks bounding box distances and possibly atom pair distances.
2807  */
2808 static void make_cluster_list_simple(const nbnxn_grid_t *gridj,
2809                                      nbnxn_pairlist_t *nbl,
2810                                      int ci, int cjf, int cjl,
2811                                      gmx_bool remove_sub_diag,
2812                                      const real *x_j,
2813                                      real rl2, float rbb2,
2814                                      int *ndistc)
2815 {
2816     const nbnxn_list_work_t *work;
2817
2818     const nbnxn_bb_t        *bb_ci;
2819     const real              *x_ci;
2820
2821     gmx_bool                 InRange;
2822     real                     d2;
2823     int                      cjf_gl, cjl_gl, cj;
2824
2825     work = nbl->work;
2826
2827     bb_ci = nbl->work->bb_ci;
2828     x_ci  = nbl->work->x_ci;
2829
2830     InRange = FALSE;
2831     while (!InRange && cjf <= cjl)
2832     {
2833         d2       = subc_bb_dist2(0, bb_ci, cjf, gridj->bb);
2834         *ndistc += 2;
2835
2836         /* Check if the distance is within the distance where
2837          * we use only the bounding box distance rbb,
2838          * or within the cut-off and there is at least one atom pair
2839          * within the cut-off.
2840          */
2841         if (d2 < rbb2)
2842         {
2843             InRange = TRUE;
2844         }
2845         else if (d2 < rl2)
2846         {
2847             int i, j;
2848
2849             cjf_gl = gridj->cell0 + cjf;
2850             for (i = 0; i < NBNXN_CPU_CLUSTER_I_SIZE && !InRange; i++)
2851             {
2852                 for (j = 0; j < NBNXN_CPU_CLUSTER_I_SIZE; j++)
2853                 {
2854                     InRange = InRange ||
2855                         (sqr(x_ci[i*STRIDE_XYZ+XX] - x_j[(cjf_gl*NBNXN_CPU_CLUSTER_I_SIZE+j)*STRIDE_XYZ+XX]) +
2856                          sqr(x_ci[i*STRIDE_XYZ+YY] - x_j[(cjf_gl*NBNXN_CPU_CLUSTER_I_SIZE+j)*STRIDE_XYZ+YY]) +
2857                          sqr(x_ci[i*STRIDE_XYZ+ZZ] - x_j[(cjf_gl*NBNXN_CPU_CLUSTER_I_SIZE+j)*STRIDE_XYZ+ZZ]) < rl2);
2858                 }
2859             }
2860             *ndistc += NBNXN_CPU_CLUSTER_I_SIZE*NBNXN_CPU_CLUSTER_I_SIZE;
2861         }
2862         if (!InRange)
2863         {
2864             cjf++;
2865         }
2866     }
2867     if (!InRange)
2868     {
2869         return;
2870     }
2871
2872     InRange = FALSE;
2873     while (!InRange && cjl > cjf)
2874     {
2875         d2       = subc_bb_dist2(0, bb_ci, cjl, gridj->bb);
2876         *ndistc += 2;
2877
2878         /* Check if the distance is within the distance where
2879          * we use only the bounding box distance rbb,
2880          * or within the cut-off and there is at least one atom pair
2881          * within the cut-off.
2882          */
2883         if (d2 < rbb2)
2884         {
2885             InRange = TRUE;
2886         }
2887         else if (d2 < rl2)
2888         {
2889             int i, j;
2890
2891             cjl_gl = gridj->cell0 + cjl;
2892             for (i = 0; i < NBNXN_CPU_CLUSTER_I_SIZE && !InRange; i++)
2893             {
2894                 for (j = 0; j < NBNXN_CPU_CLUSTER_I_SIZE; j++)
2895                 {
2896                     InRange = InRange ||
2897                         (sqr(x_ci[i*STRIDE_XYZ+XX] - x_j[(cjl_gl*NBNXN_CPU_CLUSTER_I_SIZE+j)*STRIDE_XYZ+XX]) +
2898                          sqr(x_ci[i*STRIDE_XYZ+YY] - x_j[(cjl_gl*NBNXN_CPU_CLUSTER_I_SIZE+j)*STRIDE_XYZ+YY]) +
2899                          sqr(x_ci[i*STRIDE_XYZ+ZZ] - x_j[(cjl_gl*NBNXN_CPU_CLUSTER_I_SIZE+j)*STRIDE_XYZ+ZZ]) < rl2);
2900                 }
2901             }
2902             *ndistc += NBNXN_CPU_CLUSTER_I_SIZE*NBNXN_CPU_CLUSTER_I_SIZE;
2903         }
2904         if (!InRange)
2905         {
2906             cjl--;
2907         }
2908     }
2909
2910     if (cjf <= cjl)
2911     {
2912         for (cj = cjf; cj <= cjl; cj++)
2913         {
2914             /* Store cj and the interaction mask */
2915             nbl->cj[nbl->ncj].cj   = gridj->cell0 + cj;
2916             nbl->cj[nbl->ncj].excl = get_imask(remove_sub_diag, ci, cj);
2917             nbl->ncj++;
2918         }
2919         /* Increase the closing index in i super-cell list */
2920         nbl->ci[nbl->nci].cj_ind_end = nbl->ncj;
2921     }
2922 }
2923
2924 #ifdef GMX_NBNXN_SIMD_4XN
2925 #include "nbnxn_search_simd_4xn.h"
2926 #endif
2927 #ifdef GMX_NBNXN_SIMD_2XNN
2928 #include "nbnxn_search_simd_2xnn.h"
2929 #endif
2930
2931 /* Plain C or SIMD4 code for making a pair list of super-cell sci vs scj.
2932  * Checks bounding box distances and possibly atom pair distances.
2933  */
2934 static void make_cluster_list_supersub(const nbnxn_grid_t *gridi,
2935                                        const nbnxn_grid_t *gridj,
2936                                        nbnxn_pairlist_t *nbl,
2937                                        int sci, int scj,
2938                                        gmx_bool sci_equals_scj,
2939                                        int stride, const real *x,
2940                                        real rl2, float rbb2,
2941                                        int *ndistc)
2942 {
2943     int               na_c;
2944     int               npair;
2945     int               cjo, ci1, ci, cj, cj_gl;
2946     int               cj4_ind, cj_offset;
2947     unsigned int      imask;
2948     nbnxn_cj4_t      *cj4;
2949 #ifdef NBNXN_BBXXXX
2950     const float      *pbb_ci;
2951 #else
2952     const nbnxn_bb_t *bb_ci;
2953 #endif
2954     const real       *x_ci;
2955     float            *d2l, d2;
2956     int               w;
2957 #define PRUNE_LIST_CPU_ONE
2958 #ifdef PRUNE_LIST_CPU_ONE
2959     int  ci_last = -1;
2960 #endif
2961
2962     d2l = nbl->work->d2;
2963
2964 #ifdef NBNXN_BBXXXX
2965     pbb_ci = nbl->work->pbb_ci;
2966 #else
2967     bb_ci  = nbl->work->bb_ci;
2968 #endif
2969     x_ci   = nbl->work->x_ci;
2970
2971     na_c = gridj->na_c;
2972
2973     for (cjo = 0; cjo < gridj->nsubc[scj]; cjo++)
2974     {
2975         cj4_ind   = (nbl->work->cj_ind >> NBNXN_GPU_JGROUP_SIZE_2LOG);
2976         cj_offset = nbl->work->cj_ind - cj4_ind*NBNXN_GPU_JGROUP_SIZE;
2977         cj4       = &nbl->cj4[cj4_ind];
2978
2979         cj = scj*GPU_NSUBCELL + cjo;
2980
2981         cj_gl = gridj->cell0*GPU_NSUBCELL + cj;
2982
2983         /* Initialize this j-subcell i-subcell list */
2984         cj4->cj[cj_offset] = cj_gl;
2985         imask              = 0;
2986
2987         if (sci_equals_scj)
2988         {
2989             ci1 = cjo + 1;
2990         }
2991         else
2992         {
2993             ci1 = gridi->nsubc[sci];
2994         }
2995
2996 #ifdef NBNXN_BBXXXX
2997         /* Determine all ci1 bb distances in one call with SIMD4 */
2998         subc_bb_dist2_simd4_xxxx(gridj->pbb+(cj>>STRIDE_PBB_2LOG)*NNBSBB_XXXX+(cj & (STRIDE_PBB-1)),
2999                                  ci1, pbb_ci, d2l);
3000         *ndistc += na_c*2;
3001 #endif
3002
3003         npair = 0;
3004         /* We use a fixed upper-bound instead of ci1 to help optimization */
3005         for (ci = 0; ci < GPU_NSUBCELL; ci++)
3006         {
3007             if (ci == ci1)
3008             {
3009                 break;
3010             }
3011
3012 #ifndef NBNXN_BBXXXX
3013             /* Determine the bb distance between ci and cj */
3014             d2l[ci]  = subc_bb_dist2(ci, bb_ci, cj, gridj->bb);
3015             *ndistc += 2;
3016 #endif
3017             d2 = d2l[ci];
3018
3019 #ifdef PRUNE_LIST_CPU_ALL
3020             /* Check if the distance is within the distance where
3021              * we use only the bounding box distance rbb,
3022              * or within the cut-off and there is at least one atom pair
3023              * within the cut-off. This check is very costly.
3024              */
3025             *ndistc += na_c*na_c;
3026             if (d2 < rbb2 ||
3027                 (d2 < rl2 &&
3028 #ifdef NBNXN_PBB_SIMD4
3029                  subc_in_range_simd4
3030 #else
3031                  subc_in_range_x
3032 #endif
3033                      (na_c, ci, x_ci, cj_gl, stride, x, rl2)))
3034 #else
3035             /* Check if the distance between the two bounding boxes
3036              * in within the pair-list cut-off.
3037              */
3038             if (d2 < rl2)
3039 #endif
3040             {
3041                 /* Flag this i-subcell to be taken into account */
3042                 imask |= (1U << (cj_offset*GPU_NSUBCELL+ci));
3043
3044 #ifdef PRUNE_LIST_CPU_ONE
3045                 ci_last = ci;
3046 #endif
3047
3048                 npair++;
3049             }
3050         }
3051
3052 #ifdef PRUNE_LIST_CPU_ONE
3053         /* If we only found 1 pair, check if any atoms are actually
3054          * within the cut-off, so we could get rid of it.
3055          */
3056         if (npair == 1 && d2l[ci_last] >= rbb2)
3057         {
3058             /* Avoid using function pointers here, as it's slower */
3059             if (
3060 #ifdef NBNXN_PBB_SIMD4
3061                 !subc_in_range_simd4
3062 #else
3063                 !subc_in_range_x
3064 #endif
3065                     (na_c, ci_last, x_ci, cj_gl, stride, x, rl2))
3066             {
3067                 imask &= ~(1U << (cj_offset*GPU_NSUBCELL+ci_last));
3068                 npair--;
3069             }
3070         }
3071 #endif
3072
3073         if (npair > 0)
3074         {
3075             /* We have a useful sj entry, close it now */
3076
3077             /* Set the exclucions for the ci== sj entry.
3078              * Here we don't bother to check if this entry is actually flagged,
3079              * as it will nearly always be in the list.
3080              */
3081             if (sci_equals_scj)
3082             {
3083                 set_self_and_newton_excls_supersub(nbl, cj4_ind, cj_offset, cjo);
3084             }
3085
3086             /* Copy the cluster interaction mask to the list */
3087             for (w = 0; w < NWARP; w++)
3088             {
3089                 cj4->imei[w].imask |= imask;
3090             }
3091
3092             nbl->work->cj_ind++;
3093
3094             /* Keep the count */
3095             nbl->nci_tot += npair;
3096
3097             /* Increase the closing index in i super-cell list */
3098             nbl->sci[nbl->nsci].cj4_ind_end =
3099                 ((nbl->work->cj_ind+NBNXN_GPU_JGROUP_SIZE-1) >> NBNXN_GPU_JGROUP_SIZE_2LOG);
3100         }
3101     }
3102 }
3103
3104 /* Set all atom-pair exclusions from the topology stored in excl
3105  * as masks in the pair-list for simple list i-entry nbl_ci
3106  */
3107 static void set_ci_top_excls(const nbnxn_search_t nbs,
3108                              nbnxn_pairlist_t    *nbl,
3109                              gmx_bool             diagRemoved,
3110                              int                  na_ci_2log,
3111                              int                  na_cj_2log,
3112                              const nbnxn_ci_t    *nbl_ci,
3113                              const t_blocka      *excl)
3114 {
3115     const int    *cell;
3116     int           ci;
3117     int           cj_ind_first, cj_ind_last;
3118     int           cj_first, cj_last;
3119     int           ndirect;
3120     int           i, ai, aj, si, eind, ge, se;
3121     int           found, cj_ind_0, cj_ind_1, cj_ind_m;
3122     int           cj_m;
3123     gmx_bool      Found_si;
3124     int           si_ind;
3125     nbnxn_excl_t *nbl_excl;
3126     int           inner_i, inner_e;
3127
3128     cell = nbs->cell;
3129
3130     if (nbl_ci->cj_ind_end == nbl_ci->cj_ind_start)
3131     {
3132         /* Empty list */
3133         return;
3134     }
3135
3136     ci = nbl_ci->ci;
3137
3138     cj_ind_first = nbl_ci->cj_ind_start;
3139     cj_ind_last  = nbl->ncj - 1;
3140
3141     cj_first = nbl->cj[cj_ind_first].cj;
3142     cj_last  = nbl->cj[cj_ind_last].cj;
3143
3144     /* Determine how many contiguous j-cells we have starting
3145      * from the first i-cell. This number can be used to directly
3146      * calculate j-cell indices for excluded atoms.
3147      */
3148     ndirect = 0;
3149     if (na_ci_2log == na_cj_2log)
3150     {
3151         while (cj_ind_first + ndirect <= cj_ind_last &&
3152                nbl->cj[cj_ind_first+ndirect].cj == ci + ndirect)
3153         {
3154             ndirect++;
3155         }
3156     }
3157 #ifdef NBNXN_SEARCH_BB_SIMD4
3158     else
3159     {
3160         while (cj_ind_first + ndirect <= cj_ind_last &&
3161                nbl->cj[cj_ind_first+ndirect].cj == ci_to_cj(na_cj_2log, ci) + ndirect)
3162         {
3163             ndirect++;
3164         }
3165     }
3166 #endif
3167
3168     /* Loop over the atoms in the i super-cell */
3169     for (i = 0; i < nbl->na_sc; i++)
3170     {
3171         ai = nbs->a[ci*nbl->na_sc+i];
3172         if (ai >= 0)
3173         {
3174             si  = (i>>na_ci_2log);
3175
3176             /* Loop over the topology-based exclusions for this i-atom */
3177             for (eind = excl->index[ai]; eind < excl->index[ai+1]; eind++)
3178             {
3179                 aj = excl->a[eind];
3180
3181                 if (aj == ai)
3182                 {
3183                     /* The self exclusion are already set, save some time */
3184                     continue;
3185                 }
3186
3187                 ge = cell[aj];
3188
3189                 /* Without shifts we only calculate interactions j>i
3190                  * for one-way pair-lists.
3191                  */
3192                 if (diagRemoved && ge <= ci*nbl->na_sc + i)
3193                 {
3194                     continue;
3195                 }
3196
3197                 se = (ge >> na_cj_2log);
3198
3199                 /* Could the cluster se be in our list? */
3200                 if (se >= cj_first && se <= cj_last)
3201                 {
3202                     if (se < cj_first + ndirect)
3203                     {
3204                         /* We can calculate cj_ind directly from se */
3205                         found = cj_ind_first + se - cj_first;
3206                     }
3207                     else
3208                     {
3209                         /* Search for se using bisection */
3210                         found    = -1;
3211                         cj_ind_0 = cj_ind_first + ndirect;
3212                         cj_ind_1 = cj_ind_last + 1;
3213                         while (found == -1 && cj_ind_0 < cj_ind_1)
3214                         {
3215                             cj_ind_m = (cj_ind_0 + cj_ind_1)>>1;
3216
3217                             cj_m = nbl->cj[cj_ind_m].cj;
3218
3219                             if (se == cj_m)
3220                             {
3221                                 found = cj_ind_m;
3222                             }
3223                             else if (se < cj_m)
3224                             {
3225                                 cj_ind_1 = cj_ind_m;
3226                             }
3227                             else
3228                             {
3229                                 cj_ind_0 = cj_ind_m + 1;
3230                             }
3231                         }
3232                     }
3233
3234                     if (found >= 0)
3235                     {
3236                         inner_i = i  - (si << na_ci_2log);
3237                         inner_e = ge - (se << na_cj_2log);
3238
3239                         nbl->cj[found].excl &= ~(1U<<((inner_i<<na_cj_2log) + inner_e));
3240 /* The next code line is usually not needed. We do not want to version
3241  * away the above line, because there is logic that relies on being
3242  * able to detect easily whether any exclusions exist. */
3243 #if (defined GMX_SIMD_IBM_QPX)
3244                         nbl->cj[found].interaction_mask_indices[inner_i] &= ~(1U << inner_e);
3245 #endif
3246                     }
3247                 }
3248             }
3249         }
3250     }
3251 }
3252
3253 /* Add a new i-entry to the FEP list and copy the i-properties */
3254 static gmx_inline void fep_list_new_nri_copy(t_nblist *nlist)
3255 {
3256     /* Add a new i-entry */
3257     nlist->nri++;
3258
3259     assert(nlist->nri < nlist->maxnri);
3260
3261     /* Duplicate the last i-entry, except for jindex, which continues */
3262     nlist->iinr[nlist->nri]   = nlist->iinr[nlist->nri-1];
3263     nlist->shift[nlist->nri]  = nlist->shift[nlist->nri-1];
3264     nlist->gid[nlist->nri]    = nlist->gid[nlist->nri-1];
3265     nlist->jindex[nlist->nri] = nlist->nrj;
3266 }
3267
3268 /* For load balancing of the free-energy lists over threads, we set
3269  * the maximum nrj size of an i-entry to 40. This leads to good
3270  * load balancing in the worst case scenario of a single perturbed
3271  * particle on 16 threads, while not introducing significant overhead.
3272  * Note that half of the perturbed pairs will anyhow end up in very small lists,
3273  * since non perturbed i-particles will see few perturbed j-particles).
3274  */
3275 const int max_nrj_fep = 40;
3276
3277 /* Exclude the perturbed pairs from the Verlet list. This is only done to avoid
3278  * singularities for overlapping particles (0/0), since the charges and
3279  * LJ parameters have been zeroed in the nbnxn data structure.
3280  * Simultaneously make a group pair list for the perturbed pairs.
3281  */
3282 static void make_fep_list(const nbnxn_search_t    nbs,
3283                           const nbnxn_atomdata_t *nbat,
3284                           nbnxn_pairlist_t       *nbl,
3285                           gmx_bool                bDiagRemoved,
3286                           nbnxn_ci_t             *nbl_ci,
3287                           const nbnxn_grid_t     *gridi,
3288                           const nbnxn_grid_t     *gridj,
3289                           t_nblist               *nlist)
3290 {
3291     int      ci, cj_ind_start, cj_ind_end, cj_ind, cja, cjr;
3292     int      nri_max;
3293     int      ngid, gid_i = 0, gid_j, gid;
3294     int      egp_shift, egp_mask;
3295     int      gid_cj = 0;
3296     int      i, j, ind_i, ind_j, ai, aj;
3297     int      nri;
3298     gmx_bool bFEP_i, bFEP_i_all;
3299
3300     if (nbl_ci->cj_ind_end == nbl_ci->cj_ind_start)
3301     {
3302         /* Empty list */
3303         return;
3304     }
3305
3306     ci = nbl_ci->ci;
3307
3308     cj_ind_start = nbl_ci->cj_ind_start;
3309     cj_ind_end   = nbl_ci->cj_ind_end;
3310
3311     /* In worst case we have alternating energy groups
3312      * and create #atom-pair lists, which means we need the size
3313      * of a cluster pair (na_ci*na_cj) times the number of cj's.
3314      */
3315     nri_max = nbl->na_ci*nbl->na_cj*(cj_ind_end - cj_ind_start);
3316     if (nlist->nri + nri_max > nlist->maxnri)
3317     {
3318         nlist->maxnri = over_alloc_large(nlist->nri + nri_max);
3319         reallocate_nblist(nlist);
3320     }
3321
3322     ngid = nbat->nenergrp;
3323
3324     if (ngid*gridj->na_cj > sizeof(gid_cj)*8)
3325     {
3326         gmx_fatal(FARGS, "The Verlet scheme with %dx%d kernels and free-energy only supports up to %d energy groups",
3327                   gridi->na_c, gridj->na_cj, (sizeof(gid_cj)*8)/gridj->na_cj);
3328     }
3329
3330     egp_shift = nbat->neg_2log;
3331     egp_mask  = (1<<nbat->neg_2log) - 1;
3332
3333     /* Loop over the atoms in the i sub-cell */
3334     bFEP_i_all = TRUE;
3335     for (i = 0; i < nbl->na_ci; i++)
3336     {
3337         ind_i = ci*nbl->na_ci + i;
3338         ai    = nbs->a[ind_i];
3339         if (ai >= 0)
3340         {
3341             nri                  = nlist->nri;
3342             nlist->jindex[nri+1] = nlist->jindex[nri];
3343             nlist->iinr[nri]     = ai;
3344             /* The actual energy group pair index is set later */
3345             nlist->gid[nri]      = 0;
3346             nlist->shift[nri]    = nbl_ci->shift & NBNXN_CI_SHIFT;
3347
3348             bFEP_i = gridi->fep[ci - gridi->cell0] & (1 << i);
3349
3350             bFEP_i_all = bFEP_i_all && bFEP_i;
3351
3352             if ((nlist->nrj + cj_ind_end - cj_ind_start)*nbl->na_cj > nlist->maxnrj)
3353             {
3354                 nlist->maxnrj = over_alloc_small((nlist->nrj + cj_ind_end - cj_ind_start)*nbl->na_cj);
3355                 srenew(nlist->jjnr,     nlist->maxnrj);
3356                 srenew(nlist->excl_fep, nlist->maxnrj);
3357             }
3358
3359             if (ngid > 1)
3360             {
3361                 gid_i = (nbat->energrp[ci] >> (egp_shift*i)) & egp_mask;
3362             }
3363
3364             for (cj_ind = cj_ind_start; cj_ind < cj_ind_end; cj_ind++)
3365             {
3366                 unsigned int fep_cj;
3367
3368                 cja = nbl->cj[cj_ind].cj;
3369
3370                 if (gridj->na_cj == gridj->na_c)
3371                 {
3372                     cjr    = cja - gridj->cell0;
3373                     fep_cj = gridj->fep[cjr];
3374                     if (ngid > 1)
3375                     {
3376                         gid_cj = nbat->energrp[cja];
3377                     }
3378                 }
3379                 else if (2*gridj->na_cj == gridj->na_c)
3380                 {
3381                     cjr    = cja - gridj->cell0*2;
3382                     /* Extract half of the ci fep/energrp mask */
3383                     fep_cj = (gridj->fep[cjr>>1] >> ((cjr&1)*gridj->na_cj)) & ((1<<gridj->na_cj) - 1);
3384                     if (ngid > 1)
3385                     {
3386                         gid_cj = nbat->energrp[cja>>1] >> ((cja&1)*gridj->na_cj*egp_shift) & ((1<<(gridj->na_cj*egp_shift)) - 1);
3387                     }
3388                 }
3389                 else
3390                 {
3391                     cjr    = cja - (gridj->cell0>>1);
3392                     /* Combine two ci fep masks/energrp */
3393                     fep_cj = gridj->fep[cjr*2] + (gridj->fep[cjr*2+1] << gridj->na_c);
3394                     if (ngid > 1)
3395                     {
3396                         gid_cj = nbat->energrp[cja*2] + (nbat->energrp[cja*2+1] << (gridj->na_c*egp_shift));
3397                     }
3398                 }
3399
3400                 if (bFEP_i || fep_cj != 0)
3401                 {
3402                     for (j = 0; j < nbl->na_cj; j++)
3403                     {
3404                         /* Is this interaction perturbed and not excluded? */
3405                         ind_j = cja*nbl->na_cj + j;
3406                         aj    = nbs->a[ind_j];
3407                         if (aj >= 0 &&
3408                             (bFEP_i || (fep_cj & (1 << j))) &&
3409                             (!bDiagRemoved || ind_j >= ind_i))
3410                         {
3411                             if (ngid > 1)
3412                             {
3413                                 gid_j = (gid_cj >> (j*egp_shift)) & egp_mask;
3414                                 gid   = GID(gid_i, gid_j, ngid);
3415
3416                                 if (nlist->nrj > nlist->jindex[nri] &&
3417                                     nlist->gid[nri] != gid)
3418                                 {
3419                                     /* Energy group pair changed: new list */
3420                                     fep_list_new_nri_copy(nlist);
3421                                     nri = nlist->nri;
3422                                 }
3423                                 nlist->gid[nri] = gid;
3424                             }
3425
3426                             if (nlist->nrj - nlist->jindex[nri] >= max_nrj_fep)
3427                             {
3428                                 fep_list_new_nri_copy(nlist);
3429                                 nri = nlist->nri;
3430                             }
3431
3432                             /* Add it to the FEP list */
3433                             nlist->jjnr[nlist->nrj]     = aj;
3434                             nlist->excl_fep[nlist->nrj] = (nbl->cj[cj_ind].excl >> (i*nbl->na_cj + j)) & 1;
3435                             nlist->nrj++;
3436
3437                             /* Exclude it from the normal list.
3438                              * Note that the charge has been set to zero,
3439                              * but we need to avoid 0/0, as perturbed atoms
3440                              * can be on top of each other.
3441                              * (and the LJ parameters have not been zeroed)
3442                              */
3443                             nbl->cj[cj_ind].excl &= ~(1U << (i*nbl->na_cj + j));
3444                         }
3445                     }
3446                 }
3447             }
3448
3449             if (nlist->nrj > nlist->jindex[nri])
3450             {
3451                 /* Actually add this new, non-empty, list */
3452                 nlist->nri++;
3453                 nlist->jindex[nlist->nri] = nlist->nrj;
3454             }
3455         }
3456     }
3457
3458     if (bFEP_i_all)
3459     {
3460         /* All interactions are perturbed, we can skip this entry */
3461         nbl_ci->cj_ind_end = cj_ind_start;
3462     }
3463 }
3464
3465 /* Return the index of atom a within a cluster */
3466 static gmx_inline int cj_mod_cj4(int cj)
3467 {
3468     return cj & (NBNXN_GPU_JGROUP_SIZE - 1);
3469 }
3470
3471 /* Convert a j-cluster to a cj4 group */
3472 static gmx_inline int cj_to_cj4(int cj)
3473 {
3474     return cj >> NBNXN_GPU_JGROUP_SIZE_2LOG;
3475 }
3476
3477 /* Return the index of an j-atom within a warp */
3478 static gmx_inline int a_mod_wj(int a)
3479 {
3480     return a & (NBNXN_GPU_CLUSTER_SIZE/2 - 1);
3481 }
3482
3483 /* As make_fep_list above, but for super/sub lists. */
3484 static void make_fep_list_supersub(const nbnxn_search_t    nbs,
3485                                    const nbnxn_atomdata_t *nbat,
3486                                    nbnxn_pairlist_t       *nbl,
3487                                    gmx_bool                bDiagRemoved,
3488                                    const nbnxn_sci_t      *nbl_sci,
3489                                    real                    shx,
3490                                    real                    shy,
3491                                    real                    shz,
3492                                    real                    rlist_fep2,
3493                                    const nbnxn_grid_t     *gridi,
3494                                    const nbnxn_grid_t     *gridj,
3495                                    t_nblist               *nlist)
3496 {
3497     int                sci, cj4_ind_start, cj4_ind_end, cj4_ind, gcj, cjr;
3498     int                nri_max;
3499     int                c, c_abs;
3500     int                i, j, ind_i, ind_j, ai, aj;
3501     int                nri;
3502     gmx_bool           bFEP_i;
3503     real               xi, yi, zi;
3504     const nbnxn_cj4_t *cj4;
3505
3506     if (nbl_sci->cj4_ind_end == nbl_sci->cj4_ind_start)
3507     {
3508         /* Empty list */
3509         return;
3510     }
3511
3512     sci = nbl_sci->sci;
3513
3514     cj4_ind_start = nbl_sci->cj4_ind_start;
3515     cj4_ind_end   = nbl_sci->cj4_ind_end;
3516
3517     /* Here we process one super-cell, max #atoms na_sc, versus a list
3518      * cj4 entries, each with max NBNXN_GPU_JGROUP_SIZE cj's, each
3519      * of size na_cj atoms.
3520      * On the GPU we don't support energy groups (yet).
3521      * So for each of the na_sc i-atoms, we need max one FEP list
3522      * for each max_nrj_fep j-atoms.
3523      */
3524     nri_max = nbl->na_sc*nbl->na_cj*(1 + ((cj4_ind_end - cj4_ind_start)*NBNXN_GPU_JGROUP_SIZE)/max_nrj_fep);
3525     if (nlist->nri + nri_max > nlist->maxnri)
3526     {
3527         nlist->maxnri = over_alloc_large(nlist->nri + nri_max);
3528         reallocate_nblist(nlist);
3529     }
3530
3531     /* Loop over the atoms in the i super-cluster */
3532     for (c = 0; c < GPU_NSUBCELL; c++)
3533     {
3534         c_abs = sci*GPU_NSUBCELL + c;
3535
3536         for (i = 0; i < nbl->na_ci; i++)
3537         {
3538             ind_i = c_abs*nbl->na_ci + i;
3539             ai    = nbs->a[ind_i];
3540             if (ai >= 0)
3541             {
3542                 nri                  = nlist->nri;
3543                 nlist->jindex[nri+1] = nlist->jindex[nri];
3544                 nlist->iinr[nri]     = ai;
3545                 /* With GPUs, energy groups are not supported */
3546                 nlist->gid[nri]      = 0;
3547                 nlist->shift[nri]    = nbl_sci->shift & NBNXN_CI_SHIFT;
3548
3549                 bFEP_i = (gridi->fep[c_abs - gridi->cell0] & (1 << i));
3550
3551                 xi = nbat->x[ind_i*nbat->xstride+XX] + shx;
3552                 yi = nbat->x[ind_i*nbat->xstride+YY] + shy;
3553                 zi = nbat->x[ind_i*nbat->xstride+ZZ] + shz;
3554
3555                 if ((nlist->nrj + cj4_ind_end - cj4_ind_start)*NBNXN_GPU_JGROUP_SIZE*nbl->na_cj > nlist->maxnrj)
3556                 {
3557                     nlist->maxnrj = over_alloc_small((nlist->nrj + cj4_ind_end - cj4_ind_start)*NBNXN_GPU_JGROUP_SIZE*nbl->na_cj);
3558                     srenew(nlist->jjnr,     nlist->maxnrj);
3559                     srenew(nlist->excl_fep, nlist->maxnrj);
3560                 }
3561
3562                 for (cj4_ind = cj4_ind_start; cj4_ind < cj4_ind_end; cj4_ind++)
3563                 {
3564                     cj4 = &nbl->cj4[cj4_ind];
3565
3566                     for (gcj = 0; gcj < NBNXN_GPU_JGROUP_SIZE; gcj++)
3567                     {
3568                         unsigned int fep_cj;
3569
3570                         if ((cj4->imei[0].imask & (1U << (gcj*GPU_NSUBCELL + c))) == 0)
3571                         {
3572                             /* Skip this ci for this cj */
3573                             continue;
3574                         }
3575
3576                         cjr = cj4->cj[gcj] - gridj->cell0*GPU_NSUBCELL;
3577
3578                         fep_cj = gridj->fep[cjr];
3579
3580                         if (bFEP_i || fep_cj != 0)
3581                         {
3582                             for (j = 0; j < nbl->na_cj; j++)
3583                             {
3584                                 /* Is this interaction perturbed and not excluded? */
3585                                 ind_j = (gridj->cell0*GPU_NSUBCELL + cjr)*nbl->na_cj + j;
3586                                 aj    = nbs->a[ind_j];
3587                                 if (aj >= 0 &&
3588                                     (bFEP_i || (fep_cj & (1 << j))) &&
3589                                     (!bDiagRemoved || ind_j >= ind_i))
3590                                 {
3591                                     nbnxn_excl_t *excl;
3592                                     int           excl_pair;
3593                                     unsigned int  excl_bit;
3594                                     real          dx, dy, dz;
3595
3596                                     get_nbl_exclusions_1(nbl, cj4_ind, j>>2, &excl);
3597
3598                                     excl_pair = a_mod_wj(j)*nbl->na_ci + i;
3599                                     excl_bit  = (1U << (gcj*GPU_NSUBCELL + c));
3600
3601                                     dx = nbat->x[ind_j*nbat->xstride+XX] - xi;
3602                                     dy = nbat->x[ind_j*nbat->xstride+YY] - yi;
3603                                     dz = nbat->x[ind_j*nbat->xstride+ZZ] - zi;
3604
3605                                     /* The unpruned GPU list has more than 2/3
3606                                      * of the atom pairs beyond rlist. Using
3607                                      * this list will cause a lot of overhead
3608                                      * in the CPU FEP kernels, especially
3609                                      * relative to the fast GPU kernels.
3610                                      * So we prune the FEP list here.
3611                                      */
3612                                     if (dx*dx + dy*dy + dz*dz < rlist_fep2)
3613                                     {
3614                                         if (nlist->nrj - nlist->jindex[nri] >= max_nrj_fep)
3615                                         {
3616                                             fep_list_new_nri_copy(nlist);
3617                                             nri = nlist->nri;
3618                                         }
3619
3620                                         /* Add it to the FEP list */
3621                                         nlist->jjnr[nlist->nrj]     = aj;
3622                                         nlist->excl_fep[nlist->nrj] = (excl->pair[excl_pair] & excl_bit) ? 1 : 0;
3623                                         nlist->nrj++;
3624                                     }
3625
3626                                     /* Exclude it from the normal list.
3627                                      * Note that the charge and LJ parameters have
3628                                      * been set to zero, but we need to avoid 0/0,
3629                                      * as perturbed atoms can be on top of each other.
3630                                      */
3631                                     excl->pair[excl_pair] &= ~excl_bit;
3632                                 }
3633                             }
3634
3635                             /* Note that we could mask out this pair in imask
3636                              * if all i- and/or all j-particles are perturbed.
3637                              * But since the perturbed pairs on the CPU will
3638                              * take an order of magnitude more time, the GPU
3639                              * will finish before the CPU and there is no gain.
3640                              */
3641                         }
3642                     }
3643                 }
3644
3645                 if (nlist->nrj > nlist->jindex[nri])
3646                 {
3647                     /* Actually add this new, non-empty, list */
3648                     nlist->nri++;
3649                     nlist->jindex[nlist->nri] = nlist->nrj;
3650                 }
3651             }
3652         }
3653     }
3654 }
3655
3656 /* Set all atom-pair exclusions from the topology stored in excl
3657  * as masks in the pair-list for i-super-cell entry nbl_sci
3658  */
3659 static void set_sci_top_excls(const nbnxn_search_t nbs,
3660                               nbnxn_pairlist_t    *nbl,
3661                               gmx_bool             diagRemoved,
3662                               int                  na_c_2log,
3663                               const nbnxn_sci_t   *nbl_sci,
3664                               const t_blocka      *excl)
3665 {
3666     const int    *cell;
3667     int           na_c;
3668     int           sci;
3669     int           cj_ind_first, cj_ind_last;
3670     int           cj_first, cj_last;
3671     int           ndirect;
3672     int           i, ai, aj, si, eind, ge, se;
3673     int           found, cj_ind_0, cj_ind_1, cj_ind_m;
3674     int           cj_m;
3675     gmx_bool      Found_si;
3676     int           si_ind;
3677     nbnxn_excl_t *nbl_excl;
3678     int           inner_i, inner_e, w;
3679
3680     cell = nbs->cell;
3681
3682     na_c = nbl->na_ci;
3683
3684     if (nbl_sci->cj4_ind_end == nbl_sci->cj4_ind_start)
3685     {
3686         /* Empty list */
3687         return;
3688     }
3689
3690     sci = nbl_sci->sci;
3691
3692     cj_ind_first = nbl_sci->cj4_ind_start*NBNXN_GPU_JGROUP_SIZE;
3693     cj_ind_last  = nbl->work->cj_ind - 1;
3694
3695     cj_first = nbl->cj4[nbl_sci->cj4_ind_start].cj[0];
3696     cj_last  = nbl_cj(nbl, cj_ind_last);
3697
3698     /* Determine how many contiguous j-clusters we have starting
3699      * from the first i-cluster. This number can be used to directly
3700      * calculate j-cluster indices for excluded atoms.
3701      */
3702     ndirect = 0;
3703     while (cj_ind_first + ndirect <= cj_ind_last &&
3704            nbl_cj(nbl, cj_ind_first+ndirect) == sci*GPU_NSUBCELL + ndirect)
3705     {
3706         ndirect++;
3707     }
3708
3709     /* Loop over the atoms in the i super-cell */
3710     for (i = 0; i < nbl->na_sc; i++)
3711     {
3712         ai = nbs->a[sci*nbl->na_sc+i];
3713         if (ai >= 0)
3714         {
3715             si  = (i>>na_c_2log);
3716
3717             /* Loop over the topology-based exclusions for this i-atom */
3718             for (eind = excl->index[ai]; eind < excl->index[ai+1]; eind++)
3719             {
3720                 aj = excl->a[eind];
3721
3722                 if (aj == ai)
3723                 {
3724                     /* The self exclusion are already set, save some time */
3725                     continue;
3726                 }
3727
3728                 ge = cell[aj];
3729
3730                 /* Without shifts we only calculate interactions j>i
3731                  * for one-way pair-lists.
3732                  */
3733                 if (diagRemoved && ge <= sci*nbl->na_sc + i)
3734                 {
3735                     continue;
3736                 }
3737
3738                 se = ge>>na_c_2log;
3739                 /* Could the cluster se be in our list? */
3740                 if (se >= cj_first && se <= cj_last)
3741                 {
3742                     if (se < cj_first + ndirect)
3743                     {
3744                         /* We can calculate cj_ind directly from se */
3745                         found = cj_ind_first + se - cj_first;
3746                     }
3747                     else
3748                     {
3749                         /* Search for se using bisection */
3750                         found    = -1;
3751                         cj_ind_0 = cj_ind_first + ndirect;
3752                         cj_ind_1 = cj_ind_last + 1;
3753                         while (found == -1 && cj_ind_0 < cj_ind_1)
3754                         {
3755                             cj_ind_m = (cj_ind_0 + cj_ind_1)>>1;
3756
3757                             cj_m = nbl_cj(nbl, cj_ind_m);
3758
3759                             if (se == cj_m)
3760                             {
3761                                 found = cj_ind_m;
3762                             }
3763                             else if (se < cj_m)
3764                             {
3765                                 cj_ind_1 = cj_ind_m;
3766                             }
3767                             else
3768                             {
3769                                 cj_ind_0 = cj_ind_m + 1;
3770                             }
3771                         }
3772                     }
3773
3774                     if (found >= 0)
3775                     {
3776                         inner_i = i  - si*na_c;
3777                         inner_e = ge - se*na_c;
3778
3779                         if (nbl_imask0(nbl, found) & (1U << (cj_mod_cj4(found)*GPU_NSUBCELL + si)))
3780                         {
3781                             w       = (inner_e >> 2);
3782
3783                             get_nbl_exclusions_1(nbl, cj_to_cj4(found), w, &nbl_excl);
3784
3785                             nbl_excl->pair[a_mod_wj(inner_e)*nbl->na_ci+inner_i] &=
3786                                 ~(1U << (cj_mod_cj4(found)*GPU_NSUBCELL + si));
3787                         }
3788                     }
3789                 }
3790             }
3791         }
3792     }
3793 }
3794
3795 /* Reallocate the simple ci list for at least n entries */
3796 static void nb_realloc_ci(nbnxn_pairlist_t *nbl, int n)
3797 {
3798     nbl->ci_nalloc = over_alloc_small(n);
3799     nbnxn_realloc_void((void **)&nbl->ci,
3800                        nbl->nci*sizeof(*nbl->ci),
3801                        nbl->ci_nalloc*sizeof(*nbl->ci),
3802                        nbl->alloc, nbl->free);
3803 }
3804
3805 /* Reallocate the super-cell sci list for at least n entries */
3806 static void nb_realloc_sci(nbnxn_pairlist_t *nbl, int n)
3807 {
3808     nbl->sci_nalloc = over_alloc_small(n);
3809     nbnxn_realloc_void((void **)&nbl->sci,
3810                        nbl->nsci*sizeof(*nbl->sci),
3811                        nbl->sci_nalloc*sizeof(*nbl->sci),
3812                        nbl->alloc, nbl->free);
3813 }
3814
3815 /* Make a new ci entry at index nbl->nci */
3816 static void new_ci_entry(nbnxn_pairlist_t *nbl, int ci, int shift, int flags)
3817 {
3818     if (nbl->nci + 1 > nbl->ci_nalloc)
3819     {
3820         nb_realloc_ci(nbl, nbl->nci+1);
3821     }
3822     nbl->ci[nbl->nci].ci            = ci;
3823     nbl->ci[nbl->nci].shift         = shift;
3824     /* Store the interaction flags along with the shift */
3825     nbl->ci[nbl->nci].shift        |= flags;
3826     nbl->ci[nbl->nci].cj_ind_start  = nbl->ncj;
3827     nbl->ci[nbl->nci].cj_ind_end    = nbl->ncj;
3828 }
3829
3830 /* Make a new sci entry at index nbl->nsci */
3831 static void new_sci_entry(nbnxn_pairlist_t *nbl, int sci, int shift)
3832 {
3833     if (nbl->nsci + 1 > nbl->sci_nalloc)
3834     {
3835         nb_realloc_sci(nbl, nbl->nsci+1);
3836     }
3837     nbl->sci[nbl->nsci].sci           = sci;
3838     nbl->sci[nbl->nsci].shift         = shift;
3839     nbl->sci[nbl->nsci].cj4_ind_start = nbl->ncj4;
3840     nbl->sci[nbl->nsci].cj4_ind_end   = nbl->ncj4;
3841 }
3842
3843 /* Sort the simple j-list cj on exclusions.
3844  * Entries with exclusions will all be sorted to the beginning of the list.
3845  */
3846 static void sort_cj_excl(nbnxn_cj_t *cj, int ncj,
3847                          nbnxn_list_work_t *work)
3848 {
3849     int jnew, j;
3850
3851     if (ncj > work->cj_nalloc)
3852     {
3853         work->cj_nalloc = over_alloc_large(ncj);
3854         srenew(work->cj, work->cj_nalloc);
3855     }
3856
3857     /* Make a list of the j-cells involving exclusions */
3858     jnew = 0;
3859     for (j = 0; j < ncj; j++)
3860     {
3861         if (cj[j].excl != NBNXN_INTERACTION_MASK_ALL)
3862         {
3863             work->cj[jnew++] = cj[j];
3864         }
3865     }
3866     /* Check if there are exclusions at all or not just the first entry */
3867     if (!((jnew == 0) ||
3868           (jnew == 1 && cj[0].excl != NBNXN_INTERACTION_MASK_ALL)))
3869     {
3870         for (j = 0; j < ncj; j++)
3871         {
3872             if (cj[j].excl == NBNXN_INTERACTION_MASK_ALL)
3873             {
3874                 work->cj[jnew++] = cj[j];
3875             }
3876         }
3877         for (j = 0; j < ncj; j++)
3878         {
3879             cj[j] = work->cj[j];
3880         }
3881     }
3882 }
3883
3884 /* Close this simple list i entry */
3885 static void close_ci_entry_simple(nbnxn_pairlist_t *nbl)
3886 {
3887     int jlen;
3888
3889     /* All content of the new ci entry have already been filled correctly,
3890      * we only need to increase the count here (for non empty lists).
3891      */
3892     jlen = nbl->ci[nbl->nci].cj_ind_end - nbl->ci[nbl->nci].cj_ind_start;
3893     if (jlen > 0)
3894     {
3895         sort_cj_excl(nbl->cj+nbl->ci[nbl->nci].cj_ind_start, jlen, nbl->work);
3896
3897         /* The counts below are used for non-bonded pair/flop counts
3898          * and should therefore match the available kernel setups.
3899          */
3900         if (!(nbl->ci[nbl->nci].shift & NBNXN_CI_DO_COUL(0)))
3901         {
3902             nbl->work->ncj_noq += jlen;
3903         }
3904         else if ((nbl->ci[nbl->nci].shift & NBNXN_CI_HALF_LJ(0)) ||
3905                  !(nbl->ci[nbl->nci].shift & NBNXN_CI_DO_LJ(0)))
3906         {
3907             nbl->work->ncj_hlj += jlen;
3908         }
3909
3910         nbl->nci++;
3911     }
3912 }
3913
3914 /* Split sci entry for load balancing on the GPU.
3915  * Splitting ensures we have enough lists to fully utilize the whole GPU.
3916  * With progBal we generate progressively smaller lists, which improves
3917  * load balancing. As we only know the current count on our own thread,
3918  * we will need to estimate the current total amount of i-entries.
3919  * As the lists get concatenated later, this estimate depends
3920  * both on nthread and our own thread index.
3921  */
3922 static void split_sci_entry(nbnxn_pairlist_t *nbl,
3923                             int nsp_max_av, gmx_bool progBal, int nc_bal,
3924                             int thread, int nthread)
3925 {
3926     int nsci_est;
3927     int nsp_max;
3928     int cj4_start, cj4_end, j4len, cj4;
3929     int sci;
3930     int nsp, nsp_sci, nsp_cj4, nsp_cj4_e, nsp_cj4_p;
3931     int p;
3932
3933     if (progBal)
3934     {
3935         /* Estimate the total numbers of ci's of the nblist combined
3936          * over all threads using the target number of ci's.
3937          */
3938         nsci_est = nc_bal*thread/nthread + nbl->nsci;
3939
3940         /* The first ci blocks should be larger, to avoid overhead.
3941          * The last ci blocks should be smaller, to improve load balancing.
3942          */
3943         nsp_max = max(1,
3944                       nsp_max_av*nc_bal*3/(2*(nsci_est - 1 + nc_bal)));
3945     }
3946     else
3947     {
3948         nsp_max = nsp_max_av;
3949     }
3950
3951     cj4_start = nbl->sci[nbl->nsci-1].cj4_ind_start;
3952     cj4_end   = nbl->sci[nbl->nsci-1].cj4_ind_end;
3953     j4len     = cj4_end - cj4_start;
3954
3955     if (j4len > 1 && j4len*GPU_NSUBCELL*NBNXN_GPU_JGROUP_SIZE > nsp_max)
3956     {
3957         /* Remove the last ci entry and process the cj4's again */
3958         nbl->nsci -= 1;
3959
3960         sci        = nbl->nsci;
3961         nsp        = 0;
3962         nsp_sci    = 0;
3963         nsp_cj4_e  = 0;
3964         nsp_cj4    = 0;
3965         for (cj4 = cj4_start; cj4 < cj4_end; cj4++)
3966         {
3967             nsp_cj4_p = nsp_cj4;
3968             /* Count the number of cluster pairs in this cj4 group */
3969             nsp_cj4   = 0;
3970             for (p = 0; p < GPU_NSUBCELL*NBNXN_GPU_JGROUP_SIZE; p++)
3971             {
3972                 nsp_cj4 += (nbl->cj4[cj4].imei[0].imask >> p) & 1;
3973             }
3974
3975             if (nsp_cj4 > 0 && nsp + nsp_cj4 > nsp_max)
3976             {
3977                 /* Split the list at cj4 */
3978                 nbl->sci[sci].cj4_ind_end = cj4;
3979                 /* Create a new sci entry */
3980                 sci++;
3981                 nbl->nsci++;
3982                 if (nbl->nsci+1 > nbl->sci_nalloc)
3983                 {
3984                     nb_realloc_sci(nbl, nbl->nsci+1);
3985                 }
3986                 nbl->sci[sci].sci           = nbl->sci[nbl->nsci-1].sci;
3987                 nbl->sci[sci].shift         = nbl->sci[nbl->nsci-1].shift;
3988                 nbl->sci[sci].cj4_ind_start = cj4;
3989                 nsp_sci                     = nsp;
3990                 nsp_cj4_e                   = nsp_cj4_p;
3991                 nsp                         = 0;
3992             }
3993             nsp += nsp_cj4;
3994         }
3995
3996         /* Put the remaining cj4's in the last sci entry */
3997         nbl->sci[sci].cj4_ind_end = cj4_end;
3998
3999         /* Possibly balance out the last two sci's
4000          * by moving the last cj4 of the second last sci.
4001          */
4002         if (nsp_sci - nsp_cj4_e >= nsp + nsp_cj4_e)
4003         {
4004             nbl->sci[sci-1].cj4_ind_end--;
4005             nbl->sci[sci].cj4_ind_start--;
4006         }
4007
4008         nbl->nsci++;
4009     }
4010 }
4011
4012 /* Clost this super/sub list i entry */
4013 static void close_ci_entry_supersub(nbnxn_pairlist_t *nbl,
4014                                     int nsp_max_av,
4015                                     gmx_bool progBal, int nc_bal,
4016                                     int thread, int nthread)
4017 {
4018     int j4len, tlen;
4019     int nb, b;
4020
4021     /* All content of the new ci entry have already been filled correctly,
4022      * we only need to increase the count here (for non empty lists).
4023      */
4024     j4len = nbl->sci[nbl->nsci].cj4_ind_end - nbl->sci[nbl->nsci].cj4_ind_start;
4025     if (j4len > 0)
4026     {
4027         /* We can only have complete blocks of 4 j-entries in a list,
4028          * so round the count up before closing.
4029          */
4030         nbl->ncj4         = ((nbl->work->cj_ind + NBNXN_GPU_JGROUP_SIZE - 1) >> NBNXN_GPU_JGROUP_SIZE_2LOG);
4031         nbl->work->cj_ind = nbl->ncj4*NBNXN_GPU_JGROUP_SIZE;
4032
4033         nbl->nsci++;
4034
4035         if (nsp_max_av > 0)
4036         {
4037             /* Measure the size of the new entry and potentially split it */
4038             split_sci_entry(nbl, nsp_max_av, progBal, nc_bal, thread, nthread);
4039         }
4040     }
4041 }
4042
4043 /* Syncs the working array before adding another grid pair to the list */
4044 static void sync_work(nbnxn_pairlist_t *nbl)
4045 {
4046     if (!nbl->bSimple)
4047     {
4048         nbl->work->cj_ind   = nbl->ncj4*NBNXN_GPU_JGROUP_SIZE;
4049         nbl->work->cj4_init = nbl->ncj4;
4050     }
4051 }
4052
4053 /* Clears an nbnxn_pairlist_t data structure */
4054 static void clear_pairlist(nbnxn_pairlist_t *nbl)
4055 {
4056     nbl->nci           = 0;
4057     nbl->nsci          = 0;
4058     nbl->ncj           = 0;
4059     nbl->ncj4          = 0;
4060     nbl->nci_tot       = 0;
4061     nbl->nexcl         = 1;
4062
4063     nbl->work->ncj_noq = 0;
4064     nbl->work->ncj_hlj = 0;
4065 }
4066
4067 /* Clears a group scheme pair list */
4068 static void clear_pairlist_fep(t_nblist *nl)
4069 {
4070     nl->nri = 0;
4071     nl->nrj = 0;
4072     if (nl->jindex == NULL)
4073     {
4074         snew(nl->jindex, 1);
4075     }
4076     nl->jindex[0] = 0;
4077 }
4078
4079 /* Sets a simple list i-cell bounding box, including PBC shift */
4080 static gmx_inline void set_icell_bb_simple(const nbnxn_bb_t *bb, int ci,
4081                                            real shx, real shy, real shz,
4082                                            nbnxn_bb_t *bb_ci)
4083 {
4084     bb_ci->lower[BB_X] = bb[ci].lower[BB_X] + shx;
4085     bb_ci->lower[BB_Y] = bb[ci].lower[BB_Y] + shy;
4086     bb_ci->lower[BB_Z] = bb[ci].lower[BB_Z] + shz;
4087     bb_ci->upper[BB_X] = bb[ci].upper[BB_X] + shx;
4088     bb_ci->upper[BB_Y] = bb[ci].upper[BB_Y] + shy;
4089     bb_ci->upper[BB_Z] = bb[ci].upper[BB_Z] + shz;
4090 }
4091
4092 #ifdef NBNXN_BBXXXX
4093 /* Sets a super-cell and sub cell bounding boxes, including PBC shift */
4094 static void set_icell_bbxxxx_supersub(const float *bb, int ci,
4095                                       real shx, real shy, real shz,
4096                                       float *bb_ci)
4097 {
4098     int ia, m, i;
4099
4100     ia = ci*(GPU_NSUBCELL>>STRIDE_PBB_2LOG)*NNBSBB_XXXX;
4101     for (m = 0; m < (GPU_NSUBCELL>>STRIDE_PBB_2LOG)*NNBSBB_XXXX; m += NNBSBB_XXXX)
4102     {
4103         for (i = 0; i < STRIDE_PBB; i++)
4104         {
4105             bb_ci[m+0*STRIDE_PBB+i] = bb[ia+m+0*STRIDE_PBB+i] + shx;
4106             bb_ci[m+1*STRIDE_PBB+i] = bb[ia+m+1*STRIDE_PBB+i] + shy;
4107             bb_ci[m+2*STRIDE_PBB+i] = bb[ia+m+2*STRIDE_PBB+i] + shz;
4108             bb_ci[m+3*STRIDE_PBB+i] = bb[ia+m+3*STRIDE_PBB+i] + shx;
4109             bb_ci[m+4*STRIDE_PBB+i] = bb[ia+m+4*STRIDE_PBB+i] + shy;
4110             bb_ci[m+5*STRIDE_PBB+i] = bb[ia+m+5*STRIDE_PBB+i] + shz;
4111         }
4112     }
4113 }
4114 #endif
4115
4116 /* Sets a super-cell and sub cell bounding boxes, including PBC shift */
4117 static void set_icell_bb_supersub(const nbnxn_bb_t *bb, int ci,
4118                                   real shx, real shy, real shz,
4119                                   nbnxn_bb_t *bb_ci)
4120 {
4121     int i;
4122
4123     for (i = 0; i < GPU_NSUBCELL; i++)
4124     {
4125         set_icell_bb_simple(bb, ci*GPU_NSUBCELL+i,
4126                             shx, shy, shz,
4127                             &bb_ci[i]);
4128     }
4129 }
4130
4131 /* Copies PBC shifted i-cell atom coordinates x,y,z to working array */
4132 static void icell_set_x_simple(int ci,
4133                                real shx, real shy, real shz,
4134                                int gmx_unused na_c,
4135                                int stride, const real *x,
4136                                nbnxn_list_work_t *work)
4137 {
4138     int  ia, i;
4139
4140     ia = ci*NBNXN_CPU_CLUSTER_I_SIZE;
4141
4142     for (i = 0; i < NBNXN_CPU_CLUSTER_I_SIZE; i++)
4143     {
4144         work->x_ci[i*STRIDE_XYZ+XX] = x[(ia+i)*stride+XX] + shx;
4145         work->x_ci[i*STRIDE_XYZ+YY] = x[(ia+i)*stride+YY] + shy;
4146         work->x_ci[i*STRIDE_XYZ+ZZ] = x[(ia+i)*stride+ZZ] + shz;
4147     }
4148 }
4149
4150 /* Copies PBC shifted super-cell atom coordinates x,y,z to working array */
4151 static void icell_set_x_supersub(int ci,
4152                                  real shx, real shy, real shz,
4153                                  int na_c,
4154                                  int stride, const real *x,
4155                                  nbnxn_list_work_t *work)
4156 {
4157     int   ia, i;
4158     real *x_ci;
4159
4160     x_ci = work->x_ci;
4161
4162     ia = ci*GPU_NSUBCELL*na_c;
4163     for (i = 0; i < GPU_NSUBCELL*na_c; i++)
4164     {
4165         x_ci[i*DIM + XX] = x[(ia+i)*stride + XX] + shx;
4166         x_ci[i*DIM + YY] = x[(ia+i)*stride + YY] + shy;
4167         x_ci[i*DIM + ZZ] = x[(ia+i)*stride + ZZ] + shz;
4168     }
4169 }
4170
4171 #ifdef NBNXN_SEARCH_BB_SIMD4
4172 /* Copies PBC shifted super-cell packed atom coordinates to working array */
4173 static void icell_set_x_supersub_simd4(int ci,
4174                                        real shx, real shy, real shz,
4175                                        int na_c,
4176                                        int stride, const real *x,
4177                                        nbnxn_list_work_t *work)
4178 {
4179     int   si, io, ia, i, j;
4180     real *x_ci;
4181
4182     x_ci = work->x_ci;
4183
4184     for (si = 0; si < GPU_NSUBCELL; si++)
4185     {
4186         for (i = 0; i < na_c; i += STRIDE_PBB)
4187         {
4188             io = si*na_c + i;
4189             ia = ci*GPU_NSUBCELL*na_c + io;
4190             for (j = 0; j < STRIDE_PBB; j++)
4191             {
4192                 x_ci[io*DIM + j + XX*STRIDE_PBB] = x[(ia+j)*stride+XX] + shx;
4193                 x_ci[io*DIM + j + YY*STRIDE_PBB] = x[(ia+j)*stride+YY] + shy;
4194                 x_ci[io*DIM + j + ZZ*STRIDE_PBB] = x[(ia+j)*stride+ZZ] + shz;
4195             }
4196         }
4197     }
4198 }
4199 #endif
4200
4201 static real minimum_subgrid_size_xy(const nbnxn_grid_t *grid)
4202 {
4203     if (grid->bSimple)
4204     {
4205         return min(grid->sx, grid->sy);
4206     }
4207     else
4208     {
4209         return min(grid->sx/GPU_NSUBCELL_X, grid->sy/GPU_NSUBCELL_Y);
4210     }
4211 }
4212
4213 static real effective_buffer_1x1_vs_MxN(const nbnxn_grid_t *gridi,
4214                                         const nbnxn_grid_t *gridj)
4215 {
4216     const real eff_1x1_buffer_fac_overest = 0.1;
4217
4218     /* Determine an atom-pair list cut-off buffer size for atom pairs,
4219      * to be added to rlist (including buffer) used for MxN.
4220      * This is for converting an MxN list to a 1x1 list. This means we can't
4221      * use the normal buffer estimate, as we have an MxN list in which
4222      * some atom pairs beyond rlist are missing. We want to capture
4223      * the beneficial effect of buffering by extra pairs just outside rlist,
4224      * while removing the useless pairs that are further away from rlist.
4225      * (Also the buffer could have been set manually not using the estimate.)
4226      * This buffer size is an overestimate.
4227      * We add 10% of the smallest grid sub-cell dimensions.
4228      * Note that the z-size differs per cell and we don't use this,
4229      * so we overestimate.
4230      * With PME, the 10% value gives a buffer that is somewhat larger
4231      * than the effective buffer with a tolerance of 0.005 kJ/mol/ps.
4232      * Smaller tolerances or using RF lead to a smaller effective buffer,
4233      * so 10% gives a safe overestimate.
4234      */
4235     return eff_1x1_buffer_fac_overest*(minimum_subgrid_size_xy(gridi) +
4236                                        minimum_subgrid_size_xy(gridj));
4237 }
4238
4239 /* Clusters at the cut-off only increase rlist by 60% of their size */
4240 static real nbnxn_rlist_inc_outside_fac = 0.6;
4241
4242 /* Due to the cluster size the effective pair-list is longer than
4243  * that of a simple atom pair-list. This function gives the extra distance.
4244  */
4245 real nbnxn_get_rlist_effective_inc(int cluster_size_j, real atom_density)
4246 {
4247     int  cluster_size_i;
4248     real vol_inc_i, vol_inc_j;
4249
4250     /* We should get this from the setup, but currently it's the same for
4251      * all setups, including GPUs.
4252      */
4253     cluster_size_i = NBNXN_CPU_CLUSTER_I_SIZE;
4254
4255     vol_inc_i = (cluster_size_i - 1)/atom_density;
4256     vol_inc_j = (cluster_size_j - 1)/atom_density;
4257
4258     return nbnxn_rlist_inc_outside_fac*pow(vol_inc_i + vol_inc_j, 1.0/3.0);
4259 }
4260
4261 /* Estimates the interaction volume^2 for non-local interactions */
4262 static real nonlocal_vol2(const gmx_domdec_zones_t *zones, rvec ls, real r)
4263 {
4264     int  z, d;
4265     real cl, ca, za;
4266     real vold_est;
4267     real vol2_est_tot;
4268
4269     vol2_est_tot = 0;
4270
4271     /* Here we simply add up the volumes of 1, 2 or 3 1D decomposition
4272      * not home interaction volume^2. As these volumes are not additive,
4273      * this is an overestimate, but it would only be significant in the limit
4274      * of small cells, where we anyhow need to split the lists into
4275      * as small parts as possible.
4276      */
4277
4278     for (z = 0; z < zones->n; z++)
4279     {
4280         if (zones->shift[z][XX] + zones->shift[z][YY] + zones->shift[z][ZZ] == 1)
4281         {
4282             cl = 0;
4283             ca = 1;
4284             za = 1;
4285             for (d = 0; d < DIM; d++)
4286             {
4287                 if (zones->shift[z][d] == 0)
4288                 {
4289                     cl += 0.5*ls[d];
4290                     ca *= ls[d];
4291                     za *= zones->size[z].x1[d] - zones->size[z].x0[d];
4292                 }
4293             }
4294
4295             /* 4 octants of a sphere */
4296             vold_est  = 0.25*M_PI*r*r*r*r;
4297             /* 4 quarter pie slices on the edges */
4298             vold_est += 4*cl*M_PI/6.0*r*r*r;
4299             /* One rectangular volume on a face */
4300             vold_est += ca*0.5*r*r;
4301
4302             vol2_est_tot += vold_est*za;
4303         }
4304     }
4305
4306     return vol2_est_tot;
4307 }
4308
4309 /* Estimates the average size of a full j-list for super/sub setup */
4310 static int get_nsubpair_max(const nbnxn_search_t nbs,
4311                             int                  iloc,
4312                             real                 rlist,
4313                             int                  min_ci_balanced)
4314 {
4315     const nbnxn_grid_t *grid;
4316     rvec                ls;
4317     real                xy_diag2, r_eff_sup, vol_est, nsp_est, nsp_est_nl;
4318     int                 nsubpair_max;
4319
4320     grid = &nbs->grid[0];
4321
4322     ls[XX] = (grid->c1[XX] - grid->c0[XX])/(grid->ncx*GPU_NSUBCELL_X);
4323     ls[YY] = (grid->c1[YY] - grid->c0[YY])/(grid->ncy*GPU_NSUBCELL_Y);
4324     ls[ZZ] = (grid->c1[ZZ] - grid->c0[ZZ])*grid->ncx*grid->ncy/(grid->nc*GPU_NSUBCELL_Z);
4325
4326     /* The average squared length of the diagonal of a sub cell */
4327     xy_diag2 = ls[XX]*ls[XX] + ls[YY]*ls[YY] + ls[ZZ]*ls[ZZ];
4328
4329     /* The formulas below are a heuristic estimate of the average nsj per si*/
4330     r_eff_sup = rlist + nbnxn_rlist_inc_outside_fac*sqr((grid->na_c - 1.0)/grid->na_c)*sqrt(xy_diag2/3);
4331
4332     if (!nbs->DomDec || nbs->zones->n == 1)
4333     {
4334         nsp_est_nl = 0;
4335     }
4336     else
4337     {
4338         nsp_est_nl =
4339             sqr(grid->atom_density/grid->na_c)*
4340             nonlocal_vol2(nbs->zones, ls, r_eff_sup);
4341     }
4342
4343     if (LOCAL_I(iloc))
4344     {
4345         /* Sub-cell interacts with itself */
4346         vol_est  = ls[XX]*ls[YY]*ls[ZZ];
4347         /* 6/2 rectangular volume on the faces */
4348         vol_est += (ls[XX]*ls[YY] + ls[XX]*ls[ZZ] + ls[YY]*ls[ZZ])*r_eff_sup;
4349         /* 12/2 quarter pie slices on the edges */
4350         vol_est += 2*(ls[XX] + ls[YY] + ls[ZZ])*0.25*M_PI*sqr(r_eff_sup);
4351         /* 4 octants of a sphere */
4352         vol_est += 0.5*4.0/3.0*M_PI*pow(r_eff_sup, 3);
4353
4354         nsp_est = grid->nsubc_tot*vol_est*grid->atom_density/grid->na_c;
4355
4356         /* Subtract the non-local pair count */
4357         nsp_est -= nsp_est_nl;
4358
4359         if (debug)
4360         {
4361             fprintf(debug, "nsp_est local %5.1f non-local %5.1f\n",
4362                     nsp_est, nsp_est_nl);
4363         }
4364     }
4365     else
4366     {
4367         nsp_est = nsp_est_nl;
4368     }
4369
4370     if (min_ci_balanced <= 0 || grid->nc >= min_ci_balanced || grid->nc == 0)
4371     {
4372         /* We don't need to worry */
4373         nsubpair_max = -1;
4374     }
4375     else
4376     {
4377         /* Thus the (average) maximum j-list size should be as follows */
4378         nsubpair_max = max(1, (int)(nsp_est/min_ci_balanced+0.5));
4379
4380         /* Since the target value is a maximum (this avoids high outliers,
4381          * which lead to load imbalance), not average, we add half the
4382          * number of pairs in a cj4 block to get the average about right.
4383          */
4384         nsubpair_max += GPU_NSUBCELL*NBNXN_GPU_JGROUP_SIZE/2;
4385     }
4386
4387     if (debug)
4388     {
4389         fprintf(debug, "nbl nsp estimate %.1f, nsubpair_max %d\n",
4390                 nsp_est, nsubpair_max);
4391     }
4392
4393     return nsubpair_max;
4394 }
4395
4396 /* Debug list print function */
4397 static void print_nblist_ci_cj(FILE *fp, const nbnxn_pairlist_t *nbl)
4398 {
4399     int i, j;
4400
4401     for (i = 0; i < nbl->nci; i++)
4402     {
4403         fprintf(fp, "ci %4d  shift %2d  ncj %3d\n",
4404                 nbl->ci[i].ci, nbl->ci[i].shift,
4405                 nbl->ci[i].cj_ind_end - nbl->ci[i].cj_ind_start);
4406
4407         for (j = nbl->ci[i].cj_ind_start; j < nbl->ci[i].cj_ind_end; j++)
4408         {
4409             fprintf(fp, "  cj %5d  imask %x\n",
4410                     nbl->cj[j].cj,
4411                     nbl->cj[j].excl);
4412         }
4413     }
4414 }
4415
4416 /* Debug list print function */
4417 static void print_nblist_sci_cj(FILE *fp, const nbnxn_pairlist_t *nbl)
4418 {
4419     int i, j4, j, ncp, si;
4420
4421     for (i = 0; i < nbl->nsci; i++)
4422     {
4423         fprintf(fp, "ci %4d  shift %2d  ncj4 %2d\n",
4424                 nbl->sci[i].sci, nbl->sci[i].shift,
4425                 nbl->sci[i].cj4_ind_end - nbl->sci[i].cj4_ind_start);
4426
4427         ncp = 0;
4428         for (j4 = nbl->sci[i].cj4_ind_start; j4 < nbl->sci[i].cj4_ind_end; j4++)
4429         {
4430             for (j = 0; j < NBNXN_GPU_JGROUP_SIZE; j++)
4431             {
4432                 fprintf(fp, "  sj %5d  imask %x\n",
4433                         nbl->cj4[j4].cj[j],
4434                         nbl->cj4[j4].imei[0].imask);
4435                 for (si = 0; si < GPU_NSUBCELL; si++)
4436                 {
4437                     if (nbl->cj4[j4].imei[0].imask & (1U << (j*GPU_NSUBCELL + si)))
4438                     {
4439                         ncp++;
4440                     }
4441                 }
4442             }
4443         }
4444         fprintf(fp, "ci %4d  shift %2d  ncj4 %2d ncp %3d\n",
4445                 nbl->sci[i].sci, nbl->sci[i].shift,
4446                 nbl->sci[i].cj4_ind_end - nbl->sci[i].cj4_ind_start,
4447                 ncp);
4448     }
4449 }
4450
4451 /* Combine pair lists *nbl generated on multiple threads nblc */
4452 static void combine_nblists(int nnbl, nbnxn_pairlist_t **nbl,
4453                             nbnxn_pairlist_t *nblc)
4454 {
4455     int nsci, ncj4, nexcl;
4456     int n, i;
4457
4458     if (nblc->bSimple)
4459     {
4460         gmx_incons("combine_nblists does not support simple lists");
4461     }
4462
4463     nsci  = nblc->nsci;
4464     ncj4  = nblc->ncj4;
4465     nexcl = nblc->nexcl;
4466     for (i = 0; i < nnbl; i++)
4467     {
4468         nsci  += nbl[i]->nsci;
4469         ncj4  += nbl[i]->ncj4;
4470         nexcl += nbl[i]->nexcl;
4471     }
4472
4473     if (nsci > nblc->sci_nalloc)
4474     {
4475         nb_realloc_sci(nblc, nsci);
4476     }
4477     if (ncj4 > nblc->cj4_nalloc)
4478     {
4479         nblc->cj4_nalloc = over_alloc_small(ncj4);
4480         nbnxn_realloc_void((void **)&nblc->cj4,
4481                            nblc->ncj4*sizeof(*nblc->cj4),
4482                            nblc->cj4_nalloc*sizeof(*nblc->cj4),
4483                            nblc->alloc, nblc->free);
4484     }
4485     if (nexcl > nblc->excl_nalloc)
4486     {
4487         nblc->excl_nalloc = over_alloc_small(nexcl);
4488         nbnxn_realloc_void((void **)&nblc->excl,
4489                            nblc->nexcl*sizeof(*nblc->excl),
4490                            nblc->excl_nalloc*sizeof(*nblc->excl),
4491                            nblc->alloc, nblc->free);
4492     }
4493
4494     /* Each thread should copy its own data to the combined arrays,
4495      * as otherwise data will go back and forth between different caches.
4496      */
4497 #pragma omp parallel for num_threads(gmx_omp_nthreads_get(emntPairsearch)) schedule(static)
4498     for (n = 0; n < nnbl; n++)
4499     {
4500         int                     sci_offset;
4501         int                     cj4_offset;
4502         int                     ci_offset;
4503         int                     excl_offset;
4504         int                     i, j4;
4505         const nbnxn_pairlist_t *nbli;
4506
4507         /* Determine the offset in the combined data for our thread */
4508         sci_offset  = nblc->nsci;
4509         cj4_offset  = nblc->ncj4;
4510         ci_offset   = nblc->nci_tot;
4511         excl_offset = nblc->nexcl;
4512
4513         for (i = 0; i < n; i++)
4514         {
4515             sci_offset  += nbl[i]->nsci;
4516             cj4_offset  += nbl[i]->ncj4;
4517             ci_offset   += nbl[i]->nci_tot;
4518             excl_offset += nbl[i]->nexcl;
4519         }
4520
4521         nbli = nbl[n];
4522
4523         for (i = 0; i < nbli->nsci; i++)
4524         {
4525             nblc->sci[sci_offset+i]                = nbli->sci[i];
4526             nblc->sci[sci_offset+i].cj4_ind_start += cj4_offset;
4527             nblc->sci[sci_offset+i].cj4_ind_end   += cj4_offset;
4528         }
4529
4530         for (j4 = 0; j4 < nbli->ncj4; j4++)
4531         {
4532             nblc->cj4[cj4_offset+j4]                   = nbli->cj4[j4];
4533             nblc->cj4[cj4_offset+j4].imei[0].excl_ind += excl_offset;
4534             nblc->cj4[cj4_offset+j4].imei[1].excl_ind += excl_offset;
4535         }
4536
4537         for (j4 = 0; j4 < nbli->nexcl; j4++)
4538         {
4539             nblc->excl[excl_offset+j4] = nbli->excl[j4];
4540         }
4541     }
4542
4543     for (n = 0; n < nnbl; n++)
4544     {
4545         nblc->nsci    += nbl[n]->nsci;
4546         nblc->ncj4    += nbl[n]->ncj4;
4547         nblc->nci_tot += nbl[n]->nci_tot;
4548         nblc->nexcl   += nbl[n]->nexcl;
4549     }
4550 }
4551
4552 static void balance_fep_lists(const nbnxn_search_t  nbs,
4553                               nbnxn_pairlist_set_t *nbl_lists)
4554 {
4555     int       nnbl, th;
4556     int       nri_tot, nrj_tot, nrj_target;
4557     int       th_dest;
4558     t_nblist *nbld;
4559
4560     nnbl = nbl_lists->nnbl;
4561
4562     if (nnbl == 1)
4563     {
4564         /* Nothing to balance */
4565         return;
4566     }
4567
4568     /* Count the total i-lists and pairs */
4569     nri_tot = 0;
4570     nrj_tot = 0;
4571     for (th = 0; th < nnbl; th++)
4572     {
4573         nri_tot += nbl_lists->nbl_fep[th]->nri;
4574         nrj_tot += nbl_lists->nbl_fep[th]->nrj;
4575     }
4576
4577     nrj_target = (nrj_tot + nnbl - 1)/nnbl;
4578
4579     assert(gmx_omp_nthreads_get(emntNonbonded) == nnbl);
4580
4581 #pragma omp parallel for schedule(static) num_threads(nnbl)
4582     for (th = 0; th < nnbl; th++)
4583     {
4584         t_nblist *nbl;
4585
4586         nbl = nbs->work[th].nbl_fep;
4587
4588         /* Note that here we allocate for the total size, instead of
4589          * a per-thread esimate (which is hard to obtain).
4590          */
4591         if (nri_tot > nbl->maxnri)
4592         {
4593             nbl->maxnri = over_alloc_large(nri_tot);
4594             reallocate_nblist(nbl);
4595         }
4596         if (nri_tot > nbl->maxnri || nrj_tot > nbl->maxnrj)
4597         {
4598             nbl->maxnrj = over_alloc_small(nrj_tot);
4599             srenew(nbl->jjnr, nbl->maxnrj);
4600             srenew(nbl->excl_fep, nbl->maxnrj);
4601         }
4602
4603         clear_pairlist_fep(nbl);
4604     }
4605
4606     /* Loop over the source lists and assign and copy i-entries */
4607     th_dest = 0;
4608     nbld    = nbs->work[th_dest].nbl_fep;
4609     for (th = 0; th < nnbl; th++)
4610     {
4611         t_nblist *nbls;
4612         int       i, j;
4613
4614         nbls = nbl_lists->nbl_fep[th];
4615
4616         for (i = 0; i < nbls->nri; i++)
4617         {
4618             int nrj;
4619
4620             /* The number of pairs in this i-entry */
4621             nrj = nbls->jindex[i+1] - nbls->jindex[i];
4622
4623             /* Decide if list th_dest is too large and we should procede
4624              * to the next destination list.
4625              */
4626             if (th_dest+1 < nnbl && nbld->nrj > 0 &&
4627                 nbld->nrj + nrj - nrj_target > nrj_target - nbld->nrj)
4628             {
4629                 th_dest++;
4630                 nbld = nbs->work[th_dest].nbl_fep;
4631             }
4632
4633             nbld->iinr[nbld->nri]  = nbls->iinr[i];
4634             nbld->gid[nbld->nri]   = nbls->gid[i];
4635             nbld->shift[nbld->nri] = nbls->shift[i];
4636
4637             for (j = nbls->jindex[i]; j < nbls->jindex[i+1]; j++)
4638             {
4639                 nbld->jjnr[nbld->nrj]     = nbls->jjnr[j];
4640                 nbld->excl_fep[nbld->nrj] = nbls->excl_fep[j];
4641                 nbld->nrj++;
4642             }
4643             nbld->nri++;
4644             nbld->jindex[nbld->nri] = nbld->nrj;
4645         }
4646     }
4647
4648     /* Swap the list pointers */
4649     for (th = 0; th < nnbl; th++)
4650     {
4651         t_nblist *nbl_tmp;
4652
4653         nbl_tmp                = nbl_lists->nbl_fep[th];
4654         nbl_lists->nbl_fep[th] = nbs->work[th].nbl_fep;
4655         nbs->work[th].nbl_fep  = nbl_tmp;
4656
4657         if (debug)
4658         {
4659             fprintf(debug, "nbl_fep[%d] nri %4d nrj %4d\n",
4660                     th,
4661                     nbl_lists->nbl_fep[th]->nri,
4662                     nbl_lists->nbl_fep[th]->nrj);
4663         }
4664     }
4665 }
4666
4667 /* Returns the next ci to be processes by our thread */
4668 static gmx_bool next_ci(const nbnxn_grid_t *grid,
4669                         int conv,
4670                         int nth, int ci_block,
4671                         int *ci_x, int *ci_y,
4672                         int *ci_b, int *ci)
4673 {
4674     (*ci_b)++;
4675     (*ci)++;
4676
4677     if (*ci_b == ci_block)
4678     {
4679         /* Jump to the next block assigned to this task */
4680         *ci   += (nth - 1)*ci_block;
4681         *ci_b  = 0;
4682     }
4683
4684     if (*ci >= grid->nc*conv)
4685     {
4686         return FALSE;
4687     }
4688
4689     while (*ci >= grid->cxy_ind[*ci_x*grid->ncy + *ci_y + 1]*conv)
4690     {
4691         *ci_y += 1;
4692         if (*ci_y == grid->ncy)
4693         {
4694             *ci_x += 1;
4695             *ci_y  = 0;
4696         }
4697     }
4698
4699     return TRUE;
4700 }
4701
4702 /* Returns the distance^2 for which we put cell pairs in the list
4703  * without checking atom pair distances. This is usually < rlist^2.
4704  */
4705 static float boundingbox_only_distance2(const nbnxn_grid_t *gridi,
4706                                         const nbnxn_grid_t *gridj,
4707                                         real                rlist,
4708                                         gmx_bool            simple)
4709 {
4710     /* If the distance between two sub-cell bounding boxes is less
4711      * than this distance, do not check the distance between
4712      * all particle pairs in the sub-cell, since then it is likely
4713      * that the box pair has atom pairs within the cut-off.
4714      * We use the nblist cut-off minus 0.5 times the average x/y diagonal
4715      * spacing of the sub-cells. Around 40% of the checked pairs are pruned.
4716      * Using more than 0.5 gains at most 0.5%.
4717      * If forces are calculated more than twice, the performance gain
4718      * in the force calculation outweighs the cost of checking.
4719      * Note that with subcell lists, the atom-pair distance check
4720      * is only performed when only 1 out of 8 sub-cells in within range,
4721      * this is because the GPU is much faster than the cpu.
4722      */
4723     real bbx, bby;
4724     real rbb2;
4725
4726     bbx = 0.5*(gridi->sx + gridj->sx);
4727     bby = 0.5*(gridi->sy + gridj->sy);
4728     if (!simple)
4729     {
4730         bbx /= GPU_NSUBCELL_X;
4731         bby /= GPU_NSUBCELL_Y;
4732     }
4733
4734     rbb2 = sqr(max(0, rlist - 0.5*sqrt(bbx*bbx + bby*bby)));
4735
4736 #ifndef GMX_DOUBLE
4737     return rbb2;
4738 #else
4739     return (float)((1+GMX_FLOAT_EPS)*rbb2);
4740 #endif
4741 }
4742
4743 static int get_ci_block_size(const nbnxn_grid_t *gridi,
4744                              gmx_bool bDomDec, int nth)
4745 {
4746     const int ci_block_enum      = 5;
4747     const int ci_block_denom     = 11;
4748     const int ci_block_min_atoms = 16;
4749     int       ci_block;
4750
4751     /* Here we decide how to distribute the blocks over the threads.
4752      * We use prime numbers to try to avoid that the grid size becomes
4753      * a multiple of the number of threads, which would lead to some
4754      * threads getting "inner" pairs and others getting boundary pairs,
4755      * which in turns will lead to load imbalance between threads.
4756      * Set the block size as 5/11/ntask times the average number of cells
4757      * in a y,z slab. This should ensure a quite uniform distribution
4758      * of the grid parts of the different thread along all three grid
4759      * zone boundaries with 3D domain decomposition. At the same time
4760      * the blocks will not become too small.
4761      */
4762     ci_block = (gridi->nc*ci_block_enum)/(ci_block_denom*gridi->ncx*nth);
4763
4764     /* Ensure the blocks are not too small: avoids cache invalidation */
4765     if (ci_block*gridi->na_sc < ci_block_min_atoms)
4766     {
4767         ci_block = (ci_block_min_atoms + gridi->na_sc - 1)/gridi->na_sc;
4768     }
4769
4770     /* Without domain decomposition
4771      * or with less than 3 blocks per task, divide in nth blocks.
4772      */
4773     if (!bDomDec || ci_block*3*nth > gridi->nc)
4774     {
4775         ci_block = (gridi->nc + nth - 1)/nth;
4776     }
4777
4778     return ci_block;
4779 }
4780
4781 /* Generates the part of pair-list nbl assigned to our thread */
4782 static void nbnxn_make_pairlist_part(const nbnxn_search_t nbs,
4783                                      const nbnxn_grid_t *gridi,
4784                                      const nbnxn_grid_t *gridj,
4785                                      nbnxn_search_work_t *work,
4786                                      const nbnxn_atomdata_t *nbat,
4787                                      const t_blocka *excl,
4788                                      real rlist,
4789                                      int nb_kernel_type,
4790                                      int ci_block,
4791                                      gmx_bool bFBufferFlag,
4792                                      int nsubpair_max,
4793                                      gmx_bool progBal,
4794                                      int min_ci_balanced,
4795                                      int th, int nth,
4796                                      nbnxn_pairlist_t *nbl,
4797                                      t_nblist *nbl_fep)
4798 {
4799     int               na_cj_2log;
4800     matrix            box;
4801     real              rl2, rl_fep2 = 0;
4802     float             rbb2;
4803     int               d;
4804     int               ci_b, ci, ci_x, ci_y, ci_xy, cj;
4805     ivec              shp;
4806     int               tx, ty, tz;
4807     int               shift;
4808     gmx_bool          bMakeList;
4809     real              shx, shy, shz;
4810     int               conv_i, cell0_i;
4811     const nbnxn_bb_t *bb_i = NULL;
4812 #ifdef NBNXN_BBXXXX
4813     const float      *pbb_i = NULL;
4814 #endif
4815     const float      *bbcz_i, *bbcz_j;
4816     const int        *flags_i;
4817     real              bx0, bx1, by0, by1, bz0, bz1;
4818     real              bz1_frac;
4819     real              d2cx, d2z, d2z_cx, d2z_cy, d2zx, d2zxy, d2xy;
4820     int               cxf, cxl, cyf, cyf_x, cyl;
4821     int               cx, cy;
4822     int               c0, c1, cs, cf, cl;
4823     int               ndistc;
4824     int               ncpcheck;
4825     int               gridi_flag_shift = 0, gridj_flag_shift = 0;
4826     unsigned int     *gridj_flag       = NULL;
4827     int               ncj_old_i, ncj_old_j;
4828
4829     nbs_cycle_start(&work->cc[enbsCCsearch]);
4830
4831     if (gridj->bSimple != nbl->bSimple)
4832     {
4833         gmx_incons("Grid incompatible with pair-list");
4834     }
4835
4836     sync_work(nbl);
4837     nbl->na_sc = gridj->na_sc;
4838     nbl->na_ci = gridj->na_c;
4839     nbl->na_cj = nbnxn_kernel_to_cj_size(nb_kernel_type);
4840     na_cj_2log = get_2log(nbl->na_cj);
4841
4842     nbl->rlist  = rlist;
4843
4844     if (bFBufferFlag)
4845     {
4846         /* Determine conversion of clusters to flag blocks */
4847         gridi_flag_shift = 0;
4848         while ((nbl->na_ci<<gridi_flag_shift) < NBNXN_BUFFERFLAG_SIZE)
4849         {
4850             gridi_flag_shift++;
4851         }
4852         gridj_flag_shift = 0;
4853         while ((nbl->na_cj<<gridj_flag_shift) < NBNXN_BUFFERFLAG_SIZE)
4854         {
4855             gridj_flag_shift++;
4856         }
4857
4858         gridj_flag = work->buffer_flags.flag;
4859     }
4860
4861     copy_mat(nbs->box, box);
4862
4863     rl2 = nbl->rlist*nbl->rlist;
4864
4865     if (nbs->bFEP && !nbl->bSimple)
4866     {
4867         /* Determine an atom-pair list cut-off distance for FEP atom pairs.
4868          * We should not simply use rlist, since then we would not have
4869          * the small, effective buffering of the NxN lists.
4870          * The buffer is on overestimate, but the resulting cost for pairs
4871          * beyond rlist is neglible compared to the FEP pairs within rlist.
4872          */
4873         rl_fep2 = nbl->rlist + effective_buffer_1x1_vs_MxN(gridi, gridj);
4874
4875         if (debug)
4876         {
4877             fprintf(debug, "nbl_fep atom-pair rlist %f\n", rl_fep2);
4878         }
4879         rl_fep2 = rl_fep2*rl_fep2;
4880     }
4881
4882     rbb2 = boundingbox_only_distance2(gridi, gridj, nbl->rlist, nbl->bSimple);
4883
4884     if (debug)
4885     {
4886         fprintf(debug, "nbl bounding box only distance %f\n", sqrt(rbb2));
4887     }
4888
4889     /* Set the shift range */
4890     for (d = 0; d < DIM; d++)
4891     {
4892         /* Check if we need periodicity shifts.
4893          * Without PBC or with domain decomposition we don't need them.
4894          */
4895         if (d >= ePBC2npbcdim(nbs->ePBC) || nbs->dd_dim[d])
4896         {
4897             shp[d] = 0;
4898         }
4899         else
4900         {
4901             if (d == XX &&
4902                 box[XX][XX] - fabs(box[YY][XX]) - fabs(box[ZZ][XX]) < sqrt(rl2))
4903             {
4904                 shp[d] = 2;
4905             }
4906             else
4907             {
4908                 shp[d] = 1;
4909             }
4910         }
4911     }
4912
4913     if (nbl->bSimple && !gridi->bSimple)
4914     {
4915         conv_i  = gridi->na_sc/gridj->na_sc;
4916         bb_i    = gridi->bb_simple;
4917         bbcz_i  = gridi->bbcz_simple;
4918         flags_i = gridi->flags_simple;
4919     }
4920     else
4921     {
4922         conv_i  = 1;
4923 #ifdef NBNXN_BBXXXX
4924         if (gridi->bSimple)
4925         {
4926             bb_i  = gridi->bb;
4927         }
4928         else
4929         {
4930             pbb_i = gridi->pbb;
4931         }
4932 #else
4933         /* We use the normal bounding box format for both grid types */
4934         bb_i  = gridi->bb;
4935 #endif
4936         bbcz_i  = gridi->bbcz;
4937         flags_i = gridi->flags;
4938     }
4939     cell0_i = gridi->cell0*conv_i;
4940
4941     bbcz_j = gridj->bbcz;
4942
4943     if (conv_i != 1)
4944     {
4945         /* Blocks of the conversion factor - 1 give a large repeat count
4946          * combined with a small block size. This should result in good
4947          * load balancing for both small and large domains.
4948          */
4949         ci_block = conv_i - 1;
4950     }
4951     if (debug)
4952     {
4953         fprintf(debug, "nbl nc_i %d col.av. %.1f ci_block %d\n",
4954                 gridi->nc, gridi->nc/(double)(gridi->ncx*gridi->ncy), ci_block);
4955     }
4956
4957     ndistc   = 0;
4958     ncpcheck = 0;
4959
4960     /* Initially ci_b and ci to 1 before where we want them to start,
4961      * as they will both be incremented in next_ci.
4962      */
4963     ci_b = -1;
4964     ci   = th*ci_block - 1;
4965     ci_x = 0;
4966     ci_y = 0;
4967     while (next_ci(gridi, conv_i, nth, ci_block, &ci_x, &ci_y, &ci_b, &ci))
4968     {
4969         if (nbl->bSimple && flags_i[ci] == 0)
4970         {
4971             continue;
4972         }
4973
4974         ncj_old_i = nbl->ncj;
4975
4976         d2cx = 0;
4977         if (gridj != gridi && shp[XX] == 0)
4978         {
4979             if (nbl->bSimple)
4980             {
4981                 bx1 = bb_i[ci].upper[BB_X];
4982             }
4983             else
4984             {
4985                 bx1 = gridi->c0[XX] + (ci_x+1)*gridi->sx;
4986             }
4987             if (bx1 < gridj->c0[XX])
4988             {
4989                 d2cx = sqr(gridj->c0[XX] - bx1);
4990
4991                 if (d2cx >= rl2)
4992                 {
4993                     continue;
4994                 }
4995             }
4996         }
4997
4998         ci_xy = ci_x*gridi->ncy + ci_y;
4999
5000         /* Loop over shift vectors in three dimensions */
5001         for (tz = -shp[ZZ]; tz <= shp[ZZ]; tz++)
5002         {
5003             shz = tz*box[ZZ][ZZ];
5004
5005             bz0 = bbcz_i[ci*NNBSBB_D  ] + shz;
5006             bz1 = bbcz_i[ci*NNBSBB_D+1] + shz;
5007
5008             if (tz == 0)
5009             {
5010                 d2z = 0;
5011             }
5012             else if (tz < 0)
5013             {
5014                 d2z = sqr(bz1);
5015             }
5016             else
5017             {
5018                 d2z = sqr(bz0 - box[ZZ][ZZ]);
5019             }
5020
5021             d2z_cx = d2z + d2cx;
5022
5023             if (d2z_cx >= rl2)
5024             {
5025                 continue;
5026             }
5027
5028             bz1_frac =
5029                 bz1/((real)(gridi->cxy_ind[ci_xy+1] - gridi->cxy_ind[ci_xy]));
5030             if (bz1_frac < 0)
5031             {
5032                 bz1_frac = 0;
5033             }
5034             /* The check with bz1_frac close to or larger than 1 comes later */
5035
5036             for (ty = -shp[YY]; ty <= shp[YY]; ty++)
5037             {
5038                 shy = ty*box[YY][YY] + tz*box[ZZ][YY];
5039
5040                 if (nbl->bSimple)
5041                 {
5042                     by0 = bb_i[ci].lower[BB_Y] + shy;
5043                     by1 = bb_i[ci].upper[BB_Y] + shy;
5044                 }
5045                 else
5046                 {
5047                     by0 = gridi->c0[YY] + (ci_y  )*gridi->sy + shy;
5048                     by1 = gridi->c0[YY] + (ci_y+1)*gridi->sy + shy;
5049                 }
5050
5051                 get_cell_range(by0, by1,
5052                                gridj->ncy, gridj->c0[YY], gridj->sy, gridj->inv_sy,
5053                                d2z_cx, rl2,
5054                                &cyf, &cyl);
5055
5056                 if (cyf > cyl)
5057                 {
5058                     continue;
5059                 }
5060
5061                 d2z_cy = d2z;
5062                 if (by1 < gridj->c0[YY])
5063                 {
5064                     d2z_cy += sqr(gridj->c0[YY] - by1);
5065                 }
5066                 else if (by0 > gridj->c1[YY])
5067                 {
5068                     d2z_cy += sqr(by0 - gridj->c1[YY]);
5069                 }
5070
5071                 for (tx = -shp[XX]; tx <= shp[XX]; tx++)
5072                 {
5073                     shift = XYZ2IS(tx, ty, tz);
5074
5075 #ifdef NBNXN_SHIFT_BACKWARD
5076                     if (gridi == gridj && shift > CENTRAL)
5077                     {
5078                         continue;
5079                     }
5080 #endif
5081
5082                     shx = tx*box[XX][XX] + ty*box[YY][XX] + tz*box[ZZ][XX];
5083
5084                     if (nbl->bSimple)
5085                     {
5086                         bx0 = bb_i[ci].lower[BB_X] + shx;
5087                         bx1 = bb_i[ci].upper[BB_X] + shx;
5088                     }
5089                     else
5090                     {
5091                         bx0 = gridi->c0[XX] + (ci_x  )*gridi->sx + shx;
5092                         bx1 = gridi->c0[XX] + (ci_x+1)*gridi->sx + shx;
5093                     }
5094
5095                     get_cell_range(bx0, bx1,
5096                                    gridj->ncx, gridj->c0[XX], gridj->sx, gridj->inv_sx,
5097                                    d2z_cy, rl2,
5098                                    &cxf, &cxl);
5099
5100                     if (cxf > cxl)
5101                     {
5102                         continue;
5103                     }
5104
5105                     if (nbl->bSimple)
5106                     {
5107                         new_ci_entry(nbl, cell0_i+ci, shift, flags_i[ci]);
5108                     }
5109                     else
5110                     {
5111                         new_sci_entry(nbl, cell0_i+ci, shift);
5112                     }
5113
5114 #ifndef NBNXN_SHIFT_BACKWARD
5115                     if (cxf < ci_x)
5116 #else
5117                     if (shift == CENTRAL && gridi == gridj &&
5118                         cxf < ci_x)
5119 #endif
5120                     {
5121                         /* Leave the pairs with i > j.
5122                          * x is the major index, so skip half of it.
5123                          */
5124                         cxf = ci_x;
5125                     }
5126
5127                     if (nbl->bSimple)
5128                     {
5129                         set_icell_bb_simple(bb_i, ci, shx, shy, shz,
5130                                             nbl->work->bb_ci);
5131                     }
5132                     else
5133                     {
5134 #ifdef NBNXN_BBXXXX
5135                         set_icell_bbxxxx_supersub(pbb_i, ci, shx, shy, shz,
5136                                                   nbl->work->pbb_ci);
5137 #else
5138                         set_icell_bb_supersub(bb_i, ci, shx, shy, shz,
5139                                               nbl->work->bb_ci);
5140 #endif
5141                     }
5142
5143                     nbs->icell_set_x(cell0_i+ci, shx, shy, shz,
5144                                      gridi->na_c, nbat->xstride, nbat->x,
5145                                      nbl->work);
5146
5147                     for (cx = cxf; cx <= cxl; cx++)
5148                     {
5149                         d2zx = d2z;
5150                         if (gridj->c0[XX] + cx*gridj->sx > bx1)
5151                         {
5152                             d2zx += sqr(gridj->c0[XX] + cx*gridj->sx - bx1);
5153                         }
5154                         else if (gridj->c0[XX] + (cx+1)*gridj->sx < bx0)
5155                         {
5156                             d2zx += sqr(gridj->c0[XX] + (cx+1)*gridj->sx - bx0);
5157                         }
5158
5159 #ifndef NBNXN_SHIFT_BACKWARD
5160                         if (gridi == gridj &&
5161                             cx == 0 && cyf < ci_y)
5162 #else
5163                         if (gridi == gridj &&
5164                             cx == 0 && shift == CENTRAL && cyf < ci_y)
5165 #endif
5166                         {
5167                             /* Leave the pairs with i > j.
5168                              * Skip half of y when i and j have the same x.
5169                              */
5170                             cyf_x = ci_y;
5171                         }
5172                         else
5173                         {
5174                             cyf_x = cyf;
5175                         }
5176
5177                         for (cy = cyf_x; cy <= cyl; cy++)
5178                         {
5179                             c0 = gridj->cxy_ind[cx*gridj->ncy+cy];
5180                             c1 = gridj->cxy_ind[cx*gridj->ncy+cy+1];
5181 #ifdef NBNXN_SHIFT_BACKWARD
5182                             if (gridi == gridj &&
5183                                 shift == CENTRAL && c0 < ci)
5184                             {
5185                                 c0 = ci;
5186                             }
5187 #endif
5188
5189                             d2zxy = d2zx;
5190                             if (gridj->c0[YY] + cy*gridj->sy > by1)
5191                             {
5192                                 d2zxy += sqr(gridj->c0[YY] + cy*gridj->sy - by1);
5193                             }
5194                             else if (gridj->c0[YY] + (cy+1)*gridj->sy < by0)
5195                             {
5196                                 d2zxy += sqr(gridj->c0[YY] + (cy+1)*gridj->sy - by0);
5197                             }
5198                             if (c1 > c0 && d2zxy < rl2)
5199                             {
5200                                 cs = c0 + (int)(bz1_frac*(c1 - c0));
5201                                 if (cs >= c1)
5202                                 {
5203                                     cs = c1 - 1;
5204                                 }
5205
5206                                 d2xy = d2zxy - d2z;
5207
5208                                 /* Find the lowest cell that can possibly
5209                                  * be within range.
5210                                  */
5211                                 cf = cs;
5212                                 while (cf > c0 &&
5213                                        (bbcz_j[cf*NNBSBB_D+1] >= bz0 ||
5214                                         d2xy + sqr(bbcz_j[cf*NNBSBB_D+1] - bz0) < rl2))
5215                                 {
5216                                     cf--;
5217                                 }
5218
5219                                 /* Find the highest cell that can possibly
5220                                  * be within range.
5221                                  */
5222                                 cl = cs;
5223                                 while (cl < c1-1 &&
5224                                        (bbcz_j[cl*NNBSBB_D] <= bz1 ||
5225                                         d2xy + sqr(bbcz_j[cl*NNBSBB_D] - bz1) < rl2))
5226                                 {
5227                                     cl++;
5228                                 }
5229
5230 #ifdef NBNXN_REFCODE
5231                                 {
5232                                     /* Simple reference code, for debugging,
5233                                      * overrides the more complex code above.
5234                                      */
5235                                     int k;
5236                                     cf = c1;
5237                                     cl = -1;
5238                                     for (k = c0; k < c1; k++)
5239                                     {
5240                                         if (box_dist2(bx0, bx1, by0, by1, bz0, bz1, bb+k) < rl2 &&
5241                                             k < cf)
5242                                         {
5243                                             cf = k;
5244                                         }
5245                                         if (box_dist2(bx0, bx1, by0, by1, bz0, bz1, bb+k) < rl2 &&
5246                                             k > cl)
5247                                         {
5248                                             cl = k;
5249                                         }
5250                                     }
5251                                 }
5252 #endif
5253
5254                                 if (gridi == gridj)
5255                                 {
5256                                     /* We want each atom/cell pair only once,
5257                                      * only use cj >= ci.
5258                                      */
5259 #ifndef NBNXN_SHIFT_BACKWARD
5260                                     cf = max(cf, ci);
5261 #else
5262                                     if (shift == CENTRAL)
5263                                     {
5264                                         cf = max(cf, ci);
5265                                     }
5266 #endif
5267                                 }
5268
5269                                 if (cf <= cl)
5270                                 {
5271                                     /* For f buffer flags with simple lists */
5272                                     ncj_old_j = nbl->ncj;
5273
5274                                     switch (nb_kernel_type)
5275                                     {
5276                                         case nbnxnk4x4_PlainC:
5277                                             check_subcell_list_space_simple(nbl, cl-cf+1);
5278
5279                                             make_cluster_list_simple(gridj,
5280                                                                      nbl, ci, cf, cl,
5281                                                                      (gridi == gridj && shift == CENTRAL),
5282                                                                      nbat->x,
5283                                                                      rl2, rbb2,
5284                                                                      &ndistc);
5285                                             break;
5286 #ifdef GMX_NBNXN_SIMD_4XN
5287                                         case nbnxnk4xN_SIMD_4xN:
5288                                             check_subcell_list_space_simple(nbl, ci_to_cj(na_cj_2log, cl-cf)+2);
5289                                             make_cluster_list_simd_4xn(gridj,
5290                                                                        nbl, ci, cf, cl,
5291                                                                        (gridi == gridj && shift == CENTRAL),
5292                                                                        nbat->x,
5293                                                                        rl2, rbb2,
5294                                                                        &ndistc);
5295                                             break;
5296 #endif
5297 #ifdef GMX_NBNXN_SIMD_2XNN
5298                                         case nbnxnk4xN_SIMD_2xNN:
5299                                             check_subcell_list_space_simple(nbl, ci_to_cj(na_cj_2log, cl-cf)+2);
5300                                             make_cluster_list_simd_2xnn(gridj,
5301                                                                         nbl, ci, cf, cl,
5302                                                                         (gridi == gridj && shift == CENTRAL),
5303                                                                         nbat->x,
5304                                                                         rl2, rbb2,
5305                                                                         &ndistc);
5306                                             break;
5307 #endif
5308                                         case nbnxnk8x8x8_PlainC:
5309                                         case nbnxnk8x8x8_CUDA:
5310                                             check_subcell_list_space_supersub(nbl, cl-cf+1);
5311                                             for (cj = cf; cj <= cl; cj++)
5312                                             {
5313                                                 make_cluster_list_supersub(gridi, gridj,
5314                                                                            nbl, ci, cj,
5315                                                                            (gridi == gridj && shift == CENTRAL && ci == cj),
5316                                                                            nbat->xstride, nbat->x,
5317                                                                            rl2, rbb2,
5318                                                                            &ndistc);
5319                                             }
5320                                             break;
5321                                     }
5322                                     ncpcheck += cl - cf + 1;
5323
5324                                     if (bFBufferFlag && nbl->ncj > ncj_old_j)
5325                                     {
5326                                         int cbf, cbl, cb;
5327
5328                                         cbf = nbl->cj[ncj_old_j].cj >> gridj_flag_shift;
5329                                         cbl = nbl->cj[nbl->ncj-1].cj >> gridj_flag_shift;
5330                                         for (cb = cbf; cb <= cbl; cb++)
5331                                         {
5332                                             gridj_flag[cb] = 1U<<th;
5333                                         }
5334                                     }
5335                                 }
5336                             }
5337                         }
5338                     }
5339
5340                     /* Set the exclusions for this ci list */
5341                     if (nbl->bSimple)
5342                     {
5343                         set_ci_top_excls(nbs,
5344                                          nbl,
5345                                          shift == CENTRAL && gridi == gridj,
5346                                          gridj->na_c_2log,
5347                                          na_cj_2log,
5348                                          &(nbl->ci[nbl->nci]),
5349                                          excl);
5350
5351                         if (nbs->bFEP)
5352                         {
5353                             make_fep_list(nbs, nbat, nbl,
5354                                           shift == CENTRAL && gridi == gridj,
5355                                           &(nbl->ci[nbl->nci]),
5356                                           gridi, gridj, nbl_fep);
5357                         }
5358                     }
5359                     else
5360                     {
5361                         set_sci_top_excls(nbs,
5362                                           nbl,
5363                                           shift == CENTRAL && gridi == gridj,
5364                                           gridj->na_c_2log,
5365                                           &(nbl->sci[nbl->nsci]),
5366                                           excl);
5367
5368                         if (nbs->bFEP)
5369                         {
5370                             make_fep_list_supersub(nbs, nbat, nbl,
5371                                                    shift == CENTRAL && gridi == gridj,
5372                                                    &(nbl->sci[nbl->nsci]),
5373                                                    shx, shy, shz,
5374                                                    rl_fep2,
5375                                                    gridi, gridj, nbl_fep);
5376                         }
5377                     }
5378
5379                     /* Close this ci list */
5380                     if (nbl->bSimple)
5381                     {
5382                         close_ci_entry_simple(nbl);
5383                     }
5384                     else
5385                     {
5386                         close_ci_entry_supersub(nbl,
5387                                                 nsubpair_max,
5388                                                 progBal, min_ci_balanced,
5389                                                 th, nth);
5390                     }
5391                 }
5392             }
5393         }
5394
5395         if (bFBufferFlag && nbl->ncj > ncj_old_i)
5396         {
5397             work->buffer_flags.flag[(gridi->cell0+ci)>>gridi_flag_shift] = 1U<<th;
5398         }
5399     }
5400
5401     work->ndistc = ndistc;
5402
5403     nbs_cycle_stop(&work->cc[enbsCCsearch]);
5404
5405     if (debug)
5406     {
5407         fprintf(debug, "number of distance checks %d\n", ndistc);
5408         fprintf(debug, "ncpcheck %s %d\n", gridi == gridj ? "local" : "non-local",
5409                 ncpcheck);
5410
5411         if (nbl->bSimple)
5412         {
5413             print_nblist_statistics_simple(debug, nbl, nbs, rlist);
5414         }
5415         else
5416         {
5417             print_nblist_statistics_supersub(debug, nbl, nbs, rlist);
5418         }
5419
5420         if (nbs->bFEP)
5421         {
5422             fprintf(debug, "nbl FEP list pairs: %d\n", nbl_fep->nrj);
5423         }
5424     }
5425 }
5426
5427 static void reduce_buffer_flags(const nbnxn_search_t        nbs,
5428                                 int                         nsrc,
5429                                 const nbnxn_buffer_flags_t *dest)
5430 {
5431     int                 s, b;
5432     const unsigned int *flag;
5433
5434     for (s = 0; s < nsrc; s++)
5435     {
5436         flag = nbs->work[s].buffer_flags.flag;
5437
5438         for (b = 0; b < dest->nflag; b++)
5439         {
5440             dest->flag[b] |= flag[b];
5441         }
5442     }
5443 }
5444
5445 static void print_reduction_cost(const nbnxn_buffer_flags_t *flags, int nout)
5446 {
5447     int nelem, nkeep, ncopy, nred, b, c, out;
5448
5449     nelem = 0;
5450     nkeep = 0;
5451     ncopy = 0;
5452     nred  = 0;
5453     for (b = 0; b < flags->nflag; b++)
5454     {
5455         if (flags->flag[b] == 1)
5456         {
5457             /* Only flag 0 is set, no copy of reduction required */
5458             nelem++;
5459             nkeep++;
5460         }
5461         else if (flags->flag[b] > 0)
5462         {
5463             c = 0;
5464             for (out = 0; out < nout; out++)
5465             {
5466                 if (flags->flag[b] & (1U<<out))
5467                 {
5468                     c++;
5469                 }
5470             }
5471             nelem += c;
5472             if (c == 1)
5473             {
5474                 ncopy++;
5475             }
5476             else
5477             {
5478                 nred += c;
5479             }
5480         }
5481     }
5482
5483     fprintf(debug, "nbnxn reduction: #flag %d #list %d elem %4.2f, keep %4.2f copy %4.2f red %4.2f\n",
5484             flags->nflag, nout,
5485             nelem/(double)(flags->nflag),
5486             nkeep/(double)(flags->nflag),
5487             ncopy/(double)(flags->nflag),
5488             nred/(double)(flags->nflag));
5489 }
5490
5491 /* Perform a count (linear) sort to sort the smaller lists to the end.
5492  * This avoids load imbalance on the GPU, as large lists will be
5493  * scheduled and executed first and the smaller lists later.
5494  * Load balancing between multi-processors only happens at the end
5495  * and there smaller lists lead to more effective load balancing.
5496  * The sorting is done on the cj4 count, not on the actual pair counts.
5497  * Not only does this make the sort faster, but it also results in
5498  * better load balancing than using a list sorted on exact load.
5499  * This function swaps the pointer in the pair list to avoid a copy operation.
5500  */
5501 static void sort_sci(nbnxn_pairlist_t *nbl)
5502 {
5503     nbnxn_list_work_t *work;
5504     int                m, i, s, s0, s1;
5505     nbnxn_sci_t       *sci_sort;
5506
5507     if (nbl->ncj4 <= nbl->nsci)
5508     {
5509         /* nsci = 0 or all sci have size 1, sorting won't change the order */
5510         return;
5511     }
5512
5513     work = nbl->work;
5514
5515     /* We will distinguish differences up to double the average */
5516     m = (2*nbl->ncj4)/nbl->nsci;
5517
5518     if (m + 1 > work->sort_nalloc)
5519     {
5520         work->sort_nalloc = over_alloc_large(m + 1);
5521         srenew(work->sort, work->sort_nalloc);
5522     }
5523
5524     if (work->sci_sort_nalloc != nbl->sci_nalloc)
5525     {
5526         work->sci_sort_nalloc = nbl->sci_nalloc;
5527         nbnxn_realloc_void((void **)&work->sci_sort,
5528                            0,
5529                            work->sci_sort_nalloc*sizeof(*work->sci_sort),
5530                            nbl->alloc, nbl->free);
5531     }
5532
5533     /* Count the entries of each size */
5534     for (i = 0; i <= m; i++)
5535     {
5536         work->sort[i] = 0;
5537     }
5538     for (s = 0; s < nbl->nsci; s++)
5539     {
5540         i = min(m, nbl->sci[s].cj4_ind_end - nbl->sci[s].cj4_ind_start);
5541         work->sort[i]++;
5542     }
5543     /* Calculate the offset for each count */
5544     s0            = work->sort[m];
5545     work->sort[m] = 0;
5546     for (i = m - 1; i >= 0; i--)
5547     {
5548         s1            = work->sort[i];
5549         work->sort[i] = work->sort[i + 1] + s0;
5550         s0            = s1;
5551     }
5552
5553     /* Sort entries directly into place */
5554     sci_sort = work->sci_sort;
5555     for (s = 0; s < nbl->nsci; s++)
5556     {
5557         i = min(m, nbl->sci[s].cj4_ind_end - nbl->sci[s].cj4_ind_start);
5558         sci_sort[work->sort[i]++] = nbl->sci[s];
5559     }
5560
5561     /* Swap the sci pointers so we use the new, sorted list */
5562     work->sci_sort = nbl->sci;
5563     nbl->sci       = sci_sort;
5564 }
5565
5566 /* Make a local or non-local pair-list, depending on iloc */
5567 void nbnxn_make_pairlist(const nbnxn_search_t  nbs,
5568                          nbnxn_atomdata_t     *nbat,
5569                          const t_blocka       *excl,
5570                          real                  rlist,
5571                          int                   min_ci_balanced,
5572                          nbnxn_pairlist_set_t *nbl_list,
5573                          int                   iloc,
5574                          int                   nb_kernel_type,
5575                          t_nrnb               *nrnb)
5576 {
5577     nbnxn_grid_t      *gridi, *gridj;
5578     gmx_bool           bGPUCPU;
5579     int                nzi, zi, zj0, zj1, zj;
5580     int                nsubpair_max;
5581     int                th;
5582     int                nnbl;
5583     nbnxn_pairlist_t **nbl;
5584     int                ci_block;
5585     gmx_bool           CombineNBLists;
5586     gmx_bool           progBal;
5587     int                np_tot, np_noq, np_hlj, nap;
5588
5589     /* Check if we are running hybrid GPU + CPU nbnxn mode */
5590     bGPUCPU = (!nbs->grid[0].bSimple && nbl_list->bSimple);
5591
5592     nnbl            = nbl_list->nnbl;
5593     nbl             = nbl_list->nbl;
5594     CombineNBLists  = nbl_list->bCombined;
5595
5596     if (debug)
5597     {
5598         fprintf(debug, "ns making %d nblists\n", nnbl);
5599     }
5600
5601     nbat->bUseBufferFlags = (nbat->nout > 1);
5602     /* We should re-init the flags before making the first list */
5603     if (nbat->bUseBufferFlags && (LOCAL_I(iloc) || bGPUCPU))
5604     {
5605         init_buffer_flags(&nbat->buffer_flags, nbat->natoms);
5606     }
5607
5608     if (nbl_list->bSimple)
5609     {
5610         switch (nb_kernel_type)
5611         {
5612 #ifdef GMX_NBNXN_SIMD_4XN
5613             case nbnxnk4xN_SIMD_4xN:
5614                 nbs->icell_set_x = icell_set_x_simd_4xn;
5615                 break;
5616 #endif
5617 #ifdef GMX_NBNXN_SIMD_2XNN
5618             case nbnxnk4xN_SIMD_2xNN:
5619                 nbs->icell_set_x = icell_set_x_simd_2xnn;
5620                 break;
5621 #endif
5622             default:
5623                 nbs->icell_set_x = icell_set_x_simple;
5624                 break;
5625         }
5626     }
5627     else
5628     {
5629 #ifdef NBNXN_SEARCH_BB_SIMD4
5630         nbs->icell_set_x = icell_set_x_supersub_simd4;
5631 #else
5632         nbs->icell_set_x = icell_set_x_supersub;
5633 #endif
5634     }
5635
5636     if (LOCAL_I(iloc))
5637     {
5638         /* Only zone (grid) 0 vs 0 */
5639         nzi = 1;
5640         zj0 = 0;
5641         zj1 = 1;
5642     }
5643     else
5644     {
5645         nzi = nbs->zones->nizone;
5646     }
5647
5648     if (!nbl_list->bSimple && min_ci_balanced > 0)
5649     {
5650         nsubpair_max = get_nsubpair_max(nbs, iloc, rlist, min_ci_balanced);
5651     }
5652     else
5653     {
5654         nsubpair_max = 0;
5655     }
5656
5657     /* Clear all pair-lists */
5658     for (th = 0; th < nnbl; th++)
5659     {
5660         clear_pairlist(nbl[th]);
5661
5662         if (nbs->bFEP)
5663         {
5664             clear_pairlist_fep(nbl_list->nbl_fep[th]);
5665         }
5666     }
5667
5668     for (zi = 0; zi < nzi; zi++)
5669     {
5670         gridi = &nbs->grid[zi];
5671
5672         if (NONLOCAL_I(iloc))
5673         {
5674             zj0 = nbs->zones->izone[zi].j0;
5675             zj1 = nbs->zones->izone[zi].j1;
5676             if (zi == 0)
5677             {
5678                 zj0++;
5679             }
5680         }
5681         for (zj = zj0; zj < zj1; zj++)
5682         {
5683             gridj = &nbs->grid[zj];
5684
5685             if (debug)
5686             {
5687                 fprintf(debug, "ns search grid %d vs %d\n", zi, zj);
5688             }
5689
5690             nbs_cycle_start(&nbs->cc[enbsCCsearch]);
5691
5692             if (nbl[0]->bSimple && !gridi->bSimple)
5693             {
5694                 /* Hybrid list, determine blocking later */
5695                 ci_block = 0;
5696             }
5697             else
5698             {
5699                 ci_block = get_ci_block_size(gridi, nbs->DomDec, nnbl);
5700             }
5701
5702             /* With GPU: generate progressively smaller lists for
5703              * load balancing for local only or non-local with 2 zones.
5704              */
5705             progBal = (LOCAL_I(iloc) || nbs->zones->n <= 2);
5706
5707 #pragma omp parallel for num_threads(nnbl) schedule(static)
5708             for (th = 0; th < nnbl; th++)
5709             {
5710                 /* Re-init the thread-local work flag data before making
5711                  * the first list (not an elegant conditional).
5712                  */
5713                 if (nbat->bUseBufferFlags && ((zi == 0 && zj == 0) ||
5714                                               (bGPUCPU && zi == 0 && zj == 1)))
5715                 {
5716                     init_buffer_flags(&nbs->work[th].buffer_flags, nbat->natoms);
5717                 }
5718
5719                 if (CombineNBLists && th > 0)
5720                 {
5721                     clear_pairlist(nbl[th]);
5722                 }
5723
5724                 /* Divide the i super cell equally over the nblists */
5725                 nbnxn_make_pairlist_part(nbs, gridi, gridj,
5726                                          &nbs->work[th], nbat, excl,
5727                                          rlist,
5728                                          nb_kernel_type,
5729                                          ci_block,
5730                                          nbat->bUseBufferFlags,
5731                                          nsubpair_max,
5732                                          progBal, min_ci_balanced,
5733                                          th, nnbl,
5734                                          nbl[th],
5735                                          nbl_list->nbl_fep[th]);
5736             }
5737             nbs_cycle_stop(&nbs->cc[enbsCCsearch]);
5738
5739             np_tot = 0;
5740             np_noq = 0;
5741             np_hlj = 0;
5742             for (th = 0; th < nnbl; th++)
5743             {
5744                 inc_nrnb(nrnb, eNR_NBNXN_DIST2, nbs->work[th].ndistc);
5745
5746                 if (nbl_list->bSimple)
5747                 {
5748                     np_tot += nbl[th]->ncj;
5749                     np_noq += nbl[th]->work->ncj_noq;
5750                     np_hlj += nbl[th]->work->ncj_hlj;
5751                 }
5752                 else
5753                 {
5754                     /* This count ignores potential subsequent pair pruning */
5755                     np_tot += nbl[th]->nci_tot;
5756                 }
5757             }
5758             nap                   = nbl[0]->na_ci*nbl[0]->na_cj;
5759             nbl_list->natpair_ljq = (np_tot - np_noq)*nap - np_hlj*nap/2;
5760             nbl_list->natpair_lj  = np_noq*nap;
5761             nbl_list->natpair_q   = np_hlj*nap/2;
5762
5763             if (CombineNBLists && nnbl > 1)
5764             {
5765                 nbs_cycle_start(&nbs->cc[enbsCCcombine]);
5766
5767                 combine_nblists(nnbl-1, nbl+1, nbl[0]);
5768
5769                 nbs_cycle_stop(&nbs->cc[enbsCCcombine]);
5770             }
5771         }
5772     }
5773
5774     if (!nbl_list->bSimple)
5775     {
5776         /* Sort the entries on size, large ones first */
5777         if (CombineNBLists || nnbl == 1)
5778         {
5779             sort_sci(nbl[0]);
5780         }
5781         else
5782         {
5783 #pragma omp parallel for num_threads(nnbl) schedule(static)
5784             for (th = 0; th < nnbl; th++)
5785             {
5786                 sort_sci(nbl[th]);
5787             }
5788         }
5789     }
5790
5791     if (nbat->bUseBufferFlags)
5792     {
5793         reduce_buffer_flags(nbs, nnbl, &nbat->buffer_flags);
5794     }
5795
5796     if (nbs->bFEP)
5797     {
5798         /* Balance the free-energy lists over all the threads */
5799         balance_fep_lists(nbs, nbl_list);
5800     }
5801
5802     /* Special performance logging stuff (env.var. GMX_NBNXN_CYCLE) */
5803     if (LOCAL_I(iloc))
5804     {
5805         nbs->search_count++;
5806     }
5807     if (nbs->print_cycles &&
5808         (!nbs->DomDec || (nbs->DomDec && !LOCAL_I(iloc))) &&
5809         nbs->search_count % 100 == 0)
5810     {
5811         nbs_cycle_print(stderr, nbs);
5812     }
5813
5814     if (debug && (CombineNBLists && nnbl > 1))
5815     {
5816         if (nbl[0]->bSimple)
5817         {
5818             print_nblist_statistics_simple(debug, nbl[0], nbs, rlist);
5819         }
5820         else
5821         {
5822             print_nblist_statistics_supersub(debug, nbl[0], nbs, rlist);
5823         }
5824     }
5825
5826     if (debug)
5827     {
5828         if (gmx_debug_at)
5829         {
5830             if (nbl[0]->bSimple)
5831             {
5832                 print_nblist_ci_cj(debug, nbl[0]);
5833             }
5834             else
5835             {
5836                 print_nblist_sci_cj(debug, nbl[0]);
5837             }
5838         }
5839
5840         if (nbat->bUseBufferFlags)
5841         {
5842             print_reduction_cost(&nbat->buffer_flags, nnbl);
5843         }
5844     }
5845 }