Fix qsort not being defined on Apple Clang
[alexxy/gromacs.git] / src / gromacs / mdlib / nbnxn_search.cpp
1 /*
2  * This file is part of the GROMACS molecular simulation package.
3  *
4  * Copyright (c) 2012,2013,2014,2015,2016,2017,2018, by the GROMACS development team, led by
5  * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
6  * and including many others, as listed in the AUTHORS file in the
7  * top-level source directory and at http://www.gromacs.org.
8  *
9  * GROMACS is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public License
11  * as published by the Free Software Foundation; either version 2.1
12  * of the License, or (at your option) any later version.
13  *
14  * GROMACS is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public
20  * License along with GROMACS; if not, see
21  * http://www.gnu.org/licenses, or write to the Free Software Foundation,
22  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA.
23  *
24  * If you want to redistribute modifications to GROMACS, please
25  * consider that scientific software is very special. Version
26  * control is crucial - bugs must be traceable. We will be happy to
27  * consider code for inclusion in the official distribution, but
28  * derived work must not be called official GROMACS. Details are found
29  * in the README & COPYING files - if they are missing, get the
30  * official version at http://www.gromacs.org.
31  *
32  * To help us fund GROMACS development, we humbly ask that you cite
33  * the research papers on the package. Check out http://www.gromacs.org.
34  */
35
36 #include "gmxpre.h"
37
38 #include "nbnxn_search.h"
39
40 #include "config.h"
41
42 #include <cassert>
43 #include <cmath>
44 #include <cstring>
45
46 #include <algorithm>
47
48 #include "gromacs/domdec/domdec_struct.h"
49 #include "gromacs/gmxlib/nrnb.h"
50 #include "gromacs/math/functions.h"
51 #include "gromacs/math/utilities.h"
52 #include "gromacs/math/vec.h"
53 #include "gromacs/mdlib/gmx_omp_nthreads.h"
54 #include "gromacs/mdlib/nb_verlet.h"
55 #include "gromacs/mdlib/nbnxn_atomdata.h"
56 #include "gromacs/mdlib/nbnxn_consts.h"
57 #include "gromacs/mdlib/nbnxn_grid.h"
58 #include "gromacs/mdlib/nbnxn_internal.h"
59 #include "gromacs/mdlib/nbnxn_simd.h"
60 #include "gromacs/mdlib/nbnxn_util.h"
61 #include "gromacs/mdlib/ns.h"
62 #include "gromacs/mdtypes/group.h"
63 #include "gromacs/mdtypes/md_enums.h"
64 #include "gromacs/pbcutil/ishift.h"
65 #include "gromacs/pbcutil/pbc.h"
66 #include "gromacs/simd/simd.h"
67 #include "gromacs/simd/vector_operations.h"
68 #include "gromacs/topology/block.h"
69 #include "gromacs/utility/exceptions.h"
70 #include "gromacs/utility/fatalerror.h"
71 #include "gromacs/utility/gmxomp.h"
72 #include "gromacs/utility/smalloc.h"
73
74 using namespace gmx; // TODO: Remove when this file is moved into gmx namespace
75
76
77 /* We shift the i-particles backward for PBC.
78  * This leads to more conditionals than shifting forward.
79  * We do this to get more balanced pair lists.
80  */
81 constexpr bool c_pbcShiftBackward = true;
82
83
84 static void nbs_cycle_clear(nbnxn_cycle_t *cc)
85 {
86     for (int i = 0; i < enbsCCnr; i++)
87     {
88         cc[i].count = 0;
89         cc[i].c     = 0;
90     }
91 }
92
93 static double Mcyc_av(const nbnxn_cycle_t *cc)
94 {
95     return static_cast<double>(cc->c)*1e-6/cc->count;
96 }
97
98 static void nbs_cycle_print(FILE *fp, const nbnxn_search *nbs)
99 {
100     fprintf(fp, "\n");
101     fprintf(fp, "ns %4d grid %4.1f search %4.1f red.f %5.3f",
102             nbs->cc[enbsCCgrid].count,
103             Mcyc_av(&nbs->cc[enbsCCgrid]),
104             Mcyc_av(&nbs->cc[enbsCCsearch]),
105             Mcyc_av(&nbs->cc[enbsCCreducef]));
106
107     if (nbs->work.size() > 1)
108     {
109         if (nbs->cc[enbsCCcombine].count > 0)
110         {
111             fprintf(fp, " comb %5.2f",
112                     Mcyc_av(&nbs->cc[enbsCCcombine]));
113         }
114         fprintf(fp, " s. th");
115         for (const nbnxn_search_work_t &work : nbs->work)
116         {
117             fprintf(fp, " %4.1f",
118                     Mcyc_av(&work.cc[enbsCCsearch]));
119         }
120     }
121     fprintf(fp, "\n");
122 }
123
124 /* Layout for the nonbonded NxN pair lists */
125 enum class NbnxnLayout
126 {
127     NoSimd4x4, // i-cluster size 4, j-cluster size 4
128     Simd4xN,   // i-cluster size 4, j-cluster size SIMD width
129     Simd2xNN,  // i-cluster size 4, j-cluster size half SIMD width
130     Gpu8x8x8   // i-cluster size 8, j-cluster size 8 + super-clustering
131 };
132
133 #if GMX_SIMD
134 /* Returns the j-cluster size */
135 template <NbnxnLayout layout>
136 static constexpr int jClusterSize()
137 {
138     static_assert(layout == NbnxnLayout::NoSimd4x4 || layout == NbnxnLayout::Simd4xN || layout == NbnxnLayout::Simd2xNN, "Currently jClusterSize only supports CPU layouts");
139
140     return layout == NbnxnLayout::Simd4xN ? GMX_SIMD_REAL_WIDTH : (layout == NbnxnLayout::Simd2xNN ? GMX_SIMD_REAL_WIDTH/2 : NBNXN_CPU_CLUSTER_I_SIZE);
141 }
142
143 /* Returns the j-cluster index given the i-cluster index */
144 template <int jClusterSize>
145 static inline int cjFromCi(int ci)
146 {
147     static_assert(jClusterSize == NBNXN_CPU_CLUSTER_I_SIZE/2 || jClusterSize == NBNXN_CPU_CLUSTER_I_SIZE || jClusterSize == NBNXN_CPU_CLUSTER_I_SIZE*2, "Only j-cluster sizes 2, 4 and 8 are currently implemented");
148
149     if (jClusterSize == NBNXN_CPU_CLUSTER_I_SIZE/2)
150     {
151         return ci << 1;
152     }
153     else if (jClusterSize == NBNXN_CPU_CLUSTER_I_SIZE)
154     {
155         return ci;
156     }
157     else
158     {
159         return ci >> 1;
160     }
161 }
162
163 /* Returns the j-cluster index given the i-cluster index */
164 template <NbnxnLayout layout>
165 static inline int cjFromCi(int ci)
166 {
167     constexpr int clusterSize = jClusterSize<layout>();
168
169     return cjFromCi<clusterSize>(ci);
170 }
171
172 /* Returns the nbnxn coordinate data index given the i-cluster index */
173 template <NbnxnLayout layout>
174 static inline int xIndexFromCi(int ci)
175 {
176     constexpr int clusterSize = jClusterSize<layout>();
177
178     static_assert(clusterSize == NBNXN_CPU_CLUSTER_I_SIZE/2 || clusterSize == NBNXN_CPU_CLUSTER_I_SIZE || clusterSize == NBNXN_CPU_CLUSTER_I_SIZE*2, "Only j-cluster sizes 2, 4 and 8 are currently implemented");
179
180     if (clusterSize <= NBNXN_CPU_CLUSTER_I_SIZE)
181     {
182         /* Coordinates are stored packed in groups of 4 */
183         return ci*STRIDE_P4;
184     }
185     else
186     {
187         /* Coordinates packed in 8, i-cluster size is half the packing width */
188         return (ci >> 1)*STRIDE_P8 + (ci & 1)*(c_packX8 >> 1);
189     }
190 }
191
192 /* Returns the nbnxn coordinate data index given the j-cluster index */
193 template <NbnxnLayout layout>
194 static inline int xIndexFromCj(int cj)
195 {
196     constexpr int clusterSize = jClusterSize<layout>();
197
198     static_assert(clusterSize == NBNXN_CPU_CLUSTER_I_SIZE/2 || clusterSize == NBNXN_CPU_CLUSTER_I_SIZE || clusterSize == NBNXN_CPU_CLUSTER_I_SIZE*2, "Only j-cluster sizes 2, 4 and 8 are currently implemented");
199
200     if (clusterSize == NBNXN_CPU_CLUSTER_I_SIZE/2)
201     {
202         /* Coordinates are stored packed in groups of 4 */
203         return (cj >> 1)*STRIDE_P4 + (cj & 1)*(c_packX4 >> 1);
204     }
205     else if (clusterSize == NBNXN_CPU_CLUSTER_I_SIZE)
206     {
207         /* Coordinates are stored packed in groups of 4 */
208         return cj*STRIDE_P4;
209     }
210     else
211     {
212         /* Coordinates are stored packed in groups of 8 */
213         return cj*STRIDE_P8;
214     }
215 }
216 #endif //GMX_SIMD
217
218 gmx_bool nbnxn_kernel_pairlist_simple(int nb_kernel_type)
219 {
220     if (nb_kernel_type == nbnxnkNotSet)
221     {
222         gmx_fatal(FARGS, "Non-bonded kernel type not set for Verlet-style pair-list.");
223     }
224
225     switch (nb_kernel_type)
226     {
227         case nbnxnk8x8x8_GPU:
228         case nbnxnk8x8x8_PlainC:
229             return FALSE;
230
231         case nbnxnk4x4_PlainC:
232         case nbnxnk4xN_SIMD_4xN:
233         case nbnxnk4xN_SIMD_2xNN:
234             return TRUE;
235
236         default:
237             gmx_incons("Invalid nonbonded kernel type passed!");
238             return FALSE;
239     }
240 }
241
242 /* Initializes a single nbnxn_pairlist_t data structure */
243 static void nbnxn_init_pairlist_fep(t_nblist *nl)
244 {
245     nl->type        = GMX_NBLIST_INTERACTION_FREE_ENERGY;
246     nl->igeometry   = GMX_NBLIST_GEOMETRY_PARTICLE_PARTICLE;
247     /* The interaction functions are set in the free energy kernel fuction */
248     nl->ivdw        = -1;
249     nl->ivdwmod     = -1;
250     nl->ielec       = -1;
251     nl->ielecmod    = -1;
252
253     nl->maxnri      = 0;
254     nl->maxnrj      = 0;
255     nl->nri         = 0;
256     nl->nrj         = 0;
257     nl->iinr        = nullptr;
258     nl->gid         = nullptr;
259     nl->shift       = nullptr;
260     nl->jindex      = nullptr;
261     nl->jjnr        = nullptr;
262     nl->excl_fep    = nullptr;
263
264 }
265
266 static void free_nblist(t_nblist *nl)
267 {
268     sfree(nl->iinr);
269     sfree(nl->gid);
270     sfree(nl->shift);
271     sfree(nl->jindex);
272     sfree(nl->jjnr);
273     sfree(nl->excl_fep);
274 }
275
276 nbnxn_search_work_t::nbnxn_search_work_t() :
277     cp0({{0}}
278         ),
279     buffer_flags({0, nullptr, 0}),
280     ndistc(0),
281     nbl_fep(new t_nblist),
282     cp1({{0}})
283 {
284     nbnxn_init_pairlist_fep(nbl_fep.get());
285
286     nbs_cycle_clear(cc);
287 }
288
289 nbnxn_search_work_t::~nbnxn_search_work_t()
290 {
291     sfree(buffer_flags.flag);
292
293     free_nblist(nbl_fep.get());
294 }
295
296 nbnxn_search::nbnxn_search(const ivec               *n_dd_cells,
297                            const gmx_domdec_zones_t *zones,
298                            gmx_bool                  bFEP,
299                            int                       nthread_max) :
300     bFEP(bFEP),
301     ePBC(epbcNONE), // The correct value will be set during the gridding
302     zones(zones),
303     natoms_local(0),
304     natoms_nonlocal(0),
305     search_count(0),
306     work(nthread_max)
307 {
308     // The correct value will be set during the gridding
309     clear_mat(box);
310     clear_ivec(dd_dim);
311     int numGrids = 1;
312     DomDec = n_dd_cells != nullptr;
313     if (DomDec)
314     {
315         for (int d = 0; d < DIM; d++)
316         {
317             if ((*n_dd_cells)[d] > 1)
318             {
319                 dd_dim[d] = 1;
320                 /* Each grid matches a DD zone */
321                 numGrids *= 2;
322             }
323         }
324     }
325
326     grid.resize(numGrids);
327
328     /* Initialize detailed nbsearch cycle counting */
329     print_cycles = (getenv("GMX_NBNXN_CYCLE") != nullptr);
330     nbs_cycle_clear(cc);
331 }
332
333 nbnxn_search *nbnxn_init_search(const ivec                *n_dd_cells,
334                                 const gmx_domdec_zones_t  *zones,
335                                 gmx_bool                   bFEP,
336                                 int                        nthread_max)
337 {
338     return new nbnxn_search(n_dd_cells, zones, bFEP, nthread_max);
339 }
340
341 static void init_buffer_flags(nbnxn_buffer_flags_t *flags,
342                               int                   natoms)
343 {
344     flags->nflag = (natoms + NBNXN_BUFFERFLAG_SIZE - 1)/NBNXN_BUFFERFLAG_SIZE;
345     if (flags->nflag > flags->flag_nalloc)
346     {
347         flags->flag_nalloc = over_alloc_large(flags->nflag);
348         srenew(flags->flag, flags->flag_nalloc);
349     }
350     for (int b = 0; b < flags->nflag; b++)
351     {
352         bitmask_clear(&(flags->flag[b]));
353     }
354 }
355
356 /* Returns the pair-list cutoff between a bounding box and a grid cell given an atom-to-atom pair-list cutoff
357  *
358  * Given a cutoff distance between atoms, this functions returns the cutoff
359  * distance2 between a bounding box of a group of atoms and a grid cell.
360  * Since atoms can be geometrically outside of the cell they have been
361  * assigned to (when atom groups instead of individual atoms are assigned
362  * to cells), this distance returned can be larger than the input.
363  */
364 static real listRangeForBoundingBoxToGridCell(real                rlist,
365                                               const nbnxn_grid_t &grid)
366 {
367     return rlist + grid.maxAtomGroupRadius;
368
369 }
370 /* Returns the pair-list cutoff between a grid cells given an atom-to-atom pair-list cutoff
371  *
372  * Given a cutoff distance between atoms, this functions returns the cutoff
373  * distance2 between two grid cells.
374  * Since atoms can be geometrically outside of the cell they have been
375  * assigned to (when atom groups instead of individual atoms are assigned
376  * to cells), this distance returned can be larger than the input.
377  */
378 static real listRangeForGridCellToGridCell(real                rlist,
379                                            const nbnxn_grid_t &gridi,
380                                            const nbnxn_grid_t &gridj)
381 {
382     return rlist + gridi.maxAtomGroupRadius + gridj.maxAtomGroupRadius;
383 }
384
385 /* Determines the cell range along one dimension that
386  * the bounding box b0 - b1 sees.
387  */
388 template<int dim>
389 static void get_cell_range(real b0, real b1,
390                            const nbnxn_grid_t &gridj,
391                            real d2, real rlist, int *cf, int *cl)
392 {
393     real listRangeBBToCell2 = gmx::square(listRangeForBoundingBoxToGridCell(rlist, gridj));
394     real distanceInCells    = (b0 - gridj.c0[dim])*gridj.invCellSize[dim];
395     *cf                     = std::max(static_cast<int>(distanceInCells), 0);
396
397     while (*cf > 0 &&
398            d2 + gmx::square((b0 - gridj.c0[dim]) - (*cf - 1 + 1)*gridj.cellSize[dim]) < listRangeBBToCell2)
399     {
400         (*cf)--;
401     }
402
403     *cl = std::min(static_cast<int>((b1 - gridj.c0[dim])*gridj.invCellSize[dim]), gridj.numCells[dim] - 1);
404     while (*cl < gridj.numCells[dim] - 1 &&
405            d2 + gmx::square((*cl + 1)*gridj.cellSize[dim] - (b1 - gridj.c0[dim])) < listRangeBBToCell2)
406     {
407         (*cl)++;
408     }
409 }
410
411 /* Reference code calculating the distance^2 between two bounding boxes */
412 /*
413    static float box_dist2(float bx0, float bx1, float by0,
414                        float by1, float bz0, float bz1,
415                        const nbnxn_bb_t *bb)
416    {
417     float d2;
418     float dl, dh, dm, dm0;
419
420     d2 = 0;
421
422     dl  = bx0 - bb->upper[BB_X];
423     dh  = bb->lower[BB_X] - bx1;
424     dm  = std::max(dl, dh);
425     dm0 = std::max(dm, 0.0f);
426     d2 += dm0*dm0;
427
428     dl  = by0 - bb->upper[BB_Y];
429     dh  = bb->lower[BB_Y] - by1;
430     dm  = std::max(dl, dh);
431     dm0 = std::max(dm, 0.0f);
432     d2 += dm0*dm0;
433
434     dl  = bz0 - bb->upper[BB_Z];
435     dh  = bb->lower[BB_Z] - bz1;
436     dm  = std::max(dl, dh);
437     dm0 = std::max(dm, 0.0f);
438     d2 += dm0*dm0;
439
440     return d2;
441    }
442  */
443
444 /* Plain C code calculating the distance^2 between two bounding boxes */
445 static float subc_bb_dist2(int                              si,
446                            const nbnxn_bb_t                *bb_i_ci,
447                            int                              csj,
448                            gmx::ArrayRef<const nbnxn_bb_t>  bb_j_all)
449 {
450     const nbnxn_bb_t *bb_i = bb_i_ci         +  si;
451     const nbnxn_bb_t *bb_j = bb_j_all.data() + csj;
452
453     float             d2 = 0;
454     float             dl, dh, dm, dm0;
455
456     dl  = bb_i->lower[BB_X] - bb_j->upper[BB_X];
457     dh  = bb_j->lower[BB_X] - bb_i->upper[BB_X];
458     dm  = std::max(dl, dh);
459     dm0 = std::max(dm, 0.0f);
460     d2 += dm0*dm0;
461
462     dl  = bb_i->lower[BB_Y] - bb_j->upper[BB_Y];
463     dh  = bb_j->lower[BB_Y] - bb_i->upper[BB_Y];
464     dm  = std::max(dl, dh);
465     dm0 = std::max(dm, 0.0f);
466     d2 += dm0*dm0;
467
468     dl  = bb_i->lower[BB_Z] - bb_j->upper[BB_Z];
469     dh  = bb_j->lower[BB_Z] - bb_i->upper[BB_Z];
470     dm  = std::max(dl, dh);
471     dm0 = std::max(dm, 0.0f);
472     d2 += dm0*dm0;
473
474     return d2;
475 }
476
477 #if NBNXN_SEARCH_BB_SIMD4
478
479 /* 4-wide SIMD code for bb distance for bb format xyz0 */
480 static float subc_bb_dist2_simd4(int                              si,
481                                  const nbnxn_bb_t                *bb_i_ci,
482                                  int                              csj,
483                                  gmx::ArrayRef<const nbnxn_bb_t>  bb_j_all)
484 {
485     // TODO: During SIMDv2 transition only some archs use namespace (remove when done)
486     using namespace gmx;
487
488     Simd4Float bb_i_S0, bb_i_S1;
489     Simd4Float bb_j_S0, bb_j_S1;
490     Simd4Float dl_S;
491     Simd4Float dh_S;
492     Simd4Float dm_S;
493     Simd4Float dm0_S;
494
495     bb_i_S0 = load4(&bb_i_ci[si].lower[0]);
496     bb_i_S1 = load4(&bb_i_ci[si].upper[0]);
497     bb_j_S0 = load4(&bb_j_all[csj].lower[0]);
498     bb_j_S1 = load4(&bb_j_all[csj].upper[0]);
499
500     dl_S    = bb_i_S0 - bb_j_S1;
501     dh_S    = bb_j_S0 - bb_i_S1;
502
503     dm_S    = max(dl_S, dh_S);
504     dm0_S   = max(dm_S, simd4SetZeroF());
505
506     return dotProduct(dm0_S, dm0_S);
507 }
508
509 /* Calculate bb bounding distances of bb_i[si,...,si+3] and store them in d2 */
510 #define SUBC_BB_DIST2_SIMD4_XXXX_INNER(si, bb_i, d2) \
511     {                                                \
512         int               shi;                                  \
513                                                  \
514         Simd4Float        dx_0, dy_0, dz_0;                    \
515         Simd4Float        dx_1, dy_1, dz_1;                    \
516                                                  \
517         Simd4Float        mx, my, mz;                          \
518         Simd4Float        m0x, m0y, m0z;                       \
519                                                  \
520         Simd4Float        d2x, d2y, d2z;                       \
521         Simd4Float        d2s, d2t;                            \
522                                                  \
523         shi = (si)*NNBSBB_D*DIM;                       \
524                                                  \
525         xi_l = load4((bb_i)+shi+0*STRIDE_PBB);   \
526         yi_l = load4((bb_i)+shi+1*STRIDE_PBB);   \
527         zi_l = load4((bb_i)+shi+2*STRIDE_PBB);   \
528         xi_h = load4((bb_i)+shi+3*STRIDE_PBB);   \
529         yi_h = load4((bb_i)+shi+4*STRIDE_PBB);   \
530         zi_h = load4((bb_i)+shi+5*STRIDE_PBB);   \
531                                                  \
532         dx_0 = xi_l - xj_h;                 \
533         dy_0 = yi_l - yj_h;                 \
534         dz_0 = zi_l - zj_h;                 \
535                                                  \
536         dx_1 = xj_l - xi_h;                 \
537         dy_1 = yj_l - yi_h;                 \
538         dz_1 = zj_l - zi_h;                 \
539                                                  \
540         mx   = max(dx_0, dx_1);                 \
541         my   = max(dy_0, dy_1);                 \
542         mz   = max(dz_0, dz_1);                 \
543                                                  \
544         m0x  = max(mx, zero);                   \
545         m0y  = max(my, zero);                   \
546         m0z  = max(mz, zero);                   \
547                                                  \
548         d2x  = m0x * m0x;                   \
549         d2y  = m0y * m0y;                   \
550         d2z  = m0z * m0z;                   \
551                                                  \
552         d2s  = d2x + d2y;                   \
553         d2t  = d2s + d2z;                   \
554                                                  \
555         store4((d2)+(si), d2t);                      \
556     }
557
558 /* 4-wide SIMD code for nsi bb distances for bb format xxxxyyyyzzzz */
559 static void subc_bb_dist2_simd4_xxxx(const float *bb_j,
560                                      int nsi, const float *bb_i,
561                                      float *d2)
562 {
563     // TODO: During SIMDv2 transition only some archs use namespace (remove when done)
564     using namespace gmx;
565
566     Simd4Float xj_l, yj_l, zj_l;
567     Simd4Float xj_h, yj_h, zj_h;
568     Simd4Float xi_l, yi_l, zi_l;
569     Simd4Float xi_h, yi_h, zi_h;
570
571     Simd4Float zero;
572
573     zero = setZero();
574
575     xj_l = Simd4Float(bb_j[0*STRIDE_PBB]);
576     yj_l = Simd4Float(bb_j[1*STRIDE_PBB]);
577     zj_l = Simd4Float(bb_j[2*STRIDE_PBB]);
578     xj_h = Simd4Float(bb_j[3*STRIDE_PBB]);
579     yj_h = Simd4Float(bb_j[4*STRIDE_PBB]);
580     zj_h = Simd4Float(bb_j[5*STRIDE_PBB]);
581
582     /* Here we "loop" over si (0,STRIDE_PBB) from 0 to nsi with step STRIDE_PBB.
583      * But as we know the number of iterations is 1 or 2, we unroll manually.
584      */
585     SUBC_BB_DIST2_SIMD4_XXXX_INNER(0, bb_i, d2);
586     if (STRIDE_PBB < nsi)
587     {
588         SUBC_BB_DIST2_SIMD4_XXXX_INNER(STRIDE_PBB, bb_i, d2);
589     }
590 }
591
592 #endif /* NBNXN_SEARCH_BB_SIMD4 */
593
594
595 /* Returns if any atom pair from two clusters is within distance sqrt(rlist2) */
596 static inline gmx_bool
597 clusterpair_in_range(const nbnxn_list_work_t *work,
598                      int si,
599                      int csj, int stride, const real *x_j,
600                      real rlist2)
601 {
602 #if !GMX_SIMD4_HAVE_REAL
603
604     /* Plain C version.
605      * All coordinates are stored as xyzxyz...
606      */
607
608     const real *x_i = work->x_ci;
609
610     for (int i = 0; i < c_nbnxnGpuClusterSize; i++)
611     {
612         int i0 = (si*c_nbnxnGpuClusterSize + i)*DIM;
613         for (int j = 0; j < c_nbnxnGpuClusterSize; j++)
614         {
615             int  j0 = (csj*c_nbnxnGpuClusterSize + j)*stride;
616
617             real d2 = gmx::square(x_i[i0  ] - x_j[j0  ]) + gmx::square(x_i[i0+1] - x_j[j0+1]) + gmx::square(x_i[i0+2] - x_j[j0+2]);
618
619             if (d2 < rlist2)
620             {
621                 return TRUE;
622             }
623         }
624     }
625
626     return FALSE;
627
628 #else /* !GMX_SIMD4_HAVE_REAL */
629
630     /* 4-wide SIMD version.
631      * The coordinates x_i are stored as xxxxyyyy..., x_j is stored xyzxyz...
632      * Using 8-wide AVX(2) is not faster on Intel Sandy Bridge and Haswell.
633      */
634     static_assert(c_nbnxnGpuClusterSize == 8 || c_nbnxnGpuClusterSize == 4,
635                   "A cluster is hard-coded to 4/8 atoms.");
636
637     Simd4Real   rc2_S      = Simd4Real(rlist2);
638
639     const real *x_i        = work->x_ci_simd;
640
641     int         dim_stride = c_nbnxnGpuClusterSize*DIM;
642     Simd4Real   ix_S0      = load4(x_i + si*dim_stride + 0*GMX_SIMD4_WIDTH);
643     Simd4Real   iy_S0      = load4(x_i + si*dim_stride + 1*GMX_SIMD4_WIDTH);
644     Simd4Real   iz_S0      = load4(x_i + si*dim_stride + 2*GMX_SIMD4_WIDTH);
645
646     Simd4Real   ix_S1, iy_S1, iz_S1;
647     if (c_nbnxnGpuClusterSize == 8)
648     {
649         ix_S1      = load4(x_i + si*dim_stride + 3*GMX_SIMD4_WIDTH);
650         iy_S1      = load4(x_i + si*dim_stride + 4*GMX_SIMD4_WIDTH);
651         iz_S1      = load4(x_i + si*dim_stride + 5*GMX_SIMD4_WIDTH);
652     }
653     /* We loop from the outer to the inner particles to maximize
654      * the chance that we find a pair in range quickly and return.
655      */
656     int j0 = csj*c_nbnxnGpuClusterSize;
657     int j1 = j0 + c_nbnxnGpuClusterSize - 1;
658     while (j0 < j1)
659     {
660         Simd4Real jx0_S, jy0_S, jz0_S;
661         Simd4Real jx1_S, jy1_S, jz1_S;
662
663         Simd4Real dx_S0, dy_S0, dz_S0;
664         Simd4Real dx_S1, dy_S1, dz_S1;
665         Simd4Real dx_S2, dy_S2, dz_S2;
666         Simd4Real dx_S3, dy_S3, dz_S3;
667
668         Simd4Real rsq_S0;
669         Simd4Real rsq_S1;
670         Simd4Real rsq_S2;
671         Simd4Real rsq_S3;
672
673         Simd4Bool wco_S0;
674         Simd4Bool wco_S1;
675         Simd4Bool wco_S2;
676         Simd4Bool wco_S3;
677         Simd4Bool wco_any_S01, wco_any_S23, wco_any_S;
678
679         jx0_S = Simd4Real(x_j[j0*stride+0]);
680         jy0_S = Simd4Real(x_j[j0*stride+1]);
681         jz0_S = Simd4Real(x_j[j0*stride+2]);
682
683         jx1_S = Simd4Real(x_j[j1*stride+0]);
684         jy1_S = Simd4Real(x_j[j1*stride+1]);
685         jz1_S = Simd4Real(x_j[j1*stride+2]);
686
687         /* Calculate distance */
688         dx_S0            = ix_S0 - jx0_S;
689         dy_S0            = iy_S0 - jy0_S;
690         dz_S0            = iz_S0 - jz0_S;
691         dx_S2            = ix_S0 - jx1_S;
692         dy_S2            = iy_S0 - jy1_S;
693         dz_S2            = iz_S0 - jz1_S;
694         if (c_nbnxnGpuClusterSize == 8)
695         {
696             dx_S1            = ix_S1 - jx0_S;
697             dy_S1            = iy_S1 - jy0_S;
698             dz_S1            = iz_S1 - jz0_S;
699             dx_S3            = ix_S1 - jx1_S;
700             dy_S3            = iy_S1 - jy1_S;
701             dz_S3            = iz_S1 - jz1_S;
702         }
703
704         /* rsq = dx*dx+dy*dy+dz*dz */
705         rsq_S0           = norm2(dx_S0, dy_S0, dz_S0);
706         rsq_S2           = norm2(dx_S2, dy_S2, dz_S2);
707         if (c_nbnxnGpuClusterSize == 8)
708         {
709             rsq_S1           = norm2(dx_S1, dy_S1, dz_S1);
710             rsq_S3           = norm2(dx_S3, dy_S3, dz_S3);
711         }
712
713         wco_S0           = (rsq_S0 < rc2_S);
714         wco_S2           = (rsq_S2 < rc2_S);
715         if (c_nbnxnGpuClusterSize == 8)
716         {
717             wco_S1           = (rsq_S1 < rc2_S);
718             wco_S3           = (rsq_S3 < rc2_S);
719         }
720         if (c_nbnxnGpuClusterSize == 8)
721         {
722             wco_any_S01      = wco_S0 || wco_S1;
723             wco_any_S23      = wco_S2 || wco_S3;
724             wco_any_S        = wco_any_S01 || wco_any_S23;
725         }
726         else
727         {
728             wco_any_S = wco_S0 || wco_S2;
729         }
730
731         if (anyTrue(wco_any_S))
732         {
733             return TRUE;
734         }
735
736         j0++;
737         j1--;
738     }
739
740     return FALSE;
741
742 #endif /* !GMX_SIMD4_HAVE_REAL */
743 }
744
745 /* Returns the j-cluster index for index cjIndex in a cj list */
746 static inline int nblCj(const nbnxn_cj_t *cjList, int cjIndex)
747 {
748     return cjList[cjIndex].cj;
749 }
750
751 /* Returns the j-cluster index for index cjIndex in a cj4 list */
752 static inline int nblCj(const nbnxn_cj4_t *cj4List, int cjIndex)
753 {
754     return cj4List[cjIndex/c_nbnxnGpuJgroupSize].cj[cjIndex & (c_nbnxnGpuJgroupSize - 1)];
755 }
756
757 /* Returns the i-interaction mask of the j sub-cell for index cj_ind */
758 static unsigned int nbl_imask0(const nbnxn_pairlist_t *nbl, int cj_ind)
759 {
760     return nbl->cj4[cj_ind/c_nbnxnGpuJgroupSize].imei[0].imask;
761 }
762
763 /* Ensures there is enough space for extra extra exclusion masks */
764 static void check_excl_space(nbnxn_pairlist_t *nbl, int extra)
765 {
766     if (nbl->nexcl+extra > nbl->excl_nalloc)
767     {
768         nbl->excl_nalloc = over_alloc_small(nbl->nexcl+extra);
769         nbnxn_realloc_void(reinterpret_cast<void **>(&nbl->excl),
770                            nbl->nexcl*sizeof(*nbl->excl),
771                            nbl->excl_nalloc*sizeof(*nbl->excl),
772                            nbl->alloc, nbl->free);
773     }
774 }
775
776 /* Ensures there is enough space for maxNumExtraClusters extra j-clusters in the list */
777 static void check_cell_list_space_simple(nbnxn_pairlist_t *nbl,
778                                          int               maxNumExtraClusters)
779 {
780     int cj_max;
781
782     cj_max = nbl->ncj + maxNumExtraClusters;
783
784     if (cj_max > nbl->cj_nalloc)
785     {
786         nbl->cj_nalloc = over_alloc_small(cj_max);
787         nbnxn_realloc_void(reinterpret_cast<void **>(&nbl->cj),
788                            nbl->ncj*sizeof(*nbl->cj),
789                            nbl->cj_nalloc*sizeof(*nbl->cj),
790                            nbl->alloc, nbl->free);
791
792         nbnxn_realloc_void(reinterpret_cast<void **>(&nbl->cjOuter),
793                            nbl->ncj*sizeof(*nbl->cjOuter),
794                            nbl->cj_nalloc*sizeof(*nbl->cjOuter),
795                            nbl->alloc, nbl->free);
796     }
797 }
798
799 /* Ensures there is enough space for ncell extra j-clusters in the list */
800 static void check_cell_list_space_supersub(nbnxn_pairlist_t *nbl,
801                                            int               ncell)
802 {
803     int ncj4_max, w;
804
805     /* We can have maximally nsupercell*c_gpuNumClusterPerCell sj lists */
806     /* We can store 4 j-subcell - i-supercell pairs in one struct.
807      * since we round down, we need one extra entry.
808      */
809     ncj4_max = ((nbl->work->cj_ind + ncell*c_gpuNumClusterPerCell + c_nbnxnGpuJgroupSize - 1)/c_nbnxnGpuJgroupSize);
810
811     if (ncj4_max > nbl->cj4_nalloc)
812     {
813         nbl->cj4_nalloc = over_alloc_small(ncj4_max);
814         nbnxn_realloc_void(reinterpret_cast<void **>(&nbl->cj4),
815                            nbl->work->cj4_init*sizeof(*nbl->cj4),
816                            nbl->cj4_nalloc*sizeof(*nbl->cj4),
817                            nbl->alloc, nbl->free);
818     }
819
820     if (ncj4_max > nbl->work->cj4_init)
821     {
822         for (int j4 = nbl->work->cj4_init; j4 < ncj4_max; j4++)
823         {
824             /* No i-subcells and no excl's in the list initially */
825             for (w = 0; w < c_nbnxnGpuClusterpairSplit; w++)
826             {
827                 nbl->cj4[j4].imei[w].imask    = 0U;
828                 nbl->cj4[j4].imei[w].excl_ind = 0;
829
830             }
831         }
832         nbl->work->cj4_init = ncj4_max;
833     }
834 }
835
836 /* Set all excl masks for one GPU warp no exclusions */
837 static void set_no_excls(nbnxn_excl_t *excl)
838 {
839     for (int t = 0; t < c_nbnxnGpuExclSize; t++)
840     {
841         /* Turn all interaction bits on */
842         excl->pair[t] = NBNXN_INTERACTION_MASK_ALL;
843     }
844 }
845
846 /* Initializes a single nbnxn_pairlist_t data structure */
847 static void nbnxn_init_pairlist(nbnxn_pairlist_t *nbl,
848                                 gmx_bool          bSimple,
849                                 nbnxn_alloc_t    *alloc,
850                                 nbnxn_free_t     *free)
851 {
852     if (alloc == nullptr)
853     {
854         nbl->alloc = nbnxn_alloc_aligned;
855     }
856     else
857     {
858         nbl->alloc = alloc;
859     }
860     if (free == nullptr)
861     {
862         nbl->free = nbnxn_free_aligned;
863     }
864     else
865     {
866         nbl->free = free;
867     }
868
869     nbl->bSimple     = bSimple;
870     nbl->na_sc       = 0;
871     nbl->na_ci       = 0;
872     nbl->na_cj       = 0;
873     nbl->nci         = 0;
874     nbl->ci          = nullptr;
875     nbl->ci_nalloc   = 0;
876     nbl->nsci        = 0;
877     nbl->sci         = nullptr;
878     nbl->sci_nalloc  = 0;
879     nbl->ncj         = 0;
880     nbl->ncjInUse    = 0;
881     nbl->cj          = nullptr;
882     nbl->cj_nalloc   = 0;
883     nbl->ncj4        = 0;
884     /* We need one element extra in sj, so alloc initially with 1 */
885     nbl->cj4_nalloc  = 0;
886     nbl->cj4         = nullptr;
887     nbl->nci_tot     = 0;
888
889     if (!nbl->bSimple)
890     {
891         GMX_ASSERT(c_nbnxnGpuNumClusterPerSupercluster == c_gpuNumClusterPerCell, "The search code assumes that the a super-cluster matches a search grid cell");
892
893         GMX_ASSERT(sizeof(nbl->cj4[0].imei[0].imask)*8 >= c_nbnxnGpuJgroupSize*c_gpuNumClusterPerCell, "The i super-cluster cluster interaction mask does not contain a sufficient number of bits");
894         GMX_ASSERT(sizeof(nbl->excl[0])*8 >= c_nbnxnGpuJgroupSize*c_gpuNumClusterPerCell, "The GPU exclusion mask does not contain a sufficient number of bits");
895
896         nbl->excl        = nullptr;
897         nbl->excl_nalloc = 0;
898         nbl->nexcl       = 0;
899         check_excl_space(nbl, 1);
900         nbl->nexcl       = 1;
901         set_no_excls(&nbl->excl[0]);
902     }
903
904     snew(nbl->work, 1);
905     if (nbl->bSimple)
906     {
907         snew_aligned(nbl->work->bb_ci, 1, NBNXN_SEARCH_BB_MEM_ALIGN);
908     }
909     else
910     {
911 #if NBNXN_BBXXXX
912         snew_aligned(nbl->work->pbb_ci, c_gpuNumClusterPerCell/STRIDE_PBB*NNBSBB_XXXX, NBNXN_SEARCH_BB_MEM_ALIGN);
913 #else
914         snew_aligned(nbl->work->bb_ci, c_gpuNumClusterPerCell, NBNXN_SEARCH_BB_MEM_ALIGN);
915 #endif
916     }
917     int gpu_clusterpair_nc = c_gpuNumClusterPerCell*c_nbnxnGpuClusterSize*DIM;
918     snew(nbl->work->x_ci, gpu_clusterpair_nc);
919 #if GMX_SIMD
920     snew_aligned(nbl->work->x_ci_simd,
921                  std::max(NBNXN_CPU_CLUSTER_I_SIZE*DIM*GMX_SIMD_REAL_WIDTH,
922                           gpu_clusterpair_nc),
923                  GMX_SIMD_REAL_WIDTH);
924 #endif
925     snew_aligned(nbl->work->d2, c_gpuNumClusterPerCell, NBNXN_SEARCH_BB_MEM_ALIGN);
926
927     nbl->work->sort            = nullptr;
928     nbl->work->sort_nalloc     = 0;
929     nbl->work->sci_sort        = nullptr;
930     nbl->work->sci_sort_nalloc = 0;
931 }
932
933 void nbnxn_init_pairlist_set(nbnxn_pairlist_set_t *nbl_list,
934                              gmx_bool bSimple, gmx_bool bCombined,
935                              nbnxn_alloc_t *alloc,
936                              nbnxn_free_t  *free)
937 {
938     nbl_list->bSimple   = bSimple;
939     nbl_list->bCombined = bCombined;
940
941     nbl_list->nnbl = gmx_omp_nthreads_get(emntNonbonded);
942
943     if (!nbl_list->bCombined &&
944         nbl_list->nnbl > NBNXN_BUFFERFLAG_MAX_THREADS)
945     {
946         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.",
947                   nbl_list->nnbl, NBNXN_BUFFERFLAG_MAX_THREADS, NBNXN_BUFFERFLAG_MAX_THREADS);
948     }
949
950     snew(nbl_list->nbl, nbl_list->nnbl);
951     if (bSimple && nbl_list->nnbl > 1)
952     {
953         snew(nbl_list->nbl_work, nbl_list->nnbl);
954     }
955     snew(nbl_list->nbl_fep, nbl_list->nnbl);
956     /* Execute in order to avoid memory interleaving between threads */
957 #pragma omp parallel for num_threads(nbl_list->nnbl) schedule(static)
958     for (int i = 0; i < nbl_list->nnbl; i++)
959     {
960         try
961         {
962             /* Allocate the nblist data structure locally on each thread
963              * to optimize memory access for NUMA architectures.
964              */
965             snew(nbl_list->nbl[i], 1);
966
967             /* Only list 0 is used on the GPU, use normal allocation for i>0 */
968             if (!bSimple && i == 0)
969             {
970                 nbnxn_init_pairlist(nbl_list->nbl[i], nbl_list->bSimple, alloc, free);
971             }
972             else
973             {
974                 nbnxn_init_pairlist(nbl_list->nbl[i], nbl_list->bSimple, nullptr, nullptr);
975                 if (bSimple && nbl_list->nnbl > 1)
976                 {
977                     snew(nbl_list->nbl_work[i], 1);
978                     nbnxn_init_pairlist(nbl_list->nbl_work[i], nbl_list->bSimple, nullptr, nullptr);
979                 }
980             }
981
982             snew(nbl_list->nbl_fep[i], 1);
983             nbnxn_init_pairlist_fep(nbl_list->nbl_fep[i]);
984         }
985         GMX_CATCH_ALL_AND_EXIT_WITH_FATAL_ERROR;
986     }
987 }
988
989 /* Print statistics of a pair list, used for debug output */
990 static void print_nblist_statistics_simple(FILE *fp, const nbnxn_pairlist_t *nbl,
991                                            const nbnxn_search *nbs, real rl)
992 {
993     const nbnxn_grid_t *grid;
994     int                 cs[SHIFTS];
995     int                 npexcl;
996
997     grid = &nbs->grid[0];
998
999     fprintf(fp, "nbl nci %d ncj %d\n",
1000             nbl->nci, nbl->ncjInUse);
1001     fprintf(fp, "nbl na_sc %d rl %g ncp %d per cell %.1f atoms %.1f ratio %.2f\n",
1002             nbl->na_sc, rl, nbl->ncjInUse, nbl->ncjInUse/static_cast<double>(grid->nc),
1003             nbl->ncjInUse/static_cast<double>(grid->nc)*grid->na_sc,
1004             nbl->ncjInUse/static_cast<double>(grid->nc)*grid->na_sc/(0.5*4.0/3.0*M_PI*rl*rl*rl*grid->nc*grid->na_sc/(grid->size[XX]*grid->size[YY]*grid->size[ZZ])));
1005
1006     fprintf(fp, "nbl average j cell list length %.1f\n",
1007             0.25*nbl->ncjInUse/static_cast<double>(std::max(nbl->nci, 1)));
1008
1009     for (int s = 0; s < SHIFTS; s++)
1010     {
1011         cs[s] = 0;
1012     }
1013     npexcl = 0;
1014     for (int i = 0; i < nbl->nci; i++)
1015     {
1016         cs[nbl->ci[i].shift & NBNXN_CI_SHIFT] +=
1017             nbl->ci[i].cj_ind_end - nbl->ci[i].cj_ind_start;
1018
1019         int j = nbl->ci[i].cj_ind_start;
1020         while (j < nbl->ci[i].cj_ind_end &&
1021                nbl->cj[j].excl != NBNXN_INTERACTION_MASK_ALL)
1022         {
1023             npexcl++;
1024             j++;
1025         }
1026     }
1027     fprintf(fp, "nbl cell pairs, total: %d excl: %d %.1f%%\n",
1028             nbl->ncj, npexcl, 100*npexcl/static_cast<double>(std::max(nbl->ncj, 1)));
1029     for (int s = 0; s < SHIFTS; s++)
1030     {
1031         if (cs[s] > 0)
1032         {
1033             fprintf(fp, "nbl shift %2d ncj %3d\n", s, cs[s]);
1034         }
1035     }
1036 }
1037
1038 /* Print statistics of a pair lists, used for debug output */
1039 static void print_nblist_statistics_supersub(FILE *fp, const nbnxn_pairlist_t *nbl,
1040                                              const nbnxn_search *nbs, real rl)
1041 {
1042     const nbnxn_grid_t *grid;
1043     int                 b;
1044     int                 c[c_gpuNumClusterPerCell + 1];
1045     double              sum_nsp, sum_nsp2;
1046     int                 nsp_max;
1047
1048     /* This code only produces correct statistics with domain decomposition */
1049     grid = &nbs->grid[0];
1050
1051     fprintf(fp, "nbl nsci %d ncj4 %d nsi %d excl4 %d\n",
1052             nbl->nsci, nbl->ncj4, nbl->nci_tot, nbl->nexcl);
1053     fprintf(fp, "nbl na_c %d rl %g ncp %d per cell %.1f atoms %.1f ratio %.2f\n",
1054             nbl->na_ci, rl, nbl->nci_tot, nbl->nci_tot/static_cast<double>(grid->nsubc_tot),
1055             nbl->nci_tot/static_cast<double>(grid->nsubc_tot)*grid->na_c,
1056             nbl->nci_tot/static_cast<double>(grid->nsubc_tot)*grid->na_c/(0.5*4.0/3.0*M_PI*rl*rl*rl*grid->nsubc_tot*grid->na_c/(grid->size[XX]*grid->size[YY]*grid->size[ZZ])));
1057
1058     sum_nsp  = 0;
1059     sum_nsp2 = 0;
1060     nsp_max  = 0;
1061     for (int si = 0; si <= c_gpuNumClusterPerCell; si++)
1062     {
1063         c[si] = 0;
1064     }
1065     for (int i = 0; i < nbl->nsci; i++)
1066     {
1067         int nsp;
1068
1069         nsp = 0;
1070         for (int j4 = nbl->sci[i].cj4_ind_start; j4 < nbl->sci[i].cj4_ind_end; j4++)
1071         {
1072             for (int j = 0; j < c_nbnxnGpuJgroupSize; j++)
1073             {
1074                 b = 0;
1075                 for (int si = 0; si < c_gpuNumClusterPerCell; si++)
1076                 {
1077                     if (nbl->cj4[j4].imei[0].imask & (1U << (j*c_gpuNumClusterPerCell + si)))
1078                     {
1079                         b++;
1080                     }
1081                 }
1082                 nsp += b;
1083                 c[b]++;
1084             }
1085         }
1086         sum_nsp  += nsp;
1087         sum_nsp2 += nsp*nsp;
1088         nsp_max   = std::max(nsp_max, nsp);
1089     }
1090     if (nbl->nsci > 0)
1091     {
1092         sum_nsp  /= nbl->nsci;
1093         sum_nsp2 /= nbl->nsci;
1094     }
1095     fprintf(fp, "nbl #cluster-pairs: av %.1f stddev %.1f max %d\n",
1096             sum_nsp, std::sqrt(sum_nsp2 - sum_nsp*sum_nsp), nsp_max);
1097
1098     if (nbl->ncj4 > 0)
1099     {
1100         for (b = 0; b <= c_gpuNumClusterPerCell; b++)
1101         {
1102             fprintf(fp, "nbl j-list #i-subcell %d %7d %4.1f\n",
1103                     b, c[b],
1104                     100.0*c[b]/int{nbl->ncj4*c_nbnxnGpuJgroupSize});
1105         }
1106     }
1107 }
1108
1109 /* Returns a pointer to the exclusion mask for cj4-unit cj4, warp warp */
1110 static void low_get_nbl_exclusions(nbnxn_pairlist_t *nbl, int cj4,
1111                                    int warp, nbnxn_excl_t **excl)
1112 {
1113     if (nbl->cj4[cj4].imei[warp].excl_ind == 0)
1114     {
1115         /* No exclusions set, make a new list entry */
1116         nbl->cj4[cj4].imei[warp].excl_ind = nbl->nexcl;
1117         nbl->nexcl++;
1118         *excl = &nbl->excl[nbl->cj4[cj4].imei[warp].excl_ind];
1119         set_no_excls(*excl);
1120     }
1121     else
1122     {
1123         /* We already have some exclusions, new ones can be added to the list */
1124         *excl = &nbl->excl[nbl->cj4[cj4].imei[warp].excl_ind];
1125     }
1126 }
1127
1128 /* Returns a pointer to the exclusion mask for cj4-unit cj4, warp warp,
1129  * generates a new element and allocates extra memory, if necessary.
1130  */
1131 static void get_nbl_exclusions_1(nbnxn_pairlist_t *nbl, int cj4,
1132                                  int warp, nbnxn_excl_t **excl)
1133 {
1134     if (nbl->cj4[cj4].imei[warp].excl_ind == 0)
1135     {
1136         /* We need to make a new list entry, check if we have space */
1137         check_excl_space(nbl, 1);
1138     }
1139     low_get_nbl_exclusions(nbl, cj4, warp, excl);
1140 }
1141
1142 /* Returns pointers to the exclusion masks for cj4-unit cj4 for both warps,
1143  * generates a new element and allocates extra memory, if necessary.
1144  */
1145 static void get_nbl_exclusions_2(nbnxn_pairlist_t *nbl, int cj4,
1146                                  nbnxn_excl_t **excl_w0,
1147                                  nbnxn_excl_t **excl_w1)
1148 {
1149     /* Check for space we might need */
1150     check_excl_space(nbl, 2);
1151
1152     low_get_nbl_exclusions(nbl, cj4, 0, excl_w0);
1153     low_get_nbl_exclusions(nbl, cj4, 1, excl_w1);
1154 }
1155
1156 /* Sets the self exclusions i=j and pair exclusions i>j */
1157 static void set_self_and_newton_excls_supersub(nbnxn_pairlist_t *nbl,
1158                                                int cj4_ind, int sj_offset,
1159                                                int i_cluster_in_cell)
1160 {
1161     nbnxn_excl_t *excl[c_nbnxnGpuClusterpairSplit];
1162
1163     /* Here we only set the set self and double pair exclusions */
1164
1165     static_assert(c_nbnxnGpuClusterpairSplit == 2, "");
1166
1167     get_nbl_exclusions_2(nbl, cj4_ind, &excl[0], &excl[1]);
1168
1169     /* Only minor < major bits set */
1170     for (int ej = 0; ej < nbl->na_ci; ej++)
1171     {
1172         int w = (ej>>2);
1173         for (int ei = ej; ei < nbl->na_ci; ei++)
1174         {
1175             excl[w]->pair[(ej & (c_nbnxnGpuJgroupSize-1))*nbl->na_ci + ei] &=
1176                 ~(1U << (sj_offset*c_gpuNumClusterPerCell + i_cluster_in_cell));
1177         }
1178     }
1179 }
1180
1181 /* Returns a diagonal or off-diagonal interaction mask for plain C lists */
1182 static unsigned int get_imask(gmx_bool rdiag, int ci, int cj)
1183 {
1184     return (rdiag && ci == cj ? NBNXN_INTERACTION_MASK_DIAG : NBNXN_INTERACTION_MASK_ALL);
1185 }
1186
1187 /* Returns a diagonal or off-diagonal interaction mask for cj-size=2 */
1188 gmx_unused static unsigned int get_imask_simd_j2(gmx_bool rdiag, int ci, int cj)
1189 {
1190     return (rdiag && ci*2 == cj ? NBNXN_INTERACTION_MASK_DIAG_J2_0 :
1191             (rdiag && ci*2+1 == cj ? NBNXN_INTERACTION_MASK_DIAG_J2_1 :
1192              NBNXN_INTERACTION_MASK_ALL));
1193 }
1194
1195 /* Returns a diagonal or off-diagonal interaction mask for cj-size=4 */
1196 gmx_unused static unsigned int get_imask_simd_j4(gmx_bool rdiag, int ci, int cj)
1197 {
1198     return (rdiag && ci == cj ? NBNXN_INTERACTION_MASK_DIAG : NBNXN_INTERACTION_MASK_ALL);
1199 }
1200
1201 /* Returns a diagonal or off-diagonal interaction mask for cj-size=8 */
1202 gmx_unused static unsigned int get_imask_simd_j8(gmx_bool rdiag, int ci, int cj)
1203 {
1204     return (rdiag && ci == cj*2 ? NBNXN_INTERACTION_MASK_DIAG_J8_0 :
1205             (rdiag && ci == cj*2+1 ? NBNXN_INTERACTION_MASK_DIAG_J8_1 :
1206              NBNXN_INTERACTION_MASK_ALL));
1207 }
1208
1209 #if GMX_SIMD
1210 #if GMX_SIMD_REAL_WIDTH == 2
1211 #define get_imask_simd_4xn  get_imask_simd_j2
1212 #endif
1213 #if GMX_SIMD_REAL_WIDTH == 4
1214 #define get_imask_simd_4xn  get_imask_simd_j4
1215 #endif
1216 #if GMX_SIMD_REAL_WIDTH == 8
1217 #define get_imask_simd_4xn  get_imask_simd_j8
1218 #define get_imask_simd_2xnn get_imask_simd_j4
1219 #endif
1220 #if GMX_SIMD_REAL_WIDTH == 16
1221 #define get_imask_simd_2xnn get_imask_simd_j8
1222 #endif
1223 #endif
1224
1225 /* Plain C code for checking and adding cluster-pairs to the list.
1226  *
1227  * \param[in]     gridj               The j-grid
1228  * \param[in,out] nbl                 The pair-list to store the cluster pairs in
1229  * \param[in]     icluster            The index of the i-cluster
1230  * \param[in]     jclusterFirst       The first cluster in the j-range
1231  * \param[in]     jclusterLast        The last cluster in the j-range
1232  * \param[in]     excludeSubDiagonal  Exclude atom pairs with i-index > j-index
1233  * \param[in]     x_j                 Coordinates for the j-atom, in xyz format
1234  * \param[in]     rlist2              The squared list cut-off
1235  * \param[in]     rbb2                The squared cut-off for putting cluster-pairs in the list based on bounding box distance only
1236  * \param[in,out] numDistanceChecks   The number of distance checks performed
1237  */
1238 static void
1239 makeClusterListSimple(const nbnxn_grid_t *      gridj,
1240                       nbnxn_pairlist_t *        nbl,
1241                       int                       icluster,
1242                       int                       jclusterFirst,
1243                       int                       jclusterLast,
1244                       bool                      excludeSubDiagonal,
1245                       const real * gmx_restrict x_j,
1246                       real                      rlist2,
1247                       float                     rbb2,
1248                       int * gmx_restrict        numDistanceChecks)
1249 {
1250     const nbnxn_bb_t * gmx_restrict bb_ci = nbl->work->bb_ci;
1251     const real * gmx_restrict       x_ci  = nbl->work->x_ci;
1252
1253     gmx_bool                        InRange;
1254
1255     InRange = FALSE;
1256     while (!InRange && jclusterFirst <= jclusterLast)
1257     {
1258         real d2  = subc_bb_dist2(0, bb_ci, jclusterFirst, gridj->bb);
1259         *numDistanceChecks += 2;
1260
1261         /* Check if the distance is within the distance where
1262          * we use only the bounding box distance rbb,
1263          * or within the cut-off and there is at least one atom pair
1264          * within the cut-off.
1265          */
1266         if (d2 < rbb2)
1267         {
1268             InRange = TRUE;
1269         }
1270         else if (d2 < rlist2)
1271         {
1272             int cjf_gl = gridj->cell0 + jclusterFirst;
1273             for (int i = 0; i < NBNXN_CPU_CLUSTER_I_SIZE && !InRange; i++)
1274             {
1275                 for (int j = 0; j < NBNXN_CPU_CLUSTER_I_SIZE; j++)
1276                 {
1277                     InRange = InRange ||
1278                         (gmx::square(x_ci[i*STRIDE_XYZ+XX] - x_j[(cjf_gl*NBNXN_CPU_CLUSTER_I_SIZE+j)*STRIDE_XYZ+XX]) +
1279                          gmx::square(x_ci[i*STRIDE_XYZ+YY] - x_j[(cjf_gl*NBNXN_CPU_CLUSTER_I_SIZE+j)*STRIDE_XYZ+YY]) +
1280                          gmx::square(x_ci[i*STRIDE_XYZ+ZZ] - x_j[(cjf_gl*NBNXN_CPU_CLUSTER_I_SIZE+j)*STRIDE_XYZ+ZZ]) < rlist2);
1281                 }
1282             }
1283             *numDistanceChecks += NBNXN_CPU_CLUSTER_I_SIZE*NBNXN_CPU_CLUSTER_I_SIZE;
1284         }
1285         if (!InRange)
1286         {
1287             jclusterFirst++;
1288         }
1289     }
1290     if (!InRange)
1291     {
1292         return;
1293     }
1294
1295     InRange = FALSE;
1296     while (!InRange && jclusterLast > jclusterFirst)
1297     {
1298         real d2  = subc_bb_dist2(0, bb_ci, jclusterLast, gridj->bb);
1299         *numDistanceChecks += 2;
1300
1301         /* Check if the distance is within the distance where
1302          * we use only the bounding box distance rbb,
1303          * or within the cut-off and there is at least one atom pair
1304          * within the cut-off.
1305          */
1306         if (d2 < rbb2)
1307         {
1308             InRange = TRUE;
1309         }
1310         else if (d2 < rlist2)
1311         {
1312             int cjl_gl = gridj->cell0 + jclusterLast;
1313             for (int i = 0; i < NBNXN_CPU_CLUSTER_I_SIZE && !InRange; i++)
1314             {
1315                 for (int j = 0; j < NBNXN_CPU_CLUSTER_I_SIZE; j++)
1316                 {
1317                     InRange = InRange ||
1318                         (gmx::square(x_ci[i*STRIDE_XYZ+XX] - x_j[(cjl_gl*NBNXN_CPU_CLUSTER_I_SIZE+j)*STRIDE_XYZ+XX]) +
1319                          gmx::square(x_ci[i*STRIDE_XYZ+YY] - x_j[(cjl_gl*NBNXN_CPU_CLUSTER_I_SIZE+j)*STRIDE_XYZ+YY]) +
1320                          gmx::square(x_ci[i*STRIDE_XYZ+ZZ] - x_j[(cjl_gl*NBNXN_CPU_CLUSTER_I_SIZE+j)*STRIDE_XYZ+ZZ]) < rlist2);
1321                 }
1322             }
1323             *numDistanceChecks += NBNXN_CPU_CLUSTER_I_SIZE*NBNXN_CPU_CLUSTER_I_SIZE;
1324         }
1325         if (!InRange)
1326         {
1327             jclusterLast--;
1328         }
1329     }
1330
1331     if (jclusterFirst <= jclusterLast)
1332     {
1333         for (int jcluster = jclusterFirst; jcluster <= jclusterLast; jcluster++)
1334         {
1335             /* Store cj and the interaction mask */
1336             nbl->cj[nbl->ncj].cj   = gridj->cell0 + jcluster;
1337             nbl->cj[nbl->ncj].excl = get_imask(excludeSubDiagonal, icluster, jcluster);
1338             nbl->ncj++;
1339         }
1340         /* Increase the closing index in i super-cell list */
1341         nbl->ci[nbl->nci].cj_ind_end = nbl->ncj;
1342     }
1343 }
1344
1345 #ifdef GMX_NBNXN_SIMD_4XN
1346 #include "gromacs/mdlib/nbnxn_search_simd_4xn.h"
1347 #endif
1348 #ifdef GMX_NBNXN_SIMD_2XNN
1349 #include "gromacs/mdlib/nbnxn_search_simd_2xnn.h"
1350 #endif
1351
1352 /* Plain C or SIMD4 code for making a pair list of super-cell sci vs scj.
1353  * Checks bounding box distances and possibly atom pair distances.
1354  */
1355 static void make_cluster_list_supersub(const nbnxn_grid_t *gridi,
1356                                        const nbnxn_grid_t *gridj,
1357                                        nbnxn_pairlist_t *nbl,
1358                                        int sci, int scj,
1359                                        gmx_bool sci_equals_scj,
1360                                        int stride, const real *x,
1361                                        real rlist2, float rbb2,
1362                                        int *numDistanceChecks)
1363 {
1364     nbnxn_list_work_t *work   = nbl->work;
1365
1366 #if NBNXN_BBXXXX
1367     const float       *pbb_ci = work->pbb_ci;
1368 #else
1369     const nbnxn_bb_t  *bb_ci  = work->bb_ci;
1370 #endif
1371
1372     assert(c_nbnxnGpuClusterSize == gridi->na_c);
1373     assert(c_nbnxnGpuClusterSize == gridj->na_c);
1374
1375     /* We generate the pairlist mainly based on bounding-box distances
1376      * and do atom pair distance based pruning on the GPU.
1377      * Only if a j-group contains a single cluster-pair, we try to prune
1378      * that pair based on atom distances on the CPU to avoid empty j-groups.
1379      */
1380 #define PRUNE_LIST_CPU_ONE 1
1381 #define PRUNE_LIST_CPU_ALL 0
1382
1383 #if PRUNE_LIST_CPU_ONE
1384     int  ci_last = -1;
1385 #endif
1386
1387     float *d2l = work->d2;
1388
1389     for (int subc = 0; subc < gridj->nsubc[scj]; subc++)
1390     {
1391         int          cj4_ind   = nbl->work->cj_ind/c_nbnxnGpuJgroupSize;
1392         int          cj_offset = nbl->work->cj_ind - cj4_ind*c_nbnxnGpuJgroupSize;
1393         nbnxn_cj4_t *cj4       = &nbl->cj4[cj4_ind];
1394
1395         int          cj        = scj*c_gpuNumClusterPerCell + subc;
1396
1397         int          cj_gl     = gridj->cell0*c_gpuNumClusterPerCell + cj;
1398
1399         /* Initialize this j-subcell i-subcell list */
1400         cj4->cj[cj_offset] = cj_gl;
1401
1402         int ci1;
1403         if (sci_equals_scj)
1404         {
1405             ci1 = subc + 1;
1406         }
1407         else
1408         {
1409             ci1 = gridi->nsubc[sci];
1410         }
1411
1412 #if NBNXN_BBXXXX
1413         /* Determine all ci1 bb distances in one call with SIMD4 */
1414         subc_bb_dist2_simd4_xxxx(gridj->pbb.data() + (cj >> STRIDE_PBB_2LOG)*NNBSBB_XXXX + (cj & (STRIDE_PBB-1)),
1415                                  ci1, pbb_ci, d2l);
1416         *numDistanceChecks += c_nbnxnGpuClusterSize*2;
1417 #endif
1418
1419         int          npair = 0;
1420         unsigned int imask = 0;
1421         /* We use a fixed upper-bound instead of ci1 to help optimization */
1422         for (int ci = 0; ci < c_gpuNumClusterPerCell; ci++)
1423         {
1424             if (ci == ci1)
1425             {
1426                 break;
1427             }
1428
1429 #if !NBNXN_BBXXXX
1430             /* Determine the bb distance between ci and cj */
1431             d2l[ci]             = subc_bb_dist2(ci, bb_ci, cj, gridj->bb);
1432             *numDistanceChecks += 2;
1433 #endif
1434             float d2 = d2l[ci];
1435
1436 #if PRUNE_LIST_CPU_ALL
1437             /* Check if the distance is within the distance where
1438              * we use only the bounding box distance rbb,
1439              * or within the cut-off and there is at least one atom pair
1440              * within the cut-off. This check is very costly.
1441              */
1442             *numDistanceChecks += c_nbnxnGpuClusterSize*c_nbnxnGpuClusterSize;
1443             if (d2 < rbb2 ||
1444                 (d2 < rlist2 &&
1445                  clusterpair_in_range(work, ci, cj_gl, stride, x, rlist2)))
1446 #else
1447             /* Check if the distance between the two bounding boxes
1448              * in within the pair-list cut-off.
1449              */
1450             if (d2 < rlist2)
1451 #endif
1452             {
1453                 /* Flag this i-subcell to be taken into account */
1454                 imask |= (1U << (cj_offset*c_gpuNumClusterPerCell + ci));
1455
1456 #if PRUNE_LIST_CPU_ONE
1457                 ci_last = ci;
1458 #endif
1459
1460                 npair++;
1461             }
1462         }
1463
1464 #if PRUNE_LIST_CPU_ONE
1465         /* If we only found 1 pair, check if any atoms are actually
1466          * within the cut-off, so we could get rid of it.
1467          */
1468         if (npair == 1 && d2l[ci_last] >= rbb2 &&
1469             !clusterpair_in_range(work, ci_last, cj_gl, stride, x, rlist2))
1470         {
1471             imask &= ~(1U << (cj_offset*c_gpuNumClusterPerCell + ci_last));
1472             npair--;
1473         }
1474 #endif
1475
1476         if (npair > 0)
1477         {
1478             /* We have a useful sj entry, close it now */
1479
1480             /* Set the exclusions for the ci==sj entry.
1481              * Here we don't bother to check if this entry is actually flagged,
1482              * as it will nearly always be in the list.
1483              */
1484             if (sci_equals_scj)
1485             {
1486                 set_self_and_newton_excls_supersub(nbl, cj4_ind, cj_offset, subc);
1487             }
1488
1489             /* Copy the cluster interaction mask to the list */
1490             for (int w = 0; w < c_nbnxnGpuClusterpairSplit; w++)
1491             {
1492                 cj4->imei[w].imask |= imask;
1493             }
1494
1495             nbl->work->cj_ind++;
1496
1497             /* Keep the count */
1498             nbl->nci_tot += npair;
1499
1500             /* Increase the closing index in i super-cell list */
1501             nbl->sci[nbl->nsci].cj4_ind_end =
1502                 (nbl->work->cj_ind + c_nbnxnGpuJgroupSize - 1)/c_nbnxnGpuJgroupSize;
1503         }
1504     }
1505 }
1506
1507 /* Returns how many contiguous j-clusters we have starting in the i-list */
1508 template <typename CjListType>
1509 static int numContiguousJClusters(const int         cjIndexStart,
1510                                   const int         cjIndexEnd,
1511                                   const CjListType &cjList)
1512 {
1513     const int firstJCluster = nblCj(cjList, cjIndexStart);
1514
1515     int       numContiguous = 0;
1516
1517     while (cjIndexStart + numContiguous < cjIndexEnd &&
1518            nblCj(cjList, cjIndexStart + numContiguous) == firstJCluster + numContiguous)
1519     {
1520         numContiguous++;
1521     }
1522
1523     return numContiguous;
1524 }
1525
1526 /* Helper struct for efficient searching for excluded atoms in a j-list */
1527 struct JListRanges
1528 {
1529     /* Constructor */
1530     template <typename CjListType>
1531     JListRanges(int               cjIndexStart,
1532                 int               cjIndexEnd,
1533                 const CjListType &cjList);
1534
1535     int cjIndexStart; // The start index in the j-list
1536     int cjIndexEnd;   // The end index in the j-list
1537     int cjFirst;      // The j-cluster with index cjIndexStart
1538     int cjLast;       // The j-cluster with index cjIndexEnd-1
1539     int numDirect;    // Up to cjIndexStart+numDirect the j-clusters are cjFirst + the index offset
1540 };
1541
1542 template <typename CjListType>
1543 JListRanges::JListRanges(int               cjIndexStart,
1544                          int               cjIndexEnd,
1545                          const CjListType &cjList) :
1546     cjIndexStart(cjIndexStart),
1547     cjIndexEnd(cjIndexEnd)
1548 {
1549     GMX_ASSERT(cjIndexEnd > cjIndexStart, "JListRanges should only be called with non-empty lists");
1550
1551     cjFirst   = nblCj(cjList, cjIndexStart);
1552     cjLast    = nblCj(cjList, cjIndexEnd - 1);
1553
1554     /* Determine how many contiguous j-cells we have starting
1555      * from the first i-cell. This number can be used to directly
1556      * calculate j-cell indices for excluded atoms.
1557      */
1558     numDirect = numContiguousJClusters(cjIndexStart, cjIndexEnd, cjList);
1559 }
1560
1561 /* Return the index of \p jCluster in the given range or -1 when not present
1562  *
1563  * Note: This code is executed very often and therefore performance is
1564  *       important. It should be inlined and fully optimized.
1565  */
1566 template <typename CjListType>
1567 static inline int findJClusterInJList(int                jCluster,
1568                                       const JListRanges &ranges,
1569                                       const CjListType  &cjList)
1570 {
1571     int index;
1572
1573     if (jCluster < ranges.cjFirst + ranges.numDirect)
1574     {
1575         /* We can calculate the index directly using the offset */
1576         index = ranges.cjIndexStart + jCluster - ranges.cjFirst;
1577     }
1578     else
1579     {
1580         /* Search for jCluster using bisection */
1581         index           = -1;
1582         int rangeStart  = ranges.cjIndexStart + ranges.numDirect;
1583         int rangeEnd    = ranges.cjIndexEnd;
1584         int rangeMiddle;
1585         while (index == -1 && rangeStart < rangeEnd)
1586         {
1587             rangeMiddle = (rangeStart + rangeEnd) >> 1;
1588
1589             const int clusterMiddle = nblCj(cjList, rangeMiddle);
1590
1591             if (jCluster == clusterMiddle)
1592             {
1593                 index      = rangeMiddle;
1594             }
1595             else if (jCluster < clusterMiddle)
1596             {
1597                 rangeEnd   = rangeMiddle;
1598             }
1599             else
1600             {
1601                 rangeStart = rangeMiddle + 1;
1602             }
1603         }
1604     }
1605
1606     return index;
1607 }
1608
1609 /* Set all atom-pair exclusions for a simple type list i-entry
1610  *
1611  * Set all atom-pair exclusions from the topology stored in exclusions
1612  * as masks in the pair-list for simple list entry iEntry.
1613  */
1614 static void
1615 setExclusionsForSimpleIentry(const nbnxn_search   *nbs,
1616                              nbnxn_pairlist_t     *nbl,
1617                              gmx_bool              diagRemoved,
1618                              int                   na_cj_2log,
1619                              const nbnxn_ci_t     &iEntry,
1620                              const t_blocka       &exclusions)
1621 {
1622     if (iEntry.cj_ind_end == iEntry.cj_ind_start)
1623     {
1624         /* Empty list: no exclusions */
1625         return;
1626     }
1627
1628     const JListRanges        ranges(iEntry.cj_ind_start, iEntry.cj_ind_end, nbl->cj);
1629
1630     const int                iCluster = iEntry.ci;
1631
1632     gmx::ArrayRef<const int> cell = nbs->cell;
1633
1634     /* Loop over the atoms in the i-cluster */
1635     for (int i = 0; i < nbl->na_sc; i++)
1636     {
1637         const int iIndex = iCluster*nbl->na_sc + i;
1638         const int iAtom  = nbs->a[iIndex];
1639         if (iAtom >= 0)
1640         {
1641             /* Loop over the topology-based exclusions for this i-atom */
1642             for (int exclIndex = exclusions.index[iAtom]; exclIndex < exclusions.index[iAtom + 1]; exclIndex++)
1643             {
1644                 const int jAtom = exclusions.a[exclIndex];
1645
1646                 if (jAtom == iAtom)
1647                 {
1648                     /* The self exclusion are already set, save some time */
1649                     continue;
1650                 }
1651
1652                 /* Get the index of the j-atom in the nbnxn atom data */
1653                 const int jIndex = cell[jAtom];
1654
1655                 /* Without shifts we only calculate interactions j>i
1656                  * for one-way pair-lists.
1657                  */
1658                 if (diagRemoved && jIndex <= iIndex)
1659                 {
1660                     continue;
1661                 }
1662
1663                 const int jCluster = (jIndex >> na_cj_2log);
1664
1665                 /* Could the cluster se be in our list? */
1666                 if (jCluster >= ranges.cjFirst && jCluster <= ranges.cjLast)
1667                 {
1668                     const int index =
1669                         findJClusterInJList(jCluster, ranges, nbl->cj);
1670
1671                     if (index >= 0)
1672                     {
1673                         /* We found an exclusion, clear the corresponding
1674                          * interaction bit.
1675                          */
1676                         const int innerJ     = jIndex - (jCluster << na_cj_2log);
1677
1678                         nbl->cj[index].excl &= ~(1U << ((i << na_cj_2log) + innerJ));
1679                     }
1680                 }
1681             }
1682         }
1683     }
1684 }
1685
1686 /* Add a new i-entry to the FEP list and copy the i-properties */
1687 static inline void fep_list_new_nri_copy(t_nblist *nlist)
1688 {
1689     /* Add a new i-entry */
1690     nlist->nri++;
1691
1692     assert(nlist->nri < nlist->maxnri);
1693
1694     /* Duplicate the last i-entry, except for jindex, which continues */
1695     nlist->iinr[nlist->nri]   = nlist->iinr[nlist->nri-1];
1696     nlist->shift[nlist->nri]  = nlist->shift[nlist->nri-1];
1697     nlist->gid[nlist->nri]    = nlist->gid[nlist->nri-1];
1698     nlist->jindex[nlist->nri] = nlist->nrj;
1699 }
1700
1701 /* For load balancing of the free-energy lists over threads, we set
1702  * the maximum nrj size of an i-entry to 40. This leads to good
1703  * load balancing in the worst case scenario of a single perturbed
1704  * particle on 16 threads, while not introducing significant overhead.
1705  * Note that half of the perturbed pairs will anyhow end up in very small lists,
1706  * since non perturbed i-particles will see few perturbed j-particles).
1707  */
1708 const int max_nrj_fep = 40;
1709
1710 /* Exclude the perturbed pairs from the Verlet list. This is only done to avoid
1711  * singularities for overlapping particles (0/0), since the charges and
1712  * LJ parameters have been zeroed in the nbnxn data structure.
1713  * Simultaneously make a group pair list for the perturbed pairs.
1714  */
1715 static void make_fep_list(const nbnxn_search     *nbs,
1716                           const nbnxn_atomdata_t *nbat,
1717                           nbnxn_pairlist_t       *nbl,
1718                           gmx_bool                bDiagRemoved,
1719                           nbnxn_ci_t             *nbl_ci,
1720                           const nbnxn_grid_t     *gridi,
1721                           const nbnxn_grid_t     *gridj,
1722                           t_nblist               *nlist)
1723 {
1724     int      ci, cj_ind_start, cj_ind_end, cja, cjr;
1725     int      nri_max;
1726     int      ngid, gid_i = 0, gid_j, gid;
1727     int      egp_shift, egp_mask;
1728     int      gid_cj = 0;
1729     int      ind_i, ind_j, ai, aj;
1730     int      nri;
1731     gmx_bool bFEP_i, bFEP_i_all;
1732
1733     if (nbl_ci->cj_ind_end == nbl_ci->cj_ind_start)
1734     {
1735         /* Empty list */
1736         return;
1737     }
1738
1739     ci = nbl_ci->ci;
1740
1741     cj_ind_start = nbl_ci->cj_ind_start;
1742     cj_ind_end   = nbl_ci->cj_ind_end;
1743
1744     /* In worst case we have alternating energy groups
1745      * and create #atom-pair lists, which means we need the size
1746      * of a cluster pair (na_ci*na_cj) times the number of cj's.
1747      */
1748     nri_max = nbl->na_ci*nbl->na_cj*(cj_ind_end - cj_ind_start);
1749     if (nlist->nri + nri_max > nlist->maxnri)
1750     {
1751         nlist->maxnri = over_alloc_large(nlist->nri + nri_max);
1752         reallocate_nblist(nlist);
1753     }
1754
1755     ngid = nbat->nenergrp;
1756
1757     if (ngid*gridj->na_cj > gmx::index(sizeof(gid_cj)*8))
1758     {
1759         gmx_fatal(FARGS, "The Verlet scheme with %dx%d kernels and free-energy only supports up to %zu energy groups",
1760                   gridi->na_c, gridj->na_cj, (sizeof(gid_cj)*8)/gridj->na_cj);
1761     }
1762
1763     egp_shift = nbat->neg_2log;
1764     egp_mask  = (1<<nbat->neg_2log) - 1;
1765
1766     /* Loop over the atoms in the i sub-cell */
1767     bFEP_i_all = TRUE;
1768     for (int i = 0; i < nbl->na_ci; i++)
1769     {
1770         ind_i = ci*nbl->na_ci + i;
1771         ai    = nbs->a[ind_i];
1772         if (ai >= 0)
1773         {
1774             nri                  = nlist->nri;
1775             nlist->jindex[nri+1] = nlist->jindex[nri];
1776             nlist->iinr[nri]     = ai;
1777             /* The actual energy group pair index is set later */
1778             nlist->gid[nri]      = 0;
1779             nlist->shift[nri]    = nbl_ci->shift & NBNXN_CI_SHIFT;
1780
1781             bFEP_i = ((gridi->fep[ci - gridi->cell0] & (1 << i)) != 0u);
1782
1783             bFEP_i_all = bFEP_i_all && bFEP_i;
1784
1785             if (nlist->nrj + (cj_ind_end - cj_ind_start)*nbl->na_cj > nlist->maxnrj)
1786             {
1787                 nlist->maxnrj = over_alloc_small(nlist->nrj + (cj_ind_end - cj_ind_start)*nbl->na_cj);
1788                 srenew(nlist->jjnr,     nlist->maxnrj);
1789                 srenew(nlist->excl_fep, nlist->maxnrj);
1790             }
1791
1792             if (ngid > 1)
1793             {
1794                 gid_i = (nbat->energrp[ci] >> (egp_shift*i)) & egp_mask;
1795             }
1796
1797             for (int cj_ind = cj_ind_start; cj_ind < cj_ind_end; cj_ind++)
1798             {
1799                 unsigned int fep_cj;
1800
1801                 cja = nbl->cj[cj_ind].cj;
1802
1803                 if (gridj->na_cj == gridj->na_c)
1804                 {
1805                     cjr    = cja - gridj->cell0;
1806                     fep_cj = gridj->fep[cjr];
1807                     if (ngid > 1)
1808                     {
1809                         gid_cj = nbat->energrp[cja];
1810                     }
1811                 }
1812                 else if (2*gridj->na_cj == gridj->na_c)
1813                 {
1814                     cjr    = cja - gridj->cell0*2;
1815                     /* Extract half of the ci fep/energrp mask */
1816                     fep_cj = (gridj->fep[cjr>>1] >> ((cjr&1)*gridj->na_cj)) & ((1<<gridj->na_cj) - 1);
1817                     if (ngid > 1)
1818                     {
1819                         gid_cj = nbat->energrp[cja>>1] >> ((cja&1)*gridj->na_cj*egp_shift) & ((1<<(gridj->na_cj*egp_shift)) - 1);
1820                     }
1821                 }
1822                 else
1823                 {
1824                     cjr    = cja - (gridj->cell0>>1);
1825                     /* Combine two ci fep masks/energrp */
1826                     fep_cj = gridj->fep[cjr*2] + (gridj->fep[cjr*2+1] << gridj->na_c);
1827                     if (ngid > 1)
1828                     {
1829                         gid_cj = nbat->energrp[cja*2] + (nbat->energrp[cja*2+1] << (gridj->na_c*egp_shift));
1830                     }
1831                 }
1832
1833                 if (bFEP_i || fep_cj != 0)
1834                 {
1835                     for (int j = 0; j < nbl->na_cj; j++)
1836                     {
1837                         /* Is this interaction perturbed and not excluded? */
1838                         ind_j = cja*nbl->na_cj + j;
1839                         aj    = nbs->a[ind_j];
1840                         if (aj >= 0 &&
1841                             (bFEP_i || (fep_cj & (1 << j))) &&
1842                             (!bDiagRemoved || ind_j >= ind_i))
1843                         {
1844                             if (ngid > 1)
1845                             {
1846                                 gid_j = (gid_cj >> (j*egp_shift)) & egp_mask;
1847                                 gid   = GID(gid_i, gid_j, ngid);
1848
1849                                 if (nlist->nrj > nlist->jindex[nri] &&
1850                                     nlist->gid[nri] != gid)
1851                                 {
1852                                     /* Energy group pair changed: new list */
1853                                     fep_list_new_nri_copy(nlist);
1854                                     nri = nlist->nri;
1855                                 }
1856                                 nlist->gid[nri] = gid;
1857                             }
1858
1859                             if (nlist->nrj - nlist->jindex[nri] >= max_nrj_fep)
1860                             {
1861                                 fep_list_new_nri_copy(nlist);
1862                                 nri = nlist->nri;
1863                             }
1864
1865                             /* Add it to the FEP list */
1866                             nlist->jjnr[nlist->nrj]     = aj;
1867                             nlist->excl_fep[nlist->nrj] = (nbl->cj[cj_ind].excl >> (i*nbl->na_cj + j)) & 1;
1868                             nlist->nrj++;
1869
1870                             /* Exclude it from the normal list.
1871                              * Note that the charge has been set to zero,
1872                              * but we need to avoid 0/0, as perturbed atoms
1873                              * can be on top of each other.
1874                              */
1875                             nbl->cj[cj_ind].excl &= ~(1U << (i*nbl->na_cj + j));
1876                         }
1877                     }
1878                 }
1879             }
1880
1881             if (nlist->nrj > nlist->jindex[nri])
1882             {
1883                 /* Actually add this new, non-empty, list */
1884                 nlist->nri++;
1885                 nlist->jindex[nlist->nri] = nlist->nrj;
1886             }
1887         }
1888     }
1889
1890     if (bFEP_i_all)
1891     {
1892         /* All interactions are perturbed, we can skip this entry */
1893         nbl_ci->cj_ind_end = cj_ind_start;
1894         nbl->ncjInUse     -= cj_ind_end - cj_ind_start;
1895     }
1896 }
1897
1898 /* Return the index of atom a within a cluster */
1899 static inline int cj_mod_cj4(int cj)
1900 {
1901     return cj & (c_nbnxnGpuJgroupSize - 1);
1902 }
1903
1904 /* Convert a j-cluster to a cj4 group */
1905 static inline int cj_to_cj4(int cj)
1906 {
1907     return cj/c_nbnxnGpuJgroupSize;
1908 }
1909
1910 /* Return the index of an j-atom within a warp */
1911 static inline int a_mod_wj(int a)
1912 {
1913     return a & (c_nbnxnGpuClusterSize/c_nbnxnGpuClusterpairSplit - 1);
1914 }
1915
1916 /* As make_fep_list above, but for super/sub lists. */
1917 static void make_fep_list_supersub(const nbnxn_search     *nbs,
1918                                    const nbnxn_atomdata_t *nbat,
1919                                    nbnxn_pairlist_t       *nbl,
1920                                    gmx_bool                bDiagRemoved,
1921                                    const nbnxn_sci_t      *nbl_sci,
1922                                    real                    shx,
1923                                    real                    shy,
1924                                    real                    shz,
1925                                    real                    rlist_fep2,
1926                                    const nbnxn_grid_t     *gridi,
1927                                    const nbnxn_grid_t     *gridj,
1928                                    t_nblist               *nlist)
1929 {
1930     int                sci, cj4_ind_start, cj4_ind_end, cjr;
1931     int                nri_max;
1932     int                c_abs;
1933     int                ind_i, ind_j, ai, aj;
1934     int                nri;
1935     gmx_bool           bFEP_i;
1936     real               xi, yi, zi;
1937     const nbnxn_cj4_t *cj4;
1938
1939     if (nbl_sci->cj4_ind_end == nbl_sci->cj4_ind_start)
1940     {
1941         /* Empty list */
1942         return;
1943     }
1944
1945     sci = nbl_sci->sci;
1946
1947     cj4_ind_start = nbl_sci->cj4_ind_start;
1948     cj4_ind_end   = nbl_sci->cj4_ind_end;
1949
1950     /* Here we process one super-cell, max #atoms na_sc, versus a list
1951      * cj4 entries, each with max c_nbnxnGpuJgroupSize cj's, each
1952      * of size na_cj atoms.
1953      * On the GPU we don't support energy groups (yet).
1954      * So for each of the na_sc i-atoms, we need max one FEP list
1955      * for each max_nrj_fep j-atoms.
1956      */
1957     nri_max = nbl->na_sc*nbl->na_cj*(1 + ((cj4_ind_end - cj4_ind_start)*c_nbnxnGpuJgroupSize)/max_nrj_fep);
1958     if (nlist->nri + nri_max > nlist->maxnri)
1959     {
1960         nlist->maxnri = over_alloc_large(nlist->nri + nri_max);
1961         reallocate_nblist(nlist);
1962     }
1963
1964     /* Loop over the atoms in the i super-cluster */
1965     for (int c = 0; c < c_gpuNumClusterPerCell; c++)
1966     {
1967         c_abs = sci*c_gpuNumClusterPerCell + c;
1968
1969         for (int i = 0; i < nbl->na_ci; i++)
1970         {
1971             ind_i = c_abs*nbl->na_ci + i;
1972             ai    = nbs->a[ind_i];
1973             if (ai >= 0)
1974             {
1975                 nri                  = nlist->nri;
1976                 nlist->jindex[nri+1] = nlist->jindex[nri];
1977                 nlist->iinr[nri]     = ai;
1978                 /* With GPUs, energy groups are not supported */
1979                 nlist->gid[nri]      = 0;
1980                 nlist->shift[nri]    = nbl_sci->shift & NBNXN_CI_SHIFT;
1981
1982                 bFEP_i = ((gridi->fep[c_abs - gridi->cell0*c_gpuNumClusterPerCell] & (1 << i)) != 0u);
1983
1984                 xi = nbat->x[ind_i*nbat->xstride+XX] + shx;
1985                 yi = nbat->x[ind_i*nbat->xstride+YY] + shy;
1986                 zi = nbat->x[ind_i*nbat->xstride+ZZ] + shz;
1987
1988                 if ((nlist->nrj + cj4_ind_end - cj4_ind_start)*c_nbnxnGpuJgroupSize*nbl->na_cj > nlist->maxnrj)
1989                 {
1990                     nlist->maxnrj = over_alloc_small((nlist->nrj + cj4_ind_end - cj4_ind_start)*c_nbnxnGpuJgroupSize*nbl->na_cj);
1991                     srenew(nlist->jjnr,     nlist->maxnrj);
1992                     srenew(nlist->excl_fep, nlist->maxnrj);
1993                 }
1994
1995                 for (int cj4_ind = cj4_ind_start; cj4_ind < cj4_ind_end; cj4_ind++)
1996                 {
1997                     cj4 = &nbl->cj4[cj4_ind];
1998
1999                     for (int gcj = 0; gcj < c_nbnxnGpuJgroupSize; gcj++)
2000                     {
2001                         unsigned int fep_cj;
2002
2003                         if ((cj4->imei[0].imask & (1U << (gcj*c_gpuNumClusterPerCell + c))) == 0)
2004                         {
2005                             /* Skip this ci for this cj */
2006                             continue;
2007                         }
2008
2009                         cjr = cj4->cj[gcj] - gridj->cell0*c_gpuNumClusterPerCell;
2010
2011                         fep_cj = gridj->fep[cjr];
2012
2013                         if (bFEP_i || fep_cj != 0)
2014                         {
2015                             for (int j = 0; j < nbl->na_cj; j++)
2016                             {
2017                                 /* Is this interaction perturbed and not excluded? */
2018                                 ind_j = (gridj->cell0*c_gpuNumClusterPerCell + cjr)*nbl->na_cj + j;
2019                                 aj    = nbs->a[ind_j];
2020                                 if (aj >= 0 &&
2021                                     (bFEP_i || (fep_cj & (1 << j))) &&
2022                                     (!bDiagRemoved || ind_j >= ind_i))
2023                                 {
2024                                     nbnxn_excl_t *excl;
2025                                     int           excl_pair;
2026                                     unsigned int  excl_bit;
2027                                     real          dx, dy, dz;
2028
2029                                     const int     jHalf = j/(c_nbnxnGpuClusterSize/c_nbnxnGpuClusterpairSplit);
2030                                     get_nbl_exclusions_1(nbl, cj4_ind, jHalf, &excl);
2031
2032                                     excl_pair = a_mod_wj(j)*nbl->na_ci + i;
2033                                     excl_bit  = (1U << (gcj*c_gpuNumClusterPerCell + c));
2034
2035                                     dx = nbat->x[ind_j*nbat->xstride+XX] - xi;
2036                                     dy = nbat->x[ind_j*nbat->xstride+YY] - yi;
2037                                     dz = nbat->x[ind_j*nbat->xstride+ZZ] - zi;
2038
2039                                     /* The unpruned GPU list has more than 2/3
2040                                      * of the atom pairs beyond rlist. Using
2041                                      * this list will cause a lot of overhead
2042                                      * in the CPU FEP kernels, especially
2043                                      * relative to the fast GPU kernels.
2044                                      * So we prune the FEP list here.
2045                                      */
2046                                     if (dx*dx + dy*dy + dz*dz < rlist_fep2)
2047                                     {
2048                                         if (nlist->nrj - nlist->jindex[nri] >= max_nrj_fep)
2049                                         {
2050                                             fep_list_new_nri_copy(nlist);
2051                                             nri = nlist->nri;
2052                                         }
2053
2054                                         /* Add it to the FEP list */
2055                                         nlist->jjnr[nlist->nrj]     = aj;
2056                                         nlist->excl_fep[nlist->nrj] = (excl->pair[excl_pair] & excl_bit) ? 1 : 0;
2057                                         nlist->nrj++;
2058                                     }
2059
2060                                     /* Exclude it from the normal list.
2061                                      * Note that the charge and LJ parameters have
2062                                      * been set to zero, but we need to avoid 0/0,
2063                                      * as perturbed atoms can be on top of each other.
2064                                      */
2065                                     excl->pair[excl_pair] &= ~excl_bit;
2066                                 }
2067                             }
2068
2069                             /* Note that we could mask out this pair in imask
2070                              * if all i- and/or all j-particles are perturbed.
2071                              * But since the perturbed pairs on the CPU will
2072                              * take an order of magnitude more time, the GPU
2073                              * will finish before the CPU and there is no gain.
2074                              */
2075                         }
2076                     }
2077                 }
2078
2079                 if (nlist->nrj > nlist->jindex[nri])
2080                 {
2081                     /* Actually add this new, non-empty, list */
2082                     nlist->nri++;
2083                     nlist->jindex[nlist->nri] = nlist->nrj;
2084                 }
2085             }
2086         }
2087     }
2088 }
2089
2090 /* Set all atom-pair exclusions for a GPU type list i-entry
2091  *
2092  * Sets all atom-pair exclusions from the topology stored in exclusions
2093  * as masks in the pair-list for i-super-cluster list entry iEntry.
2094  */
2095 static void
2096 setExclusionsForGpuIentry(const nbnxn_search   *nbs,
2097                           nbnxn_pairlist_t     *nbl,
2098                           gmx_bool              diagRemoved,
2099                           const nbnxn_sci_t    &iEntry,
2100                           const t_blocka       &exclusions)
2101 {
2102     if (iEntry.cj4_ind_end == iEntry.cj4_ind_start)
2103     {
2104         /* Empty list */
2105         return;
2106     }
2107
2108     /* Set the search ranges using start and end j-cluster indices.
2109      * Note that here we can not use cj4_ind_end, since the last cj4
2110      * can be only partially filled, so we use cj_ind.
2111      */
2112     const JListRanges ranges(iEntry.cj4_ind_start*c_nbnxnGpuJgroupSize,
2113                              nbl->work->cj_ind,
2114                              nbl->cj4);
2115
2116     GMX_ASSERT(nbl->na_ci == c_nbnxnGpuClusterSize, "na_ci should match the GPU cluster size");
2117     constexpr int            c_clusterSize      = c_nbnxnGpuClusterSize;
2118     constexpr int            c_superClusterSize = c_nbnxnGpuNumClusterPerSupercluster*c_nbnxnGpuClusterSize;
2119
2120     const int                iSuperCluster = iEntry.sci;
2121
2122     gmx::ArrayRef<const int> cell = nbs->cell;
2123
2124     /* Loop over the atoms in the i super-cluster */
2125     for (int i = 0; i < c_superClusterSize; i++)
2126     {
2127         const int iIndex = iSuperCluster*c_superClusterSize + i;
2128         const int iAtom  = nbs->a[iIndex];
2129         if (iAtom >= 0)
2130         {
2131             const int iCluster = i/c_clusterSize;
2132
2133             /* Loop over the topology-based exclusions for this i-atom */
2134             for (int exclIndex = exclusions.index[iAtom]; exclIndex < exclusions.index[iAtom + 1]; exclIndex++)
2135             {
2136                 const int jAtom = exclusions.a[exclIndex];
2137
2138                 if (jAtom == iAtom)
2139                 {
2140                     /* The self exclusions are already set, save some time */
2141                     continue;
2142                 }
2143
2144                 /* Get the index of the j-atom in the nbnxn atom data */
2145                 const int jIndex = cell[jAtom];
2146
2147                 /* Without shifts we only calculate interactions j>i
2148                  * for one-way pair-lists.
2149                  */
2150                 /* NOTE: We would like to use iIndex on the right hand side,
2151                  * but that makes this routine 25% slower with gcc6/7.
2152                  * Even using c_superClusterSize makes it slower.
2153                  * Either of these changes triggers peeling of the exclIndex
2154                  * loop, which apparently leads to far less efficient code.
2155                  */
2156                 if (diagRemoved && jIndex <= iSuperCluster*nbl->na_sc + i)
2157                 {
2158                     continue;
2159                 }
2160
2161                 const int jCluster = jIndex/c_clusterSize;
2162
2163                 /* Check whether the cluster is in our list? */
2164                 if (jCluster >= ranges.cjFirst && jCluster <= ranges.cjLast)
2165                 {
2166                     const int index =
2167                         findJClusterInJList(jCluster, ranges, nbl->cj4);
2168
2169                     if (index >= 0)
2170                     {
2171                         /* We found an exclusion, clear the corresponding
2172                          * interaction bit.
2173                          */
2174                         const unsigned int pairMask = (1U << (cj_mod_cj4(index)*c_gpuNumClusterPerCell + iCluster));
2175                         /* Check if the i-cluster interacts with the j-cluster */
2176                         if (nbl_imask0(nbl, index) & pairMask)
2177                         {
2178                             const int innerI = (i      & (c_clusterSize - 1));
2179                             const int innerJ = (jIndex & (c_clusterSize - 1));
2180
2181                             /* Determine which j-half (CUDA warp) we are in */
2182                             const int     jHalf = innerJ/(c_clusterSize/c_nbnxnGpuClusterpairSplit);
2183
2184                             nbnxn_excl_t *interactionMask;
2185                             get_nbl_exclusions_1(nbl, cj_to_cj4(index), jHalf, &interactionMask);
2186
2187                             interactionMask->pair[a_mod_wj(innerJ)*c_clusterSize + innerI] &= ~pairMask;
2188                         }
2189                     }
2190                 }
2191             }
2192         }
2193     }
2194 }
2195
2196 /* Reallocate the simple ci list for at least n entries */
2197 static void nb_realloc_ci(nbnxn_pairlist_t *nbl, int n)
2198 {
2199     nbl->ci_nalloc = over_alloc_small(n);
2200     nbnxn_realloc_void(reinterpret_cast<void **>(&nbl->ci),
2201                        nbl->nci*sizeof(*nbl->ci),
2202                        nbl->ci_nalloc*sizeof(*nbl->ci),
2203                        nbl->alloc, nbl->free);
2204
2205     nbnxn_realloc_void(reinterpret_cast<void **>(&nbl->ciOuter),
2206                        nbl->nci*sizeof(*nbl->ciOuter),
2207                        nbl->ci_nalloc*sizeof(*nbl->ciOuter),
2208                        nbl->alloc, nbl->free);
2209 }
2210
2211 /* Reallocate the super-cell sci list for at least n entries */
2212 static void nb_realloc_sci(nbnxn_pairlist_t *nbl, int n)
2213 {
2214     nbl->sci_nalloc = over_alloc_small(n);
2215     nbnxn_realloc_void(reinterpret_cast<void **>(&nbl->sci),
2216                        nbl->nsci*sizeof(*nbl->sci),
2217                        nbl->sci_nalloc*sizeof(*nbl->sci),
2218                        nbl->alloc, nbl->free);
2219 }
2220
2221 /* Make a new ci entry at index nbl->nci */
2222 static void new_ci_entry(nbnxn_pairlist_t *nbl, int ci, int shift, int flags)
2223 {
2224     if (nbl->nci + 1 > nbl->ci_nalloc)
2225     {
2226         nb_realloc_ci(nbl, nbl->nci+1);
2227     }
2228     nbl->ci[nbl->nci].ci            = ci;
2229     nbl->ci[nbl->nci].shift         = shift;
2230     /* Store the interaction flags along with the shift */
2231     nbl->ci[nbl->nci].shift        |= flags;
2232     nbl->ci[nbl->nci].cj_ind_start  = nbl->ncj;
2233     nbl->ci[nbl->nci].cj_ind_end    = nbl->ncj;
2234 }
2235
2236 /* Make a new sci entry at index nbl->nsci */
2237 static void new_sci_entry(nbnxn_pairlist_t *nbl, int sci, int shift)
2238 {
2239     if (nbl->nsci + 1 > nbl->sci_nalloc)
2240     {
2241         nb_realloc_sci(nbl, nbl->nsci+1);
2242     }
2243     nbl->sci[nbl->nsci].sci           = sci;
2244     nbl->sci[nbl->nsci].shift         = shift;
2245     nbl->sci[nbl->nsci].cj4_ind_start = nbl->ncj4;
2246     nbl->sci[nbl->nsci].cj4_ind_end   = nbl->ncj4;
2247 }
2248
2249 /* Sort the simple j-list cj on exclusions.
2250  * Entries with exclusions will all be sorted to the beginning of the list.
2251  */
2252 static void sort_cj_excl(nbnxn_cj_t *cj, int ncj,
2253                          nbnxn_list_work_t *work)
2254 {
2255     int jnew;
2256
2257     if (ncj > work->cj_nalloc)
2258     {
2259         work->cj_nalloc = over_alloc_large(ncj);
2260         srenew(work->cj, work->cj_nalloc);
2261     }
2262
2263     /* Make a list of the j-cells involving exclusions */
2264     jnew = 0;
2265     for (int j = 0; j < ncj; j++)
2266     {
2267         if (cj[j].excl != NBNXN_INTERACTION_MASK_ALL)
2268         {
2269             work->cj[jnew++] = cj[j];
2270         }
2271     }
2272     /* Check if there are exclusions at all or not just the first entry */
2273     if (!((jnew == 0) ||
2274           (jnew == 1 && cj[0].excl != NBNXN_INTERACTION_MASK_ALL)))
2275     {
2276         for (int j = 0; j < ncj; j++)
2277         {
2278             if (cj[j].excl == NBNXN_INTERACTION_MASK_ALL)
2279             {
2280                 work->cj[jnew++] = cj[j];
2281             }
2282         }
2283         for (int j = 0; j < ncj; j++)
2284         {
2285             cj[j] = work->cj[j];
2286         }
2287     }
2288 }
2289
2290 /* Close this simple list i entry */
2291 static void close_ci_entry_simple(nbnxn_pairlist_t *nbl)
2292 {
2293     int jlen;
2294
2295     /* All content of the new ci entry have already been filled correctly,
2296      * we only need to increase the count here (for non empty lists).
2297      */
2298     jlen = nbl->ci[nbl->nci].cj_ind_end - nbl->ci[nbl->nci].cj_ind_start;
2299     if (jlen > 0)
2300     {
2301         sort_cj_excl(nbl->cj+nbl->ci[nbl->nci].cj_ind_start, jlen, nbl->work);
2302
2303         /* The counts below are used for non-bonded pair/flop counts
2304          * and should therefore match the available kernel setups.
2305          */
2306         if (!(nbl->ci[nbl->nci].shift & NBNXN_CI_DO_COUL(0)))
2307         {
2308             nbl->work->ncj_noq += jlen;
2309         }
2310         else if ((nbl->ci[nbl->nci].shift & NBNXN_CI_HALF_LJ(0)) ||
2311                  !(nbl->ci[nbl->nci].shift & NBNXN_CI_DO_LJ(0)))
2312         {
2313             nbl->work->ncj_hlj += jlen;
2314         }
2315
2316         nbl->nci++;
2317     }
2318 }
2319
2320 /* Split sci entry for load balancing on the GPU.
2321  * Splitting ensures we have enough lists to fully utilize the whole GPU.
2322  * With progBal we generate progressively smaller lists, which improves
2323  * load balancing. As we only know the current count on our own thread,
2324  * we will need to estimate the current total amount of i-entries.
2325  * As the lists get concatenated later, this estimate depends
2326  * both on nthread and our own thread index.
2327  */
2328 static void split_sci_entry(nbnxn_pairlist_t *nbl,
2329                             int nsp_target_av,
2330                             gmx_bool progBal, float nsp_tot_est,
2331                             int thread, int nthread)
2332 {
2333     int nsp_max;
2334     int cj4_start, cj4_end, j4len;
2335     int sci;
2336     int nsp, nsp_sci, nsp_cj4, nsp_cj4_e, nsp_cj4_p;
2337
2338     if (progBal)
2339     {
2340         float nsp_est;
2341
2342         /* Estimate the total numbers of ci's of the nblist combined
2343          * over all threads using the target number of ci's.
2344          */
2345         nsp_est = (nsp_tot_est*thread)/nthread + nbl->nci_tot;
2346
2347         /* The first ci blocks should be larger, to avoid overhead.
2348          * The last ci blocks should be smaller, to improve load balancing.
2349          * The factor 3/2 makes the first block 3/2 times the target average
2350          * and ensures that the total number of blocks end up equal to
2351          * that of equally sized blocks of size nsp_target_av.
2352          */
2353         nsp_max = static_cast<int>(nsp_target_av*(nsp_tot_est*1.5/(nsp_est + nsp_tot_est)));
2354     }
2355     else
2356     {
2357         nsp_max = nsp_target_av;
2358     }
2359
2360     cj4_start = nbl->sci[nbl->nsci-1].cj4_ind_start;
2361     cj4_end   = nbl->sci[nbl->nsci-1].cj4_ind_end;
2362     j4len     = cj4_end - cj4_start;
2363
2364     if (j4len > 1 && j4len*c_gpuNumClusterPerCell*c_nbnxnGpuJgroupSize > nsp_max)
2365     {
2366         /* Remove the last ci entry and process the cj4's again */
2367         nbl->nsci -= 1;
2368
2369         sci        = nbl->nsci;
2370         nsp        = 0;
2371         nsp_sci    = 0;
2372         nsp_cj4_e  = 0;
2373         nsp_cj4    = 0;
2374         for (int cj4 = cj4_start; cj4 < cj4_end; cj4++)
2375         {
2376             nsp_cj4_p = nsp_cj4;
2377             /* Count the number of cluster pairs in this cj4 group */
2378             nsp_cj4   = 0;
2379             for (int p = 0; p < c_gpuNumClusterPerCell*c_nbnxnGpuJgroupSize; p++)
2380             {
2381                 nsp_cj4 += (nbl->cj4[cj4].imei[0].imask >> p) & 1;
2382             }
2383
2384             /* If adding the current cj4 with nsp_cj4 pairs get us further
2385              * away from our target nsp_max, split the list before this cj4.
2386              */
2387             if (nsp > 0 && nsp_max - nsp < nsp + nsp_cj4 - nsp_max)
2388             {
2389                 /* Split the list at cj4 */
2390                 nbl->sci[sci].cj4_ind_end = cj4;
2391                 /* Create a new sci entry */
2392                 sci++;
2393                 nbl->nsci++;
2394                 if (nbl->nsci+1 > nbl->sci_nalloc)
2395                 {
2396                     nb_realloc_sci(nbl, nbl->nsci+1);
2397                 }
2398                 nbl->sci[sci].sci           = nbl->sci[nbl->nsci-1].sci;
2399                 nbl->sci[sci].shift         = nbl->sci[nbl->nsci-1].shift;
2400                 nbl->sci[sci].cj4_ind_start = cj4;
2401                 nsp_sci                     = nsp;
2402                 nsp_cj4_e                   = nsp_cj4_p;
2403                 nsp                         = 0;
2404             }
2405             nsp += nsp_cj4;
2406         }
2407
2408         /* Put the remaining cj4's in the last sci entry */
2409         nbl->sci[sci].cj4_ind_end = cj4_end;
2410
2411         /* Possibly balance out the last two sci's
2412          * by moving the last cj4 of the second last sci.
2413          */
2414         if (nsp_sci - nsp_cj4_e >= nsp + nsp_cj4_e)
2415         {
2416             nbl->sci[sci-1].cj4_ind_end--;
2417             nbl->sci[sci].cj4_ind_start--;
2418         }
2419
2420         nbl->nsci++;
2421     }
2422 }
2423
2424 /* Clost this super/sub list i entry */
2425 static void close_ci_entry_supersub(nbnxn_pairlist_t *nbl,
2426                                     int nsp_max_av,
2427                                     gmx_bool progBal, float nsp_tot_est,
2428                                     int thread, int nthread)
2429 {
2430     /* All content of the new ci entry have already been filled correctly,
2431      * we only need to increase the count here (for non empty lists).
2432      */
2433     int j4len = nbl->sci[nbl->nsci].cj4_ind_end - nbl->sci[nbl->nsci].cj4_ind_start;
2434     if (j4len > 0)
2435     {
2436         /* We can only have complete blocks of 4 j-entries in a list,
2437          * so round the count up before closing.
2438          */
2439         nbl->ncj4         = (nbl->work->cj_ind + c_nbnxnGpuJgroupSize - 1)/c_nbnxnGpuJgroupSize;
2440         nbl->work->cj_ind = nbl->ncj4*c_nbnxnGpuJgroupSize;
2441
2442         nbl->nsci++;
2443
2444         if (nsp_max_av > 0)
2445         {
2446             /* Measure the size of the new entry and potentially split it */
2447             split_sci_entry(nbl, nsp_max_av, progBal, nsp_tot_est,
2448                             thread, nthread);
2449         }
2450     }
2451 }
2452
2453 /* Syncs the working array before adding another grid pair to the list */
2454 static void sync_work(nbnxn_pairlist_t *nbl)
2455 {
2456     if (!nbl->bSimple)
2457     {
2458         nbl->work->cj_ind   = nbl->ncj4*c_nbnxnGpuJgroupSize;
2459         nbl->work->cj4_init = nbl->ncj4;
2460     }
2461 }
2462
2463 /* Clears an nbnxn_pairlist_t data structure */
2464 static void clear_pairlist(nbnxn_pairlist_t *nbl)
2465 {
2466     nbl->nci           = 0;
2467     nbl->nsci          = 0;
2468     nbl->ncj           = 0;
2469     nbl->ncjInUse      = 0;
2470     nbl->ncj4          = 0;
2471     nbl->nci_tot       = 0;
2472     nbl->nciOuter      = -1;
2473     nbl->nexcl         = 1;
2474
2475     nbl->work->ncj_noq = 0;
2476     nbl->work->ncj_hlj = 0;
2477 }
2478
2479 /* Clears a group scheme pair list */
2480 static void clear_pairlist_fep(t_nblist *nl)
2481 {
2482     nl->nri = 0;
2483     nl->nrj = 0;
2484     if (nl->jindex == nullptr)
2485     {
2486         snew(nl->jindex, 1);
2487     }
2488     nl->jindex[0] = 0;
2489 }
2490
2491 /* Sets a simple list i-cell bounding box, including PBC shift */
2492 static inline void set_icell_bb_simple(gmx::ArrayRef<const nbnxn_bb_t> bb,
2493                                        int ci,
2494                                        real shx, real shy, real shz,
2495                                        nbnxn_bb_t *bb_ci)
2496 {
2497     bb_ci->lower[BB_X] = bb[ci].lower[BB_X] + shx;
2498     bb_ci->lower[BB_Y] = bb[ci].lower[BB_Y] + shy;
2499     bb_ci->lower[BB_Z] = bb[ci].lower[BB_Z] + shz;
2500     bb_ci->upper[BB_X] = bb[ci].upper[BB_X] + shx;
2501     bb_ci->upper[BB_Y] = bb[ci].upper[BB_Y] + shy;
2502     bb_ci->upper[BB_Z] = bb[ci].upper[BB_Z] + shz;
2503 }
2504
2505 #if NBNXN_BBXXXX
2506 /* Sets a super-cell and sub cell bounding boxes, including PBC shift */
2507 static void set_icell_bbxxxx_supersub(gmx::ArrayRef<const float> bb,
2508                                       int ci,
2509                                       real shx, real shy, real shz,
2510                                       float *bb_ci)
2511 {
2512     int ia = ci*(c_gpuNumClusterPerCell >> STRIDE_PBB_2LOG)*NNBSBB_XXXX;
2513     for (int m = 0; m < (c_gpuNumClusterPerCell >> STRIDE_PBB_2LOG)*NNBSBB_XXXX; m += NNBSBB_XXXX)
2514     {
2515         for (int i = 0; i < STRIDE_PBB; i++)
2516         {
2517             bb_ci[m+0*STRIDE_PBB+i] = bb[ia+m+0*STRIDE_PBB+i] + shx;
2518             bb_ci[m+1*STRIDE_PBB+i] = bb[ia+m+1*STRIDE_PBB+i] + shy;
2519             bb_ci[m+2*STRIDE_PBB+i] = bb[ia+m+2*STRIDE_PBB+i] + shz;
2520             bb_ci[m+3*STRIDE_PBB+i] = bb[ia+m+3*STRIDE_PBB+i] + shx;
2521             bb_ci[m+4*STRIDE_PBB+i] = bb[ia+m+4*STRIDE_PBB+i] + shy;
2522             bb_ci[m+5*STRIDE_PBB+i] = bb[ia+m+5*STRIDE_PBB+i] + shz;
2523         }
2524     }
2525 }
2526 #endif
2527
2528 /* Sets a super-cell and sub cell bounding boxes, including PBC shift */
2529 gmx_unused static void set_icell_bb_supersub(gmx::ArrayRef<const nbnxn_bb_t> bb,
2530                                              int ci,
2531                                              real shx, real shy, real shz,
2532                                              nbnxn_bb_t *bb_ci)
2533 {
2534     for (int i = 0; i < c_gpuNumClusterPerCell; i++)
2535     {
2536         set_icell_bb_simple(bb, ci*c_gpuNumClusterPerCell+i,
2537                             shx, shy, shz,
2538                             &bb_ci[i]);
2539     }
2540 }
2541
2542 /* Copies PBC shifted i-cell atom coordinates x,y,z to working array */
2543 static void icell_set_x_simple(int ci,
2544                                real shx, real shy, real shz,
2545                                int stride, const real *x,
2546                                nbnxn_list_work_t *work)
2547 {
2548     int ia = ci*NBNXN_CPU_CLUSTER_I_SIZE;
2549
2550     for (int i = 0; i < NBNXN_CPU_CLUSTER_I_SIZE; i++)
2551     {
2552         work->x_ci[i*STRIDE_XYZ+XX] = x[(ia+i)*stride+XX] + shx;
2553         work->x_ci[i*STRIDE_XYZ+YY] = x[(ia+i)*stride+YY] + shy;
2554         work->x_ci[i*STRIDE_XYZ+ZZ] = x[(ia+i)*stride+ZZ] + shz;
2555     }
2556 }
2557
2558 /* Copies PBC shifted super-cell atom coordinates x,y,z to working array */
2559 static void icell_set_x_supersub(int ci,
2560                                  real shx, real shy, real shz,
2561                                  int stride, const real *x,
2562                                  nbnxn_list_work_t *work)
2563 {
2564 #if !GMX_SIMD4_HAVE_REAL
2565
2566     real * x_ci = work->x_ci;
2567
2568     int    ia = ci*c_gpuNumClusterPerCell*c_nbnxnGpuClusterSize;
2569     for (int i = 0; i < c_gpuNumClusterPerCell*c_nbnxnGpuClusterSize; i++)
2570     {
2571         x_ci[i*DIM + XX] = x[(ia+i)*stride + XX] + shx;
2572         x_ci[i*DIM + YY] = x[(ia+i)*stride + YY] + shy;
2573         x_ci[i*DIM + ZZ] = x[(ia+i)*stride + ZZ] + shz;
2574     }
2575
2576 #else /* !GMX_SIMD4_HAVE_REAL */
2577
2578     real * x_ci = work->x_ci_simd;
2579
2580     for (int si = 0; si < c_gpuNumClusterPerCell; si++)
2581     {
2582         for (int i = 0; i < c_nbnxnGpuClusterSize; i += GMX_SIMD4_WIDTH)
2583         {
2584             int io = si*c_nbnxnGpuClusterSize + i;
2585             int ia = ci*c_gpuNumClusterPerCell*c_nbnxnGpuClusterSize + io;
2586             for (int j = 0; j < GMX_SIMD4_WIDTH; j++)
2587             {
2588                 x_ci[io*DIM + j + XX*GMX_SIMD4_WIDTH] = x[(ia + j)*stride + XX] + shx;
2589                 x_ci[io*DIM + j + YY*GMX_SIMD4_WIDTH] = x[(ia + j)*stride + YY] + shy;
2590                 x_ci[io*DIM + j + ZZ*GMX_SIMD4_WIDTH] = x[(ia + j)*stride + ZZ] + shz;
2591             }
2592         }
2593     }
2594
2595 #endif /* !GMX_SIMD4_HAVE_REAL */
2596 }
2597
2598 static real minimum_subgrid_size_xy(const nbnxn_grid_t *grid)
2599 {
2600     if (grid->bSimple)
2601     {
2602         return std::min(grid->cellSize[XX], grid->cellSize[YY]);
2603     }
2604     else
2605     {
2606         return std::min(grid->cellSize[XX]/c_gpuNumClusterPerCellX,
2607                         grid->cellSize[YY]/c_gpuNumClusterPerCellY);
2608     }
2609 }
2610
2611 static real effective_buffer_1x1_vs_MxN(const nbnxn_grid_t *gridi,
2612                                         const nbnxn_grid_t *gridj)
2613 {
2614     const real eff_1x1_buffer_fac_overest = 0.1;
2615
2616     /* Determine an atom-pair list cut-off buffer size for atom pairs,
2617      * to be added to rlist (including buffer) used for MxN.
2618      * This is for converting an MxN list to a 1x1 list. This means we can't
2619      * use the normal buffer estimate, as we have an MxN list in which
2620      * some atom pairs beyond rlist are missing. We want to capture
2621      * the beneficial effect of buffering by extra pairs just outside rlist,
2622      * while removing the useless pairs that are further away from rlist.
2623      * (Also the buffer could have been set manually not using the estimate.)
2624      * This buffer size is an overestimate.
2625      * We add 10% of the smallest grid sub-cell dimensions.
2626      * Note that the z-size differs per cell and we don't use this,
2627      * so we overestimate.
2628      * With PME, the 10% value gives a buffer that is somewhat larger
2629      * than the effective buffer with a tolerance of 0.005 kJ/mol/ps.
2630      * Smaller tolerances or using RF lead to a smaller effective buffer,
2631      * so 10% gives a safe overestimate.
2632      */
2633     return eff_1x1_buffer_fac_overest*(minimum_subgrid_size_xy(gridi) +
2634                                        minimum_subgrid_size_xy(gridj));
2635 }
2636
2637 /* Clusters at the cut-off only increase rlist by 60% of their size */
2638 static real nbnxn_rlist_inc_outside_fac = 0.6;
2639
2640 /* Due to the cluster size the effective pair-list is longer than
2641  * that of a simple atom pair-list. This function gives the extra distance.
2642  */
2643 real nbnxn_get_rlist_effective_inc(int cluster_size_j, real atom_density)
2644 {
2645     int  cluster_size_i;
2646     real vol_inc_i, vol_inc_j;
2647
2648     /* We should get this from the setup, but currently it's the same for
2649      * all setups, including GPUs.
2650      */
2651     cluster_size_i = NBNXN_CPU_CLUSTER_I_SIZE;
2652
2653     vol_inc_i = (cluster_size_i - 1)/atom_density;
2654     vol_inc_j = (cluster_size_j - 1)/atom_density;
2655
2656     return nbnxn_rlist_inc_outside_fac*std::cbrt(vol_inc_i + vol_inc_j);
2657 }
2658
2659 /* Estimates the interaction volume^2 for non-local interactions */
2660 static real nonlocal_vol2(const struct gmx_domdec_zones_t *zones, const rvec ls, real r)
2661 {
2662     real cl, ca, za;
2663     real vold_est;
2664     real vol2_est_tot;
2665
2666     vol2_est_tot = 0;
2667
2668     /* Here we simply add up the volumes of 1, 2 or 3 1D decomposition
2669      * not home interaction volume^2. As these volumes are not additive,
2670      * this is an overestimate, but it would only be significant in the limit
2671      * of small cells, where we anyhow need to split the lists into
2672      * as small parts as possible.
2673      */
2674
2675     for (int z = 0; z < zones->n; z++)
2676     {
2677         if (zones->shift[z][XX] + zones->shift[z][YY] + zones->shift[z][ZZ] == 1)
2678         {
2679             cl = 0;
2680             ca = 1;
2681             za = 1;
2682             for (int d = 0; d < DIM; d++)
2683             {
2684                 if (zones->shift[z][d] == 0)
2685                 {
2686                     cl += 0.5*ls[d];
2687                     ca *= ls[d];
2688                     za *= zones->size[z].x1[d] - zones->size[z].x0[d];
2689                 }
2690             }
2691
2692             /* 4 octants of a sphere */
2693             vold_est  = 0.25*M_PI*r*r*r*r;
2694             /* 4 quarter pie slices on the edges */
2695             vold_est += 4*cl*M_PI/6.0*r*r*r;
2696             /* One rectangular volume on a face */
2697             vold_est += ca*0.5*r*r;
2698
2699             vol2_est_tot += vold_est*za;
2700         }
2701     }
2702
2703     return vol2_est_tot;
2704 }
2705
2706 /* Estimates the average size of a full j-list for super/sub setup */
2707 static void get_nsubpair_target(const nbnxn_search   *nbs,
2708                                 int                   iloc,
2709                                 real                  rlist,
2710                                 int                   min_ci_balanced,
2711                                 int                  *nsubpair_target,
2712                                 float                *nsubpair_tot_est)
2713 {
2714     /* The target value of 36 seems to be the optimum for Kepler.
2715      * Maxwell is less sensitive to the exact value.
2716      */
2717     const int           nsubpair_target_min = 36;
2718     const nbnxn_grid_t *grid;
2719     rvec                ls;
2720     real                r_eff_sup, vol_est, nsp_est, nsp_est_nl;
2721
2722     grid = &nbs->grid[0];
2723
2724     /* We don't need to balance list sizes if:
2725      * - We didn't request balancing.
2726      * - The number of grid cells >= the number of lists requested,
2727      *   since we will always generate at least #cells lists.
2728      * - We don't have any cells, since then there won't be any lists.
2729      */
2730     if (min_ci_balanced <= 0 || grid->nc >= min_ci_balanced || grid->nc == 0)
2731     {
2732         /* nsubpair_target==0 signals no balancing */
2733         *nsubpair_target  = 0;
2734         *nsubpair_tot_est = 0;
2735
2736         return;
2737     }
2738
2739     ls[XX] = (grid->c1[XX] - grid->c0[XX])/(grid->numCells[XX]*c_gpuNumClusterPerCellX);
2740     ls[YY] = (grid->c1[YY] - grid->c0[YY])/(grid->numCells[YY]*c_gpuNumClusterPerCellY);
2741     ls[ZZ] = grid->na_c/(grid->atom_density*ls[XX]*ls[YY]);
2742
2743     /* The average length of the diagonal of a sub cell */
2744     real diagonal = std::sqrt(ls[XX]*ls[XX] + ls[YY]*ls[YY] + ls[ZZ]*ls[ZZ]);
2745
2746     /* The formulas below are a heuristic estimate of the average nsj per si*/
2747     r_eff_sup = rlist + nbnxn_rlist_inc_outside_fac*gmx::square((grid->na_c - 1.0)/grid->na_c)*0.5*diagonal;
2748
2749     if (!nbs->DomDec || nbs->zones->n == 1)
2750     {
2751         nsp_est_nl = 0;
2752     }
2753     else
2754     {
2755         nsp_est_nl =
2756             gmx::square(grid->atom_density/grid->na_c)*
2757             nonlocal_vol2(nbs->zones, ls, r_eff_sup);
2758     }
2759
2760     if (LOCAL_I(iloc))
2761     {
2762         /* Sub-cell interacts with itself */
2763         vol_est  = ls[XX]*ls[YY]*ls[ZZ];
2764         /* 6/2 rectangular volume on the faces */
2765         vol_est += (ls[XX]*ls[YY] + ls[XX]*ls[ZZ] + ls[YY]*ls[ZZ])*r_eff_sup;
2766         /* 12/2 quarter pie slices on the edges */
2767         vol_est += 2*(ls[XX] + ls[YY] + ls[ZZ])*0.25*M_PI*gmx::square(r_eff_sup);
2768         /* 4 octants of a sphere */
2769         vol_est += 0.5*4.0/3.0*M_PI*gmx::power3(r_eff_sup);
2770
2771         /* Estimate the number of cluster pairs as the local number of
2772          * clusters times the volume they interact with times the density.
2773          */
2774         nsp_est = grid->nsubc_tot*vol_est*grid->atom_density/grid->na_c;
2775
2776         /* Subtract the non-local pair count */
2777         nsp_est -= nsp_est_nl;
2778
2779         /* For small cut-offs nsp_est will be an underesimate.
2780          * With DD nsp_est_nl is an overestimate so nsp_est can get negative.
2781          * So to avoid too small or negative nsp_est we set a minimum of
2782          * all cells interacting with all 3^3 direct neighbors (3^3-1)/2+1=14.
2783          * This might be a slight overestimate for small non-periodic groups of
2784          * atoms as will occur for a local domain with DD, but for small
2785          * groups of atoms we'll anyhow be limited by nsubpair_target_min,
2786          * so this overestimation will not matter.
2787          */
2788         nsp_est = std::max(nsp_est, grid->nsubc_tot*14._real);
2789
2790         if (debug)
2791         {
2792             fprintf(debug, "nsp_est local %5.1f non-local %5.1f\n",
2793                     nsp_est, nsp_est_nl);
2794         }
2795     }
2796     else
2797     {
2798         nsp_est = nsp_est_nl;
2799     }
2800
2801     /* Thus the (average) maximum j-list size should be as follows.
2802      * Since there is overhead, we shouldn't make the lists too small
2803      * (and we can't chop up j-groups) so we use a minimum target size of 36.
2804      */
2805     *nsubpair_target  = std::max(nsubpair_target_min,
2806                                  roundToInt(nsp_est/min_ci_balanced));
2807     *nsubpair_tot_est = static_cast<int>(nsp_est);
2808
2809     if (debug)
2810     {
2811         fprintf(debug, "nbl nsp estimate %.1f, nsubpair_target %d\n",
2812                 nsp_est, *nsubpair_target);
2813     }
2814 }
2815
2816 /* Debug list print function */
2817 static void print_nblist_ci_cj(FILE *fp, const nbnxn_pairlist_t *nbl)
2818 {
2819     for (int i = 0; i < nbl->nci; i++)
2820     {
2821         fprintf(fp, "ci %4d  shift %2d  ncj %3d\n",
2822                 nbl->ci[i].ci, nbl->ci[i].shift,
2823                 nbl->ci[i].cj_ind_end - nbl->ci[i].cj_ind_start);
2824
2825         for (int j = nbl->ci[i].cj_ind_start; j < nbl->ci[i].cj_ind_end; j++)
2826         {
2827             fprintf(fp, "  cj %5d  imask %x\n",
2828                     nbl->cj[j].cj,
2829                     nbl->cj[j].excl);
2830         }
2831     }
2832 }
2833
2834 /* Debug list print function */
2835 static void print_nblist_sci_cj(FILE *fp, const nbnxn_pairlist_t *nbl)
2836 {
2837     for (int i = 0; i < nbl->nsci; i++)
2838     {
2839         fprintf(fp, "ci %4d  shift %2d  ncj4 %2d\n",
2840                 nbl->sci[i].sci, nbl->sci[i].shift,
2841                 nbl->sci[i].cj4_ind_end - nbl->sci[i].cj4_ind_start);
2842
2843         int ncp = 0;
2844         for (int j4 = nbl->sci[i].cj4_ind_start; j4 < nbl->sci[i].cj4_ind_end; j4++)
2845         {
2846             for (int j = 0; j < c_nbnxnGpuJgroupSize; j++)
2847             {
2848                 fprintf(fp, "  sj %5d  imask %x\n",
2849                         nbl->cj4[j4].cj[j],
2850                         nbl->cj4[j4].imei[0].imask);
2851                 for (int si = 0; si < c_gpuNumClusterPerCell; si++)
2852                 {
2853                     if (nbl->cj4[j4].imei[0].imask & (1U << (j*c_gpuNumClusterPerCell + si)))
2854                     {
2855                         ncp++;
2856                     }
2857                 }
2858             }
2859         }
2860         fprintf(fp, "ci %4d  shift %2d  ncj4 %2d ncp %3d\n",
2861                 nbl->sci[i].sci, nbl->sci[i].shift,
2862                 nbl->sci[i].cj4_ind_end - nbl->sci[i].cj4_ind_start,
2863                 ncp);
2864     }
2865 }
2866
2867 /* Combine pair lists *nbl generated on multiple threads nblc */
2868 static void combine_nblists(int nnbl, nbnxn_pairlist_t **nbl,
2869                             nbnxn_pairlist_t *nblc)
2870 {
2871     int nsci, ncj4, nexcl;
2872
2873     if (nblc->bSimple)
2874     {
2875         gmx_incons("combine_nblists does not support simple lists");
2876     }
2877
2878     nsci  = nblc->nsci;
2879     ncj4  = nblc->ncj4;
2880     nexcl = nblc->nexcl;
2881     for (int i = 0; i < nnbl; i++)
2882     {
2883         nsci  += nbl[i]->nsci;
2884         ncj4  += nbl[i]->ncj4;
2885         nexcl += nbl[i]->nexcl;
2886     }
2887
2888     if (nsci > nblc->sci_nalloc)
2889     {
2890         nb_realloc_sci(nblc, nsci);
2891     }
2892     if (ncj4 > nblc->cj4_nalloc)
2893     {
2894         nblc->cj4_nalloc = over_alloc_small(ncj4);
2895         nbnxn_realloc_void(reinterpret_cast<void **>(&nblc->cj4),
2896                            nblc->ncj4*sizeof(*nblc->cj4),
2897                            nblc->cj4_nalloc*sizeof(*nblc->cj4),
2898                            nblc->alloc, nblc->free);
2899     }
2900     if (nexcl > nblc->excl_nalloc)
2901     {
2902         nblc->excl_nalloc = over_alloc_small(nexcl);
2903         nbnxn_realloc_void(reinterpret_cast<void **>(&nblc->excl),
2904                            nblc->nexcl*sizeof(*nblc->excl),
2905                            nblc->excl_nalloc*sizeof(*nblc->excl),
2906                            nblc->alloc, nblc->free);
2907     }
2908
2909     /* Each thread should copy its own data to the combined arrays,
2910      * as otherwise data will go back and forth between different caches.
2911      */
2912 #if GMX_OPENMP && !(defined __clang_analyzer__)
2913     int nthreads = gmx_omp_nthreads_get(emntPairsearch);
2914 #endif
2915
2916 #pragma omp parallel for num_threads(nthreads) schedule(static)
2917     for (int n = 0; n < nnbl; n++)
2918     {
2919         try
2920         {
2921             int                     sci_offset;
2922             int                     cj4_offset;
2923             int                     excl_offset;
2924             const nbnxn_pairlist_t *nbli;
2925
2926             /* Determine the offset in the combined data for our thread */
2927             sci_offset  = nblc->nsci;
2928             cj4_offset  = nblc->ncj4;
2929             excl_offset = nblc->nexcl;
2930
2931             for (int i = 0; i < n; i++)
2932             {
2933                 sci_offset  += nbl[i]->nsci;
2934                 cj4_offset  += nbl[i]->ncj4;
2935                 excl_offset += nbl[i]->nexcl;
2936             }
2937
2938             nbli = nbl[n];
2939
2940             for (int i = 0; i < nbli->nsci; i++)
2941             {
2942                 nblc->sci[sci_offset+i]                = nbli->sci[i];
2943                 nblc->sci[sci_offset+i].cj4_ind_start += cj4_offset;
2944                 nblc->sci[sci_offset+i].cj4_ind_end   += cj4_offset;
2945             }
2946
2947             for (int j4 = 0; j4 < nbli->ncj4; j4++)
2948             {
2949                 nblc->cj4[cj4_offset+j4]                   = nbli->cj4[j4];
2950                 nblc->cj4[cj4_offset+j4].imei[0].excl_ind += excl_offset;
2951                 nblc->cj4[cj4_offset+j4].imei[1].excl_ind += excl_offset;
2952             }
2953
2954             for (int j4 = 0; j4 < nbli->nexcl; j4++)
2955             {
2956                 nblc->excl[excl_offset+j4] = nbli->excl[j4];
2957             }
2958         }
2959         GMX_CATCH_ALL_AND_EXIT_WITH_FATAL_ERROR;
2960     }
2961
2962     for (int n = 0; n < nnbl; n++)
2963     {
2964         nblc->nsci    += nbl[n]->nsci;
2965         nblc->ncj4    += nbl[n]->ncj4;
2966         nblc->nci_tot += nbl[n]->nci_tot;
2967         nblc->nexcl   += nbl[n]->nexcl;
2968     }
2969 }
2970
2971 static void balance_fep_lists(const nbnxn_search   *nbs,
2972                               nbnxn_pairlist_set_t *nbl_lists)
2973 {
2974     int       nnbl;
2975     int       nri_tot, nrj_tot, nrj_target;
2976     int       th_dest;
2977     t_nblist *nbld;
2978
2979     nnbl = nbl_lists->nnbl;
2980
2981     if (nnbl == 1)
2982     {
2983         /* Nothing to balance */
2984         return;
2985     }
2986
2987     /* Count the total i-lists and pairs */
2988     nri_tot = 0;
2989     nrj_tot = 0;
2990     for (int th = 0; th < nnbl; th++)
2991     {
2992         nri_tot += nbl_lists->nbl_fep[th]->nri;
2993         nrj_tot += nbl_lists->nbl_fep[th]->nrj;
2994     }
2995
2996     nrj_target = (nrj_tot + nnbl - 1)/nnbl;
2997
2998     assert(gmx_omp_nthreads_get(emntNonbonded) == nnbl);
2999
3000 #pragma omp parallel for schedule(static) num_threads(nnbl)
3001     for (int th = 0; th < nnbl; th++)
3002     {
3003         try
3004         {
3005             t_nblist *nbl = nbs->work[th].nbl_fep.get();
3006
3007             /* Note that here we allocate for the total size, instead of
3008              * a per-thread esimate (which is hard to obtain).
3009              */
3010             if (nri_tot > nbl->maxnri)
3011             {
3012                 nbl->maxnri = over_alloc_large(nri_tot);
3013                 reallocate_nblist(nbl);
3014             }
3015             if (nri_tot > nbl->maxnri || nrj_tot > nbl->maxnrj)
3016             {
3017                 nbl->maxnrj = over_alloc_small(nrj_tot);
3018                 srenew(nbl->jjnr, nbl->maxnrj);
3019                 srenew(nbl->excl_fep, nbl->maxnrj);
3020             }
3021
3022             clear_pairlist_fep(nbl);
3023         }
3024         GMX_CATCH_ALL_AND_EXIT_WITH_FATAL_ERROR;
3025     }
3026
3027     /* Loop over the source lists and assign and copy i-entries */
3028     th_dest = 0;
3029     nbld    = nbs->work[th_dest].nbl_fep.get();
3030     for (int th = 0; th < nnbl; th++)
3031     {
3032         t_nblist *nbls;
3033
3034         nbls = nbl_lists->nbl_fep[th];
3035
3036         for (int i = 0; i < nbls->nri; i++)
3037         {
3038             int nrj;
3039
3040             /* The number of pairs in this i-entry */
3041             nrj = nbls->jindex[i+1] - nbls->jindex[i];
3042
3043             /* Decide if list th_dest is too large and we should procede
3044              * to the next destination list.
3045              */
3046             if (th_dest+1 < nnbl && nbld->nrj > 0 &&
3047                 nbld->nrj + nrj - nrj_target > nrj_target - nbld->nrj)
3048             {
3049                 th_dest++;
3050                 nbld = nbs->work[th_dest].nbl_fep.get();
3051             }
3052
3053             nbld->iinr[nbld->nri]  = nbls->iinr[i];
3054             nbld->gid[nbld->nri]   = nbls->gid[i];
3055             nbld->shift[nbld->nri] = nbls->shift[i];
3056
3057             for (int j = nbls->jindex[i]; j < nbls->jindex[i+1]; j++)
3058             {
3059                 nbld->jjnr[nbld->nrj]     = nbls->jjnr[j];
3060                 nbld->excl_fep[nbld->nrj] = nbls->excl_fep[j];
3061                 nbld->nrj++;
3062             }
3063             nbld->nri++;
3064             nbld->jindex[nbld->nri] = nbld->nrj;
3065         }
3066     }
3067
3068     /* Swap the list pointers */
3069     for (int th = 0; th < nnbl; th++)
3070     {
3071         t_nblist *nbl_tmp      = nbs->work[th].nbl_fep.release();
3072         nbs->work[th].nbl_fep.reset(nbl_lists->nbl_fep[th]);
3073         nbl_lists->nbl_fep[th] = nbl_tmp;
3074
3075         if (debug)
3076         {
3077             fprintf(debug, "nbl_fep[%d] nri %4d nrj %4d\n",
3078                     th,
3079                     nbl_lists->nbl_fep[th]->nri,
3080                     nbl_lists->nbl_fep[th]->nrj);
3081         }
3082     }
3083 }
3084
3085 /* Returns the next ci to be processes by our thread */
3086 static gmx_bool next_ci(const nbnxn_grid_t *grid,
3087                         int nth, int ci_block,
3088                         int *ci_x, int *ci_y,
3089                         int *ci_b, int *ci)
3090 {
3091     (*ci_b)++;
3092     (*ci)++;
3093
3094     if (*ci_b == ci_block)
3095     {
3096         /* Jump to the next block assigned to this task */
3097         *ci   += (nth - 1)*ci_block;
3098         *ci_b  = 0;
3099     }
3100
3101     if (*ci >= grid->nc)
3102     {
3103         return FALSE;
3104     }
3105
3106     while (*ci >= grid->cxy_ind[*ci_x*grid->numCells[YY] + *ci_y + 1])
3107     {
3108         *ci_y += 1;
3109         if (*ci_y == grid->numCells[YY])
3110         {
3111             *ci_x += 1;
3112             *ci_y  = 0;
3113         }
3114     }
3115
3116     return TRUE;
3117 }
3118
3119 /* Returns the distance^2 for which we put cell pairs in the list
3120  * without checking atom pair distances. This is usually < rlist^2.
3121  */
3122 static float boundingbox_only_distance2(const nbnxn_grid_t *gridi,
3123                                         const nbnxn_grid_t *gridj,
3124                                         real                rlist,
3125                                         gmx_bool            simple)
3126 {
3127     /* If the distance between two sub-cell bounding boxes is less
3128      * than this distance, do not check the distance between
3129      * all particle pairs in the sub-cell, since then it is likely
3130      * that the box pair has atom pairs within the cut-off.
3131      * We use the nblist cut-off minus 0.5 times the average x/y diagonal
3132      * spacing of the sub-cells. Around 40% of the checked pairs are pruned.
3133      * Using more than 0.5 gains at most 0.5%.
3134      * If forces are calculated more than twice, the performance gain
3135      * in the force calculation outweighs the cost of checking.
3136      * Note that with subcell lists, the atom-pair distance check
3137      * is only performed when only 1 out of 8 sub-cells in within range,
3138      * this is because the GPU is much faster than the cpu.
3139      */
3140     real bbx, bby;
3141     real rbb2;
3142
3143     bbx = 0.5*(gridi->cellSize[XX] + gridj->cellSize[XX]);
3144     bby = 0.5*(gridi->cellSize[YY] + gridj->cellSize[YY]);
3145     if (!simple)
3146     {
3147         bbx /= c_gpuNumClusterPerCellX;
3148         bby /= c_gpuNumClusterPerCellY;
3149     }
3150
3151     rbb2 = std::max(0.0, rlist - 0.5*std::sqrt(bbx*bbx + bby*bby));
3152     rbb2 = rbb2 * rbb2;
3153
3154 #if !GMX_DOUBLE
3155     return rbb2;
3156 #else
3157     return (float)((1+GMX_FLOAT_EPS)*rbb2);
3158 #endif
3159 }
3160
3161 static int get_ci_block_size(const nbnxn_grid_t *gridi,
3162                              gmx_bool bDomDec, int nth)
3163 {
3164     const int ci_block_enum      = 5;
3165     const int ci_block_denom     = 11;
3166     const int ci_block_min_atoms = 16;
3167     int       ci_block;
3168
3169     /* Here we decide how to distribute the blocks over the threads.
3170      * We use prime numbers to try to avoid that the grid size becomes
3171      * a multiple of the number of threads, which would lead to some
3172      * threads getting "inner" pairs and others getting boundary pairs,
3173      * which in turns will lead to load imbalance between threads.
3174      * Set the block size as 5/11/ntask times the average number of cells
3175      * in a y,z slab. This should ensure a quite uniform distribution
3176      * of the grid parts of the different thread along all three grid
3177      * zone boundaries with 3D domain decomposition. At the same time
3178      * the blocks will not become too small.
3179      */
3180     ci_block = (gridi->nc*ci_block_enum)/(ci_block_denom*gridi->numCells[XX]*nth);
3181
3182     /* Ensure the blocks are not too small: avoids cache invalidation */
3183     if (ci_block*gridi->na_sc < ci_block_min_atoms)
3184     {
3185         ci_block = (ci_block_min_atoms + gridi->na_sc - 1)/gridi->na_sc;
3186     }
3187
3188     /* Without domain decomposition
3189      * or with less than 3 blocks per task, divide in nth blocks.
3190      */
3191     if (!bDomDec || nth*3*ci_block > gridi->nc)
3192     {
3193         ci_block = (gridi->nc + nth - 1)/nth;
3194     }
3195
3196     if (ci_block > 1 && (nth - 1)*ci_block >= gridi->nc)
3197     {
3198         /* Some threads have no work. Although reducing the block size
3199          * does not decrease the block count on the first few threads,
3200          * with GPUs better mixing of "upper" cells that have more empty
3201          * clusters results in a somewhat lower max load over all threads.
3202          * Without GPUs the regime of so few atoms per thread is less
3203          * performance relevant, but with 8-wide SIMD the same reasoning
3204          * applies, since the pair list uses 4 i-atom "sub-clusters".
3205          */
3206         ci_block--;
3207     }
3208
3209     return ci_block;
3210 }
3211
3212 /* Returns the number of bits to right-shift a cluster index to obtain
3213  * the corresponding force buffer flag index.
3214  */
3215 static int getBufferFlagShift(int numAtomsPerCluster)
3216 {
3217     int bufferFlagShift = 0;
3218     while ((numAtomsPerCluster << bufferFlagShift) < NBNXN_BUFFERFLAG_SIZE)
3219     {
3220         bufferFlagShift++;
3221     }
3222
3223     return bufferFlagShift;
3224 }
3225
3226 /* Generates the part of pair-list nbl assigned to our thread */
3227 static void nbnxn_make_pairlist_part(const nbnxn_search *nbs,
3228                                      const nbnxn_grid_t *gridi,
3229                                      const nbnxn_grid_t *gridj,
3230                                      nbnxn_search_work_t *work,
3231                                      const nbnxn_atomdata_t *nbat,
3232                                      const t_blocka &exclusions,
3233                                      real rlist,
3234                                      int nb_kernel_type,
3235                                      int ci_block,
3236                                      gmx_bool bFBufferFlag,
3237                                      int nsubpair_max,
3238                                      gmx_bool progBal,
3239                                      float nsubpair_tot_est,
3240                                      int th, int nth,
3241                                      nbnxn_pairlist_t *nbl,
3242                                      t_nblist *nbl_fep)
3243 {
3244     int               na_cj_2log;
3245     matrix            box;
3246     real              rlist2, rl_fep2 = 0;
3247     float             rbb2;
3248     int               ci_b, ci, ci_x, ci_y, ci_xy, cj;
3249     ivec              shp;
3250     int               shift;
3251     real              shx, shy, shz;
3252     real              bx0, bx1, by0, by1, bz0, bz1;
3253     real              bz1_frac;
3254     real              d2cx, d2z, d2z_cx, d2z_cy, d2zx, d2zxy, d2xy;
3255     int               cxf, cxl, cyf, cyf_x, cyl;
3256     int               numDistanceChecks;
3257     int               gridi_flag_shift = 0, gridj_flag_shift = 0;
3258     gmx_bitmask_t    *gridj_flag       = nullptr;
3259     int               ncj_old_i, ncj_old_j;
3260
3261     nbs_cycle_start(&work->cc[enbsCCsearch]);
3262
3263     if (gridj->bSimple != nbl->bSimple || gridi->bSimple != nbl->bSimple)
3264     {
3265         gmx_incons("Grid incompatible with pair-list");
3266     }
3267
3268     sync_work(nbl);
3269     nbl->na_sc = gridj->na_sc;
3270     nbl->na_ci = gridj->na_c;
3271     nbl->na_cj = nbnxn_kernel_to_cluster_j_size(nb_kernel_type);
3272     na_cj_2log = get_2log(nbl->na_cj);
3273
3274     nbl->rlist  = rlist;
3275
3276     if (bFBufferFlag)
3277     {
3278         /* Determine conversion of clusters to flag blocks */
3279         gridi_flag_shift = getBufferFlagShift(nbl->na_ci);
3280         gridj_flag_shift = getBufferFlagShift(nbl->na_cj);
3281
3282         gridj_flag       = work->buffer_flags.flag;
3283     }
3284
3285     copy_mat(nbs->box, box);
3286
3287     rlist2 = nbl->rlist*nbl->rlist;
3288
3289     if (nbs->bFEP && !nbl->bSimple)
3290     {
3291         /* Determine an atom-pair list cut-off distance for FEP atom pairs.
3292          * We should not simply use rlist, since then we would not have
3293          * the small, effective buffering of the NxN lists.
3294          * The buffer is on overestimate, but the resulting cost for pairs
3295          * beyond rlist is neglible compared to the FEP pairs within rlist.
3296          */
3297         rl_fep2 = nbl->rlist + effective_buffer_1x1_vs_MxN(gridi, gridj);
3298
3299         if (debug)
3300         {
3301             fprintf(debug, "nbl_fep atom-pair rlist %f\n", rl_fep2);
3302         }
3303         rl_fep2 = rl_fep2*rl_fep2;
3304     }
3305
3306     rbb2 = boundingbox_only_distance2(gridi, gridj, nbl->rlist, nbl->bSimple);
3307
3308     if (debug)
3309     {
3310         fprintf(debug, "nbl bounding box only distance %f\n", std::sqrt(rbb2));
3311     }
3312
3313     /* Set the shift range */
3314     for (int d = 0; d < DIM; d++)
3315     {
3316         /* Check if we need periodicity shifts.
3317          * Without PBC or with domain decomposition we don't need them.
3318          */
3319         if (d >= ePBC2npbcdim(nbs->ePBC) || nbs->dd_dim[d])
3320         {
3321             shp[d] = 0;
3322         }
3323         else
3324         {
3325             const real listRangeCellToCell = listRangeForGridCellToGridCell(rlist, *gridi, *gridj);
3326             if (d == XX &&
3327                 box[XX][XX] - fabs(box[YY][XX]) - fabs(box[ZZ][XX]) < listRangeCellToCell)
3328             {
3329                 shp[d] = 2;
3330             }
3331             else
3332             {
3333                 shp[d] = 1;
3334             }
3335         }
3336     }
3337     const bool bSimple = nbl->bSimple;
3338     gmx::ArrayRef<const nbnxn_bb_t> bb_i;
3339 #if NBNXN_BBXXXX
3340     gmx::ArrayRef<const float>      pbb_i;
3341     if (bSimple)
3342     {
3343         bb_i  = gridi->bb;
3344     }
3345     else
3346     {
3347         pbb_i = gridi->pbb;
3348     }
3349 #else
3350     /* We use the normal bounding box format for both grid types */
3351     bb_i  = gridi->bb;
3352 #endif
3353     gmx::ArrayRef<const float> bbcz_i  = gridi->bbcz;
3354     gmx::ArrayRef<const int>   flags_i = gridi->flags;
3355     gmx::ArrayRef<const float> bbcz_j  = gridj->bbcz;
3356     int                        cell0_i = gridi->cell0;
3357
3358     if (debug)
3359     {
3360         fprintf(debug, "nbl nc_i %d col.av. %.1f ci_block %d\n",
3361                 gridi->nc, gridi->nc/static_cast<double>(gridi->numCells[XX]*gridi->numCells[YY]), ci_block);
3362     }
3363
3364     numDistanceChecks = 0;
3365
3366     const real listRangeBBToJCell2 = gmx::square(listRangeForBoundingBoxToGridCell(rlist, *gridj));
3367
3368     /* Initially ci_b and ci to 1 before where we want them to start,
3369      * as they will both be incremented in next_ci.
3370      */
3371     ci_b = -1;
3372     ci   = th*ci_block - 1;
3373     ci_x = 0;
3374     ci_y = 0;
3375     while (next_ci(gridi, nth, ci_block, &ci_x, &ci_y, &ci_b, &ci))
3376     {
3377         if (bSimple && flags_i[ci] == 0)
3378         {
3379             continue;
3380         }
3381
3382         ncj_old_i = nbl->ncj;
3383
3384         d2cx = 0;
3385         if (gridj != gridi && shp[XX] == 0)
3386         {
3387             if (bSimple)
3388             {
3389                 bx1 = bb_i[ci].upper[BB_X];
3390             }
3391             else
3392             {
3393                 bx1 = gridi->c0[XX] + (ci_x+1)*gridi->cellSize[XX];
3394             }
3395             if (bx1 < gridj->c0[XX])
3396             {
3397                 d2cx = gmx::square(gridj->c0[XX] - bx1);
3398
3399                 if (d2cx >= listRangeBBToJCell2)
3400                 {
3401                     continue;
3402                 }
3403             }
3404         }
3405
3406         ci_xy = ci_x*gridi->numCells[YY] + ci_y;
3407
3408         /* Loop over shift vectors in three dimensions */
3409         for (int tz = -shp[ZZ]; tz <= shp[ZZ]; tz++)
3410         {
3411             shz = tz*box[ZZ][ZZ];
3412
3413             bz0 = bbcz_i[ci*NNBSBB_D  ] + shz;
3414             bz1 = bbcz_i[ci*NNBSBB_D+1] + shz;
3415
3416             if (tz == 0)
3417             {
3418                 d2z = 0;
3419             }
3420             else if (tz < 0)
3421             {
3422                 d2z = gmx::square(bz1);
3423             }
3424             else
3425             {
3426                 d2z = gmx::square(bz0 - box[ZZ][ZZ]);
3427             }
3428
3429             d2z_cx = d2z + d2cx;
3430
3431             if (d2z_cx >= rlist2)
3432             {
3433                 continue;
3434             }
3435
3436             bz1_frac = bz1/(gridi->cxy_ind[ci_xy+1] - gridi->cxy_ind[ci_xy]);
3437             if (bz1_frac < 0)
3438             {
3439                 bz1_frac = 0;
3440             }
3441             /* The check with bz1_frac close to or larger than 1 comes later */
3442
3443             for (int ty = -shp[YY]; ty <= shp[YY]; ty++)
3444             {
3445                 shy = ty*box[YY][YY] + tz*box[ZZ][YY];
3446
3447                 if (bSimple)
3448                 {
3449                     by0 = bb_i[ci].lower[BB_Y] + shy;
3450                     by1 = bb_i[ci].upper[BB_Y] + shy;
3451                 }
3452                 else
3453                 {
3454                     by0 = gridi->c0[YY] + (ci_y  )*gridi->cellSize[YY] + shy;
3455                     by1 = gridi->c0[YY] + (ci_y+1)*gridi->cellSize[YY] + shy;
3456                 }
3457
3458                 get_cell_range<YY>(by0, by1,
3459                                    *gridj,
3460                                    d2z_cx, rlist,
3461                                    &cyf, &cyl);
3462
3463                 if (cyf > cyl)
3464                 {
3465                     continue;
3466                 }
3467
3468                 d2z_cy = d2z;
3469                 if (by1 < gridj->c0[YY])
3470                 {
3471                     d2z_cy += gmx::square(gridj->c0[YY] - by1);
3472                 }
3473                 else if (by0 > gridj->c1[YY])
3474                 {
3475                     d2z_cy += gmx::square(by0 - gridj->c1[YY]);
3476                 }
3477
3478                 for (int tx = -shp[XX]; tx <= shp[XX]; tx++)
3479                 {
3480                     shift = XYZ2IS(tx, ty, tz);
3481
3482                     if (c_pbcShiftBackward && gridi == gridj && shift > CENTRAL)
3483                     {
3484                         continue;
3485                     }
3486
3487                     shx = tx*box[XX][XX] + ty*box[YY][XX] + tz*box[ZZ][XX];
3488
3489                     if (bSimple)
3490                     {
3491                         bx0 = bb_i[ci].lower[BB_X] + shx;
3492                         bx1 = bb_i[ci].upper[BB_X] + shx;
3493                     }
3494                     else
3495                     {
3496                         bx0 = gridi->c0[XX] + (ci_x  )*gridi->cellSize[XX] + shx;
3497                         bx1 = gridi->c0[XX] + (ci_x+1)*gridi->cellSize[XX] + shx;
3498                     }
3499
3500                     get_cell_range<XX>(bx0, bx1,
3501                                        *gridj,
3502                                        d2z_cy, rlist,
3503                                        &cxf, &cxl);
3504
3505                     if (cxf > cxl)
3506                     {
3507                         continue;
3508                     }
3509
3510                     if (bSimple)
3511                     {
3512                         new_ci_entry(nbl, cell0_i+ci, shift, flags_i[ci]);
3513                     }
3514                     else
3515                     {
3516                         new_sci_entry(nbl, cell0_i+ci, shift);
3517                     }
3518
3519                     if ((!c_pbcShiftBackward || (shift == CENTRAL &&
3520                                                  gridi == gridj)) &&
3521                         cxf < ci_x)
3522                     {
3523                         /* Leave the pairs with i > j.
3524                          * x is the major index, so skip half of it.
3525                          */
3526                         cxf = ci_x;
3527                     }
3528
3529                     if (bSimple)
3530                     {
3531                         set_icell_bb_simple(bb_i, ci, shx, shy, shz,
3532                                             nbl->work->bb_ci);
3533                     }
3534                     else
3535                     {
3536 #if NBNXN_BBXXXX
3537                         set_icell_bbxxxx_supersub(pbb_i, ci, shx, shy, shz,
3538                                                   nbl->work->pbb_ci);
3539 #else
3540                         set_icell_bb_supersub(bb_i, ci, shx, shy, shz,
3541                                               nbl->work->bb_ci);
3542 #endif
3543                     }
3544
3545                     nbs->icell_set_x(cell0_i+ci, shx, shy, shz,
3546                                      nbat->xstride, nbat->x,
3547                                      nbl->work);
3548
3549                     for (int cx = cxf; cx <= cxl; cx++)
3550                     {
3551                         d2zx = d2z;
3552                         if (gridj->c0[XX] + cx*gridj->cellSize[XX] > bx1)
3553                         {
3554                             d2zx += gmx::square(gridj->c0[XX] + cx*gridj->cellSize[XX] - bx1);
3555                         }
3556                         else if (gridj->c0[XX] + (cx+1)*gridj->cellSize[XX] < bx0)
3557                         {
3558                             d2zx += gmx::square(gridj->c0[XX] + (cx+1)*gridj->cellSize[XX] - bx0);
3559                         }
3560
3561                         if (gridi == gridj &&
3562                             cx == 0 &&
3563                             (!c_pbcShiftBackward || shift == CENTRAL) &&
3564                             cyf < ci_y)
3565                         {
3566                             /* Leave the pairs with i > j.
3567                              * Skip half of y when i and j have the same x.
3568                              */
3569                             cyf_x = ci_y;
3570                         }
3571                         else
3572                         {
3573                             cyf_x = cyf;
3574                         }
3575
3576                         for (int cy = cyf_x; cy <= cyl; cy++)
3577                         {
3578                             const int columnStart = gridj->cxy_ind[cx*gridj->numCells[YY] + cy];
3579                             const int columnEnd   = gridj->cxy_ind[cx*gridj->numCells[YY] + cy + 1];
3580
3581                             d2zxy = d2zx;
3582                             if (gridj->c0[YY] + cy*gridj->cellSize[YY] > by1)
3583                             {
3584                                 d2zxy += gmx::square(gridj->c0[YY] + cy*gridj->cellSize[YY] - by1);
3585                             }
3586                             else if (gridj->c0[YY] + (cy+1)*gridj->cellSize[YY] < by0)
3587                             {
3588                                 d2zxy += gmx::square(gridj->c0[YY] + (cy+1)*gridj->cellSize[YY] - by0);
3589                             }
3590                             if (columnStart < columnEnd && d2zxy < listRangeBBToJCell2)
3591                             {
3592                                 /* To improve efficiency in the common case
3593                                  * of a homogeneous particle distribution,
3594                                  * we estimate the index of the middle cell
3595                                  * in range (midCell). We search down and up
3596                                  * starting from this index.
3597                                  *
3598                                  * Note that the bbcz_j array contains bounds
3599                                  * for i-clusters, thus for clusters of 4 atoms.
3600                                  * For the common case where the j-cluster size
3601                                  * is 8, we could step with a stride of 2,
3602                                  * but we do not do this because it would
3603                                  * complicate this code even more.
3604                                  */
3605                                 int midCell = columnStart + static_cast<int>(bz1_frac*(columnEnd - columnStart));
3606                                 if (midCell >= columnEnd)
3607                                 {
3608                                     midCell = columnEnd - 1;
3609                                 }
3610
3611                                 d2xy = d2zxy - d2z;
3612
3613                                 /* Find the lowest cell that can possibly
3614                                  * be within range.
3615                                  * Check if we hit the bottom of the grid,
3616                                  * if the j-cell is below the i-cell and if so,
3617                                  * if it is within range.
3618                                  */
3619                                 int downTestCell = midCell;
3620                                 while (downTestCell >= columnStart &&
3621                                        (bbcz_j[downTestCell*NNBSBB_D + 1] >= bz0 ||
3622                                         d2xy + gmx::square(bbcz_j[downTestCell*NNBSBB_D + 1] - bz0) < rlist2))
3623                                 {
3624                                     downTestCell--;
3625                                 }
3626                                 int firstCell = downTestCell + 1;
3627
3628                                 /* Find the highest cell that can possibly
3629                                  * be within range.
3630                                  * Check if we hit the top of the grid,
3631                                  * if the j-cell is above the i-cell and if so,
3632                                  * if it is within range.
3633                                  */
3634                                 int upTestCell = midCell + 1;
3635                                 while (upTestCell < columnEnd &&
3636                                        (bbcz_j[upTestCell*NNBSBB_D] <= bz1 ||
3637                                         d2xy + gmx::square(bbcz_j[upTestCell*NNBSBB_D] - bz1) < rlist2))
3638                                 {
3639                                     upTestCell++;
3640                                 }
3641                                 int lastCell = upTestCell - 1;
3642
3643 #define NBNXN_REFCODE 0
3644 #if NBNXN_REFCODE
3645                                 {
3646                                     /* Simple reference code, for debugging,
3647                                      * overrides the more complex code above.
3648                                      */
3649                                     firstCell = columnEnd;
3650                                     lastCell  = -1;
3651                                     for (int k = columnStart; k < columnEnd; k++)
3652                                     {
3653                                         if (d2xy + gmx::square(bbcz_j[k*NNBSBB_D + 1] - bz0) < rlist2 &&
3654                                             k < firstCell)
3655                                         {
3656                                             firstCell = k;
3657                                         }
3658                                         if (d2xy + gmx::square(bbcz_j[k*NNBSBB_D] - bz1) < rlist2 &&
3659                                             k > lastCell)
3660                                         {
3661                                             lastCell = k;
3662                                         }
3663                                     }
3664                                 }
3665 #endif
3666
3667                                 if (gridi == gridj)
3668                                 {
3669                                     /* We want each atom/cell pair only once,
3670                                      * only use cj >= ci.
3671                                      */
3672                                     if (!c_pbcShiftBackward || shift == CENTRAL)
3673                                     {
3674                                         firstCell = std::max(firstCell, ci);
3675                                     }
3676                                 }
3677
3678                                 if (firstCell <= lastCell)
3679                                 {
3680                                     GMX_ASSERT(firstCell >= columnStart && lastCell < columnEnd, "The range should reside within the current grid column");
3681
3682                                     /* For f buffer flags with simple lists */
3683                                     ncj_old_j = nbl->ncj;
3684
3685                                     if (bSimple)
3686                                     {
3687                                         /* We have a maximum of 2 j-clusters
3688                                          * per i-cluster sized cell.
3689                                          */
3690                                         check_cell_list_space_simple(nbl, 2*(lastCell - firstCell + 1));
3691                                     }
3692                                     else
3693                                     {
3694                                         check_cell_list_space_supersub(nbl, lastCell - firstCell + 1);
3695                                     }
3696
3697                                     switch (nb_kernel_type)
3698                                     {
3699                                         case nbnxnk4x4_PlainC:
3700                                             makeClusterListSimple(gridj,
3701                                                                   nbl, ci, firstCell, lastCell,
3702                                                                   (gridi == gridj && shift == CENTRAL),
3703                                                                   nbat->x,
3704                                                                   rlist2, rbb2,
3705                                                                   &numDistanceChecks);
3706                                             break;
3707 #ifdef GMX_NBNXN_SIMD_4XN
3708                                         case nbnxnk4xN_SIMD_4xN:
3709                                             makeClusterListSimd4xn(gridj,
3710                                                                    nbl, ci, firstCell, lastCell,
3711                                                                    (gridi == gridj && shift == CENTRAL),
3712                                                                    nbat->x,
3713                                                                    rlist2, rbb2,
3714                                                                    &numDistanceChecks);
3715                                             break;
3716 #endif
3717 #ifdef GMX_NBNXN_SIMD_2XNN
3718                                         case nbnxnk4xN_SIMD_2xNN:
3719                                             makeClusterListSimd2xnn(gridj,
3720                                                                     nbl, ci, firstCell, lastCell,
3721                                                                     (gridi == gridj && shift == CENTRAL),
3722                                                                     nbat->x,
3723                                                                     rlist2, rbb2,
3724                                                                     &numDistanceChecks);
3725                                             break;
3726 #endif
3727                                         case nbnxnk8x8x8_PlainC:
3728                                         case nbnxnk8x8x8_GPU:
3729                                             for (cj = firstCell; cj <= lastCell; cj++)
3730                                             {
3731                                                 make_cluster_list_supersub(gridi, gridj,
3732                                                                            nbl, ci, cj,
3733                                                                            (gridi == gridj && shift == CENTRAL && ci == cj),
3734                                                                            nbat->xstride, nbat->x,
3735                                                                            rlist2, rbb2,
3736                                                                            &numDistanceChecks);
3737                                             }
3738                                             break;
3739                                     }
3740
3741                                     if (bFBufferFlag && nbl->ncj > ncj_old_j)
3742                                     {
3743                                         int cbf = nbl->cj[ncj_old_j].cj >> gridj_flag_shift;
3744                                         int cbl = nbl->cj[nbl->ncj-1].cj >> gridj_flag_shift;
3745                                         for (int cb = cbf; cb <= cbl; cb++)
3746                                         {
3747                                             bitmask_init_bit(&gridj_flag[cb], th);
3748                                         }
3749                                     }
3750
3751                                     nbl->ncjInUse += nbl->ncj - ncj_old_j;
3752                                 }
3753                             }
3754                         }
3755                     }
3756
3757                     /* Set the exclusions for this ci list */
3758                     if (bSimple)
3759                     {
3760                         setExclusionsForSimpleIentry(nbs,
3761                                                      nbl,
3762                                                      shift == CENTRAL && gridi == gridj,
3763                                                      na_cj_2log,
3764                                                      nbl->ci[nbl->nci],
3765                                                      exclusions);
3766
3767                         if (nbs->bFEP)
3768                         {
3769                             make_fep_list(nbs, nbat, nbl,
3770                                           shift == CENTRAL && gridi == gridj,
3771                                           &(nbl->ci[nbl->nci]),
3772                                           gridi, gridj, nbl_fep);
3773                         }
3774                     }
3775                     else
3776                     {
3777                         setExclusionsForGpuIentry(nbs,
3778                                                   nbl,
3779                                                   shift == CENTRAL && gridi == gridj,
3780                                                   nbl->sci[nbl->nsci],
3781                                                   exclusions);
3782
3783                         if (nbs->bFEP)
3784                         {
3785                             make_fep_list_supersub(nbs, nbat, nbl,
3786                                                    shift == CENTRAL && gridi == gridj,
3787                                                    &(nbl->sci[nbl->nsci]),
3788                                                    shx, shy, shz,
3789                                                    rl_fep2,
3790                                                    gridi, gridj, nbl_fep);
3791                         }
3792                     }
3793
3794                     /* Close this ci list */
3795                     if (bSimple)
3796                     {
3797                         close_ci_entry_simple(nbl);
3798                     }
3799                     else
3800                     {
3801                         close_ci_entry_supersub(nbl,
3802                                                 nsubpair_max,
3803                                                 progBal, nsubpair_tot_est,
3804                                                 th, nth);
3805                     }
3806                 }
3807             }
3808         }
3809
3810         if (bFBufferFlag && nbl->ncj > ncj_old_i)
3811         {
3812             bitmask_init_bit(&(work->buffer_flags.flag[(gridi->cell0+ci)>>gridi_flag_shift]), th);
3813         }
3814     }
3815
3816     work->ndistc = numDistanceChecks;
3817
3818     nbs_cycle_stop(&work->cc[enbsCCsearch]);
3819
3820     GMX_ASSERT(nbl->ncjInUse == nbl->ncj || nbs->bFEP, "Without free-energy all cj pair-list entries should be in use. Note that subsequent code does not make use of the equality, this check is only here to catch bugs");
3821
3822     if (debug)
3823     {
3824         fprintf(debug, "number of distance checks %d\n", numDistanceChecks);
3825
3826         if (bSimple)
3827         {
3828             print_nblist_statistics_simple(debug, nbl, nbs, rlist);
3829         }
3830         else
3831         {
3832             print_nblist_statistics_supersub(debug, nbl, nbs, rlist);
3833         }
3834
3835         if (nbs->bFEP)
3836         {
3837             fprintf(debug, "nbl FEP list pairs: %d\n", nbl_fep->nrj);
3838         }
3839     }
3840 }
3841
3842 static void reduce_buffer_flags(const nbnxn_search         *nbs,
3843                                 int                         nsrc,
3844                                 const nbnxn_buffer_flags_t *dest)
3845 {
3846     for (int s = 0; s < nsrc; s++)
3847     {
3848         gmx_bitmask_t * flag = nbs->work[s].buffer_flags.flag;
3849
3850         for (int b = 0; b < dest->nflag; b++)
3851         {
3852             bitmask_union(&(dest->flag[b]), flag[b]);
3853         }
3854     }
3855 }
3856
3857 static void print_reduction_cost(const nbnxn_buffer_flags_t *flags, int nout)
3858 {
3859     int           nelem, nkeep, ncopy, nred, out;
3860     gmx_bitmask_t mask_0;
3861
3862     nelem = 0;
3863     nkeep = 0;
3864     ncopy = 0;
3865     nred  = 0;
3866     bitmask_init_bit(&mask_0, 0);
3867     for (int b = 0; b < flags->nflag; b++)
3868     {
3869         if (bitmask_is_equal(flags->flag[b], mask_0))
3870         {
3871             /* Only flag 0 is set, no copy of reduction required */
3872             nelem++;
3873             nkeep++;
3874         }
3875         else if (!bitmask_is_zero(flags->flag[b]))
3876         {
3877             int c = 0;
3878             for (out = 0; out < nout; out++)
3879             {
3880                 if (bitmask_is_set(flags->flag[b], out))
3881                 {
3882                     c++;
3883                 }
3884             }
3885             nelem += c;
3886             if (c == 1)
3887             {
3888                 ncopy++;
3889             }
3890             else
3891             {
3892                 nred += c;
3893             }
3894         }
3895     }
3896
3897     fprintf(debug, "nbnxn reduction: #flag %d #list %d elem %4.2f, keep %4.2f copy %4.2f red %4.2f\n",
3898             flags->nflag, nout,
3899             nelem/static_cast<double>(flags->nflag),
3900             nkeep/static_cast<double>(flags->nflag),
3901             ncopy/static_cast<double>(flags->nflag),
3902             nred/static_cast<double>(flags->nflag));
3903 }
3904
3905 /* Copies the list entries from src to dest when cjStart <= *cjGlobal < cjEnd.
3906  * *cjGlobal is updated with the cj count in src.
3907  * When setFlags==true, flag bit t is set in flag for all i and j clusters.
3908  */
3909 template<bool setFlags>
3910 static void copySelectedListRange(const nbnxn_ci_t * gmx_restrict srcCi,
3911                                   const nbnxn_pairlist_t * gmx_restrict src,
3912                                   nbnxn_pairlist_t * gmx_restrict dest,
3913                                   gmx_bitmask_t *flag,
3914                                   int iFlagShift, int jFlagShift, int t)
3915 {
3916     int ncj = srcCi->cj_ind_end - srcCi->cj_ind_start;
3917
3918     if (dest->nci + 1 >= dest->ci_nalloc)
3919     {
3920         nb_realloc_ci(dest, dest->nci + 1);
3921     }
3922     check_cell_list_space_simple(dest, ncj);
3923
3924     dest->ci[dest->nci]              = *srcCi;
3925     dest->ci[dest->nci].cj_ind_start = dest->ncj;
3926     dest->ci[dest->nci].cj_ind_end   = dest->ncj + ncj;
3927
3928     if (setFlags)
3929     {
3930         bitmask_init_bit(&flag[srcCi->ci >> iFlagShift], t);
3931     }
3932
3933     for (int j = srcCi->cj_ind_start; j < srcCi->cj_ind_end; j++)
3934     {
3935         dest->cj[dest->ncj++] = src->cj[j];
3936
3937         if (setFlags)
3938         {
3939             /* NOTE: This is relatively expensive, since this
3940              * operation is done for all elements in the list,
3941              * whereas at list generation this is done only
3942              * once for each flag entry.
3943              */
3944             bitmask_init_bit(&flag[src->cj[j].cj >> jFlagShift], t);
3945         }
3946     }
3947
3948     dest->nci++;
3949 }
3950
3951 /* This routine re-balances the pairlists such that all are nearly equally
3952  * sized. Only whole i-entries are moved between lists. These are moved
3953  * between the ends of the lists, such that the buffer reduction cost should
3954  * not change significantly.
3955  * Note that all original reduction flags are currently kept. This can lead
3956  * to reduction of parts of the force buffer that could be avoided. But since
3957  * the original lists are quite balanced, this will only give minor overhead.
3958  */
3959 static void rebalanceSimpleLists(int                                  numLists,
3960                                  nbnxn_pairlist_t * const * const     srcSet,
3961                                  nbnxn_pairlist_t                   **destSet,
3962                                  gmx::ArrayRef<nbnxn_search_work_t>   searchWork)
3963 {
3964     int ncjTotal = 0;
3965     for (int s = 0; s < numLists; s++)
3966     {
3967         ncjTotal += srcSet[s]->ncjInUse;
3968     }
3969     int ncjTarget = (ncjTotal + numLists - 1)/numLists;
3970
3971 #pragma omp parallel num_threads(numLists)
3972     {
3973         int t       = gmx_omp_get_thread_num();
3974
3975         int cjStart = ncjTarget* t;
3976         int cjEnd   = ncjTarget*(t + 1);
3977
3978         /* The destination pair-list for task/thread t */
3979         nbnxn_pairlist_t *dest = destSet[t];
3980
3981         clear_pairlist(dest);
3982         dest->bSimple = srcSet[0]->bSimple;
3983         dest->na_ci   = srcSet[0]->na_ci;
3984         dest->na_cj   = srcSet[0]->na_cj;
3985
3986         /* Note that the flags in the work struct (still) contain flags
3987          * for all entries that are present in srcSet->nbl[t].
3988          */
3989         gmx_bitmask_t *flag       = searchWork[t].buffer_flags.flag;
3990
3991         int            iFlagShift = getBufferFlagShift(dest->na_ci);
3992         int            jFlagShift = getBufferFlagShift(dest->na_cj);
3993
3994         int            cjGlobal   = 0;
3995         for (int s = 0; s < numLists && cjGlobal < cjEnd; s++)
3996         {
3997             const nbnxn_pairlist_t *src = srcSet[s];
3998
3999             if (cjGlobal + src->ncjInUse > cjStart)
4000             {
4001                 for (int i = 0; i < src->nci && cjGlobal < cjEnd; i++)
4002                 {
4003                     const nbnxn_ci_t *srcCi = &src->ci[i];
4004                     int               ncj   = srcCi->cj_ind_end - srcCi->cj_ind_start;
4005                     if (cjGlobal >= cjStart)
4006                     {
4007                         /* If the source list is not our own, we need to set
4008                          * extra flags (the template bool parameter).
4009                          */
4010                         if (s != t)
4011                         {
4012                             copySelectedListRange
4013                             <true>
4014                                 (srcCi, src, dest,
4015                                 flag, iFlagShift, jFlagShift, t);
4016                         }
4017                         else
4018                         {
4019                             copySelectedListRange
4020                             <false>
4021                                 (srcCi, src,
4022                                 dest, flag, iFlagShift, jFlagShift, t);
4023                         }
4024                     }
4025                     cjGlobal += ncj;
4026                 }
4027             }
4028             else
4029             {
4030                 cjGlobal += src->ncjInUse;
4031             }
4032         }
4033
4034         dest->ncjInUse = dest->ncj;
4035     }
4036
4037 #ifndef NDEBUG
4038     int ncjTotalNew = 0;
4039     for (int s = 0; s < numLists; s++)
4040     {
4041         ncjTotalNew += destSet[s]->ncjInUse;
4042     }
4043     GMX_RELEASE_ASSERT(ncjTotalNew == ncjTotal, "The total size of the lists before and after rebalancing should match");
4044 #endif
4045 }
4046
4047 /* Returns if the pairlists are so imbalanced that it is worth rebalancing. */
4048 static bool checkRebalanceSimpleLists(const nbnxn_pairlist_set_t *listSet)
4049 {
4050     int numLists = listSet->nnbl;
4051     int ncjMax   = 0;
4052     int ncjTotal = 0;
4053     for (int s = 0; s < numLists; s++)
4054     {
4055         ncjMax    = std::max(ncjMax, listSet->nbl[s]->ncjInUse);
4056         ncjTotal += listSet->nbl[s]->ncjInUse;
4057     }
4058     if (debug)
4059     {
4060         fprintf(debug, "Pair-list ncjMax %d ncjTotal %d\n", ncjMax, ncjTotal);
4061     }
4062     /* The rebalancing adds 3% extra time to the search. Heuristically we
4063      * determined that under common conditions the non-bonded kernel balance
4064      * improvement will outweigh this when the imbalance is more than 3%.
4065      * But this will, obviously, depend on search vs kernel time and nstlist.
4066      */
4067     const real rebalanceTolerance = 1.03;
4068
4069     return numLists*ncjMax > ncjTotal*rebalanceTolerance;
4070 }
4071
4072 /* Perform a count (linear) sort to sort the smaller lists to the end.
4073  * This avoids load imbalance on the GPU, as large lists will be
4074  * scheduled and executed first and the smaller lists later.
4075  * Load balancing between multi-processors only happens at the end
4076  * and there smaller lists lead to more effective load balancing.
4077  * The sorting is done on the cj4 count, not on the actual pair counts.
4078  * Not only does this make the sort faster, but it also results in
4079  * better load balancing than using a list sorted on exact load.
4080  * This function swaps the pointer in the pair list to avoid a copy operation.
4081  */
4082 static void sort_sci(nbnxn_pairlist_t *nbl)
4083 {
4084     nbnxn_list_work_t *work;
4085     int                m, s0, s1;
4086     nbnxn_sci_t       *sci_sort;
4087
4088     if (nbl->ncj4 <= nbl->nsci)
4089     {
4090         /* nsci = 0 or all sci have size 1, sorting won't change the order */
4091         return;
4092     }
4093
4094     work = nbl->work;
4095
4096     /* We will distinguish differences up to double the average */
4097     m = (2*nbl->ncj4)/nbl->nsci;
4098
4099     if (m + 1 > work->sort_nalloc)
4100     {
4101         work->sort_nalloc = over_alloc_large(m + 1);
4102         srenew(work->sort, work->sort_nalloc);
4103     }
4104
4105     if (work->sci_sort_nalloc != nbl->sci_nalloc)
4106     {
4107         work->sci_sort_nalloc = nbl->sci_nalloc;
4108         nbnxn_realloc_void(reinterpret_cast<void **>(&work->sci_sort),
4109                            0,
4110                            work->sci_sort_nalloc*sizeof(*work->sci_sort),
4111                            nbl->alloc, nbl->free);
4112     }
4113
4114     /* Count the entries of each size */
4115     for (int i = 0; i <= m; i++)
4116     {
4117         work->sort[i] = 0;
4118     }
4119     for (int s = 0; s < nbl->nsci; s++)
4120     {
4121         int i = std::min(m, nbl->sci[s].cj4_ind_end - nbl->sci[s].cj4_ind_start);
4122         work->sort[i]++;
4123     }
4124     /* Calculate the offset for each count */
4125     s0            = work->sort[m];
4126     work->sort[m] = 0;
4127     for (int i = m - 1; i >= 0; i--)
4128     {
4129         s1            = work->sort[i];
4130         work->sort[i] = work->sort[i + 1] + s0;
4131         s0            = s1;
4132     }
4133
4134     /* Sort entries directly into place */
4135     sci_sort = work->sci_sort;
4136     for (int s = 0; s < nbl->nsci; s++)
4137     {
4138         int i = std::min(m, nbl->sci[s].cj4_ind_end - nbl->sci[s].cj4_ind_start);
4139         sci_sort[work->sort[i]++] = nbl->sci[s];
4140     }
4141
4142     /* Swap the sci pointers so we use the new, sorted list */
4143     work->sci_sort = nbl->sci;
4144     nbl->sci       = sci_sort;
4145 }
4146
4147 /* Make a local or non-local pair-list, depending on iloc */
4148 void nbnxn_make_pairlist(nbnxn_search         *nbs,
4149                          nbnxn_atomdata_t     *nbat,
4150                          const t_blocka       *excl,
4151                          real                  rlist,
4152                          int                   min_ci_balanced,
4153                          nbnxn_pairlist_set_t *nbl_list,
4154                          int                   iloc,
4155                          int                   nb_kernel_type,
4156                          t_nrnb               *nrnb)
4157 {
4158     nbnxn_grid_t      *gridi, *gridj;
4159     int                nzi, zj0, zj1;
4160     int                nsubpair_target;
4161     float              nsubpair_tot_est;
4162     int                nnbl;
4163     nbnxn_pairlist_t **nbl;
4164     int                ci_block;
4165     gmx_bool           CombineNBLists;
4166     gmx_bool           progBal;
4167     int                np_tot, np_noq, np_hlj, nap;
4168
4169     nnbl            = nbl_list->nnbl;
4170     nbl             = nbl_list->nbl;
4171     CombineNBLists  = nbl_list->bCombined;
4172
4173     if (debug)
4174     {
4175         fprintf(debug, "ns making %d nblists\n", nnbl);
4176     }
4177
4178     nbat->bUseBufferFlags = (nbat->nout > 1);
4179     /* We should re-init the flags before making the first list */
4180     if (nbat->bUseBufferFlags && LOCAL_I(iloc))
4181     {
4182         init_buffer_flags(&nbat->buffer_flags, nbat->natoms);
4183     }
4184
4185     if (nbl_list->bSimple)
4186     {
4187 #if GMX_SIMD
4188         switch (nb_kernel_type)
4189         {
4190 #ifdef GMX_NBNXN_SIMD_4XN
4191             case nbnxnk4xN_SIMD_4xN:
4192                 nbs->icell_set_x = icell_set_x_simd_4xn;
4193                 break;
4194 #endif
4195 #ifdef GMX_NBNXN_SIMD_2XNN
4196             case nbnxnk4xN_SIMD_2xNN:
4197                 nbs->icell_set_x = icell_set_x_simd_2xnn;
4198                 break;
4199 #endif
4200             default:
4201                 nbs->icell_set_x = icell_set_x_simple;
4202                 break;
4203         }
4204 #else   // GMX_SIMD
4205         /* MSVC 2013 complains about switch statements without case */
4206         nbs->icell_set_x = icell_set_x_simple;
4207 #endif  // GMX_SIMD
4208     }
4209     else
4210     {
4211         nbs->icell_set_x = icell_set_x_supersub;
4212     }
4213
4214     if (LOCAL_I(iloc))
4215     {
4216         /* Only zone (grid) 0 vs 0 */
4217         nzi = 1;
4218         zj0 = 0;
4219         zj1 = 1;
4220     }
4221     else
4222     {
4223         nzi = nbs->zones->nizone;
4224     }
4225
4226     if (!nbl_list->bSimple && min_ci_balanced > 0)
4227     {
4228         get_nsubpair_target(nbs, iloc, rlist, min_ci_balanced,
4229                             &nsubpair_target, &nsubpair_tot_est);
4230     }
4231     else
4232     {
4233         nsubpair_target  = 0;
4234         nsubpair_tot_est = 0;
4235     }
4236
4237     /* Clear all pair-lists */
4238     for (int th = 0; th < nnbl; th++)
4239     {
4240         clear_pairlist(nbl[th]);
4241
4242         if (nbs->bFEP)
4243         {
4244             clear_pairlist_fep(nbl_list->nbl_fep[th]);
4245         }
4246     }
4247
4248     for (int zi = 0; zi < nzi; zi++)
4249     {
4250         gridi = &nbs->grid[zi];
4251
4252         if (NONLOCAL_I(iloc))
4253         {
4254             zj0 = nbs->zones->izone[zi].j0;
4255             zj1 = nbs->zones->izone[zi].j1;
4256             if (zi == 0)
4257             {
4258                 zj0++;
4259             }
4260         }
4261         for (int zj = zj0; zj < zj1; zj++)
4262         {
4263             gridj = &nbs->grid[zj];
4264
4265             if (debug)
4266             {
4267                 fprintf(debug, "ns search grid %d vs %d\n", zi, zj);
4268             }
4269
4270             nbs_cycle_start(&nbs->cc[enbsCCsearch]);
4271
4272             ci_block = get_ci_block_size(gridi, nbs->DomDec, nnbl);
4273
4274             /* With GPU: generate progressively smaller lists for
4275              * load balancing for local only or non-local with 2 zones.
4276              */
4277             progBal = (LOCAL_I(iloc) || nbs->zones->n <= 2);
4278
4279 #pragma omp parallel for num_threads(nnbl) schedule(static)
4280             for (int th = 0; th < nnbl; th++)
4281             {
4282                 try
4283                 {
4284                     /* Re-init the thread-local work flag data before making
4285                      * the first list (not an elegant conditional).
4286                      */
4287                     if (nbat->bUseBufferFlags && ((zi == 0 && zj == 0)))
4288                     {
4289                         init_buffer_flags(&nbs->work[th].buffer_flags, nbat->natoms);
4290                     }
4291
4292                     if (CombineNBLists && th > 0)
4293                     {
4294                         clear_pairlist(nbl[th]);
4295                     }
4296
4297                     /* Divide the i super cell equally over the nblists */
4298                     nbnxn_make_pairlist_part(nbs, gridi, gridj,
4299                                              &nbs->work[th], nbat, *excl,
4300                                              rlist,
4301                                              nb_kernel_type,
4302                                              ci_block,
4303                                              nbat->bUseBufferFlags,
4304                                              nsubpair_target,
4305                                              progBal, nsubpair_tot_est,
4306                                              th, nnbl,
4307                                              nbl[th],
4308                                              nbl_list->nbl_fep[th]);
4309                 }
4310                 GMX_CATCH_ALL_AND_EXIT_WITH_FATAL_ERROR;
4311             }
4312             nbs_cycle_stop(&nbs->cc[enbsCCsearch]);
4313
4314             np_tot = 0;
4315             np_noq = 0;
4316             np_hlj = 0;
4317             for (int th = 0; th < nnbl; th++)
4318             {
4319                 inc_nrnb(nrnb, eNR_NBNXN_DIST2, nbs->work[th].ndistc);
4320
4321                 if (nbl_list->bSimple)
4322                 {
4323                     np_tot += nbl[th]->ncj;
4324                     np_noq += nbl[th]->work->ncj_noq;
4325                     np_hlj += nbl[th]->work->ncj_hlj;
4326                 }
4327                 else
4328                 {
4329                     /* This count ignores potential subsequent pair pruning */
4330                     np_tot += nbl[th]->nci_tot;
4331                 }
4332             }
4333             nap                   = nbl[0]->na_ci*nbl[0]->na_cj;
4334             nbl_list->natpair_ljq = (np_tot - np_noq)*nap - np_hlj*nap/2;
4335             nbl_list->natpair_lj  = np_noq*nap;
4336             nbl_list->natpair_q   = np_hlj*nap/2;
4337
4338             if (CombineNBLists && nnbl > 1)
4339             {
4340                 nbs_cycle_start(&nbs->cc[enbsCCcombine]);
4341
4342                 combine_nblists(nnbl-1, nbl+1, nbl[0]);
4343
4344                 nbs_cycle_stop(&nbs->cc[enbsCCcombine]);
4345             }
4346         }
4347     }
4348
4349     if (nbl_list->bSimple)
4350     {
4351         if (nnbl > 1 && checkRebalanceSimpleLists(nbl_list))
4352         {
4353             rebalanceSimpleLists(nbl_list->nnbl, nbl_list->nbl, nbl_list->nbl_work, nbs->work);
4354
4355             /* Swap the pointer of the sets of pair lists */
4356             nbnxn_pairlist_t **tmp = nbl_list->nbl;
4357             nbl_list->nbl          = nbl_list->nbl_work;
4358             nbl_list->nbl_work     = tmp;
4359         }
4360     }
4361     else
4362     {
4363         /* Sort the entries on size, large ones first */
4364         if (CombineNBLists || nnbl == 1)
4365         {
4366             sort_sci(nbl[0]);
4367         }
4368         else
4369         {
4370 #pragma omp parallel for num_threads(nnbl) schedule(static)
4371             for (int th = 0; th < nnbl; th++)
4372             {
4373                 try
4374                 {
4375                     sort_sci(nbl[th]);
4376                 }
4377                 GMX_CATCH_ALL_AND_EXIT_WITH_FATAL_ERROR;
4378             }
4379         }
4380     }
4381
4382     if (nbat->bUseBufferFlags)
4383     {
4384         reduce_buffer_flags(nbs, nbl_list->nnbl, &nbat->buffer_flags);
4385     }
4386
4387     if (nbs->bFEP)
4388     {
4389         /* Balance the free-energy lists over all the threads */
4390         balance_fep_lists(nbs, nbl_list);
4391     }
4392
4393     /* This is a fresh list, so not pruned, stored using ci and nci.
4394      * ciOuter and nciOuter are invalid at this point.
4395      */
4396     GMX_ASSERT(nbl_list->nbl[0]->nciOuter == -1, "nciOuter should have been set to -1 to signal that it is invalid");
4397
4398     /* Special performance logging stuff (env.var. GMX_NBNXN_CYCLE) */
4399     if (LOCAL_I(iloc))
4400     {
4401         nbs->search_count++;
4402     }
4403     if (nbs->print_cycles &&
4404         (!nbs->DomDec || !LOCAL_I(iloc)) &&
4405         nbs->search_count % 100 == 0)
4406     {
4407         nbs_cycle_print(stderr, nbs);
4408     }
4409
4410     /* If we have more than one list, they either got rebalancing (CPU)
4411      * or combined (GPU), so we should dump the final result to debug.
4412      */
4413     if (debug && nbl_list->nnbl > 1)
4414     {
4415         if (nbl_list->bSimple)
4416         {
4417             for (int t = 0; t < nbl_list->nnbl; t++)
4418             {
4419                 print_nblist_statistics_simple(debug, nbl_list->nbl[t], nbs, rlist);
4420             }
4421         }
4422         else
4423         {
4424             print_nblist_statistics_supersub(debug, nbl_list->nbl[0], nbs, rlist);
4425         }
4426     }
4427
4428     if (debug)
4429     {
4430         if (gmx_debug_at)
4431         {
4432             if (nbl_list->bSimple)
4433             {
4434                 for (int t = 0; t < nbl_list->nnbl; t++)
4435                 {
4436                     print_nblist_ci_cj(debug, nbl_list->nbl[t]);
4437                 }
4438             }
4439             else
4440             {
4441                 print_nblist_sci_cj(debug, nbl_list->nbl[0]);
4442             }
4443         }
4444
4445         if (nbat->bUseBufferFlags)
4446         {
4447             print_reduction_cost(&nbat->buffer_flags, nbl_list->nnbl);
4448         }
4449     }
4450 }
4451
4452 void nbnxnPrepareListForDynamicPruning(nbnxn_pairlist_set_t *listSet)
4453 {
4454     /* TODO: Restructure the lists so we have actual outer and inner
4455      *       list objects so we can set a single pointer instead of
4456      *       swapping several pointers.
4457      */
4458
4459     for (int i = 0; i < listSet->nnbl; i++)
4460     {
4461         /* The search produced a list in ci/cj.
4462          * Swap the list pointers so we get the outer list is ciOuter,cjOuter
4463          * and we can prune that to get an inner list in ci/cj.
4464          */
4465         nbnxn_pairlist_t *list = listSet->nbl[i];
4466         list->nciOuter         = list->nci;
4467
4468         nbnxn_ci_t *ciTmp      = list->ciOuter;
4469         list->ciOuter          = list->ci;
4470         list->ci               = ciTmp;
4471
4472         nbnxn_cj_t *cjTmp      = list->cjOuter;
4473         list->cjOuter          = list->cj;
4474         list->cj               = cjTmp;
4475
4476         /* Signal that this inner list is currently invalid */
4477         list->nci              = -1;
4478     }
4479 }