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