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