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