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