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