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