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