Add optional NVIDIA Management Library (NVML) Integration
[alexxy/gromacs.git] / src / gromacs / mdlib / nbnxn_search.c
1 /*
2  * This file is part of the GROMACS molecular simulation package.
3  *
4  * Copyright (c) 2012,2013,2014, 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 <math.h>
44 #include <string.h>
45
46 #include "gromacs/legacyheaders/gmx_omp_nthreads.h"
47 #include "gromacs/legacyheaders/macros.h"
48 #include "gromacs/legacyheaders/nrnb.h"
49 #include "gromacs/legacyheaders/ns.h"
50 #include "gromacs/legacyheaders/types/commrec.h"
51 #include "gromacs/math/utilities.h"
52 #include "gromacs/math/vec.h"
53 #include "gromacs/mdlib/nb_verlet.h"
54 #include "gromacs/mdlib/nbnxn_atomdata.h"
55 #include "gromacs/mdlib/nbnxn_consts.h"
56 #include "gromacs/pbcutil/ishift.h"
57 #include "gromacs/pbcutil/pbc.h"
58 #include "gromacs/utility/smalloc.h"
59
60 /* nbnxn_internal.h included gromacs/simd/macros.h */
61 #include "gromacs/mdlib/nbnxn_internal.h"
62 #ifdef GMX_SIMD
63 #include "gromacs/simd/vector_operations.h"
64 #endif
65
66 #ifdef NBNXN_SEARCH_BB_SIMD4
67 /* Always use 4-wide SIMD for bounding box calculations */
68
69 #    ifndef GMX_DOUBLE
70 /* Single precision BBs + coordinates, we can also load coordinates with SIMD */
71 #        define NBNXN_SEARCH_SIMD4_FLOAT_X_BB
72 #    endif
73
74 #    if defined NBNXN_SEARCH_SIMD4_FLOAT_X_BB && (GPU_NSUBCELL == 4 || GPU_NSUBCELL == 8)
75 /* Store bounding boxes with x, y and z coordinates in packs of 4 */
76 #        define NBNXN_PBB_SIMD4
77 #    endif
78
79 /* The packed bounding box coordinate stride is always set to 4.
80  * With AVX we could use 8, but that turns out not to be faster.
81  */
82 #    define STRIDE_PBB        4
83 #    define STRIDE_PBB_2LOG   2
84
85 #endif /* NBNXN_SEARCH_BB_SIMD4 */
86
87 #ifdef GMX_NBNXN_SIMD
88
89 /* The functions below are macros as they are performance sensitive */
90
91 /* 4x4 list, pack=4: no complex conversion required */
92 /* i-cluster to j-cluster conversion */
93 #define CI_TO_CJ_J4(ci)   (ci)
94 /* cluster index to coordinate array index conversion */
95 #define X_IND_CI_J4(ci)  ((ci)*STRIDE_P4)
96 #define X_IND_CJ_J4(cj)  ((cj)*STRIDE_P4)
97
98 /* 4x2 list, pack=4: j-cluster size is half the packing width */
99 /* i-cluster to j-cluster conversion */
100 #define CI_TO_CJ_J2(ci)  ((ci)<<1)
101 /* cluster index to coordinate array index conversion */
102 #define X_IND_CI_J2(ci)  ((ci)*STRIDE_P4)
103 #define X_IND_CJ_J2(cj)  (((cj)>>1)*STRIDE_P4 + ((cj) & 1)*(PACK_X4>>1))
104
105 /* 4x8 list, pack=8: i-cluster size is half the packing width */
106 /* i-cluster to j-cluster conversion */
107 #define CI_TO_CJ_J8(ci)  ((ci)>>1)
108 /* cluster index to coordinate array index conversion */
109 #define X_IND_CI_J8(ci)  (((ci)>>1)*STRIDE_P8 + ((ci) & 1)*(PACK_X8>>1))
110 #define X_IND_CJ_J8(cj)  ((cj)*STRIDE_P8)
111
112 /* The j-cluster size is matched to the SIMD width */
113 #if GMX_SIMD_REAL_WIDTH == 2
114 #define CI_TO_CJ_SIMD_4XN(ci)  CI_TO_CJ_J2(ci)
115 #define X_IND_CI_SIMD_4XN(ci)  X_IND_CI_J2(ci)
116 #define X_IND_CJ_SIMD_4XN(cj)  X_IND_CJ_J2(cj)
117 #else
118 #if GMX_SIMD_REAL_WIDTH == 4
119 #define CI_TO_CJ_SIMD_4XN(ci)  CI_TO_CJ_J4(ci)
120 #define X_IND_CI_SIMD_4XN(ci)  X_IND_CI_J4(ci)
121 #define X_IND_CJ_SIMD_4XN(cj)  X_IND_CJ_J4(cj)
122 #else
123 #if GMX_SIMD_REAL_WIDTH == 8
124 #define CI_TO_CJ_SIMD_4XN(ci)  CI_TO_CJ_J8(ci)
125 #define X_IND_CI_SIMD_4XN(ci)  X_IND_CI_J8(ci)
126 #define X_IND_CJ_SIMD_4XN(cj)  X_IND_CJ_J8(cj)
127 /* Half SIMD with j-cluster size */
128 #define CI_TO_CJ_SIMD_2XNN(ci) CI_TO_CJ_J4(ci)
129 #define X_IND_CI_SIMD_2XNN(ci) X_IND_CI_J4(ci)
130 #define X_IND_CJ_SIMD_2XNN(cj) X_IND_CJ_J4(cj)
131 #else
132 #if GMX_SIMD_REAL_WIDTH == 16
133 #define CI_TO_CJ_SIMD_2XNN(ci) CI_TO_CJ_J8(ci)
134 #define X_IND_CI_SIMD_2XNN(ci) X_IND_CI_J8(ci)
135 #define X_IND_CJ_SIMD_2XNN(cj) X_IND_CJ_J8(cj)
136 #else
137 #error "unsupported GMX_SIMD_REAL_WIDTH"
138 #endif
139 #endif
140 #endif
141 #endif
142
143 #endif /* GMX_NBNXN_SIMD */
144
145
146 #ifdef NBNXN_SEARCH_BB_SIMD4
147 /* Store bounding boxes corners as quadruplets: xxxxyyyyzzzz */
148 #define NBNXN_BBXXXX
149 /* Size of bounding box corners quadruplet */
150 #define NNBSBB_XXXX      (NNBSBB_D*DIM*STRIDE_PBB)
151 #endif
152
153 /* We shift the i-particles backward for PBC.
154  * This leads to more conditionals than shifting forward.
155  * We do this to get more balanced pair lists.
156  */
157 #define NBNXN_SHIFT_BACKWARD
158
159
160 /* This define is a lazy way to avoid interdependence of the grid
161  * and searching data structures.
162  */
163 #define NBNXN_NA_SC_MAX (GPU_NSUBCELL*NBNXN_GPU_CLUSTER_SIZE)
164
165
166 static void nbs_cycle_clear(nbnxn_cycle_t *cc)
167 {
168     int i;
169
170     for (i = 0; i < enbsCCnr; i++)
171     {
172         cc[i].count = 0;
173         cc[i].c     = 0;
174     }
175 }
176
177 static double Mcyc_av(const nbnxn_cycle_t *cc)
178 {
179     return (double)cc->c*1e-6/cc->count;
180 }
181
182 static void nbs_cycle_print(FILE *fp, const nbnxn_search_t nbs)
183 {
184     int n;
185     int t;
186
187     fprintf(fp, "\n");
188     fprintf(fp, "ns %4d grid %4.1f search %4.1f red.f %5.3f",
189             nbs->cc[enbsCCgrid].count,
190             Mcyc_av(&nbs->cc[enbsCCgrid]),
191             Mcyc_av(&nbs->cc[enbsCCsearch]),
192             Mcyc_av(&nbs->cc[enbsCCreducef]));
193
194     if (nbs->nthread_max > 1)
195     {
196         if (nbs->cc[enbsCCcombine].count > 0)
197         {
198             fprintf(fp, " comb %5.2f",
199                     Mcyc_av(&nbs->cc[enbsCCcombine]));
200         }
201         fprintf(fp, " s. th");
202         for (t = 0; t < nbs->nthread_max; t++)
203         {
204             fprintf(fp, " %4.1f",
205                     Mcyc_av(&nbs->work[t].cc[enbsCCsearch]));
206         }
207     }
208     fprintf(fp, "\n");
209 }
210
211 static void nbnxn_grid_init(nbnxn_grid_t * grid)
212 {
213     grid->cxy_na      = NULL;
214     grid->cxy_ind     = NULL;
215     grid->cxy_nalloc  = 0;
216     grid->bb          = NULL;
217     grid->bbj         = NULL;
218     grid->nc_nalloc   = 0;
219 }
220
221 static int get_2log(int n)
222 {
223     int log2;
224
225     log2 = 0;
226     while ((1<<log2) < n)
227     {
228         log2++;
229     }
230     if ((1<<log2) != n)
231     {
232         gmx_fatal(FARGS, "nbnxn na_c (%d) is not a power of 2", n);
233     }
234
235     return log2;
236 }
237
238 static int nbnxn_kernel_to_ci_size(int nb_kernel_type)
239 {
240     switch (nb_kernel_type)
241     {
242         case nbnxnk4x4_PlainC:
243         case nbnxnk4xN_SIMD_4xN:
244         case nbnxnk4xN_SIMD_2xNN:
245             return NBNXN_CPU_CLUSTER_I_SIZE;
246         case nbnxnk8x8x8_CUDA:
247         case nbnxnk8x8x8_PlainC:
248             /* The cluster size for super/sub lists is only set here.
249              * Any value should work for the pair-search and atomdata code.
250              * The kernels, of course, might require a particular value.
251              */
252             return NBNXN_GPU_CLUSTER_SIZE;
253         default:
254             gmx_incons("unknown kernel type");
255     }
256
257     return 0;
258 }
259
260 int nbnxn_kernel_to_cj_size(int nb_kernel_type)
261 {
262     int nbnxn_simd_width = 0;
263     int cj_size          = 0;
264
265 #ifdef GMX_NBNXN_SIMD
266     nbnxn_simd_width = GMX_SIMD_REAL_WIDTH;
267 #endif
268
269     switch (nb_kernel_type)
270     {
271         case nbnxnk4x4_PlainC:
272             cj_size = NBNXN_CPU_CLUSTER_I_SIZE;
273             break;
274         case nbnxnk4xN_SIMD_4xN:
275             cj_size = nbnxn_simd_width;
276             break;
277         case nbnxnk4xN_SIMD_2xNN:
278             cj_size = nbnxn_simd_width/2;
279             break;
280         case nbnxnk8x8x8_CUDA:
281         case nbnxnk8x8x8_PlainC:
282             cj_size = nbnxn_kernel_to_ci_size(nb_kernel_type);
283             break;
284         default:
285             gmx_incons("unknown kernel type");
286     }
287
288     return cj_size;
289 }
290
291 static int ci_to_cj(int na_cj_2log, int ci)
292 {
293     switch (na_cj_2log)
294     {
295         case 2: return ci;     break;
296         case 1: return (ci<<1); break;
297         case 3: return (ci>>1); break;
298     }
299
300     return 0;
301 }
302
303 gmx_bool nbnxn_kernel_pairlist_simple(int nb_kernel_type)
304 {
305     if (nb_kernel_type == nbnxnkNotSet)
306     {
307         gmx_fatal(FARGS, "Non-bonded kernel type not set for Verlet-style pair-list.");
308     }
309
310     switch (nb_kernel_type)
311     {
312         case nbnxnk8x8x8_CUDA:
313         case nbnxnk8x8x8_PlainC:
314             return FALSE;
315
316         case nbnxnk4x4_PlainC:
317         case nbnxnk4xN_SIMD_4xN:
318         case nbnxnk4xN_SIMD_2xNN:
319             return TRUE;
320
321         default:
322             gmx_incons("Invalid nonbonded kernel type passed!");
323             return FALSE;
324     }
325 }
326
327 /* Initializes a single nbnxn_pairlist_t data structure */
328 static void nbnxn_init_pairlist_fep(t_nblist *nl)
329 {
330     nl->type        = GMX_NBLIST_INTERACTION_FREE_ENERGY;
331     nl->igeometry   = GMX_NBLIST_GEOMETRY_PARTICLE_PARTICLE;
332     /* The interaction functions are set in the free energy kernel fuction */
333     nl->ivdw        = -1;
334     nl->ivdwmod     = -1;
335     nl->ielec       = -1;
336     nl->ielecmod    = -1;
337
338     nl->maxnri      = 0;
339     nl->maxnrj      = 0;
340     nl->nri         = 0;
341     nl->nrj         = 0;
342     nl->iinr        = NULL;
343     nl->gid         = NULL;
344     nl->shift       = NULL;
345     nl->jindex      = NULL;
346     nl->jjnr        = NULL;
347     nl->excl_fep    = NULL;
348
349 }
350
351 void nbnxn_init_search(nbnxn_search_t    * nbs_ptr,
352                        ivec               *n_dd_cells,
353                        gmx_domdec_zones_t *zones,
354                        gmx_bool            bFEP,
355                        int                 nthread_max)
356 {
357     nbnxn_search_t nbs;
358     int            d, g, t;
359
360     snew(nbs, 1);
361     *nbs_ptr = nbs;
362
363     nbs->bFEP   = bFEP;
364
365     nbs->DomDec = (n_dd_cells != NULL);
366
367     clear_ivec(nbs->dd_dim);
368     nbs->ngrid = 1;
369     if (nbs->DomDec)
370     {
371         nbs->zones = zones;
372
373         for (d = 0; d < DIM; d++)
374         {
375             if ((*n_dd_cells)[d] > 1)
376             {
377                 nbs->dd_dim[d] = 1;
378                 /* Each grid matches a DD zone */
379                 nbs->ngrid *= 2;
380             }
381         }
382     }
383
384     snew(nbs->grid, nbs->ngrid);
385     for (g = 0; g < nbs->ngrid; g++)
386     {
387         nbnxn_grid_init(&nbs->grid[g]);
388     }
389     nbs->cell        = NULL;
390     nbs->cell_nalloc = 0;
391     nbs->a           = NULL;
392     nbs->a_nalloc    = 0;
393
394     nbs->nthread_max = nthread_max;
395
396     /* Initialize the work data structures for each thread */
397     snew(nbs->work, nbs->nthread_max);
398     for (t = 0; t < nbs->nthread_max; t++)
399     {
400         nbs->work[t].cxy_na           = NULL;
401         nbs->work[t].cxy_na_nalloc    = 0;
402         nbs->work[t].sort_work        = NULL;
403         nbs->work[t].sort_work_nalloc = 0;
404
405         snew(nbs->work[t].nbl_fep, 1);
406         nbnxn_init_pairlist_fep(nbs->work[t].nbl_fep);
407     }
408
409     /* Initialize detailed nbsearch cycle counting */
410     nbs->print_cycles = (getenv("GMX_NBNXN_CYCLE") != 0);
411     nbs->search_count = 0;
412     nbs_cycle_clear(nbs->cc);
413     for (t = 0; t < nbs->nthread_max; t++)
414     {
415         nbs_cycle_clear(nbs->work[t].cc);
416     }
417 }
418
419 static real grid_atom_density(int n, rvec corner0, rvec corner1)
420 {
421     rvec size;
422
423     if (n == 0)
424     {
425         /* To avoid zero density we use a minimum of 1 atom */
426         n = 1;
427     }
428
429     rvec_sub(corner1, corner0, size);
430
431     return n/(size[XX]*size[YY]*size[ZZ]);
432 }
433
434 static int set_grid_size_xy(const nbnxn_search_t nbs,
435                             nbnxn_grid_t *grid,
436                             int dd_zone,
437                             int n, rvec corner0, rvec corner1,
438                             real atom_density)
439 {
440     rvec size;
441     int  na_c;
442     real adens, tlen, tlen_x, tlen_y, nc_max;
443     int  t;
444
445     rvec_sub(corner1, corner0, size);
446
447     if (n > grid->na_sc)
448     {
449         assert(atom_density > 0);
450
451         /* target cell length */
452         if (grid->bSimple)
453         {
454             /* To minimize the zero interactions, we should make
455              * the largest of the i/j cell cubic.
456              */
457             na_c = max(grid->na_c, grid->na_cj);
458
459             /* Approximately cubic cells */
460             tlen   = pow(na_c/atom_density, 1.0/3.0);
461             tlen_x = tlen;
462             tlen_y = tlen;
463         }
464         else
465         {
466             /* Approximately cubic sub cells */
467             tlen   = pow(grid->na_c/atom_density, 1.0/3.0);
468             tlen_x = tlen*GPU_NSUBCELL_X;
469             tlen_y = tlen*GPU_NSUBCELL_Y;
470         }
471         /* We round ncx and ncy down, because we get less cell pairs
472          * in the nbsist when the fixed cell dimensions (x,y) are
473          * larger than the variable one (z) than the other way around.
474          */
475         grid->ncx = max(1, (int)(size[XX]/tlen_x));
476         grid->ncy = max(1, (int)(size[YY]/tlen_y));
477     }
478     else
479     {
480         grid->ncx = 1;
481         grid->ncy = 1;
482     }
483
484     grid->sx     = size[XX]/grid->ncx;
485     grid->sy     = size[YY]/grid->ncy;
486     grid->inv_sx = 1/grid->sx;
487     grid->inv_sy = 1/grid->sy;
488
489     if (dd_zone > 0)
490     {
491         /* This is a non-home zone, add an extra row of cells
492          * for particles communicated for bonded interactions.
493          * These can be beyond the cut-off. It doesn't matter where
494          * they end up on the grid, but for performance it's better
495          * if they don't end up in cells that can be within cut-off range.
496          */
497         grid->ncx++;
498         grid->ncy++;
499     }
500
501     /* We need one additional cell entry for particles moved by DD */
502     if (grid->ncx*grid->ncy+1 > grid->cxy_nalloc)
503     {
504         grid->cxy_nalloc = over_alloc_large(grid->ncx*grid->ncy+1);
505         srenew(grid->cxy_na, grid->cxy_nalloc);
506         srenew(grid->cxy_ind, grid->cxy_nalloc+1);
507     }
508     for (t = 0; t < nbs->nthread_max; t++)
509     {
510         if (grid->ncx*grid->ncy+1 > nbs->work[t].cxy_na_nalloc)
511         {
512             nbs->work[t].cxy_na_nalloc = over_alloc_large(grid->ncx*grid->ncy+1);
513             srenew(nbs->work[t].cxy_na, nbs->work[t].cxy_na_nalloc);
514         }
515     }
516
517     /* Worst case scenario of 1 atom in each last cell */
518     if (grid->na_cj <= grid->na_c)
519     {
520         nc_max = n/grid->na_sc + grid->ncx*grid->ncy;
521     }
522     else
523     {
524         nc_max = n/grid->na_sc + grid->ncx*grid->ncy*grid->na_cj/grid->na_c;
525     }
526
527     if (nc_max > grid->nc_nalloc)
528     {
529         grid->nc_nalloc = over_alloc_large(nc_max);
530         srenew(grid->nsubc, grid->nc_nalloc);
531         srenew(grid->bbcz, grid->nc_nalloc*NNBSBB_D);
532
533         sfree_aligned(grid->bb);
534         /* This snew also zeros the contents, this avoid possible
535          * floating exceptions in SIMD with the unused bb elements.
536          */
537         if (grid->bSimple)
538         {
539             snew_aligned(grid->bb, grid->nc_nalloc, 16);
540         }
541         else
542         {
543 #ifdef NBNXN_BBXXXX
544             int pbb_nalloc;
545
546             pbb_nalloc = grid->nc_nalloc*GPU_NSUBCELL/STRIDE_PBB*NNBSBB_XXXX;
547             snew_aligned(grid->pbb, pbb_nalloc, 16);
548 #else
549             snew_aligned(grid->bb, grid->nc_nalloc*GPU_NSUBCELL, 16);
550 #endif
551         }
552
553         if (grid->bSimple)
554         {
555             if (grid->na_cj == grid->na_c)
556             {
557                 grid->bbj = grid->bb;
558             }
559             else
560             {
561                 sfree_aligned(grid->bbj);
562                 snew_aligned(grid->bbj, grid->nc_nalloc*grid->na_c/grid->na_cj, 16);
563             }
564         }
565
566         srenew(grid->flags, grid->nc_nalloc);
567         if (nbs->bFEP)
568         {
569             srenew(grid->fep, grid->nc_nalloc*grid->na_sc/grid->na_c);
570         }
571     }
572
573     copy_rvec(corner0, grid->c0);
574     copy_rvec(corner1, grid->c1);
575     copy_rvec(size,    grid->size);
576
577     return nc_max;
578 }
579
580 /* We need to sort paricles in grid columns on z-coordinate.
581  * As particle are very often distributed homogeneously, we a sorting
582  * algorithm similar to pigeonhole sort. We multiply the z-coordinate
583  * by a factor, cast to an int and try to store in that hole. If the hole
584  * is full, we move this or another particle. A second pass is needed to make
585  * contiguous elements. SORT_GRID_OVERSIZE is the ratio of holes to particles.
586  * 4 is the optimal value for homogeneous particle distribution and allows
587  * for an O(#particles) sort up till distributions were all particles are
588  * concentrated in 1/4 of the space. No NlogN fallback is implemented,
589  * as it can be expensive to detect imhomogeneous particle distributions.
590  * SGSF is the maximum ratio of holes used, in the worst case all particles
591  * end up in the last hole and we need #particles extra holes at the end.
592  */
593 #define SORT_GRID_OVERSIZE 4
594 #define SGSF (SORT_GRID_OVERSIZE + 1)
595
596 /* Sort particle index a on coordinates x along dim.
597  * Backwards tells if we want decreasing iso increasing coordinates.
598  * h0 is the minimum of the coordinate range.
599  * invh is the 1/length of the sorting range.
600  * n_per_h (>=n) is the expected average number of particles per 1/invh
601  * sort is the sorting work array.
602  * sort should have a size of at least n_per_h*SORT_GRID_OVERSIZE + n,
603  * or easier, allocate at least n*SGSF elements.
604  */
605 static void sort_atoms(int dim, gmx_bool Backwards,
606                        int gmx_unused dd_zone,
607                        int *a, int n, rvec *x,
608                        real h0, real invh, int n_per_h,
609                        int *sort)
610 {
611     int nsort, i, c;
612     int zi, zim, zi_min, zi_max;
613     int cp, tmp;
614
615     if (n <= 1)
616     {
617         /* Nothing to do */
618         return;
619     }
620
621 #ifndef NDEBUG
622     if (n > n_per_h)
623     {
624         gmx_incons("n > n_per_h");
625     }
626 #endif
627
628     /* Transform the inverse range height into the inverse hole height */
629     invh *= n_per_h*SORT_GRID_OVERSIZE;
630
631     /* Set nsort to the maximum possible number of holes used.
632      * In worst case all n elements end up in the last bin.
633      */
634     nsort = n_per_h*SORT_GRID_OVERSIZE + n;
635
636     /* Determine the index range used, so we can limit it for the second pass */
637     zi_min = INT_MAX;
638     zi_max = -1;
639
640     /* Sort the particles using a simple index sort */
641     for (i = 0; i < n; i++)
642     {
643         /* The cast takes care of float-point rounding effects below zero.
644          * This code assumes particles are less than 1/SORT_GRID_OVERSIZE
645          * times the box height out of the box.
646          */
647         zi = (int)((x[a[i]][dim] - h0)*invh);
648
649 #ifndef NDEBUG
650         /* As we can have rounding effect, we use > iso >= here */
651         if (zi < 0 || (dd_zone == 0 && zi > n_per_h*SORT_GRID_OVERSIZE))
652         {
653             gmx_fatal(FARGS, "(int)((x[%d][%c]=%f - %f)*%f) = %d, not in 0 - %d*%d\n",
654                       a[i], 'x'+dim, x[a[i]][dim], h0, invh, zi,
655                       n_per_h, SORT_GRID_OVERSIZE);
656         }
657 #endif
658
659         /* In a non-local domain, particles communcated for bonded interactions
660          * can be far beyond the grid size, which is set by the non-bonded
661          * cut-off distance. We sort such particles into the last cell.
662          */
663         if (zi > n_per_h*SORT_GRID_OVERSIZE)
664         {
665             zi = n_per_h*SORT_GRID_OVERSIZE;
666         }
667
668         /* Ideally this particle should go in sort cell zi,
669          * but that might already be in use,
670          * in that case find the first empty cell higher up
671          */
672         if (sort[zi] < 0)
673         {
674             sort[zi] = a[i];
675             zi_min   = min(zi_min, zi);
676             zi_max   = max(zi_max, zi);
677         }
678         else
679         {
680             /* We have multiple atoms in the same sorting slot.
681              * Sort on real z for minimal bounding box size.
682              * There is an extra check for identical z to ensure
683              * well-defined output order, independent of input order
684              * to ensure binary reproducibility after restarts.
685              */
686             while (sort[zi] >= 0 && ( x[a[i]][dim] >  x[sort[zi]][dim] ||
687                                       (x[a[i]][dim] == x[sort[zi]][dim] &&
688                                        a[i] > sort[zi])))
689             {
690                 zi++;
691             }
692
693             if (sort[zi] >= 0)
694             {
695                 /* Shift all elements by one slot until we find an empty slot */
696                 cp  = sort[zi];
697                 zim = zi + 1;
698                 while (sort[zim] >= 0)
699                 {
700                     tmp       = sort[zim];
701                     sort[zim] = cp;
702                     cp        = tmp;
703                     zim++;
704                 }
705                 sort[zim] = cp;
706                 zi_max    = max(zi_max, zim);
707             }
708             sort[zi] = a[i];
709             zi_max   = max(zi_max, zi);
710         }
711     }
712
713     c = 0;
714     if (!Backwards)
715     {
716         for (zi = 0; zi < nsort; zi++)
717         {
718             if (sort[zi] >= 0)
719             {
720                 a[c++]   = sort[zi];
721                 sort[zi] = -1;
722             }
723         }
724     }
725     else
726     {
727         for (zi = zi_max; zi >= zi_min; zi--)
728         {
729             if (sort[zi] >= 0)
730             {
731                 a[c++]   = sort[zi];
732                 sort[zi] = -1;
733             }
734         }
735     }
736     if (c < n)
737     {
738         gmx_incons("Lost particles while sorting");
739     }
740 }
741
742 #ifdef GMX_DOUBLE
743 #define R2F_D(x) ((float)((x) >= 0 ? ((1-GMX_FLOAT_EPS)*(x)) : ((1+GMX_FLOAT_EPS)*(x))))
744 #define R2F_U(x) ((float)((x) >= 0 ? ((1+GMX_FLOAT_EPS)*(x)) : ((1-GMX_FLOAT_EPS)*(x))))
745 #else
746 #define R2F_D(x) (x)
747 #define R2F_U(x) (x)
748 #endif
749
750 /* Coordinate order x,y,z, bb order xyz0 */
751 static void calc_bounding_box(int na, int stride, const real *x, nbnxn_bb_t *bb)
752 {
753     int  i, j;
754     real xl, xh, yl, yh, zl, zh;
755
756     i  = 0;
757     xl = x[i+XX];
758     xh = x[i+XX];
759     yl = x[i+YY];
760     yh = x[i+YY];
761     zl = x[i+ZZ];
762     zh = x[i+ZZ];
763     i += stride;
764     for (j = 1; j < na; j++)
765     {
766         xl = min(xl, x[i+XX]);
767         xh = max(xh, x[i+XX]);
768         yl = min(yl, x[i+YY]);
769         yh = max(yh, x[i+YY]);
770         zl = min(zl, x[i+ZZ]);
771         zh = max(zh, x[i+ZZ]);
772         i += stride;
773     }
774     /* Note: possible double to float conversion here */
775     bb->lower[BB_X] = R2F_D(xl);
776     bb->lower[BB_Y] = R2F_D(yl);
777     bb->lower[BB_Z] = R2F_D(zl);
778     bb->upper[BB_X] = R2F_U(xh);
779     bb->upper[BB_Y] = R2F_U(yh);
780     bb->upper[BB_Z] = R2F_U(zh);
781 }
782
783 /* Packed coordinates, bb order xyz0 */
784 static void calc_bounding_box_x_x4(int na, const real *x, nbnxn_bb_t *bb)
785 {
786     int  j;
787     real xl, xh, yl, yh, zl, zh;
788
789     xl = x[XX*PACK_X4];
790     xh = x[XX*PACK_X4];
791     yl = x[YY*PACK_X4];
792     yh = x[YY*PACK_X4];
793     zl = x[ZZ*PACK_X4];
794     zh = x[ZZ*PACK_X4];
795     for (j = 1; j < na; j++)
796     {
797         xl = min(xl, x[j+XX*PACK_X4]);
798         xh = max(xh, x[j+XX*PACK_X4]);
799         yl = min(yl, x[j+YY*PACK_X4]);
800         yh = max(yh, x[j+YY*PACK_X4]);
801         zl = min(zl, x[j+ZZ*PACK_X4]);
802         zh = max(zh, x[j+ZZ*PACK_X4]);
803     }
804     /* Note: possible double to float conversion here */
805     bb->lower[BB_X] = R2F_D(xl);
806     bb->lower[BB_Y] = R2F_D(yl);
807     bb->lower[BB_Z] = R2F_D(zl);
808     bb->upper[BB_X] = R2F_U(xh);
809     bb->upper[BB_Y] = R2F_U(yh);
810     bb->upper[BB_Z] = R2F_U(zh);
811 }
812
813 /* Packed coordinates, bb order xyz0 */
814 static void calc_bounding_box_x_x8(int na, const real *x, nbnxn_bb_t *bb)
815 {
816     int  j;
817     real xl, xh, yl, yh, zl, zh;
818
819     xl = x[XX*PACK_X8];
820     xh = x[XX*PACK_X8];
821     yl = x[YY*PACK_X8];
822     yh = x[YY*PACK_X8];
823     zl = x[ZZ*PACK_X8];
824     zh = x[ZZ*PACK_X8];
825     for (j = 1; j < na; j++)
826     {
827         xl = min(xl, x[j+XX*PACK_X8]);
828         xh = max(xh, x[j+XX*PACK_X8]);
829         yl = min(yl, x[j+YY*PACK_X8]);
830         yh = max(yh, x[j+YY*PACK_X8]);
831         zl = min(zl, x[j+ZZ*PACK_X8]);
832         zh = max(zh, x[j+ZZ*PACK_X8]);
833     }
834     /* Note: possible double to float conversion here */
835     bb->lower[BB_X] = R2F_D(xl);
836     bb->lower[BB_Y] = R2F_D(yl);
837     bb->lower[BB_Z] = R2F_D(zl);
838     bb->upper[BB_X] = R2F_U(xh);
839     bb->upper[BB_Y] = R2F_U(yh);
840     bb->upper[BB_Z] = R2F_U(zh);
841 }
842
843 /* Packed coordinates, bb order xyz0 */
844 static void calc_bounding_box_x_x4_halves(int na, const real *x,
845                                           nbnxn_bb_t *bb, nbnxn_bb_t *bbj)
846 {
847     calc_bounding_box_x_x4(min(na, 2), x, bbj);
848
849     if (na > 2)
850     {
851         calc_bounding_box_x_x4(min(na-2, 2), x+(PACK_X4>>1), bbj+1);
852     }
853     else
854     {
855         /* Set the "empty" bounding box to the same as the first one,
856          * so we don't need to treat special cases in the rest of the code.
857          */
858 #ifdef NBNXN_SEARCH_BB_SIMD4
859         gmx_simd4_store_f(&bbj[1].lower[0], gmx_simd4_load_f(&bbj[0].lower[0]));
860         gmx_simd4_store_f(&bbj[1].upper[0], gmx_simd4_load_f(&bbj[0].upper[0]));
861 #else
862         bbj[1] = bbj[0];
863 #endif
864     }
865
866 #ifdef NBNXN_SEARCH_BB_SIMD4
867     gmx_simd4_store_f(&bb->lower[0],
868                       gmx_simd4_min_f(gmx_simd4_load_f(&bbj[0].lower[0]),
869                                       gmx_simd4_load_f(&bbj[1].lower[0])));
870     gmx_simd4_store_f(&bb->upper[0],
871                       gmx_simd4_max_f(gmx_simd4_load_f(&bbj[0].upper[0]),
872                                       gmx_simd4_load_f(&bbj[1].upper[0])));
873 #else
874     {
875         int i;
876
877         for (i = 0; i < NNBSBB_C; i++)
878         {
879             bb->lower[i] = min(bbj[0].lower[i], bbj[1].lower[i]);
880             bb->upper[i] = max(bbj[0].upper[i], bbj[1].upper[i]);
881         }
882     }
883 #endif
884 }
885
886 #ifdef NBNXN_SEARCH_BB_SIMD4
887
888 /* Coordinate order xyz, bb order xxxxyyyyzzzz */
889 static void calc_bounding_box_xxxx(int na, int stride, const real *x, float *bb)
890 {
891     int  i, j;
892     real xl, xh, yl, yh, zl, zh;
893
894     i  = 0;
895     xl = x[i+XX];
896     xh = x[i+XX];
897     yl = x[i+YY];
898     yh = x[i+YY];
899     zl = x[i+ZZ];
900     zh = x[i+ZZ];
901     i += stride;
902     for (j = 1; j < na; j++)
903     {
904         xl = min(xl, x[i+XX]);
905         xh = max(xh, x[i+XX]);
906         yl = min(yl, x[i+YY]);
907         yh = max(yh, x[i+YY]);
908         zl = min(zl, x[i+ZZ]);
909         zh = max(zh, x[i+ZZ]);
910         i += stride;
911     }
912     /* Note: possible double to float conversion here */
913     bb[0*STRIDE_PBB] = R2F_D(xl);
914     bb[1*STRIDE_PBB] = R2F_D(yl);
915     bb[2*STRIDE_PBB] = R2F_D(zl);
916     bb[3*STRIDE_PBB] = R2F_U(xh);
917     bb[4*STRIDE_PBB] = R2F_U(yh);
918     bb[5*STRIDE_PBB] = R2F_U(zh);
919 }
920
921 #endif /* NBNXN_SEARCH_BB_SIMD4 */
922
923 #ifdef NBNXN_SEARCH_SIMD4_FLOAT_X_BB
924
925 /* Coordinate order xyz?, bb order xyz0 */
926 static void calc_bounding_box_simd4(int na, const float *x, nbnxn_bb_t *bb)
927 {
928     gmx_simd4_float_t bb_0_S, bb_1_S;
929     gmx_simd4_float_t x_S;
930
931     int               i;
932
933     bb_0_S = gmx_simd4_load_f(x);
934     bb_1_S = bb_0_S;
935
936     for (i = 1; i < na; i++)
937     {
938         x_S    = gmx_simd4_load_f(x+i*NNBSBB_C);
939         bb_0_S = gmx_simd4_min_f(bb_0_S, x_S);
940         bb_1_S = gmx_simd4_max_f(bb_1_S, x_S);
941     }
942
943     gmx_simd4_store_f(&bb->lower[0], bb_0_S);
944     gmx_simd4_store_f(&bb->upper[0], bb_1_S);
945 }
946
947 /* Coordinate order xyz?, bb order xxxxyyyyzzzz */
948 static void calc_bounding_box_xxxx_simd4(int na, const float *x,
949                                          nbnxn_bb_t *bb_work_aligned,
950                                          real *bb)
951 {
952     calc_bounding_box_simd4(na, x, bb_work_aligned);
953
954     bb[0*STRIDE_PBB] = bb_work_aligned->lower[BB_X];
955     bb[1*STRIDE_PBB] = bb_work_aligned->lower[BB_Y];
956     bb[2*STRIDE_PBB] = bb_work_aligned->lower[BB_Z];
957     bb[3*STRIDE_PBB] = bb_work_aligned->upper[BB_X];
958     bb[4*STRIDE_PBB] = bb_work_aligned->upper[BB_Y];
959     bb[5*STRIDE_PBB] = bb_work_aligned->upper[BB_Z];
960 }
961
962 #endif /* NBNXN_SEARCH_SIMD4_FLOAT_X_BB */
963
964
965 /* Combines pairs of consecutive bounding boxes */
966 static void combine_bounding_box_pairs(nbnxn_grid_t *grid, const nbnxn_bb_t *bb)
967 {
968     int    i, j, sc2, nc2, c2;
969
970     for (i = 0; i < grid->ncx*grid->ncy; i++)
971     {
972         /* Starting bb in a column is expected to be 2-aligned */
973         sc2 = grid->cxy_ind[i]>>1;
974         /* For odd numbers skip the last bb here */
975         nc2 = (grid->cxy_na[i]+3)>>(2+1);
976         for (c2 = sc2; c2 < sc2+nc2; c2++)
977         {
978 #ifdef NBNXN_SEARCH_BB_SIMD4
979             gmx_simd4_float_t min_S, max_S;
980
981             min_S = gmx_simd4_min_f(gmx_simd4_load_f(&bb[c2*2+0].lower[0]),
982                                     gmx_simd4_load_f(&bb[c2*2+1].lower[0]));
983             max_S = gmx_simd4_max_f(gmx_simd4_load_f(&bb[c2*2+0].upper[0]),
984                                     gmx_simd4_load_f(&bb[c2*2+1].upper[0]));
985             gmx_simd4_store_f(&grid->bbj[c2].lower[0], min_S);
986             gmx_simd4_store_f(&grid->bbj[c2].upper[0], max_S);
987 #else
988             for (j = 0; j < NNBSBB_C; j++)
989             {
990                 grid->bbj[c2].lower[j] = min(bb[c2*2+0].lower[j],
991                                              bb[c2*2+1].lower[j]);
992                 grid->bbj[c2].upper[j] = max(bb[c2*2+0].upper[j],
993                                              bb[c2*2+1].upper[j]);
994             }
995 #endif
996         }
997         if (((grid->cxy_na[i]+3)>>2) & 1)
998         {
999             /* The bb count in this column is odd: duplicate the last bb */
1000             for (j = 0; j < NNBSBB_C; j++)
1001             {
1002                 grid->bbj[c2].lower[j] = bb[c2*2].lower[j];
1003                 grid->bbj[c2].upper[j] = bb[c2*2].upper[j];
1004             }
1005         }
1006     }
1007 }
1008
1009
1010 /* Prints the average bb size, used for debug output */
1011 static void print_bbsizes_simple(FILE                *fp,
1012                                  const nbnxn_grid_t  *grid)
1013 {
1014     int  c, d;
1015     dvec ba;
1016
1017     clear_dvec(ba);
1018     for (c = 0; c < grid->nc; c++)
1019     {
1020         for (d = 0; d < DIM; d++)
1021         {
1022             ba[d] += grid->bb[c].upper[d] - grid->bb[c].lower[d];
1023         }
1024     }
1025     dsvmul(1.0/grid->nc, ba, ba);
1026
1027     fprintf(fp, "ns bb: grid %4.2f %4.2f %4.2f abs %4.2f %4.2f %4.2f rel %4.2f %4.2f %4.2f\n",
1028             grid->sx,
1029             grid->sy,
1030             grid->na_c/(grid->atom_density*grid->sx*grid->sy),
1031             ba[XX], ba[YY], ba[ZZ],
1032             ba[XX]/grid->sx,
1033             ba[YY]/grid->sy,
1034             ba[ZZ]/(grid->na_c/(grid->atom_density*grid->sx*grid->sy)));
1035 }
1036
1037 /* Prints the average bb size, used for debug output */
1038 static void print_bbsizes_supersub(FILE                *fp,
1039                                    const nbnxn_grid_t  *grid)
1040 {
1041     int  ns, c, s;
1042     dvec ba;
1043
1044     clear_dvec(ba);
1045     ns = 0;
1046     for (c = 0; c < grid->nc; c++)
1047     {
1048 #ifdef NBNXN_BBXXXX
1049         for (s = 0; s < grid->nsubc[c]; s += STRIDE_PBB)
1050         {
1051             int cs_w, i, d;
1052
1053             cs_w = (c*GPU_NSUBCELL + s)/STRIDE_PBB;
1054             for (i = 0; i < STRIDE_PBB; i++)
1055             {
1056                 for (d = 0; d < DIM; d++)
1057                 {
1058                     ba[d] +=
1059                         grid->pbb[cs_w*NNBSBB_XXXX+(DIM+d)*STRIDE_PBB+i] -
1060                         grid->pbb[cs_w*NNBSBB_XXXX+     d *STRIDE_PBB+i];
1061                 }
1062             }
1063         }
1064 #else
1065         for (s = 0; s < grid->nsubc[c]; s++)
1066         {
1067             int cs, d;
1068
1069             cs = c*GPU_NSUBCELL + s;
1070             for (d = 0; d < DIM; d++)
1071             {
1072                 ba[d] += grid->bb[cs].upper[d] - grid->bb[cs].lower[d];
1073             }
1074         }
1075 #endif
1076         ns += grid->nsubc[c];
1077     }
1078     dsvmul(1.0/ns, ba, ba);
1079
1080     fprintf(fp, "ns bb: grid %4.2f %4.2f %4.2f abs %4.2f %4.2f %4.2f rel %4.2f %4.2f %4.2f\n",
1081             grid->sx/GPU_NSUBCELL_X,
1082             grid->sy/GPU_NSUBCELL_Y,
1083             grid->na_sc/(grid->atom_density*grid->sx*grid->sy*GPU_NSUBCELL_Z),
1084             ba[XX], ba[YY], ba[ZZ],
1085             ba[XX]*GPU_NSUBCELL_X/grid->sx,
1086             ba[YY]*GPU_NSUBCELL_Y/grid->sy,
1087             ba[ZZ]/(grid->na_sc/(grid->atom_density*grid->sx*grid->sy*GPU_NSUBCELL_Z)));
1088 }
1089
1090 /* Potentially sorts atoms on LJ coefficients !=0 and ==0.
1091  * Also sets interaction flags.
1092  */
1093 void sort_on_lj(int na_c,
1094                 int a0, int a1, const int *atinfo,
1095                 int *order,
1096                 int *flags)
1097 {
1098     int      subc, s, a, n1, n2, a_lj_max, i, j;
1099     int      sort1[NBNXN_NA_SC_MAX/GPU_NSUBCELL];
1100     int      sort2[NBNXN_NA_SC_MAX/GPU_NSUBCELL];
1101     gmx_bool haveQ, bFEP;
1102
1103     *flags = 0;
1104
1105     subc = 0;
1106     for (s = a0; s < a1; s += na_c)
1107     {
1108         /* Make lists for this (sub-)cell on atoms with and without LJ */
1109         n1       = 0;
1110         n2       = 0;
1111         haveQ    = FALSE;
1112         a_lj_max = -1;
1113         for (a = s; a < min(s+na_c, a1); a++)
1114         {
1115             haveQ = haveQ || GET_CGINFO_HAS_Q(atinfo[order[a]]);
1116
1117             if (GET_CGINFO_HAS_VDW(atinfo[order[a]]))
1118             {
1119                 sort1[n1++] = order[a];
1120                 a_lj_max    = a;
1121             }
1122             else
1123             {
1124                 sort2[n2++] = order[a];
1125             }
1126         }
1127
1128         /* If we don't have atoms with LJ, there's nothing to sort */
1129         if (n1 > 0)
1130         {
1131             *flags |= NBNXN_CI_DO_LJ(subc);
1132
1133             if (2*n1 <= na_c)
1134             {
1135                 /* Only sort when strictly necessary. Ordering particles
1136                  * Ordering particles can lead to less accurate summation
1137                  * due to rounding, both for LJ and Coulomb interactions.
1138                  */
1139                 if (2*(a_lj_max - s) >= na_c)
1140                 {
1141                     for (i = 0; i < n1; i++)
1142                     {
1143                         order[a0+i] = sort1[i];
1144                     }
1145                     for (j = 0; j < n2; j++)
1146                     {
1147                         order[a0+n1+j] = sort2[j];
1148                     }
1149                 }
1150
1151                 *flags |= NBNXN_CI_HALF_LJ(subc);
1152             }
1153         }
1154         if (haveQ)
1155         {
1156             *flags |= NBNXN_CI_DO_COUL(subc);
1157         }
1158         subc++;
1159     }
1160 }
1161
1162 /* Fill a pair search cell with atoms.
1163  * Potentially sorts atoms and sets the interaction flags.
1164  */
1165 void fill_cell(const nbnxn_search_t nbs,
1166                nbnxn_grid_t *grid,
1167                nbnxn_atomdata_t *nbat,
1168                int a0, int a1,
1169                const int *atinfo,
1170                rvec *x,
1171                int sx, int sy, int sz,
1172                nbnxn_bb_t gmx_unused *bb_work_aligned)
1173 {
1174     int         na, a;
1175     size_t      offset;
1176     nbnxn_bb_t *bb_ptr;
1177 #ifdef NBNXN_BBXXXX
1178     float      *pbb_ptr;
1179 #endif
1180
1181     na = a1 - a0;
1182
1183     if (grid->bSimple)
1184     {
1185         sort_on_lj(grid->na_c, a0, a1, atinfo, nbs->a,
1186                    grid->flags+(a0>>grid->na_c_2log)-grid->cell0);
1187     }
1188
1189     if (nbs->bFEP)
1190     {
1191         /* Set the fep flag for perturbed atoms in this (sub-)cell */
1192         int c, at;
1193
1194         /* The grid-local cluster/(sub-)cell index */
1195         c            = (a0 >> grid->na_c_2log) - grid->cell0*(grid->bSimple ? 1 : GPU_NSUBCELL);
1196         grid->fep[c] = 0;
1197         for (at = a0; at < a1; at++)
1198         {
1199             if (nbs->a[at] >= 0 && GET_CGINFO_FEP(atinfo[nbs->a[at]]))
1200             {
1201                 grid->fep[c] |= (1 << (at - a0));
1202             }
1203         }
1204     }
1205
1206     /* Now we have sorted the atoms, set the cell indices */
1207     for (a = a0; a < a1; a++)
1208     {
1209         nbs->cell[nbs->a[a]] = a;
1210     }
1211
1212     copy_rvec_to_nbat_real(nbs->a+a0, a1-a0, grid->na_c, x,
1213                            nbat->XFormat, nbat->x, a0,
1214                            sx, sy, sz);
1215
1216     if (nbat->XFormat == nbatX4)
1217     {
1218         /* Store the bounding boxes as xyz.xyz. */
1219         offset = (a0 - grid->cell0*grid->na_sc) >> grid->na_c_2log;
1220         bb_ptr = grid->bb + offset;
1221
1222 #if defined GMX_NBNXN_SIMD && GMX_SIMD_REAL_WIDTH == 2
1223         if (2*grid->na_cj == grid->na_c)
1224         {
1225             calc_bounding_box_x_x4_halves(na, nbat->x+X4_IND_A(a0), bb_ptr,
1226                                           grid->bbj+offset*2);
1227         }
1228         else
1229 #endif
1230         {
1231             calc_bounding_box_x_x4(na, nbat->x+X4_IND_A(a0), bb_ptr);
1232         }
1233     }
1234     else if (nbat->XFormat == nbatX8)
1235     {
1236         /* Store the bounding boxes as xyz.xyz. */
1237         offset = (a0 - grid->cell0*grid->na_sc) >> grid->na_c_2log;
1238         bb_ptr = grid->bb + offset;
1239
1240         calc_bounding_box_x_x8(na, nbat->x+X8_IND_A(a0), bb_ptr);
1241     }
1242 #ifdef NBNXN_BBXXXX
1243     else if (!grid->bSimple)
1244     {
1245         /* Store the bounding boxes in a format convenient
1246          * for SIMD4 calculations: xxxxyyyyzzzz...
1247          */
1248         pbb_ptr =
1249             grid->pbb +
1250             ((a0-grid->cell0*grid->na_sc)>>(grid->na_c_2log+STRIDE_PBB_2LOG))*NNBSBB_XXXX +
1251             (((a0-grid->cell0*grid->na_sc)>>grid->na_c_2log) & (STRIDE_PBB-1));
1252
1253 #ifdef NBNXN_SEARCH_SIMD4_FLOAT_X_BB
1254         if (nbat->XFormat == nbatXYZQ)
1255         {
1256             calc_bounding_box_xxxx_simd4(na, nbat->x+a0*nbat->xstride,
1257                                          bb_work_aligned, pbb_ptr);
1258         }
1259         else
1260 #endif
1261         {
1262             calc_bounding_box_xxxx(na, nbat->xstride, nbat->x+a0*nbat->xstride,
1263                                    pbb_ptr);
1264         }
1265         if (gmx_debug_at)
1266         {
1267             fprintf(debug, "%2d %2d %2d bb %5.2f %5.2f %5.2f %5.2f %5.2f %5.2f\n",
1268                     sx, sy, sz,
1269                     pbb_ptr[0*STRIDE_PBB], pbb_ptr[3*STRIDE_PBB],
1270                     pbb_ptr[1*STRIDE_PBB], pbb_ptr[4*STRIDE_PBB],
1271                     pbb_ptr[2*STRIDE_PBB], pbb_ptr[5*STRIDE_PBB]);
1272         }
1273     }
1274 #endif
1275     else
1276     {
1277         /* Store the bounding boxes as xyz.xyz. */
1278         bb_ptr = grid->bb+((a0-grid->cell0*grid->na_sc)>>grid->na_c_2log);
1279
1280         calc_bounding_box(na, nbat->xstride, nbat->x+a0*nbat->xstride,
1281                           bb_ptr);
1282
1283         if (gmx_debug_at)
1284         {
1285             int bbo;
1286             bbo = (a0 - grid->cell0*grid->na_sc)/grid->na_c;
1287             fprintf(debug, "%2d %2d %2d bb %5.2f %5.2f %5.2f %5.2f %5.2f %5.2f\n",
1288                     sx, sy, sz,
1289                     grid->bb[bbo].lower[BB_X],
1290                     grid->bb[bbo].lower[BB_Y],
1291                     grid->bb[bbo].lower[BB_Z],
1292                     grid->bb[bbo].upper[BB_X],
1293                     grid->bb[bbo].upper[BB_Y],
1294                     grid->bb[bbo].upper[BB_Z]);
1295         }
1296     }
1297 }
1298
1299 /* Spatially sort the atoms within one grid column */
1300 static void sort_columns_simple(const nbnxn_search_t nbs,
1301                                 int dd_zone,
1302                                 nbnxn_grid_t *grid,
1303                                 int a0, int a1,
1304                                 const int *atinfo,
1305                                 rvec *x,
1306                                 nbnxn_atomdata_t *nbat,
1307                                 int cxy_start, int cxy_end,
1308                                 int *sort_work)
1309 {
1310     int  cxy;
1311     int  cx, cy, cz, ncz, cfilled, c;
1312     int  na, ash, ind, a;
1313     int  na_c, ash_c;
1314
1315     if (debug)
1316     {
1317         fprintf(debug, "cell0 %d sorting columns %d - %d, atoms %d - %d\n",
1318                 grid->cell0, cxy_start, cxy_end, a0, a1);
1319     }
1320
1321     /* Sort the atoms within each x,y column in 3 dimensions */
1322     for (cxy = cxy_start; cxy < cxy_end; cxy++)
1323     {
1324         cx = cxy/grid->ncy;
1325         cy = cxy - cx*grid->ncy;
1326
1327         na  = grid->cxy_na[cxy];
1328         ncz = grid->cxy_ind[cxy+1] - grid->cxy_ind[cxy];
1329         ash = (grid->cell0 + grid->cxy_ind[cxy])*grid->na_sc;
1330
1331         /* Sort the atoms within each x,y column on z coordinate */
1332         sort_atoms(ZZ, FALSE, dd_zone,
1333                    nbs->a+ash, na, x,
1334                    grid->c0[ZZ],
1335                    1.0/grid->size[ZZ], ncz*grid->na_sc,
1336                    sort_work);
1337
1338         /* Fill the ncz cells in this column */
1339         cfilled = grid->cxy_ind[cxy];
1340         for (cz = 0; cz < ncz; cz++)
1341         {
1342             c  = grid->cxy_ind[cxy] + cz;
1343
1344             ash_c = ash + cz*grid->na_sc;
1345             na_c  = min(grid->na_sc, na-(ash_c-ash));
1346
1347             fill_cell(nbs, grid, nbat,
1348                       ash_c, ash_c+na_c, atinfo, x,
1349                       grid->na_sc*cx + (dd_zone >> 2),
1350                       grid->na_sc*cy + (dd_zone & 3),
1351                       grid->na_sc*cz,
1352                       NULL);
1353
1354             /* This copy to bbcz is not really necessary.
1355              * But it allows to use the same grid search code
1356              * for the simple and supersub cell setups.
1357              */
1358             if (na_c > 0)
1359             {
1360                 cfilled = c;
1361             }
1362             grid->bbcz[c*NNBSBB_D  ] = grid->bb[cfilled].lower[BB_Z];
1363             grid->bbcz[c*NNBSBB_D+1] = grid->bb[cfilled].upper[BB_Z];
1364         }
1365
1366         /* Set the unused atom indices to -1 */
1367         for (ind = na; ind < ncz*grid->na_sc; ind++)
1368         {
1369             nbs->a[ash+ind] = -1;
1370         }
1371     }
1372 }
1373
1374 /* Spatially sort the atoms within one grid column */
1375 static void sort_columns_supersub(const nbnxn_search_t nbs,
1376                                   int dd_zone,
1377                                   nbnxn_grid_t *grid,
1378                                   int a0, int a1,
1379                                   const int *atinfo,
1380                                   rvec *x,
1381                                   nbnxn_atomdata_t *nbat,
1382                                   int cxy_start, int cxy_end,
1383                                   int *sort_work)
1384 {
1385     int        cxy;
1386     int        cx, cy, cz = -1, c = -1, ncz;
1387     int        na, ash, na_c, ind, a;
1388     int        subdiv_z, sub_z, na_z, ash_z;
1389     int        subdiv_y, sub_y, na_y, ash_y;
1390     int        subdiv_x, sub_x, na_x, ash_x;
1391
1392     nbnxn_bb_t bb_work_array[2], *bb_work_aligned;
1393
1394     bb_work_aligned = (nbnxn_bb_t *)(((size_t)(bb_work_array+1)) & (~((size_t)15)));
1395
1396     if (debug)
1397     {
1398         fprintf(debug, "cell0 %d sorting columns %d - %d, atoms %d - %d\n",
1399                 grid->cell0, cxy_start, cxy_end, a0, a1);
1400     }
1401
1402     subdiv_x = grid->na_c;
1403     subdiv_y = GPU_NSUBCELL_X*subdiv_x;
1404     subdiv_z = GPU_NSUBCELL_Y*subdiv_y;
1405
1406     /* Sort the atoms within each x,y column in 3 dimensions */
1407     for (cxy = cxy_start; cxy < cxy_end; cxy++)
1408     {
1409         cx = cxy/grid->ncy;
1410         cy = cxy - cx*grid->ncy;
1411
1412         na  = grid->cxy_na[cxy];
1413         ncz = grid->cxy_ind[cxy+1] - grid->cxy_ind[cxy];
1414         ash = (grid->cell0 + grid->cxy_ind[cxy])*grid->na_sc;
1415
1416         /* Sort the atoms within each x,y column on z coordinate */
1417         sort_atoms(ZZ, FALSE, dd_zone,
1418                    nbs->a+ash, na, x,
1419                    grid->c0[ZZ],
1420                    1.0/grid->size[ZZ], ncz*grid->na_sc,
1421                    sort_work);
1422
1423         /* This loop goes over the supercells and subcells along z at once */
1424         for (sub_z = 0; sub_z < ncz*GPU_NSUBCELL_Z; sub_z++)
1425         {
1426             ash_z = ash + sub_z*subdiv_z;
1427             na_z  = min(subdiv_z, na-(ash_z-ash));
1428
1429             /* We have already sorted on z */
1430
1431             if (sub_z % GPU_NSUBCELL_Z == 0)
1432             {
1433                 cz = sub_z/GPU_NSUBCELL_Z;
1434                 c  = grid->cxy_ind[cxy] + cz;
1435
1436                 /* The number of atoms in this supercell */
1437                 na_c = min(grid->na_sc, na-(ash_z-ash));
1438
1439                 grid->nsubc[c] = min(GPU_NSUBCELL, (na_c+grid->na_c-1)/grid->na_c);
1440
1441                 /* Store the z-boundaries of the super cell */
1442                 grid->bbcz[c*NNBSBB_D  ] = x[nbs->a[ash_z]][ZZ];
1443                 grid->bbcz[c*NNBSBB_D+1] = x[nbs->a[ash_z+na_c-1]][ZZ];
1444             }
1445
1446 #if GPU_NSUBCELL_Y > 1
1447             /* Sort the atoms along y */
1448             sort_atoms(YY, (sub_z & 1), dd_zone,
1449                        nbs->a+ash_z, na_z, x,
1450                        grid->c0[YY]+cy*grid->sy,
1451                        grid->inv_sy, subdiv_z,
1452                        sort_work);
1453 #endif
1454
1455             for (sub_y = 0; sub_y < GPU_NSUBCELL_Y; sub_y++)
1456             {
1457                 ash_y = ash_z + sub_y*subdiv_y;
1458                 na_y  = min(subdiv_y, na-(ash_y-ash));
1459
1460 #if GPU_NSUBCELL_X > 1
1461                 /* Sort the atoms along x */
1462                 sort_atoms(XX, ((cz*GPU_NSUBCELL_Y + sub_y) & 1), dd_zone,
1463                            nbs->a+ash_y, na_y, x,
1464                            grid->c0[XX]+cx*grid->sx,
1465                            grid->inv_sx, subdiv_y,
1466                            sort_work);
1467 #endif
1468
1469                 for (sub_x = 0; sub_x < GPU_NSUBCELL_X; sub_x++)
1470                 {
1471                     ash_x = ash_y + sub_x*subdiv_x;
1472                     na_x  = min(subdiv_x, na-(ash_x-ash));
1473
1474                     fill_cell(nbs, grid, nbat,
1475                               ash_x, ash_x+na_x, atinfo, x,
1476                               grid->na_c*(cx*GPU_NSUBCELL_X+sub_x) + (dd_zone >> 2),
1477                               grid->na_c*(cy*GPU_NSUBCELL_Y+sub_y) + (dd_zone & 3),
1478                               grid->na_c*sub_z,
1479                               bb_work_aligned);
1480                 }
1481             }
1482         }
1483
1484         /* Set the unused atom indices to -1 */
1485         for (ind = na; ind < ncz*grid->na_sc; ind++)
1486         {
1487             nbs->a[ash+ind] = -1;
1488         }
1489     }
1490 }
1491
1492 /* Determine in which grid column atoms should go */
1493 static void calc_column_indices(nbnxn_grid_t *grid,
1494                                 int a0, int a1,
1495                                 rvec *x,
1496                                 int dd_zone, const int *move,
1497                                 int thread, int nthread,
1498                                 int *cell,
1499                                 int *cxy_na)
1500 {
1501     int  n0, n1, i;
1502     int  cx, cy;
1503
1504     /* We add one extra cell for particles which moved during DD */
1505     for (i = 0; i < grid->ncx*grid->ncy+1; i++)
1506     {
1507         cxy_na[i] = 0;
1508     }
1509
1510     n0 = a0 + (int)((thread+0)*(a1 - a0))/nthread;
1511     n1 = a0 + (int)((thread+1)*(a1 - a0))/nthread;
1512     if (dd_zone == 0)
1513     {
1514         /* Home zone */
1515         for (i = n0; i < n1; i++)
1516         {
1517             if (move == NULL || move[i] >= 0)
1518             {
1519                 /* We need to be careful with rounding,
1520                  * particles might be a few bits outside the local zone.
1521                  * The int cast takes care of the lower bound,
1522                  * we will explicitly take care of the upper bound.
1523                  */
1524                 cx = (int)((x[i][XX] - grid->c0[XX])*grid->inv_sx);
1525                 cy = (int)((x[i][YY] - grid->c0[YY])*grid->inv_sy);
1526
1527 #ifndef NDEBUG
1528                 if (cx < 0 || cx > grid->ncx ||
1529                     cy < 0 || cy > grid->ncy)
1530                 {
1531                     gmx_fatal(FARGS,
1532                               "grid cell cx %d cy %d out of range (max %d %d)\n"
1533                               "atom %f %f %f, grid->c0 %f %f",
1534                               cx, cy, grid->ncx, grid->ncy,
1535                               x[i][XX], x[i][YY], x[i][ZZ], grid->c0[XX], grid->c0[YY]);
1536                 }
1537 #endif
1538                 /* Take care of potential rouding issues */
1539                 cx = min(cx, grid->ncx - 1);
1540                 cy = min(cy, grid->ncy - 1);
1541
1542                 /* For the moment cell will contain only the, grid local,
1543                  * x and y indices, not z.
1544                  */
1545                 cell[i] = cx*grid->ncy + cy;
1546             }
1547             else
1548             {
1549                 /* Put this moved particle after the end of the grid,
1550                  * so we can process it later without using conditionals.
1551                  */
1552                 cell[i] = grid->ncx*grid->ncy;
1553             }
1554
1555             cxy_na[cell[i]]++;
1556         }
1557     }
1558     else
1559     {
1560         /* Non-home zone */
1561         for (i = n0; i < n1; i++)
1562         {
1563             cx = (int)((x[i][XX] - grid->c0[XX])*grid->inv_sx);
1564             cy = (int)((x[i][YY] - grid->c0[YY])*grid->inv_sy);
1565
1566             /* For non-home zones there could be particles outside
1567              * the non-bonded cut-off range, which have been communicated
1568              * for bonded interactions only. For the result it doesn't
1569              * matter where these end up on the grid. For performance
1570              * we put them in an extra row at the border.
1571              */
1572             cx = max(cx, 0);
1573             cx = min(cx, grid->ncx - 1);
1574             cy = max(cy, 0);
1575             cy = min(cy, grid->ncy - 1);
1576
1577             /* For the moment cell will contain only the, grid local,
1578              * x and y indices, not z.
1579              */
1580             cell[i] = cx*grid->ncy + cy;
1581
1582             cxy_na[cell[i]]++;
1583         }
1584     }
1585 }
1586
1587 /* Determine in which grid cells the atoms should go */
1588 static void calc_cell_indices(const nbnxn_search_t nbs,
1589                               int dd_zone,
1590                               nbnxn_grid_t *grid,
1591                               int a0, int a1,
1592                               const int *atinfo,
1593                               rvec *x,
1594                               const int *move,
1595                               nbnxn_atomdata_t *nbat)
1596 {
1597     int   n0, n1, i;
1598     int   cx, cy, cxy, ncz_max, ncz;
1599     int   nthread, thread;
1600     int  *cxy_na, cxy_na_i;
1601
1602     nthread = gmx_omp_nthreads_get(emntPairsearch);
1603
1604 #pragma omp parallel for num_threads(nthread) schedule(static)
1605     for (thread = 0; thread < nthread; thread++)
1606     {
1607         calc_column_indices(grid, a0, a1, x, dd_zone, move, thread, nthread,
1608                             nbs->cell, nbs->work[thread].cxy_na);
1609     }
1610
1611     /* Make the cell index as a function of x and y */
1612     ncz_max          = 0;
1613     ncz              = 0;
1614     grid->cxy_ind[0] = 0;
1615     for (i = 0; i < grid->ncx*grid->ncy+1; i++)
1616     {
1617         /* We set ncz_max at the beginning of the loop iso at the end
1618          * to skip i=grid->ncx*grid->ncy which are moved particles
1619          * that do not need to be ordered on the grid.
1620          */
1621         if (ncz > ncz_max)
1622         {
1623             ncz_max = ncz;
1624         }
1625         cxy_na_i = nbs->work[0].cxy_na[i];
1626         for (thread = 1; thread < nthread; thread++)
1627         {
1628             cxy_na_i += nbs->work[thread].cxy_na[i];
1629         }
1630         ncz = (cxy_na_i + grid->na_sc - 1)/grid->na_sc;
1631         if (nbat->XFormat == nbatX8)
1632         {
1633             /* Make the number of cell a multiple of 2 */
1634             ncz = (ncz + 1) & ~1;
1635         }
1636         grid->cxy_ind[i+1] = grid->cxy_ind[i] + ncz;
1637         /* Clear cxy_na, so we can reuse the array below */
1638         grid->cxy_na[i] = 0;
1639     }
1640     grid->nc = grid->cxy_ind[grid->ncx*grid->ncy] - grid->cxy_ind[0];
1641
1642     nbat->natoms = (grid->cell0 + grid->nc)*grid->na_sc;
1643
1644     if (debug)
1645     {
1646         fprintf(debug, "ns na_sc %d na_c %d super-cells: %d x %d y %d z %.1f maxz %d\n",
1647                 grid->na_sc, grid->na_c, grid->nc,
1648                 grid->ncx, grid->ncy, grid->nc/((double)(grid->ncx*grid->ncy)),
1649                 ncz_max);
1650         if (gmx_debug_at)
1651         {
1652             i = 0;
1653             for (cy = 0; cy < grid->ncy; cy++)
1654             {
1655                 for (cx = 0; cx < grid->ncx; cx++)
1656                 {
1657                     fprintf(debug, " %2d", grid->cxy_ind[i+1]-grid->cxy_ind[i]);
1658                     i++;
1659                 }
1660                 fprintf(debug, "\n");
1661             }
1662         }
1663     }
1664
1665     /* Make sure the work array for sorting is large enough */
1666     if (ncz_max*grid->na_sc*SGSF > nbs->work[0].sort_work_nalloc)
1667     {
1668         for (thread = 0; thread < nbs->nthread_max; thread++)
1669         {
1670             nbs->work[thread].sort_work_nalloc =
1671                 over_alloc_large(ncz_max*grid->na_sc*SGSF);
1672             srenew(nbs->work[thread].sort_work,
1673                    nbs->work[thread].sort_work_nalloc);
1674             /* When not in use, all elements should be -1 */
1675             for (i = 0; i < nbs->work[thread].sort_work_nalloc; i++)
1676             {
1677                 nbs->work[thread].sort_work[i] = -1;
1678             }
1679         }
1680     }
1681
1682     /* Now we know the dimensions we can fill the grid.
1683      * This is the first, unsorted fill. We sort the columns after this.
1684      */
1685     for (i = a0; i < a1; i++)
1686     {
1687         /* At this point nbs->cell contains the local grid x,y indices */
1688         cxy = nbs->cell[i];
1689         nbs->a[(grid->cell0 + grid->cxy_ind[cxy])*grid->na_sc + grid->cxy_na[cxy]++] = i;
1690     }
1691
1692     if (dd_zone == 0)
1693     {
1694         /* Set the cell indices for the moved particles */
1695         n0 = grid->nc*grid->na_sc;
1696         n1 = grid->nc*grid->na_sc+grid->cxy_na[grid->ncx*grid->ncy];
1697         if (dd_zone == 0)
1698         {
1699             for (i = n0; i < n1; i++)
1700             {
1701                 nbs->cell[nbs->a[i]] = i;
1702             }
1703         }
1704     }
1705
1706     /* Sort the super-cell columns along z into the sub-cells. */
1707 #pragma omp parallel for num_threads(nthread) schedule(static)
1708     for (thread = 0; thread < nthread; thread++)
1709     {
1710         if (grid->bSimple)
1711         {
1712             sort_columns_simple(nbs, dd_zone, grid, a0, a1, atinfo, x, nbat,
1713                                 ((thread+0)*grid->ncx*grid->ncy)/nthread,
1714                                 ((thread+1)*grid->ncx*grid->ncy)/nthread,
1715                                 nbs->work[thread].sort_work);
1716         }
1717         else
1718         {
1719             sort_columns_supersub(nbs, dd_zone, grid, a0, a1, atinfo, x, nbat,
1720                                   ((thread+0)*grid->ncx*grid->ncy)/nthread,
1721                                   ((thread+1)*grid->ncx*grid->ncy)/nthread,
1722                                   nbs->work[thread].sort_work);
1723         }
1724     }
1725
1726     if (grid->bSimple && nbat->XFormat == nbatX8)
1727     {
1728         combine_bounding_box_pairs(grid, grid->bb);
1729     }
1730
1731     if (!grid->bSimple)
1732     {
1733         grid->nsubc_tot = 0;
1734         for (i = 0; i < grid->nc; i++)
1735         {
1736             grid->nsubc_tot += grid->nsubc[i];
1737         }
1738     }
1739
1740     if (debug)
1741     {
1742         if (grid->bSimple)
1743         {
1744             print_bbsizes_simple(debug, grid);
1745         }
1746         else
1747         {
1748             fprintf(debug, "ns non-zero sub-cells: %d average atoms %.2f\n",
1749                     grid->nsubc_tot, (a1-a0)/(double)grid->nsubc_tot);
1750
1751             print_bbsizes_supersub(debug, grid);
1752         }
1753     }
1754 }
1755
1756 static void init_buffer_flags(nbnxn_buffer_flags_t *flags,
1757                               int                   natoms)
1758 {
1759     int b;
1760
1761     flags->nflag = (natoms + NBNXN_BUFFERFLAG_SIZE - 1)/NBNXN_BUFFERFLAG_SIZE;
1762     if (flags->nflag > flags->flag_nalloc)
1763     {
1764         flags->flag_nalloc = over_alloc_large(flags->nflag);
1765         srenew(flags->flag, flags->flag_nalloc);
1766     }
1767     for (b = 0; b < flags->nflag; b++)
1768     {
1769         bitmask_clear(&(flags->flag[b]));
1770     }
1771 }
1772
1773 /* Sets up a grid and puts the atoms on the grid.
1774  * This function only operates on one domain of the domain decompostion.
1775  * Note that without domain decomposition there is only one domain.
1776  */
1777 void nbnxn_put_on_grid(nbnxn_search_t nbs,
1778                        int ePBC, matrix box,
1779                        int dd_zone,
1780                        rvec corner0, rvec corner1,
1781                        int a0, int a1,
1782                        real atom_density,
1783                        const int *atinfo,
1784                        rvec *x,
1785                        int nmoved, int *move,
1786                        int nb_kernel_type,
1787                        nbnxn_atomdata_t *nbat)
1788 {
1789     nbnxn_grid_t *grid;
1790     int           n;
1791     int           nc_max_grid, nc_max;
1792
1793     grid = &nbs->grid[dd_zone];
1794
1795     nbs_cycle_start(&nbs->cc[enbsCCgrid]);
1796
1797     grid->bSimple = nbnxn_kernel_pairlist_simple(nb_kernel_type);
1798
1799     grid->na_c      = nbnxn_kernel_to_ci_size(nb_kernel_type);
1800     grid->na_cj     = nbnxn_kernel_to_cj_size(nb_kernel_type);
1801     grid->na_sc     = (grid->bSimple ? 1 : GPU_NSUBCELL)*grid->na_c;
1802     grid->na_c_2log = get_2log(grid->na_c);
1803
1804     nbat->na_c = grid->na_c;
1805
1806     if (dd_zone == 0)
1807     {
1808         grid->cell0 = 0;
1809     }
1810     else
1811     {
1812         grid->cell0 =
1813             (nbs->grid[dd_zone-1].cell0 + nbs->grid[dd_zone-1].nc)*
1814             nbs->grid[dd_zone-1].na_sc/grid->na_sc;
1815     }
1816
1817     n = a1 - a0;
1818
1819     if (dd_zone == 0)
1820     {
1821         nbs->ePBC = ePBC;
1822         copy_mat(box, nbs->box);
1823
1824         /* Avoid zero density */
1825         if (atom_density > 0)
1826         {
1827             grid->atom_density = atom_density;
1828         }
1829         else
1830         {
1831             grid->atom_density = grid_atom_density(n-nmoved, corner0, corner1);
1832         }
1833
1834         grid->cell0 = 0;
1835
1836         nbs->natoms_local    = a1 - nmoved;
1837         /* We assume that nbnxn_put_on_grid is called first
1838          * for the local atoms (dd_zone=0).
1839          */
1840         nbs->natoms_nonlocal = a1 - nmoved;
1841
1842         if (debug)
1843         {
1844             fprintf(debug, "natoms_local = %5d atom_density = %5.1f\n",
1845                     nbs->natoms_local, grid->atom_density);
1846         }
1847     }
1848     else
1849     {
1850         nbs->natoms_nonlocal = max(nbs->natoms_nonlocal, a1);
1851     }
1852
1853     /* We always use the home zone (grid[0]) for setting the cell size,
1854      * since determining densities for non-local zones is difficult.
1855      */
1856     nc_max_grid = set_grid_size_xy(nbs, grid,
1857                                    dd_zone, n-nmoved, corner0, corner1,
1858                                    nbs->grid[0].atom_density);
1859
1860     nc_max = grid->cell0 + nc_max_grid;
1861
1862     if (a1 > nbs->cell_nalloc)
1863     {
1864         nbs->cell_nalloc = over_alloc_large(a1);
1865         srenew(nbs->cell, nbs->cell_nalloc);
1866     }
1867
1868     /* To avoid conditionals we store the moved particles at the end of a,
1869      * make sure we have enough space.
1870      */
1871     if (nc_max*grid->na_sc + nmoved > nbs->a_nalloc)
1872     {
1873         nbs->a_nalloc = over_alloc_large(nc_max*grid->na_sc + nmoved);
1874         srenew(nbs->a, nbs->a_nalloc);
1875     }
1876
1877     /* We need padding up to a multiple of the buffer flag size: simply add */
1878     if (nc_max*grid->na_sc + NBNXN_BUFFERFLAG_SIZE > nbat->nalloc)
1879     {
1880         nbnxn_atomdata_realloc(nbat, nc_max*grid->na_sc+NBNXN_BUFFERFLAG_SIZE);
1881     }
1882
1883     calc_cell_indices(nbs, dd_zone, grid, a0, a1, atinfo, x, move, nbat);
1884
1885     if (dd_zone == 0)
1886     {
1887         nbat->natoms_local = nbat->natoms;
1888     }
1889
1890     nbs_cycle_stop(&nbs->cc[enbsCCgrid]);
1891 }
1892
1893 /* Calls nbnxn_put_on_grid for all non-local domains */
1894 void nbnxn_put_on_grid_nonlocal(nbnxn_search_t            nbs,
1895                                 const gmx_domdec_zones_t *zones,
1896                                 const int                *atinfo,
1897                                 rvec                     *x,
1898                                 int                       nb_kernel_type,
1899                                 nbnxn_atomdata_t         *nbat)
1900 {
1901     int  zone, d;
1902     rvec c0, c1;
1903
1904     for (zone = 1; zone < zones->n; zone++)
1905     {
1906         for (d = 0; d < DIM; d++)
1907         {
1908             c0[d] = zones->size[zone].bb_x0[d];
1909             c1[d] = zones->size[zone].bb_x1[d];
1910         }
1911
1912         nbnxn_put_on_grid(nbs, nbs->ePBC, NULL,
1913                           zone, c0, c1,
1914                           zones->cg_range[zone],
1915                           zones->cg_range[zone+1],
1916                           -1,
1917                           atinfo,
1918                           x,
1919                           0, NULL,
1920                           nb_kernel_type,
1921                           nbat);
1922     }
1923 }
1924
1925 /* Add simple grid type information to the local super/sub grid */
1926 void nbnxn_grid_add_simple(nbnxn_search_t    nbs,
1927                            nbnxn_atomdata_t *nbat)
1928 {
1929     nbnxn_grid_t *grid;
1930     float        *bbcz;
1931     nbnxn_bb_t   *bb;
1932     int           ncd, sc;
1933     int           nthreads gmx_unused;
1934
1935     grid = &nbs->grid[0];
1936
1937     if (grid->bSimple)
1938     {
1939         gmx_incons("nbnxn_grid_simple called with a simple grid");
1940     }
1941
1942     ncd = grid->na_sc/NBNXN_CPU_CLUSTER_I_SIZE;
1943
1944     if (grid->nc*ncd > grid->nc_nalloc_simple)
1945     {
1946         grid->nc_nalloc_simple = over_alloc_large(grid->nc*ncd);
1947         srenew(grid->bbcz_simple, grid->nc_nalloc_simple*NNBSBB_D);
1948         srenew(grid->bb_simple, grid->nc_nalloc_simple);
1949         srenew(grid->flags_simple, grid->nc_nalloc_simple);
1950         if (nbat->XFormat)
1951         {
1952             sfree_aligned(grid->bbj);
1953             snew_aligned(grid->bbj, grid->nc_nalloc_simple/2, 16);
1954         }
1955     }
1956
1957     bbcz = grid->bbcz_simple;
1958     bb   = grid->bb_simple;
1959
1960     nthreads = gmx_omp_nthreads_get(emntPairsearch);
1961 #pragma omp parallel for num_threads(nthreads) schedule(static)
1962     for (sc = 0; sc < grid->nc; sc++)
1963     {
1964         int c, tx, na;
1965
1966         for (c = 0; c < ncd; c++)
1967         {
1968             tx = sc*ncd + c;
1969
1970             na = NBNXN_CPU_CLUSTER_I_SIZE;
1971             while (na > 0 &&
1972                    nbat->type[tx*NBNXN_CPU_CLUSTER_I_SIZE+na-1] == nbat->ntype-1)
1973             {
1974                 na--;
1975             }
1976
1977             if (na > 0)
1978             {
1979                 switch (nbat->XFormat)
1980                 {
1981                     case nbatX4:
1982                         /* PACK_X4==NBNXN_CPU_CLUSTER_I_SIZE, so this is simple */
1983                         calc_bounding_box_x_x4(na, nbat->x+tx*STRIDE_P4,
1984                                                bb+tx);
1985                         break;
1986                     case nbatX8:
1987                         /* PACK_X8>NBNXN_CPU_CLUSTER_I_SIZE, more complicated */
1988                         calc_bounding_box_x_x8(na, nbat->x+X8_IND_A(tx*NBNXN_CPU_CLUSTER_I_SIZE),
1989                                                bb+tx);
1990                         break;
1991                     default:
1992                         calc_bounding_box(na, nbat->xstride,
1993                                           nbat->x+tx*NBNXN_CPU_CLUSTER_I_SIZE*nbat->xstride,
1994                                           bb+tx);
1995                         break;
1996                 }
1997                 bbcz[tx*NNBSBB_D+0] = bb[tx].lower[BB_Z];
1998                 bbcz[tx*NNBSBB_D+1] = bb[tx].upper[BB_Z];
1999
2000                 /* No interaction optimization yet here */
2001                 grid->flags_simple[tx] = NBNXN_CI_DO_LJ(0) | NBNXN_CI_DO_COUL(0);
2002             }
2003             else
2004             {
2005                 grid->flags_simple[tx] = 0;
2006             }
2007         }
2008     }
2009
2010     if (grid->bSimple && nbat->XFormat == nbatX8)
2011     {
2012         combine_bounding_box_pairs(grid, grid->bb_simple);
2013     }
2014 }
2015
2016 void nbnxn_get_ncells(nbnxn_search_t nbs, int *ncx, int *ncy)
2017 {
2018     *ncx = nbs->grid[0].ncx;
2019     *ncy = nbs->grid[0].ncy;
2020 }
2021
2022 void nbnxn_get_atomorder(nbnxn_search_t nbs, int **a, int *n)
2023 {
2024     const nbnxn_grid_t *grid;
2025
2026     grid = &nbs->grid[0];
2027
2028     /* Return the atom order for the home cell (index 0) */
2029     *a  = nbs->a;
2030
2031     *n = grid->cxy_ind[grid->ncx*grid->ncy]*grid->na_sc;
2032 }
2033
2034 void nbnxn_set_atomorder(nbnxn_search_t nbs)
2035 {
2036     nbnxn_grid_t *grid;
2037     int           ao, cx, cy, cxy, cz, j;
2038
2039     /* Set the atom order for the home cell (index 0) */
2040     grid = &nbs->grid[0];
2041
2042     ao = 0;
2043     for (cx = 0; cx < grid->ncx; cx++)
2044     {
2045         for (cy = 0; cy < grid->ncy; cy++)
2046         {
2047             cxy = cx*grid->ncy + cy;
2048             j   = grid->cxy_ind[cxy]*grid->na_sc;
2049             for (cz = 0; cz < grid->cxy_na[cxy]; cz++)
2050             {
2051                 nbs->a[j]     = ao;
2052                 nbs->cell[ao] = j;
2053                 ao++;
2054                 j++;
2055             }
2056         }
2057     }
2058 }
2059
2060 /* Determines the cell range along one dimension that
2061  * the bounding box b0 - b1 sees.
2062  */
2063 static void get_cell_range(real b0, real b1,
2064                            int nc, real c0, real s, real invs,
2065                            real d2, real r2, int *cf, int *cl)
2066 {
2067     *cf = max((int)((b0 - c0)*invs), 0);
2068
2069     while (*cf > 0 && d2 + sqr((b0 - c0) - (*cf-1+1)*s) < r2)
2070     {
2071         (*cf)--;
2072     }
2073
2074     *cl = min((int)((b1 - c0)*invs), nc-1);
2075     while (*cl < nc-1 && d2 + sqr((*cl+1)*s - (b1 - c0)) < r2)
2076     {
2077         (*cl)++;
2078     }
2079 }
2080
2081 /* Reference code calculating the distance^2 between two bounding boxes */
2082 static float box_dist2(float bx0, float bx1, float by0,
2083                        float by1, float bz0, float bz1,
2084                        const nbnxn_bb_t *bb)
2085 {
2086     float d2;
2087     float dl, dh, dm, dm0;
2088
2089     d2 = 0;
2090
2091     dl  = bx0 - bb->upper[BB_X];
2092     dh  = bb->lower[BB_X] - bx1;
2093     dm  = max(dl, dh);
2094     dm0 = max(dm, 0);
2095     d2 += dm0*dm0;
2096
2097     dl  = by0 - bb->upper[BB_Y];
2098     dh  = bb->lower[BB_Y] - by1;
2099     dm  = max(dl, dh);
2100     dm0 = max(dm, 0);
2101     d2 += dm0*dm0;
2102
2103     dl  = bz0 - bb->upper[BB_Z];
2104     dh  = bb->lower[BB_Z] - bz1;
2105     dm  = max(dl, dh);
2106     dm0 = max(dm, 0);
2107     d2 += dm0*dm0;
2108
2109     return d2;
2110 }
2111
2112 /* Plain C code calculating the distance^2 between two bounding boxes */
2113 static float subc_bb_dist2(int si, const nbnxn_bb_t *bb_i_ci,
2114                            int csj, const nbnxn_bb_t *bb_j_all)
2115 {
2116     const nbnxn_bb_t *bb_i, *bb_j;
2117     float             d2;
2118     float             dl, dh, dm, dm0;
2119
2120     bb_i = bb_i_ci  +  si;
2121     bb_j = bb_j_all + csj;
2122
2123     d2 = 0;
2124
2125     dl  = bb_i->lower[BB_X] - bb_j->upper[BB_X];
2126     dh  = bb_j->lower[BB_X] - bb_i->upper[BB_X];
2127     dm  = max(dl, dh);
2128     dm0 = max(dm, 0);
2129     d2 += dm0*dm0;
2130
2131     dl  = bb_i->lower[BB_Y] - bb_j->upper[BB_Y];
2132     dh  = bb_j->lower[BB_Y] - bb_i->upper[BB_Y];
2133     dm  = max(dl, dh);
2134     dm0 = max(dm, 0);
2135     d2 += dm0*dm0;
2136
2137     dl  = bb_i->lower[BB_Z] - bb_j->upper[BB_Z];
2138     dh  = bb_j->lower[BB_Z] - bb_i->upper[BB_Z];
2139     dm  = max(dl, dh);
2140     dm0 = max(dm, 0);
2141     d2 += dm0*dm0;
2142
2143     return d2;
2144 }
2145
2146 #ifdef NBNXN_SEARCH_BB_SIMD4
2147
2148 /* 4-wide SIMD code for bb distance for bb format xyz0 */
2149 static float subc_bb_dist2_simd4(int si, const nbnxn_bb_t *bb_i_ci,
2150                                  int csj, const nbnxn_bb_t *bb_j_all)
2151 {
2152     gmx_simd4_float_t bb_i_S0, bb_i_S1;
2153     gmx_simd4_float_t bb_j_S0, bb_j_S1;
2154     gmx_simd4_float_t dl_S;
2155     gmx_simd4_float_t dh_S;
2156     gmx_simd4_float_t dm_S;
2157     gmx_simd4_float_t dm0_S;
2158
2159     bb_i_S0 = gmx_simd4_load_f(&bb_i_ci[si].lower[0]);
2160     bb_i_S1 = gmx_simd4_load_f(&bb_i_ci[si].upper[0]);
2161     bb_j_S0 = gmx_simd4_load_f(&bb_j_all[csj].lower[0]);
2162     bb_j_S1 = gmx_simd4_load_f(&bb_j_all[csj].upper[0]);
2163
2164     dl_S    = gmx_simd4_sub_f(bb_i_S0, bb_j_S1);
2165     dh_S    = gmx_simd4_sub_f(bb_j_S0, bb_i_S1);
2166
2167     dm_S    = gmx_simd4_max_f(dl_S, dh_S);
2168     dm0_S   = gmx_simd4_max_f(dm_S, gmx_simd4_setzero_f());
2169
2170     return gmx_simd4_dotproduct3_f(dm0_S, dm0_S);
2171 }
2172
2173 /* Calculate bb bounding distances of bb_i[si,...,si+3] and store them in d2 */
2174 #define SUBC_BB_DIST2_SIMD4_XXXX_INNER(si, bb_i, d2) \
2175     {                                                \
2176         int               shi;                                  \
2177                                                  \
2178         gmx_simd4_float_t dx_0, dy_0, dz_0;                    \
2179         gmx_simd4_float_t dx_1, dy_1, dz_1;                    \
2180                                                  \
2181         gmx_simd4_float_t mx, my, mz;                          \
2182         gmx_simd4_float_t m0x, m0y, m0z;                       \
2183                                                  \
2184         gmx_simd4_float_t d2x, d2y, d2z;                       \
2185         gmx_simd4_float_t d2s, d2t;                            \
2186                                                  \
2187         shi = si*NNBSBB_D*DIM;                       \
2188                                                  \
2189         xi_l = gmx_simd4_load_f(bb_i+shi+0*STRIDE_PBB);   \
2190         yi_l = gmx_simd4_load_f(bb_i+shi+1*STRIDE_PBB);   \
2191         zi_l = gmx_simd4_load_f(bb_i+shi+2*STRIDE_PBB);   \
2192         xi_h = gmx_simd4_load_f(bb_i+shi+3*STRIDE_PBB);   \
2193         yi_h = gmx_simd4_load_f(bb_i+shi+4*STRIDE_PBB);   \
2194         zi_h = gmx_simd4_load_f(bb_i+shi+5*STRIDE_PBB);   \
2195                                                  \
2196         dx_0 = gmx_simd4_sub_f(xi_l, xj_h);                 \
2197         dy_0 = gmx_simd4_sub_f(yi_l, yj_h);                 \
2198         dz_0 = gmx_simd4_sub_f(zi_l, zj_h);                 \
2199                                                  \
2200         dx_1 = gmx_simd4_sub_f(xj_l, xi_h);                 \
2201         dy_1 = gmx_simd4_sub_f(yj_l, yi_h);                 \
2202         dz_1 = gmx_simd4_sub_f(zj_l, zi_h);                 \
2203                                                  \
2204         mx   = gmx_simd4_max_f(dx_0, dx_1);                 \
2205         my   = gmx_simd4_max_f(dy_0, dy_1);                 \
2206         mz   = gmx_simd4_max_f(dz_0, dz_1);                 \
2207                                                  \
2208         m0x  = gmx_simd4_max_f(mx, zero);                   \
2209         m0y  = gmx_simd4_max_f(my, zero);                   \
2210         m0z  = gmx_simd4_max_f(mz, zero);                   \
2211                                                  \
2212         d2x  = gmx_simd4_mul_f(m0x, m0x);                   \
2213         d2y  = gmx_simd4_mul_f(m0y, m0y);                   \
2214         d2z  = gmx_simd4_mul_f(m0z, m0z);                   \
2215                                                  \
2216         d2s  = gmx_simd4_add_f(d2x, d2y);                   \
2217         d2t  = gmx_simd4_add_f(d2s, d2z);                   \
2218                                                  \
2219         gmx_simd4_store_f(d2+si, d2t);                      \
2220     }
2221
2222 /* 4-wide SIMD code for nsi bb distances for bb format xxxxyyyyzzzz */
2223 static void subc_bb_dist2_simd4_xxxx(const float *bb_j,
2224                                      int nsi, const float *bb_i,
2225                                      float *d2)
2226 {
2227     gmx_simd4_float_t xj_l, yj_l, zj_l;
2228     gmx_simd4_float_t xj_h, yj_h, zj_h;
2229     gmx_simd4_float_t xi_l, yi_l, zi_l;
2230     gmx_simd4_float_t xi_h, yi_h, zi_h;
2231
2232     gmx_simd4_float_t zero;
2233
2234     zero = gmx_simd4_setzero_f();
2235
2236     xj_l = gmx_simd4_set1_f(bb_j[0*STRIDE_PBB]);
2237     yj_l = gmx_simd4_set1_f(bb_j[1*STRIDE_PBB]);
2238     zj_l = gmx_simd4_set1_f(bb_j[2*STRIDE_PBB]);
2239     xj_h = gmx_simd4_set1_f(bb_j[3*STRIDE_PBB]);
2240     yj_h = gmx_simd4_set1_f(bb_j[4*STRIDE_PBB]);
2241     zj_h = gmx_simd4_set1_f(bb_j[5*STRIDE_PBB]);
2242
2243     /* Here we "loop" over si (0,STRIDE_PBB) from 0 to nsi with step STRIDE_PBB.
2244      * But as we know the number of iterations is 1 or 2, we unroll manually.
2245      */
2246     SUBC_BB_DIST2_SIMD4_XXXX_INNER(0, bb_i, d2);
2247     if (STRIDE_PBB < nsi)
2248     {
2249         SUBC_BB_DIST2_SIMD4_XXXX_INNER(STRIDE_PBB, bb_i, d2);
2250     }
2251 }
2252
2253 #endif /* NBNXN_SEARCH_BB_SIMD4 */
2254
2255 /* Plain C function which determines if any atom pair between two cells
2256  * is within distance sqrt(rl2).
2257  */
2258 static gmx_bool subc_in_range_x(int na_c,
2259                                 int si, const real *x_i,
2260                                 int csj, int stride, const real *x_j,
2261                                 real rl2)
2262 {
2263     int  i, j, i0, j0;
2264     real d2;
2265
2266     for (i = 0; i < na_c; i++)
2267     {
2268         i0 = (si*na_c + i)*DIM;
2269         for (j = 0; j < na_c; j++)
2270         {
2271             j0 = (csj*na_c + j)*stride;
2272
2273             d2 = sqr(x_i[i0  ] - x_j[j0  ]) +
2274                 sqr(x_i[i0+1] - x_j[j0+1]) +
2275                 sqr(x_i[i0+2] - x_j[j0+2]);
2276
2277             if (d2 < rl2)
2278             {
2279                 return TRUE;
2280             }
2281         }
2282     }
2283
2284     return FALSE;
2285 }
2286
2287 #ifdef NBNXN_SEARCH_SIMD4_FLOAT_X_BB
2288
2289 /* 4-wide SIMD function which determines if any atom pair between two cells,
2290  * both with 8 atoms, is within distance sqrt(rl2).
2291  * Using 8-wide AVX is not faster on Intel Sandy Bridge.
2292  */
2293 static gmx_bool subc_in_range_simd4(int na_c,
2294                                     int si, const real *x_i,
2295                                     int csj, int stride, const real *x_j,
2296                                     real rl2)
2297 {
2298     gmx_simd4_real_t ix_S0, iy_S0, iz_S0;
2299     gmx_simd4_real_t ix_S1, iy_S1, iz_S1;
2300
2301     gmx_simd4_real_t rc2_S;
2302
2303     int              dim_stride;
2304     int              j0, j1;
2305
2306     rc2_S   = gmx_simd4_set1_r(rl2);
2307
2308     dim_stride = NBNXN_GPU_CLUSTER_SIZE/STRIDE_PBB*DIM;
2309     ix_S0      = gmx_simd4_load_r(x_i+(si*dim_stride+0)*STRIDE_PBB);
2310     iy_S0      = gmx_simd4_load_r(x_i+(si*dim_stride+1)*STRIDE_PBB);
2311     iz_S0      = gmx_simd4_load_r(x_i+(si*dim_stride+2)*STRIDE_PBB);
2312     ix_S1      = gmx_simd4_load_r(x_i+(si*dim_stride+3)*STRIDE_PBB);
2313     iy_S1      = gmx_simd4_load_r(x_i+(si*dim_stride+4)*STRIDE_PBB);
2314     iz_S1      = gmx_simd4_load_r(x_i+(si*dim_stride+5)*STRIDE_PBB);
2315
2316     /* We loop from the outer to the inner particles to maximize
2317      * the chance that we find a pair in range quickly and return.
2318      */
2319     j0 = csj*na_c;
2320     j1 = j0 + na_c - 1;
2321     while (j0 < j1)
2322     {
2323         gmx_simd4_real_t jx0_S, jy0_S, jz0_S;
2324         gmx_simd4_real_t jx1_S, jy1_S, jz1_S;
2325
2326         gmx_simd4_real_t dx_S0, dy_S0, dz_S0;
2327         gmx_simd4_real_t dx_S1, dy_S1, dz_S1;
2328         gmx_simd4_real_t dx_S2, dy_S2, dz_S2;
2329         gmx_simd4_real_t dx_S3, dy_S3, dz_S3;
2330
2331         gmx_simd4_real_t rsq_S0;
2332         gmx_simd4_real_t rsq_S1;
2333         gmx_simd4_real_t rsq_S2;
2334         gmx_simd4_real_t rsq_S3;
2335
2336         gmx_simd4_bool_t wco_S0;
2337         gmx_simd4_bool_t wco_S1;
2338         gmx_simd4_bool_t wco_S2;
2339         gmx_simd4_bool_t wco_S3;
2340         gmx_simd4_bool_t wco_any_S01, wco_any_S23, wco_any_S;
2341
2342         jx0_S = gmx_simd4_set1_r(x_j[j0*stride+0]);
2343         jy0_S = gmx_simd4_set1_r(x_j[j0*stride+1]);
2344         jz0_S = gmx_simd4_set1_r(x_j[j0*stride+2]);
2345
2346         jx1_S = gmx_simd4_set1_r(x_j[j1*stride+0]);
2347         jy1_S = gmx_simd4_set1_r(x_j[j1*stride+1]);
2348         jz1_S = gmx_simd4_set1_r(x_j[j1*stride+2]);
2349
2350         /* Calculate distance */
2351         dx_S0            = gmx_simd4_sub_r(ix_S0, jx0_S);
2352         dy_S0            = gmx_simd4_sub_r(iy_S0, jy0_S);
2353         dz_S0            = gmx_simd4_sub_r(iz_S0, jz0_S);
2354         dx_S1            = gmx_simd4_sub_r(ix_S1, jx0_S);
2355         dy_S1            = gmx_simd4_sub_r(iy_S1, jy0_S);
2356         dz_S1            = gmx_simd4_sub_r(iz_S1, jz0_S);
2357         dx_S2            = gmx_simd4_sub_r(ix_S0, jx1_S);
2358         dy_S2            = gmx_simd4_sub_r(iy_S0, jy1_S);
2359         dz_S2            = gmx_simd4_sub_r(iz_S0, jz1_S);
2360         dx_S3            = gmx_simd4_sub_r(ix_S1, jx1_S);
2361         dy_S3            = gmx_simd4_sub_r(iy_S1, jy1_S);
2362         dz_S3            = gmx_simd4_sub_r(iz_S1, jz1_S);
2363
2364         /* rsq = dx*dx+dy*dy+dz*dz */
2365         rsq_S0           = gmx_simd4_calc_rsq_r(dx_S0, dy_S0, dz_S0);
2366         rsq_S1           = gmx_simd4_calc_rsq_r(dx_S1, dy_S1, dz_S1);
2367         rsq_S2           = gmx_simd4_calc_rsq_r(dx_S2, dy_S2, dz_S2);
2368         rsq_S3           = gmx_simd4_calc_rsq_r(dx_S3, dy_S3, dz_S3);
2369
2370         wco_S0           = gmx_simd4_cmplt_r(rsq_S0, rc2_S);
2371         wco_S1           = gmx_simd4_cmplt_r(rsq_S1, rc2_S);
2372         wco_S2           = gmx_simd4_cmplt_r(rsq_S2, rc2_S);
2373         wco_S3           = gmx_simd4_cmplt_r(rsq_S3, rc2_S);
2374
2375         wco_any_S01      = gmx_simd4_or_b(wco_S0, wco_S1);
2376         wco_any_S23      = gmx_simd4_or_b(wco_S2, wco_S3);
2377         wco_any_S        = gmx_simd4_or_b(wco_any_S01, wco_any_S23);
2378
2379         if (gmx_simd4_anytrue_b(wco_any_S))
2380         {
2381             return TRUE;
2382         }
2383
2384         j0++;
2385         j1--;
2386     }
2387     return FALSE;
2388
2389 }
2390 #endif
2391
2392
2393 /* Returns the j sub-cell for index cj_ind */
2394 static int nbl_cj(const nbnxn_pairlist_t *nbl, int cj_ind)
2395 {
2396     return nbl->cj4[cj_ind >> NBNXN_GPU_JGROUP_SIZE_2LOG].cj[cj_ind & (NBNXN_GPU_JGROUP_SIZE - 1)];
2397 }
2398
2399 /* Returns the i-interaction mask of the j sub-cell for index cj_ind */
2400 static unsigned int nbl_imask0(const nbnxn_pairlist_t *nbl, int cj_ind)
2401 {
2402     return nbl->cj4[cj_ind >> NBNXN_GPU_JGROUP_SIZE_2LOG].imei[0].imask;
2403 }
2404
2405 /* Ensures there is enough space for extra extra exclusion masks */
2406 static void check_excl_space(nbnxn_pairlist_t *nbl, int extra)
2407 {
2408     if (nbl->nexcl+extra > nbl->excl_nalloc)
2409     {
2410         nbl->excl_nalloc = over_alloc_small(nbl->nexcl+extra);
2411         nbnxn_realloc_void((void **)&nbl->excl,
2412                            nbl->nexcl*sizeof(*nbl->excl),
2413                            nbl->excl_nalloc*sizeof(*nbl->excl),
2414                            nbl->alloc, nbl->free);
2415     }
2416 }
2417
2418 /* Ensures there is enough space for ncell extra j-cells in the list */
2419 static void check_subcell_list_space_simple(nbnxn_pairlist_t *nbl,
2420                                             int               ncell)
2421 {
2422     int cj_max;
2423
2424     cj_max = nbl->ncj + ncell;
2425
2426     if (cj_max > nbl->cj_nalloc)
2427     {
2428         nbl->cj_nalloc = over_alloc_small(cj_max);
2429         nbnxn_realloc_void((void **)&nbl->cj,
2430                            nbl->ncj*sizeof(*nbl->cj),
2431                            nbl->cj_nalloc*sizeof(*nbl->cj),
2432                            nbl->alloc, nbl->free);
2433     }
2434 }
2435
2436 /* Ensures there is enough space for ncell extra j-subcells in the list */
2437 static void check_subcell_list_space_supersub(nbnxn_pairlist_t *nbl,
2438                                               int               nsupercell)
2439 {
2440     int ncj4_max, j4, j, w, t;
2441
2442 #define NWARP       2
2443 #define WARP_SIZE  32
2444
2445     /* We can have maximally nsupercell*GPU_NSUBCELL sj lists */
2446     /* We can store 4 j-subcell - i-supercell pairs in one struct.
2447      * since we round down, we need one extra entry.
2448      */
2449     ncj4_max = ((nbl->work->cj_ind + nsupercell*GPU_NSUBCELL + NBNXN_GPU_JGROUP_SIZE - 1) >> NBNXN_GPU_JGROUP_SIZE_2LOG);
2450
2451     if (ncj4_max > nbl->cj4_nalloc)
2452     {
2453         nbl->cj4_nalloc = over_alloc_small(ncj4_max);
2454         nbnxn_realloc_void((void **)&nbl->cj4,
2455                            nbl->work->cj4_init*sizeof(*nbl->cj4),
2456                            nbl->cj4_nalloc*sizeof(*nbl->cj4),
2457                            nbl->alloc, nbl->free);
2458     }
2459
2460     if (ncj4_max > nbl->work->cj4_init)
2461     {
2462         for (j4 = nbl->work->cj4_init; j4 < ncj4_max; j4++)
2463         {
2464             /* No i-subcells and no excl's in the list initially */
2465             for (w = 0; w < NWARP; w++)
2466             {
2467                 nbl->cj4[j4].imei[w].imask    = 0U;
2468                 nbl->cj4[j4].imei[w].excl_ind = 0;
2469
2470             }
2471         }
2472         nbl->work->cj4_init = ncj4_max;
2473     }
2474 }
2475
2476 /* Set all excl masks for one GPU warp no exclusions */
2477 static void set_no_excls(nbnxn_excl_t *excl)
2478 {
2479     int t;
2480
2481     for (t = 0; t < WARP_SIZE; t++)
2482     {
2483         /* Turn all interaction bits on */
2484         excl->pair[t] = NBNXN_INTERACTION_MASK_ALL;
2485     }
2486 }
2487
2488 /* Initializes a single nbnxn_pairlist_t data structure */
2489 static void nbnxn_init_pairlist(nbnxn_pairlist_t *nbl,
2490                                 gmx_bool          bSimple,
2491                                 nbnxn_alloc_t    *alloc,
2492                                 nbnxn_free_t     *free)
2493 {
2494     if (alloc == NULL)
2495     {
2496         nbl->alloc = nbnxn_alloc_aligned;
2497     }
2498     else
2499     {
2500         nbl->alloc = alloc;
2501     }
2502     if (free == NULL)
2503     {
2504         nbl->free = nbnxn_free_aligned;
2505     }
2506     else
2507     {
2508         nbl->free = free;
2509     }
2510
2511     nbl->bSimple     = bSimple;
2512     nbl->na_sc       = 0;
2513     nbl->na_ci       = 0;
2514     nbl->na_cj       = 0;
2515     nbl->nci         = 0;
2516     nbl->ci          = NULL;
2517     nbl->ci_nalloc   = 0;
2518     nbl->ncj         = 0;
2519     nbl->cj          = NULL;
2520     nbl->cj_nalloc   = 0;
2521     nbl->ncj4        = 0;
2522     /* We need one element extra in sj, so alloc initially with 1 */
2523     nbl->cj4_nalloc  = 0;
2524     nbl->cj4         = NULL;
2525     nbl->nci_tot     = 0;
2526
2527     if (!nbl->bSimple)
2528     {
2529         nbl->excl        = NULL;
2530         nbl->excl_nalloc = 0;
2531         nbl->nexcl       = 0;
2532         check_excl_space(nbl, 1);
2533         nbl->nexcl       = 1;
2534         set_no_excls(&nbl->excl[0]);
2535     }
2536
2537     snew(nbl->work, 1);
2538     if (nbl->bSimple)
2539     {
2540         snew_aligned(nbl->work->bb_ci, 1, NBNXN_SEARCH_BB_MEM_ALIGN);
2541     }
2542     else
2543     {
2544 #ifdef NBNXN_BBXXXX
2545         snew_aligned(nbl->work->pbb_ci, GPU_NSUBCELL/STRIDE_PBB*NNBSBB_XXXX, NBNXN_SEARCH_BB_MEM_ALIGN);
2546 #else
2547         snew_aligned(nbl->work->bb_ci, GPU_NSUBCELL, NBNXN_SEARCH_BB_MEM_ALIGN);
2548 #endif
2549     }
2550     snew_aligned(nbl->work->x_ci, NBNXN_NA_SC_MAX*DIM, NBNXN_SEARCH_BB_MEM_ALIGN);
2551 #ifdef GMX_NBNXN_SIMD
2552     snew_aligned(nbl->work->x_ci_simd_4xn, 1, NBNXN_MEM_ALIGN);
2553     snew_aligned(nbl->work->x_ci_simd_2xnn, 1, NBNXN_MEM_ALIGN);
2554 #endif
2555     snew_aligned(nbl->work->d2, GPU_NSUBCELL, NBNXN_SEARCH_BB_MEM_ALIGN);
2556
2557     nbl->work->sort            = NULL;
2558     nbl->work->sort_nalloc     = 0;
2559     nbl->work->sci_sort        = NULL;
2560     nbl->work->sci_sort_nalloc = 0;
2561 }
2562
2563 void nbnxn_init_pairlist_set(nbnxn_pairlist_set_t *nbl_list,
2564                              gmx_bool bSimple, gmx_bool bCombined,
2565                              nbnxn_alloc_t *alloc,
2566                              nbnxn_free_t  *free)
2567 {
2568     int i;
2569
2570     nbl_list->bSimple   = bSimple;
2571     nbl_list->bCombined = bCombined;
2572
2573     nbl_list->nnbl = gmx_omp_nthreads_get(emntNonbonded);
2574
2575     if (!nbl_list->bCombined &&
2576         nbl_list->nnbl > NBNXN_BUFFERFLAG_MAX_THREADS)
2577     {
2578         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.",
2579                   nbl_list->nnbl, NBNXN_BUFFERFLAG_MAX_THREADS, NBNXN_BUFFERFLAG_MAX_THREADS);
2580     }
2581
2582     snew(nbl_list->nbl, nbl_list->nnbl);
2583     snew(nbl_list->nbl_fep, nbl_list->nnbl);
2584     /* Execute in order to avoid memory interleaving between threads */
2585 #pragma omp parallel for num_threads(nbl_list->nnbl) schedule(static)
2586     for (i = 0; i < nbl_list->nnbl; i++)
2587     {
2588         /* Allocate the nblist data structure locally on each thread
2589          * to optimize memory access for NUMA architectures.
2590          */
2591         snew(nbl_list->nbl[i], 1);
2592
2593         /* Only list 0 is used on the GPU, use normal allocation for i>0 */
2594         if (i == 0)
2595         {
2596             nbnxn_init_pairlist(nbl_list->nbl[i], nbl_list->bSimple, alloc, free);
2597         }
2598         else
2599         {
2600             nbnxn_init_pairlist(nbl_list->nbl[i], nbl_list->bSimple, NULL, NULL);
2601         }
2602
2603         snew(nbl_list->nbl_fep[i], 1);
2604         nbnxn_init_pairlist_fep(nbl_list->nbl_fep[i]);
2605     }
2606 }
2607
2608 /* Print statistics of a pair list, used for debug output */
2609 static void print_nblist_statistics_simple(FILE *fp, const nbnxn_pairlist_t *nbl,
2610                                            const nbnxn_search_t nbs, real rl)
2611 {
2612     const nbnxn_grid_t *grid;
2613     int                 cs[SHIFTS];
2614     int                 s, i, j;
2615     int                 npexcl;
2616
2617     /* This code only produces correct statistics with domain decomposition */
2618     grid = &nbs->grid[0];
2619
2620     fprintf(fp, "nbl nci %d ncj %d\n",
2621             nbl->nci, nbl->ncj);
2622     fprintf(fp, "nbl na_sc %d rl %g ncp %d per cell %.1f atoms %.1f ratio %.2f\n",
2623             nbl->na_sc, rl, nbl->ncj, nbl->ncj/(double)grid->nc,
2624             nbl->ncj/(double)grid->nc*grid->na_sc,
2625             nbl->ncj/(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])));
2626
2627     fprintf(fp, "nbl average j cell list length %.1f\n",
2628             0.25*nbl->ncj/(double)nbl->nci);
2629
2630     for (s = 0; s < SHIFTS; s++)
2631     {
2632         cs[s] = 0;
2633     }
2634     npexcl = 0;
2635     for (i = 0; i < nbl->nci; i++)
2636     {
2637         cs[nbl->ci[i].shift & NBNXN_CI_SHIFT] +=
2638             nbl->ci[i].cj_ind_end - nbl->ci[i].cj_ind_start;
2639
2640         j = nbl->ci[i].cj_ind_start;
2641         while (j < nbl->ci[i].cj_ind_end &&
2642                nbl->cj[j].excl != NBNXN_INTERACTION_MASK_ALL)
2643         {
2644             npexcl++;
2645             j++;
2646         }
2647     }
2648     fprintf(fp, "nbl cell pairs, total: %d excl: %d %.1f%%\n",
2649             nbl->ncj, npexcl, 100*npexcl/(double)nbl->ncj);
2650     for (s = 0; s < SHIFTS; s++)
2651     {
2652         if (cs[s] > 0)
2653         {
2654             fprintf(fp, "nbl shift %2d ncj %3d\n", s, cs[s]);
2655         }
2656     }
2657 }
2658
2659 /* Print statistics of a pair lists, used for debug output */
2660 static void print_nblist_statistics_supersub(FILE *fp, const nbnxn_pairlist_t *nbl,
2661                                              const nbnxn_search_t nbs, real rl)
2662 {
2663     const nbnxn_grid_t *grid;
2664     int                 i, j4, j, si, b;
2665     int                 c[GPU_NSUBCELL+1];
2666
2667     /* This code only produces correct statistics with domain decomposition */
2668     grid = &nbs->grid[0];
2669
2670     fprintf(fp, "nbl nsci %d ncj4 %d nsi %d excl4 %d\n",
2671             nbl->nsci, nbl->ncj4, nbl->nci_tot, nbl->nexcl);
2672     fprintf(fp, "nbl na_c %d rl %g ncp %d per cell %.1f atoms %.1f ratio %.2f\n",
2673             nbl->na_ci, rl, nbl->nci_tot, nbl->nci_tot/(double)grid->nsubc_tot,
2674             nbl->nci_tot/(double)grid->nsubc_tot*grid->na_c,
2675             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])));
2676
2677     fprintf(fp, "nbl average j super cell list length %.1f\n",
2678             0.25*nbl->ncj4/(double)nbl->nsci);
2679     fprintf(fp, "nbl average i sub cell list length %.1f\n",
2680             nbl->nci_tot/((double)nbl->ncj4));
2681
2682     for (si = 0; si <= GPU_NSUBCELL; si++)
2683     {
2684         c[si] = 0;
2685     }
2686     for (i = 0; i < nbl->nsci; i++)
2687     {
2688         for (j4 = nbl->sci[i].cj4_ind_start; j4 < nbl->sci[i].cj4_ind_end; j4++)
2689         {
2690             for (j = 0; j < NBNXN_GPU_JGROUP_SIZE; j++)
2691             {
2692                 b = 0;
2693                 for (si = 0; si < GPU_NSUBCELL; si++)
2694                 {
2695                     if (nbl->cj4[j4].imei[0].imask & (1U << (j*GPU_NSUBCELL + si)))
2696                     {
2697                         b++;
2698                     }
2699                 }
2700                 c[b]++;
2701             }
2702         }
2703     }
2704     for (b = 0; b <= GPU_NSUBCELL; b++)
2705     {
2706         fprintf(fp, "nbl j-list #i-subcell %d %7d %4.1f\n",
2707                 b, c[b], 100.0*c[b]/(double)(nbl->ncj4*NBNXN_GPU_JGROUP_SIZE));
2708     }
2709 }
2710
2711 /* Returns a pointer to the exclusion mask for cj4-unit cj4, warp warp */
2712 static void low_get_nbl_exclusions(nbnxn_pairlist_t *nbl, int cj4,
2713                                    int warp, nbnxn_excl_t **excl)
2714 {
2715     if (nbl->cj4[cj4].imei[warp].excl_ind == 0)
2716     {
2717         /* No exclusions set, make a new list entry */
2718         nbl->cj4[cj4].imei[warp].excl_ind = nbl->nexcl;
2719         nbl->nexcl++;
2720         *excl = &nbl->excl[nbl->cj4[cj4].imei[warp].excl_ind];
2721         set_no_excls(*excl);
2722     }
2723     else
2724     {
2725         /* We already have some exclusions, new ones can be added to the list */
2726         *excl = &nbl->excl[nbl->cj4[cj4].imei[warp].excl_ind];
2727     }
2728 }
2729
2730 /* Returns a pointer to the exclusion mask for cj4-unit cj4, warp warp,
2731  * generates a new element and allocates extra memory, if necessary.
2732  */
2733 static void get_nbl_exclusions_1(nbnxn_pairlist_t *nbl, int cj4,
2734                                  int warp, nbnxn_excl_t **excl)
2735 {
2736     if (nbl->cj4[cj4].imei[warp].excl_ind == 0)
2737     {
2738         /* We need to make a new list entry, check if we have space */
2739         check_excl_space(nbl, 1);
2740     }
2741     low_get_nbl_exclusions(nbl, cj4, warp, excl);
2742 }
2743
2744 /* Returns pointers to the exclusion mask for cj4-unit cj4 for both warps,
2745  * generates a new element and allocates extra memory, if necessary.
2746  */
2747 static void get_nbl_exclusions_2(nbnxn_pairlist_t *nbl, int cj4,
2748                                  nbnxn_excl_t **excl_w0,
2749                                  nbnxn_excl_t **excl_w1)
2750 {
2751     /* Check for space we might need */
2752     check_excl_space(nbl, 2);
2753
2754     low_get_nbl_exclusions(nbl, cj4, 0, excl_w0);
2755     low_get_nbl_exclusions(nbl, cj4, 1, excl_w1);
2756 }
2757
2758 /* Sets the self exclusions i=j and pair exclusions i>j */
2759 static void set_self_and_newton_excls_supersub(nbnxn_pairlist_t *nbl,
2760                                                int cj4_ind, int sj_offset,
2761                                                int si)
2762 {
2763     nbnxn_excl_t *excl[2];
2764     int           ei, ej, w;
2765
2766     /* Here we only set the set self and double pair exclusions */
2767
2768     get_nbl_exclusions_2(nbl, cj4_ind, &excl[0], &excl[1]);
2769
2770     /* Only minor < major bits set */
2771     for (ej = 0; ej < nbl->na_ci; ej++)
2772     {
2773         w = (ej>>2);
2774         for (ei = ej; ei < nbl->na_ci; ei++)
2775         {
2776             excl[w]->pair[(ej & (NBNXN_GPU_JGROUP_SIZE-1))*nbl->na_ci + ei] &=
2777                 ~(1U << (sj_offset*GPU_NSUBCELL + si));
2778         }
2779     }
2780 }
2781
2782 /* Returns a diagonal or off-diagonal interaction mask for plain C lists */
2783 static unsigned int get_imask(gmx_bool rdiag, int ci, int cj)
2784 {
2785     return (rdiag && ci == cj ? NBNXN_INTERACTION_MASK_DIAG : NBNXN_INTERACTION_MASK_ALL);
2786 }
2787
2788 /* Returns a diagonal or off-diagonal interaction mask for cj-size=2 */
2789 static unsigned int get_imask_simd_j2(gmx_bool rdiag, int ci, int cj)
2790 {
2791     return (rdiag && ci*2 == cj ? NBNXN_INTERACTION_MASK_DIAG_J2_0 :
2792             (rdiag && ci*2+1 == cj ? NBNXN_INTERACTION_MASK_DIAG_J2_1 :
2793              NBNXN_INTERACTION_MASK_ALL));
2794 }
2795
2796 /* Returns a diagonal or off-diagonal interaction mask for cj-size=4 */
2797 static unsigned int get_imask_simd_j4(gmx_bool rdiag, int ci, int cj)
2798 {
2799     return (rdiag && ci == cj ? NBNXN_INTERACTION_MASK_DIAG : NBNXN_INTERACTION_MASK_ALL);
2800 }
2801
2802 /* Returns a diagonal or off-diagonal interaction mask for cj-size=8 */
2803 static unsigned int get_imask_simd_j8(gmx_bool rdiag, int ci, int cj)
2804 {
2805     return (rdiag && ci == cj*2 ? NBNXN_INTERACTION_MASK_DIAG_J8_0 :
2806             (rdiag && ci == cj*2+1 ? NBNXN_INTERACTION_MASK_DIAG_J8_1 :
2807              NBNXN_INTERACTION_MASK_ALL));
2808 }
2809
2810 #ifdef GMX_NBNXN_SIMD
2811 #if GMX_SIMD_REAL_WIDTH == 2
2812 #define get_imask_simd_4xn  get_imask_simd_j2
2813 #endif
2814 #if GMX_SIMD_REAL_WIDTH == 4
2815 #define get_imask_simd_4xn  get_imask_simd_j4
2816 #endif
2817 #if GMX_SIMD_REAL_WIDTH == 8
2818 #define get_imask_simd_4xn  get_imask_simd_j8
2819 #define get_imask_simd_2xnn get_imask_simd_j4
2820 #endif
2821 #if GMX_SIMD_REAL_WIDTH == 16
2822 #define get_imask_simd_2xnn get_imask_simd_j8
2823 #endif
2824 #endif
2825
2826 /* Plain C code for making a pair list of cell ci vs cell cjf-cjl.
2827  * Checks bounding box distances and possibly atom pair distances.
2828  */
2829 static void make_cluster_list_simple(const nbnxn_grid_t *gridj,
2830                                      nbnxn_pairlist_t *nbl,
2831                                      int ci, int cjf, int cjl,
2832                                      gmx_bool remove_sub_diag,
2833                                      const real *x_j,
2834                                      real rl2, float rbb2,
2835                                      int *ndistc)
2836 {
2837     const nbnxn_list_work_t *work;
2838
2839     const nbnxn_bb_t        *bb_ci;
2840     const real              *x_ci;
2841
2842     gmx_bool                 InRange;
2843     real                     d2;
2844     int                      cjf_gl, cjl_gl, cj;
2845
2846     work = nbl->work;
2847
2848     bb_ci = nbl->work->bb_ci;
2849     x_ci  = nbl->work->x_ci;
2850
2851     InRange = FALSE;
2852     while (!InRange && cjf <= cjl)
2853     {
2854         d2       = subc_bb_dist2(0, bb_ci, cjf, gridj->bb);
2855         *ndistc += 2;
2856
2857         /* Check if the distance is within the distance where
2858          * we use only the bounding box distance rbb,
2859          * or within the cut-off and there is at least one atom pair
2860          * within the cut-off.
2861          */
2862         if (d2 < rbb2)
2863         {
2864             InRange = TRUE;
2865         }
2866         else if (d2 < rl2)
2867         {
2868             int i, j;
2869
2870             cjf_gl = gridj->cell0 + cjf;
2871             for (i = 0; i < NBNXN_CPU_CLUSTER_I_SIZE && !InRange; i++)
2872             {
2873                 for (j = 0; j < NBNXN_CPU_CLUSTER_I_SIZE; j++)
2874                 {
2875                     InRange = InRange ||
2876                         (sqr(x_ci[i*STRIDE_XYZ+XX] - x_j[(cjf_gl*NBNXN_CPU_CLUSTER_I_SIZE+j)*STRIDE_XYZ+XX]) +
2877                          sqr(x_ci[i*STRIDE_XYZ+YY] - x_j[(cjf_gl*NBNXN_CPU_CLUSTER_I_SIZE+j)*STRIDE_XYZ+YY]) +
2878                          sqr(x_ci[i*STRIDE_XYZ+ZZ] - x_j[(cjf_gl*NBNXN_CPU_CLUSTER_I_SIZE+j)*STRIDE_XYZ+ZZ]) < rl2);
2879                 }
2880             }
2881             *ndistc += NBNXN_CPU_CLUSTER_I_SIZE*NBNXN_CPU_CLUSTER_I_SIZE;
2882         }
2883         if (!InRange)
2884         {
2885             cjf++;
2886         }
2887     }
2888     if (!InRange)
2889     {
2890         return;
2891     }
2892
2893     InRange = FALSE;
2894     while (!InRange && cjl > cjf)
2895     {
2896         d2       = subc_bb_dist2(0, bb_ci, cjl, gridj->bb);
2897         *ndistc += 2;
2898
2899         /* Check if the distance is within the distance where
2900          * we use only the bounding box distance rbb,
2901          * or within the cut-off and there is at least one atom pair
2902          * within the cut-off.
2903          */
2904         if (d2 < rbb2)
2905         {
2906             InRange = TRUE;
2907         }
2908         else if (d2 < rl2)
2909         {
2910             int i, j;
2911
2912             cjl_gl = gridj->cell0 + cjl;
2913             for (i = 0; i < NBNXN_CPU_CLUSTER_I_SIZE && !InRange; i++)
2914             {
2915                 for (j = 0; j < NBNXN_CPU_CLUSTER_I_SIZE; j++)
2916                 {
2917                     InRange = InRange ||
2918                         (sqr(x_ci[i*STRIDE_XYZ+XX] - x_j[(cjl_gl*NBNXN_CPU_CLUSTER_I_SIZE+j)*STRIDE_XYZ+XX]) +
2919                          sqr(x_ci[i*STRIDE_XYZ+YY] - x_j[(cjl_gl*NBNXN_CPU_CLUSTER_I_SIZE+j)*STRIDE_XYZ+YY]) +
2920                          sqr(x_ci[i*STRIDE_XYZ+ZZ] - x_j[(cjl_gl*NBNXN_CPU_CLUSTER_I_SIZE+j)*STRIDE_XYZ+ZZ]) < rl2);
2921                 }
2922             }
2923             *ndistc += NBNXN_CPU_CLUSTER_I_SIZE*NBNXN_CPU_CLUSTER_I_SIZE;
2924         }
2925         if (!InRange)
2926         {
2927             cjl--;
2928         }
2929     }
2930
2931     if (cjf <= cjl)
2932     {
2933         for (cj = cjf; cj <= cjl; cj++)
2934         {
2935             /* Store cj and the interaction mask */
2936             nbl->cj[nbl->ncj].cj   = gridj->cell0 + cj;
2937             nbl->cj[nbl->ncj].excl = get_imask(remove_sub_diag, ci, cj);
2938             nbl->ncj++;
2939         }
2940         /* Increase the closing index in i super-cell list */
2941         nbl->ci[nbl->nci].cj_ind_end = nbl->ncj;
2942     }
2943 }
2944
2945 #ifdef GMX_NBNXN_SIMD_4XN
2946 #include "gromacs/mdlib/nbnxn_search_simd_4xn.h"
2947 #endif
2948 #ifdef GMX_NBNXN_SIMD_2XNN
2949 #include "gromacs/mdlib/nbnxn_search_simd_2xnn.h"
2950 #endif
2951
2952 /* Plain C or SIMD4 code for making a pair list of super-cell sci vs scj.
2953  * Checks bounding box distances and possibly atom pair distances.
2954  */
2955 static void make_cluster_list_supersub(const nbnxn_grid_t *gridi,
2956                                        const nbnxn_grid_t *gridj,
2957                                        nbnxn_pairlist_t *nbl,
2958                                        int sci, int scj,
2959                                        gmx_bool sci_equals_scj,
2960                                        int stride, const real *x,
2961                                        real rl2, float rbb2,
2962                                        int *ndistc)
2963 {
2964     int               na_c;
2965     int               npair;
2966     int               cjo, ci1, ci, cj, cj_gl;
2967     int               cj4_ind, cj_offset;
2968     unsigned int      imask;
2969     nbnxn_cj4_t      *cj4;
2970 #ifdef NBNXN_BBXXXX
2971     const float      *pbb_ci;
2972 #else
2973     const nbnxn_bb_t *bb_ci;
2974 #endif
2975     const real       *x_ci;
2976     float            *d2l, d2;
2977     int               w;
2978 #define PRUNE_LIST_CPU_ONE
2979 #ifdef PRUNE_LIST_CPU_ONE
2980     int  ci_last = -1;
2981 #endif
2982
2983     d2l = nbl->work->d2;
2984
2985 #ifdef NBNXN_BBXXXX
2986     pbb_ci = nbl->work->pbb_ci;
2987 #else
2988     bb_ci  = nbl->work->bb_ci;
2989 #endif
2990     x_ci   = nbl->work->x_ci;
2991
2992     na_c = gridj->na_c;
2993
2994     for (cjo = 0; cjo < gridj->nsubc[scj]; cjo++)
2995     {
2996         cj4_ind   = (nbl->work->cj_ind >> NBNXN_GPU_JGROUP_SIZE_2LOG);
2997         cj_offset = nbl->work->cj_ind - cj4_ind*NBNXN_GPU_JGROUP_SIZE;
2998         cj4       = &nbl->cj4[cj4_ind];
2999
3000         cj = scj*GPU_NSUBCELL + cjo;
3001
3002         cj_gl = gridj->cell0*GPU_NSUBCELL + cj;
3003
3004         /* Initialize this j-subcell i-subcell list */
3005         cj4->cj[cj_offset] = cj_gl;
3006         imask              = 0;
3007
3008         if (sci_equals_scj)
3009         {
3010             ci1 = cjo + 1;
3011         }
3012         else
3013         {
3014             ci1 = gridi->nsubc[sci];
3015         }
3016
3017 #ifdef NBNXN_BBXXXX
3018         /* Determine all ci1 bb distances in one call with SIMD4 */
3019         subc_bb_dist2_simd4_xxxx(gridj->pbb+(cj>>STRIDE_PBB_2LOG)*NNBSBB_XXXX+(cj & (STRIDE_PBB-1)),
3020                                  ci1, pbb_ci, d2l);
3021         *ndistc += na_c*2;
3022 #endif
3023
3024         npair = 0;
3025         /* We use a fixed upper-bound instead of ci1 to help optimization */
3026         for (ci = 0; ci < GPU_NSUBCELL; ci++)
3027         {
3028             if (ci == ci1)
3029             {
3030                 break;
3031             }
3032
3033 #ifndef NBNXN_BBXXXX
3034             /* Determine the bb distance between ci and cj */
3035             d2l[ci]  = subc_bb_dist2(ci, bb_ci, cj, gridj->bb);
3036             *ndistc += 2;
3037 #endif
3038             d2 = d2l[ci];
3039
3040 #ifdef PRUNE_LIST_CPU_ALL
3041             /* Check if the distance is within the distance where
3042              * we use only the bounding box distance rbb,
3043              * or within the cut-off and there is at least one atom pair
3044              * within the cut-off. This check is very costly.
3045              */
3046             *ndistc += na_c*na_c;
3047             if (d2 < rbb2 ||
3048                 (d2 < rl2 &&
3049 #ifdef NBNXN_PBB_SIMD4
3050                  subc_in_range_simd4
3051 #else
3052                  subc_in_range_x
3053 #endif
3054                      (na_c, ci, x_ci, cj_gl, stride, x, rl2)))
3055 #else
3056             /* Check if the distance between the two bounding boxes
3057              * in within the pair-list cut-off.
3058              */
3059             if (d2 < rl2)
3060 #endif
3061             {
3062                 /* Flag this i-subcell to be taken into account */
3063                 imask |= (1U << (cj_offset*GPU_NSUBCELL+ci));
3064
3065 #ifdef PRUNE_LIST_CPU_ONE
3066                 ci_last = ci;
3067 #endif
3068
3069                 npair++;
3070             }
3071         }
3072
3073 #ifdef PRUNE_LIST_CPU_ONE
3074         /* If we only found 1 pair, check if any atoms are actually
3075          * within the cut-off, so we could get rid of it.
3076          */
3077         if (npair == 1 && d2l[ci_last] >= rbb2)
3078         {
3079             /* Avoid using function pointers here, as it's slower */
3080             if (
3081 #ifdef NBNXN_PBB_SIMD4
3082                 !subc_in_range_simd4
3083 #else
3084                 !subc_in_range_x
3085 #endif
3086                     (na_c, ci_last, x_ci, cj_gl, stride, x, rl2))
3087             {
3088                 imask &= ~(1U << (cj_offset*GPU_NSUBCELL+ci_last));
3089                 npair--;
3090             }
3091         }
3092 #endif
3093
3094         if (npair > 0)
3095         {
3096             /* We have a useful sj entry, close it now */
3097
3098             /* Set the exclucions for the ci== sj entry.
3099              * Here we don't bother to check if this entry is actually flagged,
3100              * as it will nearly always be in the list.
3101              */
3102             if (sci_equals_scj)
3103             {
3104                 set_self_and_newton_excls_supersub(nbl, cj4_ind, cj_offset, cjo);
3105             }
3106
3107             /* Copy the cluster interaction mask to the list */
3108             for (w = 0; w < NWARP; w++)
3109             {
3110                 cj4->imei[w].imask |= imask;
3111             }
3112
3113             nbl->work->cj_ind++;
3114
3115             /* Keep the count */
3116             nbl->nci_tot += npair;
3117
3118             /* Increase the closing index in i super-cell list */
3119             nbl->sci[nbl->nsci].cj4_ind_end =
3120                 ((nbl->work->cj_ind+NBNXN_GPU_JGROUP_SIZE-1) >> NBNXN_GPU_JGROUP_SIZE_2LOG);
3121         }
3122     }
3123 }
3124
3125 /* Set all atom-pair exclusions from the topology stored in excl
3126  * as masks in the pair-list for simple list i-entry nbl_ci
3127  */
3128 static void set_ci_top_excls(const nbnxn_search_t nbs,
3129                              nbnxn_pairlist_t    *nbl,
3130                              gmx_bool             diagRemoved,
3131                              int                  na_ci_2log,
3132                              int                  na_cj_2log,
3133                              const nbnxn_ci_t    *nbl_ci,
3134                              const t_blocka      *excl)
3135 {
3136     const int    *cell;
3137     int           ci;
3138     int           cj_ind_first, cj_ind_last;
3139     int           cj_first, cj_last;
3140     int           ndirect;
3141     int           i, ai, aj, si, eind, ge, se;
3142     int           found, cj_ind_0, cj_ind_1, cj_ind_m;
3143     int           cj_m;
3144     gmx_bool      Found_si;
3145     int           si_ind;
3146     nbnxn_excl_t *nbl_excl;
3147     int           inner_i, inner_e;
3148
3149     cell = nbs->cell;
3150
3151     if (nbl_ci->cj_ind_end == nbl_ci->cj_ind_start)
3152     {
3153         /* Empty list */
3154         return;
3155     }
3156
3157     ci = nbl_ci->ci;
3158
3159     cj_ind_first = nbl_ci->cj_ind_start;
3160     cj_ind_last  = nbl->ncj - 1;
3161
3162     cj_first = nbl->cj[cj_ind_first].cj;
3163     cj_last  = nbl->cj[cj_ind_last].cj;
3164
3165     /* Determine how many contiguous j-cells we have starting
3166      * from the first i-cell. This number can be used to directly
3167      * calculate j-cell indices for excluded atoms.
3168      */
3169     ndirect = 0;
3170     if (na_ci_2log == na_cj_2log)
3171     {
3172         while (cj_ind_first + ndirect <= cj_ind_last &&
3173                nbl->cj[cj_ind_first+ndirect].cj == ci + ndirect)
3174         {
3175             ndirect++;
3176         }
3177     }
3178 #ifdef NBNXN_SEARCH_BB_SIMD4
3179     else
3180     {
3181         while (cj_ind_first + ndirect <= cj_ind_last &&
3182                nbl->cj[cj_ind_first+ndirect].cj == ci_to_cj(na_cj_2log, ci) + ndirect)
3183         {
3184             ndirect++;
3185         }
3186     }
3187 #endif
3188
3189     /* Loop over the atoms in the i super-cell */
3190     for (i = 0; i < nbl->na_sc; i++)
3191     {
3192         ai = nbs->a[ci*nbl->na_sc+i];
3193         if (ai >= 0)
3194         {
3195             si  = (i>>na_ci_2log);
3196
3197             /* Loop over the topology-based exclusions for this i-atom */
3198             for (eind = excl->index[ai]; eind < excl->index[ai+1]; eind++)
3199             {
3200                 aj = excl->a[eind];
3201
3202                 if (aj == ai)
3203                 {
3204                     /* The self exclusion are already set, save some time */
3205                     continue;
3206                 }
3207
3208                 ge = cell[aj];
3209
3210                 /* Without shifts we only calculate interactions j>i
3211                  * for one-way pair-lists.
3212                  */
3213                 if (diagRemoved && ge <= ci*nbl->na_sc + i)
3214                 {
3215                     continue;
3216                 }
3217
3218                 se = (ge >> na_cj_2log);
3219
3220                 /* Could the cluster se be in our list? */
3221                 if (se >= cj_first && se <= cj_last)
3222                 {
3223                     if (se < cj_first + ndirect)
3224                     {
3225                         /* We can calculate cj_ind directly from se */
3226                         found = cj_ind_first + se - cj_first;
3227                     }
3228                     else
3229                     {
3230                         /* Search for se using bisection */
3231                         found    = -1;
3232                         cj_ind_0 = cj_ind_first + ndirect;
3233                         cj_ind_1 = cj_ind_last + 1;
3234                         while (found == -1 && cj_ind_0 < cj_ind_1)
3235                         {
3236                             cj_ind_m = (cj_ind_0 + cj_ind_1)>>1;
3237
3238                             cj_m = nbl->cj[cj_ind_m].cj;
3239
3240                             if (se == cj_m)
3241                             {
3242                                 found = cj_ind_m;
3243                             }
3244                             else if (se < cj_m)
3245                             {
3246                                 cj_ind_1 = cj_ind_m;
3247                             }
3248                             else
3249                             {
3250                                 cj_ind_0 = cj_ind_m + 1;
3251                             }
3252                         }
3253                     }
3254
3255                     if (found >= 0)
3256                     {
3257                         inner_i = i  - (si << na_ci_2log);
3258                         inner_e = ge - (se << na_cj_2log);
3259
3260                         nbl->cj[found].excl &= ~(1U<<((inner_i<<na_cj_2log) + inner_e));
3261 /* The next code line is usually not needed. We do not want to version
3262  * away the above line, because there is logic that relies on being
3263  * able to detect easily whether any exclusions exist. */
3264 #if (defined GMX_SIMD_IBM_QPX)
3265                         nbl->cj[found].interaction_mask_indices[inner_i] &= ~(1U << inner_e);
3266 #endif
3267                     }
3268                 }
3269             }
3270         }
3271     }
3272 }
3273
3274 /* Add a new i-entry to the FEP list and copy the i-properties */
3275 static gmx_inline void fep_list_new_nri_copy(t_nblist *nlist)
3276 {
3277     /* Add a new i-entry */
3278     nlist->nri++;
3279
3280     assert(nlist->nri < nlist->maxnri);
3281
3282     /* Duplicate the last i-entry, except for jindex, which continues */
3283     nlist->iinr[nlist->nri]   = nlist->iinr[nlist->nri-1];
3284     nlist->shift[nlist->nri]  = nlist->shift[nlist->nri-1];
3285     nlist->gid[nlist->nri]    = nlist->gid[nlist->nri-1];
3286     nlist->jindex[nlist->nri] = nlist->nrj;
3287 }
3288
3289 /* For load balancing of the free-energy lists over threads, we set
3290  * the maximum nrj size of an i-entry to 40. This leads to good
3291  * load balancing in the worst case scenario of a single perturbed
3292  * particle on 16 threads, while not introducing significant overhead.
3293  * Note that half of the perturbed pairs will anyhow end up in very small lists,
3294  * since non perturbed i-particles will see few perturbed j-particles).
3295  */
3296 const int max_nrj_fep = 40;
3297
3298 /* Exclude the perturbed pairs from the Verlet list. This is only done to avoid
3299  * singularities for overlapping particles (0/0), since the charges and
3300  * LJ parameters have been zeroed in the nbnxn data structure.
3301  * Simultaneously make a group pair list for the perturbed pairs.
3302  */
3303 static void make_fep_list(const nbnxn_search_t    nbs,
3304                           const nbnxn_atomdata_t *nbat,
3305                           nbnxn_pairlist_t       *nbl,
3306                           gmx_bool                bDiagRemoved,
3307                           nbnxn_ci_t             *nbl_ci,
3308                           const nbnxn_grid_t     *gridi,
3309                           const nbnxn_grid_t     *gridj,
3310                           t_nblist               *nlist)
3311 {
3312     int      ci, cj_ind_start, cj_ind_end, cj_ind, cja, cjr;
3313     int      nri_max;
3314     int      ngid, gid_i = 0, gid_j, gid;
3315     int      egp_shift, egp_mask;
3316     int      gid_cj = 0;
3317     int      i, j, ind_i, ind_j, ai, aj;
3318     int      nri;
3319     gmx_bool bFEP_i, bFEP_i_all;
3320
3321     if (nbl_ci->cj_ind_end == nbl_ci->cj_ind_start)
3322     {
3323         /* Empty list */
3324         return;
3325     }
3326
3327     ci = nbl_ci->ci;
3328
3329     cj_ind_start = nbl_ci->cj_ind_start;
3330     cj_ind_end   = nbl_ci->cj_ind_end;
3331
3332     /* In worst case we have alternating energy groups
3333      * and create #atom-pair lists, which means we need the size
3334      * of a cluster pair (na_ci*na_cj) times the number of cj's.
3335      */
3336     nri_max = nbl->na_ci*nbl->na_cj*(cj_ind_end - cj_ind_start);
3337     if (nlist->nri + nri_max > nlist->maxnri)
3338     {
3339         nlist->maxnri = over_alloc_large(nlist->nri + nri_max);
3340         reallocate_nblist(nlist);
3341     }
3342
3343     ngid = nbat->nenergrp;
3344
3345     if (ngid*gridj->na_cj > sizeof(gid_cj)*8)
3346     {
3347         gmx_fatal(FARGS, "The Verlet scheme with %dx%d kernels and free-energy only supports up to %d energy groups",
3348                   gridi->na_c, gridj->na_cj, (sizeof(gid_cj)*8)/gridj->na_cj);
3349     }
3350
3351     egp_shift = nbat->neg_2log;
3352     egp_mask  = (1<<nbat->neg_2log) - 1;
3353
3354     /* Loop over the atoms in the i sub-cell */
3355     bFEP_i_all = TRUE;
3356     for (i = 0; i < nbl->na_ci; i++)
3357     {
3358         ind_i = ci*nbl->na_ci + i;
3359         ai    = nbs->a[ind_i];
3360         if (ai >= 0)
3361         {
3362             nri                  = nlist->nri;
3363             nlist->jindex[nri+1] = nlist->jindex[nri];
3364             nlist->iinr[nri]     = ai;
3365             /* The actual energy group pair index is set later */
3366             nlist->gid[nri]      = 0;
3367             nlist->shift[nri]    = nbl_ci->shift & NBNXN_CI_SHIFT;
3368
3369             bFEP_i = gridi->fep[ci - gridi->cell0] & (1 << i);
3370
3371             bFEP_i_all = bFEP_i_all && bFEP_i;
3372
3373             if ((nlist->nrj + cj_ind_end - cj_ind_start)*nbl->na_cj > nlist->maxnrj)
3374             {
3375                 nlist->maxnrj = over_alloc_small((nlist->nrj + cj_ind_end - cj_ind_start)*nbl->na_cj);
3376                 srenew(nlist->jjnr,     nlist->maxnrj);
3377                 srenew(nlist->excl_fep, nlist->maxnrj);
3378             }
3379
3380             if (ngid > 1)
3381             {
3382                 gid_i = (nbat->energrp[ci] >> (egp_shift*i)) & egp_mask;
3383             }
3384
3385             for (cj_ind = cj_ind_start; cj_ind < cj_ind_end; cj_ind++)
3386             {
3387                 unsigned int fep_cj;
3388
3389                 cja = nbl->cj[cj_ind].cj;
3390
3391                 if (gridj->na_cj == gridj->na_c)
3392                 {
3393                     cjr    = cja - gridj->cell0;
3394                     fep_cj = gridj->fep[cjr];
3395                     if (ngid > 1)
3396                     {
3397                         gid_cj = nbat->energrp[cja];
3398                     }
3399                 }
3400                 else if (2*gridj->na_cj == gridj->na_c)
3401                 {
3402                     cjr    = cja - gridj->cell0*2;
3403                     /* Extract half of the ci fep/energrp mask */
3404                     fep_cj = (gridj->fep[cjr>>1] >> ((cjr&1)*gridj->na_cj)) & ((1<<gridj->na_cj) - 1);
3405                     if (ngid > 1)
3406                     {
3407                         gid_cj = nbat->energrp[cja>>1] >> ((cja&1)*gridj->na_cj*egp_shift) & ((1<<(gridj->na_cj*egp_shift)) - 1);
3408                     }
3409                 }
3410                 else
3411                 {
3412                     cjr    = cja - (gridj->cell0>>1);
3413                     /* Combine two ci fep masks/energrp */
3414                     fep_cj = gridj->fep[cjr*2] + (gridj->fep[cjr*2+1] << gridj->na_c);
3415                     if (ngid > 1)
3416                     {
3417                         gid_cj = nbat->energrp[cja*2] + (nbat->energrp[cja*2+1] << (gridj->na_c*egp_shift));
3418                     }
3419                 }
3420
3421                 if (bFEP_i || fep_cj != 0)
3422                 {
3423                     for (j = 0; j < nbl->na_cj; j++)
3424                     {
3425                         /* Is this interaction perturbed and not excluded? */
3426                         ind_j = cja*nbl->na_cj + j;
3427                         aj    = nbs->a[ind_j];
3428                         if (aj >= 0 &&
3429                             (bFEP_i || (fep_cj & (1 << j))) &&
3430                             (!bDiagRemoved || ind_j >= ind_i))
3431                         {
3432                             if (ngid > 1)
3433                             {
3434                                 gid_j = (gid_cj >> (j*egp_shift)) & egp_mask;
3435                                 gid   = GID(gid_i, gid_j, ngid);
3436
3437                                 if (nlist->nrj > nlist->jindex[nri] &&
3438                                     nlist->gid[nri] != gid)
3439                                 {
3440                                     /* Energy group pair changed: new list */
3441                                     fep_list_new_nri_copy(nlist);
3442                                     nri = nlist->nri;
3443                                 }
3444                                 nlist->gid[nri] = gid;
3445                             }
3446
3447                             if (nlist->nrj - nlist->jindex[nri] >= max_nrj_fep)
3448                             {
3449                                 fep_list_new_nri_copy(nlist);
3450                                 nri = nlist->nri;
3451                             }
3452
3453                             /* Add it to the FEP list */
3454                             nlist->jjnr[nlist->nrj]     = aj;
3455                             nlist->excl_fep[nlist->nrj] = (nbl->cj[cj_ind].excl >> (i*nbl->na_cj + j)) & 1;
3456                             nlist->nrj++;
3457
3458                             /* Exclude it from the normal list.
3459                              * Note that the charge has been set to zero,
3460                              * but we need to avoid 0/0, as perturbed atoms
3461                              * can be on top of each other.
3462                              */
3463                             nbl->cj[cj_ind].excl &= ~(1U << (i*nbl->na_cj + j));
3464                         }
3465                     }
3466                 }
3467             }
3468
3469             if (nlist->nrj > nlist->jindex[nri])
3470             {
3471                 /* Actually add this new, non-empty, list */
3472                 nlist->nri++;
3473                 nlist->jindex[nlist->nri] = nlist->nrj;
3474             }
3475         }
3476     }
3477
3478     if (bFEP_i_all)
3479     {
3480         /* All interactions are perturbed, we can skip this entry */
3481         nbl_ci->cj_ind_end = cj_ind_start;
3482     }
3483 }
3484
3485 /* Return the index of atom a within a cluster */
3486 static gmx_inline int cj_mod_cj4(int cj)
3487 {
3488     return cj & (NBNXN_GPU_JGROUP_SIZE - 1);
3489 }
3490
3491 /* Convert a j-cluster to a cj4 group */
3492 static gmx_inline int cj_to_cj4(int cj)
3493 {
3494     return cj >> NBNXN_GPU_JGROUP_SIZE_2LOG;
3495 }
3496
3497 /* Return the index of an j-atom within a warp */
3498 static gmx_inline int a_mod_wj(int a)
3499 {
3500     return a & (NBNXN_GPU_CLUSTER_SIZE/2 - 1);
3501 }
3502
3503 /* As make_fep_list above, but for super/sub lists. */
3504 static void make_fep_list_supersub(const nbnxn_search_t    nbs,
3505                                    const nbnxn_atomdata_t *nbat,
3506                                    nbnxn_pairlist_t       *nbl,
3507                                    gmx_bool                bDiagRemoved,
3508                                    const nbnxn_sci_t      *nbl_sci,
3509                                    real                    shx,
3510                                    real                    shy,
3511                                    real                    shz,
3512                                    real                    rlist_fep2,
3513                                    const nbnxn_grid_t     *gridi,
3514                                    const nbnxn_grid_t     *gridj,
3515                                    t_nblist               *nlist)
3516 {
3517     int                sci, cj4_ind_start, cj4_ind_end, cj4_ind, gcj, cjr;
3518     int                nri_max;
3519     int                c, c_abs;
3520     int                i, j, ind_i, ind_j, ai, aj;
3521     int                nri;
3522     gmx_bool           bFEP_i;
3523     real               xi, yi, zi;
3524     const nbnxn_cj4_t *cj4;
3525
3526     if (nbl_sci->cj4_ind_end == nbl_sci->cj4_ind_start)
3527     {
3528         /* Empty list */
3529         return;
3530     }
3531
3532     sci = nbl_sci->sci;
3533
3534     cj4_ind_start = nbl_sci->cj4_ind_start;
3535     cj4_ind_end   = nbl_sci->cj4_ind_end;
3536
3537     /* Here we process one super-cell, max #atoms na_sc, versus a list
3538      * cj4 entries, each with max NBNXN_GPU_JGROUP_SIZE cj's, each
3539      * of size na_cj atoms.
3540      * On the GPU we don't support energy groups (yet).
3541      * So for each of the na_sc i-atoms, we need max one FEP list
3542      * for each max_nrj_fep j-atoms.
3543      */
3544     nri_max = nbl->na_sc*nbl->na_cj*(1 + ((cj4_ind_end - cj4_ind_start)*NBNXN_GPU_JGROUP_SIZE)/max_nrj_fep);
3545     if (nlist->nri + nri_max > nlist->maxnri)
3546     {
3547         nlist->maxnri = over_alloc_large(nlist->nri + nri_max);
3548         reallocate_nblist(nlist);
3549     }
3550
3551     /* Loop over the atoms in the i super-cluster */
3552     for (c = 0; c < GPU_NSUBCELL; c++)
3553     {
3554         c_abs = sci*GPU_NSUBCELL + c;
3555
3556         for (i = 0; i < nbl->na_ci; i++)
3557         {
3558             ind_i = c_abs*nbl->na_ci + i;
3559             ai    = nbs->a[ind_i];
3560             if (ai >= 0)
3561             {
3562                 nri                  = nlist->nri;
3563                 nlist->jindex[nri+1] = nlist->jindex[nri];
3564                 nlist->iinr[nri]     = ai;
3565                 /* With GPUs, energy groups are not supported */
3566                 nlist->gid[nri]      = 0;
3567                 nlist->shift[nri]    = nbl_sci->shift & NBNXN_CI_SHIFT;
3568
3569                 bFEP_i = (gridi->fep[c_abs - gridi->cell0] & (1 << i));
3570
3571                 xi = nbat->x[ind_i*nbat->xstride+XX] + shx;
3572                 yi = nbat->x[ind_i*nbat->xstride+YY] + shy;
3573                 zi = nbat->x[ind_i*nbat->xstride+ZZ] + shz;
3574
3575                 if ((nlist->nrj + cj4_ind_end - cj4_ind_start)*NBNXN_GPU_JGROUP_SIZE*nbl->na_cj > nlist->maxnrj)
3576                 {
3577                     nlist->maxnrj = over_alloc_small((nlist->nrj + cj4_ind_end - cj4_ind_start)*NBNXN_GPU_JGROUP_SIZE*nbl->na_cj);
3578                     srenew(nlist->jjnr,     nlist->maxnrj);
3579                     srenew(nlist->excl_fep, nlist->maxnrj);
3580                 }
3581
3582                 for (cj4_ind = cj4_ind_start; cj4_ind < cj4_ind_end; cj4_ind++)
3583                 {
3584                     cj4 = &nbl->cj4[cj4_ind];
3585
3586                     for (gcj = 0; gcj < NBNXN_GPU_JGROUP_SIZE; gcj++)
3587                     {
3588                         unsigned int fep_cj;
3589
3590                         if ((cj4->imei[0].imask & (1U << (gcj*GPU_NSUBCELL + c))) == 0)
3591                         {
3592                             /* Skip this ci for this cj */
3593                             continue;
3594                         }
3595
3596                         cjr = cj4->cj[gcj] - gridj->cell0*GPU_NSUBCELL;
3597
3598                         fep_cj = gridj->fep[cjr];
3599
3600                         if (bFEP_i || fep_cj != 0)
3601                         {
3602                             for (j = 0; j < nbl->na_cj; j++)
3603                             {
3604                                 /* Is this interaction perturbed and not excluded? */
3605                                 ind_j = (gridj->cell0*GPU_NSUBCELL + cjr)*nbl->na_cj + j;
3606                                 aj    = nbs->a[ind_j];
3607                                 if (aj >= 0 &&
3608                                     (bFEP_i || (fep_cj & (1 << j))) &&
3609                                     (!bDiagRemoved || ind_j >= ind_i))
3610                                 {
3611                                     nbnxn_excl_t *excl;
3612                                     int           excl_pair;
3613                                     unsigned int  excl_bit;
3614                                     real          dx, dy, dz;
3615
3616                                     get_nbl_exclusions_1(nbl, cj4_ind, j>>2, &excl);
3617
3618                                     excl_pair = a_mod_wj(j)*nbl->na_ci + i;
3619                                     excl_bit  = (1U << (gcj*GPU_NSUBCELL + c));
3620
3621                                     dx = nbat->x[ind_j*nbat->xstride+XX] - xi;
3622                                     dy = nbat->x[ind_j*nbat->xstride+YY] - yi;
3623                                     dz = nbat->x[ind_j*nbat->xstride+ZZ] - zi;
3624
3625                                     /* The unpruned GPU list has more than 2/3
3626                                      * of the atom pairs beyond rlist. Using
3627                                      * this list will cause a lot of overhead
3628                                      * in the CPU FEP kernels, especially
3629                                      * relative to the fast GPU kernels.
3630                                      * So we prune the FEP list here.
3631                                      */
3632                                     if (dx*dx + dy*dy + dz*dz < rlist_fep2)
3633                                     {
3634                                         if (nlist->nrj - nlist->jindex[nri] >= max_nrj_fep)
3635                                         {
3636                                             fep_list_new_nri_copy(nlist);
3637                                             nri = nlist->nri;
3638                                         }
3639
3640                                         /* Add it to the FEP list */
3641                                         nlist->jjnr[nlist->nrj]     = aj;
3642                                         nlist->excl_fep[nlist->nrj] = (excl->pair[excl_pair] & excl_bit) ? 1 : 0;
3643                                         nlist->nrj++;
3644                                     }
3645
3646                                     /* Exclude it from the normal list.
3647                                      * Note that the charge and LJ parameters have
3648                                      * been set to zero, but we need to avoid 0/0,
3649                                      * as perturbed atoms can be on top of each other.
3650                                      */
3651                                     excl->pair[excl_pair] &= ~excl_bit;
3652                                 }
3653                             }
3654
3655                             /* Note that we could mask out this pair in imask
3656                              * if all i- and/or all j-particles are perturbed.
3657                              * But since the perturbed pairs on the CPU will
3658                              * take an order of magnitude more time, the GPU
3659                              * will finish before the CPU and there is no gain.
3660                              */
3661                         }
3662                     }
3663                 }
3664
3665                 if (nlist->nrj > nlist->jindex[nri])
3666                 {
3667                     /* Actually add this new, non-empty, list */
3668                     nlist->nri++;
3669                     nlist->jindex[nlist->nri] = nlist->nrj;
3670                 }
3671             }
3672         }
3673     }
3674 }
3675
3676 /* Set all atom-pair exclusions from the topology stored in excl
3677  * as masks in the pair-list for i-super-cell entry nbl_sci
3678  */
3679 static void set_sci_top_excls(const nbnxn_search_t nbs,
3680                               nbnxn_pairlist_t    *nbl,
3681                               gmx_bool             diagRemoved,
3682                               int                  na_c_2log,
3683                               const nbnxn_sci_t   *nbl_sci,
3684                               const t_blocka      *excl)
3685 {
3686     const int    *cell;
3687     int           na_c;
3688     int           sci;
3689     int           cj_ind_first, cj_ind_last;
3690     int           cj_first, cj_last;
3691     int           ndirect;
3692     int           i, ai, aj, si, eind, ge, se;
3693     int           found, cj_ind_0, cj_ind_1, cj_ind_m;
3694     int           cj_m;
3695     gmx_bool      Found_si;
3696     int           si_ind;
3697     nbnxn_excl_t *nbl_excl;
3698     int           inner_i, inner_e, w;
3699
3700     cell = nbs->cell;
3701
3702     na_c = nbl->na_ci;
3703
3704     if (nbl_sci->cj4_ind_end == nbl_sci->cj4_ind_start)
3705     {
3706         /* Empty list */
3707         return;
3708     }
3709
3710     sci = nbl_sci->sci;
3711
3712     cj_ind_first = nbl_sci->cj4_ind_start*NBNXN_GPU_JGROUP_SIZE;
3713     cj_ind_last  = nbl->work->cj_ind - 1;
3714
3715     cj_first = nbl->cj4[nbl_sci->cj4_ind_start].cj[0];
3716     cj_last  = nbl_cj(nbl, cj_ind_last);
3717
3718     /* Determine how many contiguous j-clusters we have starting
3719      * from the first i-cluster. This number can be used to directly
3720      * calculate j-cluster indices for excluded atoms.
3721      */
3722     ndirect = 0;
3723     while (cj_ind_first + ndirect <= cj_ind_last &&
3724            nbl_cj(nbl, cj_ind_first+ndirect) == sci*GPU_NSUBCELL + ndirect)
3725     {
3726         ndirect++;
3727     }
3728
3729     /* Loop over the atoms in the i super-cell */
3730     for (i = 0; i < nbl->na_sc; i++)
3731     {
3732         ai = nbs->a[sci*nbl->na_sc+i];
3733         if (ai >= 0)
3734         {
3735             si  = (i>>na_c_2log);
3736
3737             /* Loop over the topology-based exclusions for this i-atom */
3738             for (eind = excl->index[ai]; eind < excl->index[ai+1]; eind++)
3739             {
3740                 aj = excl->a[eind];
3741
3742                 if (aj == ai)
3743                 {
3744                     /* The self exclusion are already set, save some time */
3745                     continue;
3746                 }
3747
3748                 ge = cell[aj];
3749
3750                 /* Without shifts we only calculate interactions j>i
3751                  * for one-way pair-lists.
3752                  */
3753                 if (diagRemoved && ge <= sci*nbl->na_sc + i)
3754                 {
3755                     continue;
3756                 }
3757
3758                 se = ge>>na_c_2log;
3759                 /* Could the cluster se be in our list? */
3760                 if (se >= cj_first && se <= cj_last)
3761                 {
3762                     if (se < cj_first + ndirect)
3763                     {
3764                         /* We can calculate cj_ind directly from se */
3765                         found = cj_ind_first + se - cj_first;
3766                     }
3767                     else
3768                     {
3769                         /* Search for se using bisection */
3770                         found    = -1;
3771                         cj_ind_0 = cj_ind_first + ndirect;
3772                         cj_ind_1 = cj_ind_last + 1;
3773                         while (found == -1 && cj_ind_0 < cj_ind_1)
3774                         {
3775                             cj_ind_m = (cj_ind_0 + cj_ind_1)>>1;
3776
3777                             cj_m = nbl_cj(nbl, cj_ind_m);
3778
3779                             if (se == cj_m)
3780                             {
3781                                 found = cj_ind_m;
3782                             }
3783                             else if (se < cj_m)
3784                             {
3785                                 cj_ind_1 = cj_ind_m;
3786                             }
3787                             else
3788                             {
3789                                 cj_ind_0 = cj_ind_m + 1;
3790                             }
3791                         }
3792                     }
3793
3794                     if (found >= 0)
3795                     {
3796                         inner_i = i  - si*na_c;
3797                         inner_e = ge - se*na_c;
3798
3799                         if (nbl_imask0(nbl, found) & (1U << (cj_mod_cj4(found)*GPU_NSUBCELL + si)))
3800                         {
3801                             w       = (inner_e >> 2);
3802
3803                             get_nbl_exclusions_1(nbl, cj_to_cj4(found), w, &nbl_excl);
3804
3805                             nbl_excl->pair[a_mod_wj(inner_e)*nbl->na_ci+inner_i] &=
3806                                 ~(1U << (cj_mod_cj4(found)*GPU_NSUBCELL + si));
3807                         }
3808                     }
3809                 }
3810             }
3811         }
3812     }
3813 }
3814
3815 /* Reallocate the simple ci list for at least n entries */
3816 static void nb_realloc_ci(nbnxn_pairlist_t *nbl, int n)
3817 {
3818     nbl->ci_nalloc = over_alloc_small(n);
3819     nbnxn_realloc_void((void **)&nbl->ci,
3820                        nbl->nci*sizeof(*nbl->ci),
3821                        nbl->ci_nalloc*sizeof(*nbl->ci),
3822                        nbl->alloc, nbl->free);
3823 }
3824
3825 /* Reallocate the super-cell sci list for at least n entries */
3826 static void nb_realloc_sci(nbnxn_pairlist_t *nbl, int n)
3827 {
3828     nbl->sci_nalloc = over_alloc_small(n);
3829     nbnxn_realloc_void((void **)&nbl->sci,
3830                        nbl->nsci*sizeof(*nbl->sci),
3831                        nbl->sci_nalloc*sizeof(*nbl->sci),
3832                        nbl->alloc, nbl->free);
3833 }
3834
3835 /* Make a new ci entry at index nbl->nci */
3836 static void new_ci_entry(nbnxn_pairlist_t *nbl, int ci, int shift, int flags)
3837 {
3838     if (nbl->nci + 1 > nbl->ci_nalloc)
3839     {
3840         nb_realloc_ci(nbl, nbl->nci+1);
3841     }
3842     nbl->ci[nbl->nci].ci            = ci;
3843     nbl->ci[nbl->nci].shift         = shift;
3844     /* Store the interaction flags along with the shift */
3845     nbl->ci[nbl->nci].shift        |= flags;
3846     nbl->ci[nbl->nci].cj_ind_start  = nbl->ncj;
3847     nbl->ci[nbl->nci].cj_ind_end    = nbl->ncj;
3848 }
3849
3850 /* Make a new sci entry at index nbl->nsci */
3851 static void new_sci_entry(nbnxn_pairlist_t *nbl, int sci, int shift)
3852 {
3853     if (nbl->nsci + 1 > nbl->sci_nalloc)
3854     {
3855         nb_realloc_sci(nbl, nbl->nsci+1);
3856     }
3857     nbl->sci[nbl->nsci].sci           = sci;
3858     nbl->sci[nbl->nsci].shift         = shift;
3859     nbl->sci[nbl->nsci].cj4_ind_start = nbl->ncj4;
3860     nbl->sci[nbl->nsci].cj4_ind_end   = nbl->ncj4;
3861 }
3862
3863 /* Sort the simple j-list cj on exclusions.
3864  * Entries with exclusions will all be sorted to the beginning of the list.
3865  */
3866 static void sort_cj_excl(nbnxn_cj_t *cj, int ncj,
3867                          nbnxn_list_work_t *work)
3868 {
3869     int jnew, j;
3870
3871     if (ncj > work->cj_nalloc)
3872     {
3873         work->cj_nalloc = over_alloc_large(ncj);
3874         srenew(work->cj, work->cj_nalloc);
3875     }
3876
3877     /* Make a list of the j-cells involving exclusions */
3878     jnew = 0;
3879     for (j = 0; j < ncj; j++)
3880     {
3881         if (cj[j].excl != NBNXN_INTERACTION_MASK_ALL)
3882         {
3883             work->cj[jnew++] = cj[j];
3884         }
3885     }
3886     /* Check if there are exclusions at all or not just the first entry */
3887     if (!((jnew == 0) ||
3888           (jnew == 1 && cj[0].excl != NBNXN_INTERACTION_MASK_ALL)))
3889     {
3890         for (j = 0; j < ncj; j++)
3891         {
3892             if (cj[j].excl == NBNXN_INTERACTION_MASK_ALL)
3893             {
3894                 work->cj[jnew++] = cj[j];
3895             }
3896         }
3897         for (j = 0; j < ncj; j++)
3898         {
3899             cj[j] = work->cj[j];
3900         }
3901     }
3902 }
3903
3904 /* Close this simple list i entry */
3905 static void close_ci_entry_simple(nbnxn_pairlist_t *nbl)
3906 {
3907     int jlen;
3908
3909     /* All content of the new ci entry have already been filled correctly,
3910      * we only need to increase the count here (for non empty lists).
3911      */
3912     jlen = nbl->ci[nbl->nci].cj_ind_end - nbl->ci[nbl->nci].cj_ind_start;
3913     if (jlen > 0)
3914     {
3915         sort_cj_excl(nbl->cj+nbl->ci[nbl->nci].cj_ind_start, jlen, nbl->work);
3916
3917         /* The counts below are used for non-bonded pair/flop counts
3918          * and should therefore match the available kernel setups.
3919          */
3920         if (!(nbl->ci[nbl->nci].shift & NBNXN_CI_DO_COUL(0)))
3921         {
3922             nbl->work->ncj_noq += jlen;
3923         }
3924         else if ((nbl->ci[nbl->nci].shift & NBNXN_CI_HALF_LJ(0)) ||
3925                  !(nbl->ci[nbl->nci].shift & NBNXN_CI_DO_LJ(0)))
3926         {
3927             nbl->work->ncj_hlj += jlen;
3928         }
3929
3930         nbl->nci++;
3931     }
3932 }
3933
3934 /* Split sci entry for load balancing on the GPU.
3935  * Splitting ensures we have enough lists to fully utilize the whole GPU.
3936  * With progBal we generate progressively smaller lists, which improves
3937  * load balancing. As we only know the current count on our own thread,
3938  * we will need to estimate the current total amount of i-entries.
3939  * As the lists get concatenated later, this estimate depends
3940  * both on nthread and our own thread index.
3941  */
3942 static void split_sci_entry(nbnxn_pairlist_t *nbl,
3943                             int nsp_max_av, gmx_bool progBal, int nc_bal,
3944                             int thread, int nthread)
3945 {
3946     int nsci_est;
3947     int nsp_max;
3948     int cj4_start, cj4_end, j4len, cj4;
3949     int sci;
3950     int nsp, nsp_sci, nsp_cj4, nsp_cj4_e, nsp_cj4_p;
3951     int p;
3952
3953     if (progBal)
3954     {
3955         /* Estimate the total numbers of ci's of the nblist combined
3956          * over all threads using the target number of ci's.
3957          */
3958         nsci_est = nc_bal*thread/nthread + nbl->nsci;
3959
3960         /* The first ci blocks should be larger, to avoid overhead.
3961          * The last ci blocks should be smaller, to improve load balancing.
3962          */
3963         nsp_max = max(1,
3964                       nsp_max_av*nc_bal*3/(2*(nsci_est - 1 + nc_bal)));
3965     }
3966     else
3967     {
3968         nsp_max = nsp_max_av;
3969     }
3970
3971     cj4_start = nbl->sci[nbl->nsci-1].cj4_ind_start;
3972     cj4_end   = nbl->sci[nbl->nsci-1].cj4_ind_end;
3973     j4len     = cj4_end - cj4_start;
3974
3975     if (j4len > 1 && j4len*GPU_NSUBCELL*NBNXN_GPU_JGROUP_SIZE > nsp_max)
3976     {
3977         /* Remove the last ci entry and process the cj4's again */
3978         nbl->nsci -= 1;
3979
3980         sci        = nbl->nsci;
3981         nsp        = 0;
3982         nsp_sci    = 0;
3983         nsp_cj4_e  = 0;
3984         nsp_cj4    = 0;
3985         for (cj4 = cj4_start; cj4 < cj4_end; cj4++)
3986         {
3987             nsp_cj4_p = nsp_cj4;
3988             /* Count the number of cluster pairs in this cj4 group */
3989             nsp_cj4   = 0;
3990             for (p = 0; p < GPU_NSUBCELL*NBNXN_GPU_JGROUP_SIZE; p++)
3991             {
3992                 nsp_cj4 += (nbl->cj4[cj4].imei[0].imask >> p) & 1;
3993             }
3994
3995             if (nsp_cj4 > 0 && nsp + nsp_cj4 > nsp_max)
3996             {
3997                 /* Split the list at cj4 */
3998                 nbl->sci[sci].cj4_ind_end = cj4;
3999                 /* Create a new sci entry */
4000                 sci++;
4001                 nbl->nsci++;
4002                 if (nbl->nsci+1 > nbl->sci_nalloc)
4003                 {
4004                     nb_realloc_sci(nbl, nbl->nsci+1);
4005                 }
4006                 nbl->sci[sci].sci           = nbl->sci[nbl->nsci-1].sci;
4007                 nbl->sci[sci].shift         = nbl->sci[nbl->nsci-1].shift;
4008                 nbl->sci[sci].cj4_ind_start = cj4;
4009                 nsp_sci                     = nsp;
4010                 nsp_cj4_e                   = nsp_cj4_p;
4011                 nsp                         = 0;
4012             }
4013             nsp += nsp_cj4;
4014         }
4015
4016         /* Put the remaining cj4's in the last sci entry */
4017         nbl->sci[sci].cj4_ind_end = cj4_end;
4018
4019         /* Possibly balance out the last two sci's
4020          * by moving the last cj4 of the second last sci.
4021          */
4022         if (nsp_sci - nsp_cj4_e >= nsp + nsp_cj4_e)
4023         {
4024             nbl->sci[sci-1].cj4_ind_end--;
4025             nbl->sci[sci].cj4_ind_start--;
4026         }
4027
4028         nbl->nsci++;
4029     }
4030 }
4031
4032 /* Clost this super/sub list i entry */
4033 static void close_ci_entry_supersub(nbnxn_pairlist_t *nbl,
4034                                     int nsp_max_av,
4035                                     gmx_bool progBal, int nc_bal,
4036                                     int thread, int nthread)
4037 {
4038     int j4len, tlen;
4039     int nb, b;
4040
4041     /* All content of the new ci entry have already been filled correctly,
4042      * we only need to increase the count here (for non empty lists).
4043      */
4044     j4len = nbl->sci[nbl->nsci].cj4_ind_end - nbl->sci[nbl->nsci].cj4_ind_start;
4045     if (j4len > 0)
4046     {
4047         /* We can only have complete blocks of 4 j-entries in a list,
4048          * so round the count up before closing.
4049          */
4050         nbl->ncj4         = ((nbl->work->cj_ind + NBNXN_GPU_JGROUP_SIZE - 1) >> NBNXN_GPU_JGROUP_SIZE_2LOG);
4051         nbl->work->cj_ind = nbl->ncj4*NBNXN_GPU_JGROUP_SIZE;
4052
4053         nbl->nsci++;
4054
4055         if (nsp_max_av > 0)
4056         {
4057             /* Measure the size of the new entry and potentially split it */
4058             split_sci_entry(nbl, nsp_max_av, progBal, nc_bal, thread, nthread);
4059         }
4060     }
4061 }
4062
4063 /* Syncs the working array before adding another grid pair to the list */
4064 static void sync_work(nbnxn_pairlist_t *nbl)
4065 {
4066     if (!nbl->bSimple)
4067     {
4068         nbl->work->cj_ind   = nbl->ncj4*NBNXN_GPU_JGROUP_SIZE;
4069         nbl->work->cj4_init = nbl->ncj4;
4070     }
4071 }
4072
4073 /* Clears an nbnxn_pairlist_t data structure */
4074 static void clear_pairlist(nbnxn_pairlist_t *nbl)
4075 {
4076     nbl->nci           = 0;
4077     nbl->nsci          = 0;
4078     nbl->ncj           = 0;
4079     nbl->ncj4          = 0;
4080     nbl->nci_tot       = 0;
4081     nbl->nexcl         = 1;
4082
4083     nbl->work->ncj_noq = 0;
4084     nbl->work->ncj_hlj = 0;
4085 }
4086
4087 /* Clears a group scheme pair list */
4088 static void clear_pairlist_fep(t_nblist *nl)
4089 {
4090     nl->nri = 0;
4091     nl->nrj = 0;
4092     if (nl->jindex == NULL)
4093     {
4094         snew(nl->jindex, 1);
4095     }
4096     nl->jindex[0] = 0;
4097 }
4098
4099 /* Sets a simple list i-cell bounding box, including PBC shift */
4100 static gmx_inline void set_icell_bb_simple(const nbnxn_bb_t *bb, int ci,
4101                                            real shx, real shy, real shz,
4102                                            nbnxn_bb_t *bb_ci)
4103 {
4104     bb_ci->lower[BB_X] = bb[ci].lower[BB_X] + shx;
4105     bb_ci->lower[BB_Y] = bb[ci].lower[BB_Y] + shy;
4106     bb_ci->lower[BB_Z] = bb[ci].lower[BB_Z] + shz;
4107     bb_ci->upper[BB_X] = bb[ci].upper[BB_X] + shx;
4108     bb_ci->upper[BB_Y] = bb[ci].upper[BB_Y] + shy;
4109     bb_ci->upper[BB_Z] = bb[ci].upper[BB_Z] + shz;
4110 }
4111
4112 #ifdef NBNXN_BBXXXX
4113 /* Sets a super-cell and sub cell bounding boxes, including PBC shift */
4114 static void set_icell_bbxxxx_supersub(const float *bb, int ci,
4115                                       real shx, real shy, real shz,
4116                                       float *bb_ci)
4117 {
4118     int ia, m, i;
4119
4120     ia = ci*(GPU_NSUBCELL>>STRIDE_PBB_2LOG)*NNBSBB_XXXX;
4121     for (m = 0; m < (GPU_NSUBCELL>>STRIDE_PBB_2LOG)*NNBSBB_XXXX; m += NNBSBB_XXXX)
4122     {
4123         for (i = 0; i < STRIDE_PBB; i++)
4124         {
4125             bb_ci[m+0*STRIDE_PBB+i] = bb[ia+m+0*STRIDE_PBB+i] + shx;
4126             bb_ci[m+1*STRIDE_PBB+i] = bb[ia+m+1*STRIDE_PBB+i] + shy;
4127             bb_ci[m+2*STRIDE_PBB+i] = bb[ia+m+2*STRIDE_PBB+i] + shz;
4128             bb_ci[m+3*STRIDE_PBB+i] = bb[ia+m+3*STRIDE_PBB+i] + shx;
4129             bb_ci[m+4*STRIDE_PBB+i] = bb[ia+m+4*STRIDE_PBB+i] + shy;
4130             bb_ci[m+5*STRIDE_PBB+i] = bb[ia+m+5*STRIDE_PBB+i] + shz;
4131         }
4132     }
4133 }
4134 #endif
4135
4136 /* Sets a super-cell and sub cell bounding boxes, including PBC shift */
4137 static void set_icell_bb_supersub(const nbnxn_bb_t *bb, int ci,
4138                                   real shx, real shy, real shz,
4139                                   nbnxn_bb_t *bb_ci)
4140 {
4141     int i;
4142
4143     for (i = 0; i < GPU_NSUBCELL; i++)
4144     {
4145         set_icell_bb_simple(bb, ci*GPU_NSUBCELL+i,
4146                             shx, shy, shz,
4147                             &bb_ci[i]);
4148     }
4149 }
4150
4151 /* Copies PBC shifted i-cell atom coordinates x,y,z to working array */
4152 static void icell_set_x_simple(int ci,
4153                                real shx, real shy, real shz,
4154                                int gmx_unused na_c,
4155                                int stride, const real *x,
4156                                nbnxn_list_work_t *work)
4157 {
4158     int  ia, i;
4159
4160     ia = ci*NBNXN_CPU_CLUSTER_I_SIZE;
4161
4162     for (i = 0; i < NBNXN_CPU_CLUSTER_I_SIZE; i++)
4163     {
4164         work->x_ci[i*STRIDE_XYZ+XX] = x[(ia+i)*stride+XX] + shx;
4165         work->x_ci[i*STRIDE_XYZ+YY] = x[(ia+i)*stride+YY] + shy;
4166         work->x_ci[i*STRIDE_XYZ+ZZ] = x[(ia+i)*stride+ZZ] + shz;
4167     }
4168 }
4169
4170 /* Copies PBC shifted super-cell atom coordinates x,y,z to working array */
4171 static void icell_set_x_supersub(int ci,
4172                                  real shx, real shy, real shz,
4173                                  int na_c,
4174                                  int stride, const real *x,
4175                                  nbnxn_list_work_t *work)
4176 {
4177     int   ia, i;
4178     real *x_ci;
4179
4180     x_ci = work->x_ci;
4181
4182     ia = ci*GPU_NSUBCELL*na_c;
4183     for (i = 0; i < GPU_NSUBCELL*na_c; i++)
4184     {
4185         x_ci[i*DIM + XX] = x[(ia+i)*stride + XX] + shx;
4186         x_ci[i*DIM + YY] = x[(ia+i)*stride + YY] + shy;
4187         x_ci[i*DIM + ZZ] = x[(ia+i)*stride + ZZ] + shz;
4188     }
4189 }
4190
4191 #ifdef NBNXN_SEARCH_BB_SIMD4
4192 /* Copies PBC shifted super-cell packed atom coordinates to working array */
4193 static void icell_set_x_supersub_simd4(int ci,
4194                                        real shx, real shy, real shz,
4195                                        int na_c,
4196                                        int stride, const real *x,
4197                                        nbnxn_list_work_t *work)
4198 {
4199     int   si, io, ia, i, j;
4200     real *x_ci;
4201
4202     x_ci = work->x_ci;
4203
4204     for (si = 0; si < GPU_NSUBCELL; si++)
4205     {
4206         for (i = 0; i < na_c; i += STRIDE_PBB)
4207         {
4208             io = si*na_c + i;
4209             ia = ci*GPU_NSUBCELL*na_c + io;
4210             for (j = 0; j < STRIDE_PBB; j++)
4211             {
4212                 x_ci[io*DIM + j + XX*STRIDE_PBB] = x[(ia+j)*stride+XX] + shx;
4213                 x_ci[io*DIM + j + YY*STRIDE_PBB] = x[(ia+j)*stride+YY] + shy;
4214                 x_ci[io*DIM + j + ZZ*STRIDE_PBB] = x[(ia+j)*stride+ZZ] + shz;
4215             }
4216         }
4217     }
4218 }
4219 #endif
4220
4221 static real minimum_subgrid_size_xy(const nbnxn_grid_t *grid)
4222 {
4223     if (grid->bSimple)
4224     {
4225         return min(grid->sx, grid->sy);
4226     }
4227     else
4228     {
4229         return min(grid->sx/GPU_NSUBCELL_X, grid->sy/GPU_NSUBCELL_Y);
4230     }
4231 }
4232
4233 static real effective_buffer_1x1_vs_MxN(const nbnxn_grid_t *gridi,
4234                                         const nbnxn_grid_t *gridj)
4235 {
4236     const real eff_1x1_buffer_fac_overest = 0.1;
4237
4238     /* Determine an atom-pair list cut-off buffer size for atom pairs,
4239      * to be added to rlist (including buffer) used for MxN.
4240      * This is for converting an MxN list to a 1x1 list. This means we can't
4241      * use the normal buffer estimate, as we have an MxN list in which
4242      * some atom pairs beyond rlist are missing. We want to capture
4243      * the beneficial effect of buffering by extra pairs just outside rlist,
4244      * while removing the useless pairs that are further away from rlist.
4245      * (Also the buffer could have been set manually not using the estimate.)
4246      * This buffer size is an overestimate.
4247      * We add 10% of the smallest grid sub-cell dimensions.
4248      * Note that the z-size differs per cell and we don't use this,
4249      * so we overestimate.
4250      * With PME, the 10% value gives a buffer that is somewhat larger
4251      * than the effective buffer with a tolerance of 0.005 kJ/mol/ps.
4252      * Smaller tolerances or using RF lead to a smaller effective buffer,
4253      * so 10% gives a safe overestimate.
4254      */
4255     return eff_1x1_buffer_fac_overest*(minimum_subgrid_size_xy(gridi) +
4256                                        minimum_subgrid_size_xy(gridj));
4257 }
4258
4259 /* Clusters at the cut-off only increase rlist by 60% of their size */
4260 static real nbnxn_rlist_inc_outside_fac = 0.6;
4261
4262 /* Due to the cluster size the effective pair-list is longer than
4263  * that of a simple atom pair-list. This function gives the extra distance.
4264  */
4265 real nbnxn_get_rlist_effective_inc(int cluster_size_j, real atom_density)
4266 {
4267     int  cluster_size_i;
4268     real vol_inc_i, vol_inc_j;
4269
4270     /* We should get this from the setup, but currently it's the same for
4271      * all setups, including GPUs.
4272      */
4273     cluster_size_i = NBNXN_CPU_CLUSTER_I_SIZE;
4274
4275     vol_inc_i = (cluster_size_i - 1)/atom_density;
4276     vol_inc_j = (cluster_size_j - 1)/atom_density;
4277
4278     return nbnxn_rlist_inc_outside_fac*pow(vol_inc_i + vol_inc_j, 1.0/3.0);
4279 }
4280
4281 /* Estimates the interaction volume^2 for non-local interactions */
4282 static real nonlocal_vol2(const gmx_domdec_zones_t *zones, rvec ls, real r)
4283 {
4284     int  z, d;
4285     real cl, ca, za;
4286     real vold_est;
4287     real vol2_est_tot;
4288
4289     vol2_est_tot = 0;
4290
4291     /* Here we simply add up the volumes of 1, 2 or 3 1D decomposition
4292      * not home interaction volume^2. As these volumes are not additive,
4293      * this is an overestimate, but it would only be significant in the limit
4294      * of small cells, where we anyhow need to split the lists into
4295      * as small parts as possible.
4296      */
4297
4298     for (z = 0; z < zones->n; z++)
4299     {
4300         if (zones->shift[z][XX] + zones->shift[z][YY] + zones->shift[z][ZZ] == 1)
4301         {
4302             cl = 0;
4303             ca = 1;
4304             za = 1;
4305             for (d = 0; d < DIM; d++)
4306             {
4307                 if (zones->shift[z][d] == 0)
4308                 {
4309                     cl += 0.5*ls[d];
4310                     ca *= ls[d];
4311                     za *= zones->size[z].x1[d] - zones->size[z].x0[d];
4312                 }
4313             }
4314
4315             /* 4 octants of a sphere */
4316             vold_est  = 0.25*M_PI*r*r*r*r;
4317             /* 4 quarter pie slices on the edges */
4318             vold_est += 4*cl*M_PI/6.0*r*r*r;
4319             /* One rectangular volume on a face */
4320             vold_est += ca*0.5*r*r;
4321
4322             vol2_est_tot += vold_est*za;
4323         }
4324     }
4325
4326     return vol2_est_tot;
4327 }
4328
4329 /* Estimates the average size of a full j-list for super/sub setup */
4330 static int get_nsubpair_max(const nbnxn_search_t nbs,
4331                             int                  iloc,
4332                             real                 rlist,
4333                             int                  min_ci_balanced)
4334 {
4335     const nbnxn_grid_t *grid;
4336     rvec                ls;
4337     real                xy_diag2, r_eff_sup, vol_est, nsp_est, nsp_est_nl;
4338     int                 nsubpair_max;
4339
4340     grid = &nbs->grid[0];
4341
4342     ls[XX] = (grid->c1[XX] - grid->c0[XX])/(grid->ncx*GPU_NSUBCELL_X);
4343     ls[YY] = (grid->c1[YY] - grid->c0[YY])/(grid->ncy*GPU_NSUBCELL_Y);
4344     ls[ZZ] = (grid->c1[ZZ] - grid->c0[ZZ])*grid->ncx*grid->ncy/(grid->nc*GPU_NSUBCELL_Z);
4345
4346     /* The average squared length of the diagonal of a sub cell */
4347     xy_diag2 = ls[XX]*ls[XX] + ls[YY]*ls[YY] + ls[ZZ]*ls[ZZ];
4348
4349     /* The formulas below are a heuristic estimate of the average nsj per si*/
4350     r_eff_sup = rlist + nbnxn_rlist_inc_outside_fac*sqr((grid->na_c - 1.0)/grid->na_c)*sqrt(xy_diag2/3);
4351
4352     if (!nbs->DomDec || nbs->zones->n == 1)
4353     {
4354         nsp_est_nl = 0;
4355     }
4356     else
4357     {
4358         nsp_est_nl =
4359             sqr(grid->atom_density/grid->na_c)*
4360             nonlocal_vol2(nbs->zones, ls, r_eff_sup);
4361     }
4362
4363     if (LOCAL_I(iloc))
4364     {
4365         /* Sub-cell interacts with itself */
4366         vol_est  = ls[XX]*ls[YY]*ls[ZZ];
4367         /* 6/2 rectangular volume on the faces */
4368         vol_est += (ls[XX]*ls[YY] + ls[XX]*ls[ZZ] + ls[YY]*ls[ZZ])*r_eff_sup;
4369         /* 12/2 quarter pie slices on the edges */
4370         vol_est += 2*(ls[XX] + ls[YY] + ls[ZZ])*0.25*M_PI*sqr(r_eff_sup);
4371         /* 4 octants of a sphere */
4372         vol_est += 0.5*4.0/3.0*M_PI*pow(r_eff_sup, 3);
4373
4374         nsp_est = grid->nsubc_tot*vol_est*grid->atom_density/grid->na_c;
4375
4376         /* Subtract the non-local pair count */
4377         nsp_est -= nsp_est_nl;
4378
4379         if (debug)
4380         {
4381             fprintf(debug, "nsp_est local %5.1f non-local %5.1f\n",
4382                     nsp_est, nsp_est_nl);
4383         }
4384     }
4385     else
4386     {
4387         nsp_est = nsp_est_nl;
4388     }
4389
4390     if (min_ci_balanced <= 0 || grid->nc >= min_ci_balanced || grid->nc == 0)
4391     {
4392         /* We don't need to worry */
4393         nsubpair_max = -1;
4394     }
4395     else
4396     {
4397         /* Thus the (average) maximum j-list size should be as follows */
4398         nsubpair_max = max(1, (int)(nsp_est/min_ci_balanced+0.5));
4399
4400         /* Since the target value is a maximum (this avoids high outliers,
4401          * which lead to load imbalance), not average, we add half the
4402          * number of pairs in a cj4 block to get the average about right.
4403          */
4404         nsubpair_max += GPU_NSUBCELL*NBNXN_GPU_JGROUP_SIZE/2;
4405     }
4406
4407     if (debug)
4408     {
4409         fprintf(debug, "nbl nsp estimate %.1f, nsubpair_max %d\n",
4410                 nsp_est, nsubpair_max);
4411     }
4412
4413     return nsubpair_max;
4414 }
4415
4416 /* Debug list print function */
4417 static void print_nblist_ci_cj(FILE *fp, const nbnxn_pairlist_t *nbl)
4418 {
4419     int i, j;
4420
4421     for (i = 0; i < nbl->nci; i++)
4422     {
4423         fprintf(fp, "ci %4d  shift %2d  ncj %3d\n",
4424                 nbl->ci[i].ci, nbl->ci[i].shift,
4425                 nbl->ci[i].cj_ind_end - nbl->ci[i].cj_ind_start);
4426
4427         for (j = nbl->ci[i].cj_ind_start; j < nbl->ci[i].cj_ind_end; j++)
4428         {
4429             fprintf(fp, "  cj %5d  imask %x\n",
4430                     nbl->cj[j].cj,
4431                     nbl->cj[j].excl);
4432         }
4433     }
4434 }
4435
4436 /* Debug list print function */
4437 static void print_nblist_sci_cj(FILE *fp, const nbnxn_pairlist_t *nbl)
4438 {
4439     int i, j4, j, ncp, si;
4440
4441     for (i = 0; i < nbl->nsci; i++)
4442     {
4443         fprintf(fp, "ci %4d  shift %2d  ncj4 %2d\n",
4444                 nbl->sci[i].sci, nbl->sci[i].shift,
4445                 nbl->sci[i].cj4_ind_end - nbl->sci[i].cj4_ind_start);
4446
4447         ncp = 0;
4448         for (j4 = nbl->sci[i].cj4_ind_start; j4 < nbl->sci[i].cj4_ind_end; j4++)
4449         {
4450             for (j = 0; j < NBNXN_GPU_JGROUP_SIZE; j++)
4451             {
4452                 fprintf(fp, "  sj %5d  imask %x\n",
4453                         nbl->cj4[j4].cj[j],
4454                         nbl->cj4[j4].imei[0].imask);
4455                 for (si = 0; si < GPU_NSUBCELL; si++)
4456                 {
4457                     if (nbl->cj4[j4].imei[0].imask & (1U << (j*GPU_NSUBCELL + si)))
4458                     {
4459                         ncp++;
4460                     }
4461                 }
4462             }
4463         }
4464         fprintf(fp, "ci %4d  shift %2d  ncj4 %2d ncp %3d\n",
4465                 nbl->sci[i].sci, nbl->sci[i].shift,
4466                 nbl->sci[i].cj4_ind_end - nbl->sci[i].cj4_ind_start,
4467                 ncp);
4468     }
4469 }
4470
4471 /* Combine pair lists *nbl generated on multiple threads nblc */
4472 static void combine_nblists(int nnbl, nbnxn_pairlist_t **nbl,
4473                             nbnxn_pairlist_t *nblc)
4474 {
4475     int nsci, ncj4, nexcl;
4476     int n, i;
4477     int nthreads gmx_unused;
4478
4479     if (nblc->bSimple)
4480     {
4481         gmx_incons("combine_nblists does not support simple lists");
4482     }
4483
4484     nsci  = nblc->nsci;
4485     ncj4  = nblc->ncj4;
4486     nexcl = nblc->nexcl;
4487     for (i = 0; i < nnbl; i++)
4488     {
4489         nsci  += nbl[i]->nsci;
4490         ncj4  += nbl[i]->ncj4;
4491         nexcl += nbl[i]->nexcl;
4492     }
4493
4494     if (nsci > nblc->sci_nalloc)
4495     {
4496         nb_realloc_sci(nblc, nsci);
4497     }
4498     if (ncj4 > nblc->cj4_nalloc)
4499     {
4500         nblc->cj4_nalloc = over_alloc_small(ncj4);
4501         nbnxn_realloc_void((void **)&nblc->cj4,
4502                            nblc->ncj4*sizeof(*nblc->cj4),
4503                            nblc->cj4_nalloc*sizeof(*nblc->cj4),
4504                            nblc->alloc, nblc->free);
4505     }
4506     if (nexcl > nblc->excl_nalloc)
4507     {
4508         nblc->excl_nalloc = over_alloc_small(nexcl);
4509         nbnxn_realloc_void((void **)&nblc->excl,
4510                            nblc->nexcl*sizeof(*nblc->excl),
4511                            nblc->excl_nalloc*sizeof(*nblc->excl),
4512                            nblc->alloc, nblc->free);
4513     }
4514
4515     /* Each thread should copy its own data to the combined arrays,
4516      * as otherwise data will go back and forth between different caches.
4517      */
4518     nthreads = gmx_omp_nthreads_get(emntPairsearch);
4519 #pragma omp parallel for num_threads(nthreads) schedule(static)
4520     for (n = 0; n < nnbl; n++)
4521     {
4522         int                     sci_offset;
4523         int                     cj4_offset;
4524         int                     ci_offset;
4525         int                     excl_offset;
4526         int                     i, j4;
4527         const nbnxn_pairlist_t *nbli;
4528
4529         /* Determine the offset in the combined data for our thread */
4530         sci_offset  = nblc->nsci;
4531         cj4_offset  = nblc->ncj4;
4532         ci_offset   = nblc->nci_tot;
4533         excl_offset = nblc->nexcl;
4534
4535         for (i = 0; i < n; i++)
4536         {
4537             sci_offset  += nbl[i]->nsci;
4538             cj4_offset  += nbl[i]->ncj4;
4539             ci_offset   += nbl[i]->nci_tot;
4540             excl_offset += nbl[i]->nexcl;
4541         }
4542
4543         nbli = nbl[n];
4544
4545         for (i = 0; i < nbli->nsci; i++)
4546         {
4547             nblc->sci[sci_offset+i]                = nbli->sci[i];
4548             nblc->sci[sci_offset+i].cj4_ind_start += cj4_offset;
4549             nblc->sci[sci_offset+i].cj4_ind_end   += cj4_offset;
4550         }
4551
4552         for (j4 = 0; j4 < nbli->ncj4; j4++)
4553         {
4554             nblc->cj4[cj4_offset+j4]                   = nbli->cj4[j4];
4555             nblc->cj4[cj4_offset+j4].imei[0].excl_ind += excl_offset;
4556             nblc->cj4[cj4_offset+j4].imei[1].excl_ind += excl_offset;
4557         }
4558
4559         for (j4 = 0; j4 < nbli->nexcl; j4++)
4560         {
4561             nblc->excl[excl_offset+j4] = nbli->excl[j4];
4562         }
4563     }
4564
4565     for (n = 0; n < nnbl; n++)
4566     {
4567         nblc->nsci    += nbl[n]->nsci;
4568         nblc->ncj4    += nbl[n]->ncj4;
4569         nblc->nci_tot += nbl[n]->nci_tot;
4570         nblc->nexcl   += nbl[n]->nexcl;
4571     }
4572 }
4573
4574 static void balance_fep_lists(const nbnxn_search_t  nbs,
4575                               nbnxn_pairlist_set_t *nbl_lists)
4576 {
4577     int       nnbl, th;
4578     int       nri_tot, nrj_tot, nrj_target;
4579     int       th_dest;
4580     t_nblist *nbld;
4581
4582     nnbl = nbl_lists->nnbl;
4583
4584     if (nnbl == 1)
4585     {
4586         /* Nothing to balance */
4587         return;
4588     }
4589
4590     /* Count the total i-lists and pairs */
4591     nri_tot = 0;
4592     nrj_tot = 0;
4593     for (th = 0; th < nnbl; th++)
4594     {
4595         nri_tot += nbl_lists->nbl_fep[th]->nri;
4596         nrj_tot += nbl_lists->nbl_fep[th]->nrj;
4597     }
4598
4599     nrj_target = (nrj_tot + nnbl - 1)/nnbl;
4600
4601     assert(gmx_omp_nthreads_get(emntNonbonded) == nnbl);
4602
4603 #pragma omp parallel for schedule(static) num_threads(nnbl)
4604     for (th = 0; th < nnbl; th++)
4605     {
4606         t_nblist *nbl;
4607
4608         nbl = nbs->work[th].nbl_fep;
4609
4610         /* Note that here we allocate for the total size, instead of
4611          * a per-thread esimate (which is hard to obtain).
4612          */
4613         if (nri_tot > nbl->maxnri)
4614         {
4615             nbl->maxnri = over_alloc_large(nri_tot);
4616             reallocate_nblist(nbl);
4617         }
4618         if (nri_tot > nbl->maxnri || nrj_tot > nbl->maxnrj)
4619         {
4620             nbl->maxnrj = over_alloc_small(nrj_tot);
4621             srenew(nbl->jjnr, nbl->maxnrj);
4622             srenew(nbl->excl_fep, nbl->maxnrj);
4623         }
4624
4625         clear_pairlist_fep(nbl);
4626     }
4627
4628     /* Loop over the source lists and assign and copy i-entries */
4629     th_dest = 0;
4630     nbld    = nbs->work[th_dest].nbl_fep;
4631     for (th = 0; th < nnbl; th++)
4632     {
4633         t_nblist *nbls;
4634         int       i, j;
4635
4636         nbls = nbl_lists->nbl_fep[th];
4637
4638         for (i = 0; i < nbls->nri; i++)
4639         {
4640             int nrj;
4641
4642             /* The number of pairs in this i-entry */
4643             nrj = nbls->jindex[i+1] - nbls->jindex[i];
4644
4645             /* Decide if list th_dest is too large and we should procede
4646              * to the next destination list.
4647              */
4648             if (th_dest+1 < nnbl && nbld->nrj > 0 &&
4649                 nbld->nrj + nrj - nrj_target > nrj_target - nbld->nrj)
4650             {
4651                 th_dest++;
4652                 nbld = nbs->work[th_dest].nbl_fep;
4653             }
4654
4655             nbld->iinr[nbld->nri]  = nbls->iinr[i];
4656             nbld->gid[nbld->nri]   = nbls->gid[i];
4657             nbld->shift[nbld->nri] = nbls->shift[i];
4658
4659             for (j = nbls->jindex[i]; j < nbls->jindex[i+1]; j++)
4660             {
4661                 nbld->jjnr[nbld->nrj]     = nbls->jjnr[j];
4662                 nbld->excl_fep[nbld->nrj] = nbls->excl_fep[j];
4663                 nbld->nrj++;
4664             }
4665             nbld->nri++;
4666             nbld->jindex[nbld->nri] = nbld->nrj;
4667         }
4668     }
4669
4670     /* Swap the list pointers */
4671     for (th = 0; th < nnbl; th++)
4672     {
4673         t_nblist *nbl_tmp;
4674
4675         nbl_tmp                = nbl_lists->nbl_fep[th];
4676         nbl_lists->nbl_fep[th] = nbs->work[th].nbl_fep;
4677         nbs->work[th].nbl_fep  = nbl_tmp;
4678
4679         if (debug)
4680         {
4681             fprintf(debug, "nbl_fep[%d] nri %4d nrj %4d\n",
4682                     th,
4683                     nbl_lists->nbl_fep[th]->nri,
4684                     nbl_lists->nbl_fep[th]->nrj);
4685         }
4686     }
4687 }
4688
4689 /* Returns the next ci to be processes by our thread */
4690 static gmx_bool next_ci(const nbnxn_grid_t *grid,
4691                         int conv,
4692                         int nth, int ci_block,
4693                         int *ci_x, int *ci_y,
4694                         int *ci_b, int *ci)
4695 {
4696     (*ci_b)++;
4697     (*ci)++;
4698
4699     if (*ci_b == ci_block)
4700     {
4701         /* Jump to the next block assigned to this task */
4702         *ci   += (nth - 1)*ci_block;
4703         *ci_b  = 0;
4704     }
4705
4706     if (*ci >= grid->nc*conv)
4707     {
4708         return FALSE;
4709     }
4710
4711     while (*ci >= grid->cxy_ind[*ci_x*grid->ncy + *ci_y + 1]*conv)
4712     {
4713         *ci_y += 1;
4714         if (*ci_y == grid->ncy)
4715         {
4716             *ci_x += 1;
4717             *ci_y  = 0;
4718         }
4719     }
4720
4721     return TRUE;
4722 }
4723
4724 /* Returns the distance^2 for which we put cell pairs in the list
4725  * without checking atom pair distances. This is usually < rlist^2.
4726  */
4727 static float boundingbox_only_distance2(const nbnxn_grid_t *gridi,
4728                                         const nbnxn_grid_t *gridj,
4729                                         real                rlist,
4730                                         gmx_bool            simple)
4731 {
4732     /* If the distance between two sub-cell bounding boxes is less
4733      * than this distance, do not check the distance between
4734      * all particle pairs in the sub-cell, since then it is likely
4735      * that the box pair has atom pairs within the cut-off.
4736      * We use the nblist cut-off minus 0.5 times the average x/y diagonal
4737      * spacing of the sub-cells. Around 40% of the checked pairs are pruned.
4738      * Using more than 0.5 gains at most 0.5%.
4739      * If forces are calculated more than twice, the performance gain
4740      * in the force calculation outweighs the cost of checking.
4741      * Note that with subcell lists, the atom-pair distance check
4742      * is only performed when only 1 out of 8 sub-cells in within range,
4743      * this is because the GPU is much faster than the cpu.
4744      */
4745     real bbx, bby;
4746     real rbb2;
4747
4748     bbx = 0.5*(gridi->sx + gridj->sx);
4749     bby = 0.5*(gridi->sy + gridj->sy);
4750     if (!simple)
4751     {
4752         bbx /= GPU_NSUBCELL_X;
4753         bby /= GPU_NSUBCELL_Y;
4754     }
4755
4756     rbb2 = sqr(max(0, rlist - 0.5*sqrt(bbx*bbx + bby*bby)));
4757
4758 #ifndef GMX_DOUBLE
4759     return rbb2;
4760 #else
4761     return (float)((1+GMX_FLOAT_EPS)*rbb2);
4762 #endif
4763 }
4764
4765 static int get_ci_block_size(const nbnxn_grid_t *gridi,
4766                              gmx_bool bDomDec, int nth)
4767 {
4768     const int ci_block_enum      = 5;
4769     const int ci_block_denom     = 11;
4770     const int ci_block_min_atoms = 16;
4771     int       ci_block;
4772
4773     /* Here we decide how to distribute the blocks over the threads.
4774      * We use prime numbers to try to avoid that the grid size becomes
4775      * a multiple of the number of threads, which would lead to some
4776      * threads getting "inner" pairs and others getting boundary pairs,
4777      * which in turns will lead to load imbalance between threads.
4778      * Set the block size as 5/11/ntask times the average number of cells
4779      * in a y,z slab. This should ensure a quite uniform distribution
4780      * of the grid parts of the different thread along all three grid
4781      * zone boundaries with 3D domain decomposition. At the same time
4782      * the blocks will not become too small.
4783      */
4784     ci_block = (gridi->nc*ci_block_enum)/(ci_block_denom*gridi->ncx*nth);
4785
4786     /* Ensure the blocks are not too small: avoids cache invalidation */
4787     if (ci_block*gridi->na_sc < ci_block_min_atoms)
4788     {
4789         ci_block = (ci_block_min_atoms + gridi->na_sc - 1)/gridi->na_sc;
4790     }
4791
4792     /* Without domain decomposition
4793      * or with less than 3 blocks per task, divide in nth blocks.
4794      */
4795     if (!bDomDec || ci_block*3*nth > gridi->nc)
4796     {
4797         ci_block = (gridi->nc + nth - 1)/nth;
4798     }
4799
4800     return ci_block;
4801 }
4802
4803 /* Generates the part of pair-list nbl assigned to our thread */
4804 static void nbnxn_make_pairlist_part(const nbnxn_search_t nbs,
4805                                      const nbnxn_grid_t *gridi,
4806                                      const nbnxn_grid_t *gridj,
4807                                      nbnxn_search_work_t *work,
4808                                      const nbnxn_atomdata_t *nbat,
4809                                      const t_blocka *excl,
4810                                      real rlist,
4811                                      int nb_kernel_type,
4812                                      int ci_block,
4813                                      gmx_bool bFBufferFlag,
4814                                      int nsubpair_max,
4815                                      gmx_bool progBal,
4816                                      int min_ci_balanced,
4817                                      int th, int nth,
4818                                      nbnxn_pairlist_t *nbl,
4819                                      t_nblist *nbl_fep)
4820 {
4821     int               na_cj_2log;
4822     matrix            box;
4823     real              rl2, rl_fep2 = 0;
4824     float             rbb2;
4825     int               d;
4826     int               ci_b, ci, ci_x, ci_y, ci_xy, cj;
4827     ivec              shp;
4828     int               tx, ty, tz;
4829     int               shift;
4830     gmx_bool          bMakeList;
4831     real              shx, shy, shz;
4832     int               conv_i, cell0_i;
4833     const nbnxn_bb_t *bb_i = NULL;
4834 #ifdef NBNXN_BBXXXX
4835     const float      *pbb_i = NULL;
4836 #endif
4837     const float      *bbcz_i, *bbcz_j;
4838     const int        *flags_i;
4839     real              bx0, bx1, by0, by1, bz0, bz1;
4840     real              bz1_frac;
4841     real              d2cx, d2z, d2z_cx, d2z_cy, d2zx, d2zxy, d2xy;
4842     int               cxf, cxl, cyf, cyf_x, cyl;
4843     int               cx, cy;
4844     int               c0, c1, cs, cf, cl;
4845     int               ndistc;
4846     int               ncpcheck;
4847     int               gridi_flag_shift = 0, gridj_flag_shift = 0;
4848     gmx_bitmask_t    *gridj_flag       = NULL;
4849     int               ncj_old_i, ncj_old_j;
4850
4851     nbs_cycle_start(&work->cc[enbsCCsearch]);
4852
4853     if (gridj->bSimple != nbl->bSimple)
4854     {
4855         gmx_incons("Grid incompatible with pair-list");
4856     }
4857
4858     sync_work(nbl);
4859     nbl->na_sc = gridj->na_sc;
4860     nbl->na_ci = gridj->na_c;
4861     nbl->na_cj = nbnxn_kernel_to_cj_size(nb_kernel_type);
4862     na_cj_2log = get_2log(nbl->na_cj);
4863
4864     nbl->rlist  = rlist;
4865
4866     if (bFBufferFlag)
4867     {
4868         /* Determine conversion of clusters to flag blocks */
4869         gridi_flag_shift = 0;
4870         while ((nbl->na_ci<<gridi_flag_shift) < NBNXN_BUFFERFLAG_SIZE)
4871         {
4872             gridi_flag_shift++;
4873         }
4874         gridj_flag_shift = 0;
4875         while ((nbl->na_cj<<gridj_flag_shift) < NBNXN_BUFFERFLAG_SIZE)
4876         {
4877             gridj_flag_shift++;
4878         }
4879
4880         gridj_flag = work->buffer_flags.flag;
4881     }
4882
4883     copy_mat(nbs->box, box);
4884
4885     rl2 = nbl->rlist*nbl->rlist;
4886
4887     if (nbs->bFEP && !nbl->bSimple)
4888     {
4889         /* Determine an atom-pair list cut-off distance for FEP atom pairs.
4890          * We should not simply use rlist, since then we would not have
4891          * the small, effective buffering of the NxN lists.
4892          * The buffer is on overestimate, but the resulting cost for pairs
4893          * beyond rlist is neglible compared to the FEP pairs within rlist.
4894          */
4895         rl_fep2 = nbl->rlist + effective_buffer_1x1_vs_MxN(gridi, gridj);
4896
4897         if (debug)
4898         {
4899             fprintf(debug, "nbl_fep atom-pair rlist %f\n", rl_fep2);
4900         }
4901         rl_fep2 = rl_fep2*rl_fep2;
4902     }
4903
4904     rbb2 = boundingbox_only_distance2(gridi, gridj, nbl->rlist, nbl->bSimple);
4905
4906     if (debug)
4907     {
4908         fprintf(debug, "nbl bounding box only distance %f\n", sqrt(rbb2));
4909     }
4910
4911     /* Set the shift range */
4912     for (d = 0; d < DIM; d++)
4913     {
4914         /* Check if we need periodicity shifts.
4915          * Without PBC or with domain decomposition we don't need them.
4916          */
4917         if (d >= ePBC2npbcdim(nbs->ePBC) || nbs->dd_dim[d])
4918         {
4919             shp[d] = 0;
4920         }
4921         else
4922         {
4923             if (d == XX &&
4924                 box[XX][XX] - fabs(box[YY][XX]) - fabs(box[ZZ][XX]) < sqrt(rl2))
4925             {
4926                 shp[d] = 2;
4927             }
4928             else
4929             {
4930                 shp[d] = 1;
4931             }
4932         }
4933     }
4934
4935     if (nbl->bSimple && !gridi->bSimple)
4936     {
4937         conv_i  = gridi->na_sc/gridj->na_sc;
4938         bb_i    = gridi->bb_simple;
4939         bbcz_i  = gridi->bbcz_simple;
4940         flags_i = gridi->flags_simple;
4941     }
4942     else
4943     {
4944         conv_i  = 1;
4945 #ifdef NBNXN_BBXXXX
4946         if (gridi->bSimple)
4947         {
4948             bb_i  = gridi->bb;
4949         }
4950         else
4951         {
4952             pbb_i = gridi->pbb;
4953         }
4954 #else
4955         /* We use the normal bounding box format for both grid types */
4956         bb_i  = gridi->bb;
4957 #endif
4958         bbcz_i  = gridi->bbcz;
4959         flags_i = gridi->flags;
4960     }
4961     cell0_i = gridi->cell0*conv_i;
4962
4963     bbcz_j = gridj->bbcz;
4964
4965     if (conv_i != 1)
4966     {
4967         /* Blocks of the conversion factor - 1 give a large repeat count
4968          * combined with a small block size. This should result in good
4969          * load balancing for both small and large domains.
4970          */
4971         ci_block = conv_i - 1;
4972     }
4973     if (debug)
4974     {
4975         fprintf(debug, "nbl nc_i %d col.av. %.1f ci_block %d\n",
4976                 gridi->nc, gridi->nc/(double)(gridi->ncx*gridi->ncy), ci_block);
4977     }
4978
4979     ndistc   = 0;
4980     ncpcheck = 0;
4981
4982     /* Initially ci_b and ci to 1 before where we want them to start,
4983      * as they will both be incremented in next_ci.
4984      */
4985     ci_b = -1;
4986     ci   = th*ci_block - 1;
4987     ci_x = 0;
4988     ci_y = 0;
4989     while (next_ci(gridi, conv_i, nth, ci_block, &ci_x, &ci_y, &ci_b, &ci))
4990     {
4991         if (nbl->bSimple && flags_i[ci] == 0)
4992         {
4993             continue;
4994         }
4995
4996         ncj_old_i = nbl->ncj;
4997
4998         d2cx = 0;
4999         if (gridj != gridi && shp[XX] == 0)
5000         {
5001             if (nbl->bSimple)
5002             {
5003                 bx1 = bb_i[ci].upper[BB_X];
5004             }
5005             else
5006             {
5007                 bx1 = gridi->c0[XX] + (ci_x+1)*gridi->sx;
5008             }
5009             if (bx1 < gridj->c0[XX])
5010             {
5011                 d2cx = sqr(gridj->c0[XX] - bx1);
5012
5013                 if (d2cx >= rl2)
5014                 {
5015                     continue;
5016                 }
5017             }
5018         }
5019
5020         ci_xy = ci_x*gridi->ncy + ci_y;
5021
5022         /* Loop over shift vectors in three dimensions */
5023         for (tz = -shp[ZZ]; tz <= shp[ZZ]; tz++)
5024         {
5025             shz = tz*box[ZZ][ZZ];
5026
5027             bz0 = bbcz_i[ci*NNBSBB_D  ] + shz;
5028             bz1 = bbcz_i[ci*NNBSBB_D+1] + shz;
5029
5030             if (tz == 0)
5031             {
5032                 d2z = 0;
5033             }
5034             else if (tz < 0)
5035             {
5036                 d2z = sqr(bz1);
5037             }
5038             else
5039             {
5040                 d2z = sqr(bz0 - box[ZZ][ZZ]);
5041             }
5042
5043             d2z_cx = d2z + d2cx;
5044
5045             if (d2z_cx >= rl2)
5046             {
5047                 continue;
5048             }
5049
5050             bz1_frac =
5051                 bz1/((real)(gridi->cxy_ind[ci_xy+1] - gridi->cxy_ind[ci_xy]));
5052             if (bz1_frac < 0)
5053             {
5054                 bz1_frac = 0;
5055             }
5056             /* The check with bz1_frac close to or larger than 1 comes later */
5057
5058             for (ty = -shp[YY]; ty <= shp[YY]; ty++)
5059             {
5060                 shy = ty*box[YY][YY] + tz*box[ZZ][YY];
5061
5062                 if (nbl->bSimple)
5063                 {
5064                     by0 = bb_i[ci].lower[BB_Y] + shy;
5065                     by1 = bb_i[ci].upper[BB_Y] + shy;
5066                 }
5067                 else
5068                 {
5069                     by0 = gridi->c0[YY] + (ci_y  )*gridi->sy + shy;
5070                     by1 = gridi->c0[YY] + (ci_y+1)*gridi->sy + shy;
5071                 }
5072
5073                 get_cell_range(by0, by1,
5074                                gridj->ncy, gridj->c0[YY], gridj->sy, gridj->inv_sy,
5075                                d2z_cx, rl2,
5076                                &cyf, &cyl);
5077
5078                 if (cyf > cyl)
5079                 {
5080                     continue;
5081                 }
5082
5083                 d2z_cy = d2z;
5084                 if (by1 < gridj->c0[YY])
5085                 {
5086                     d2z_cy += sqr(gridj->c0[YY] - by1);
5087                 }
5088                 else if (by0 > gridj->c1[YY])
5089                 {
5090                     d2z_cy += sqr(by0 - gridj->c1[YY]);
5091                 }
5092
5093                 for (tx = -shp[XX]; tx <= shp[XX]; tx++)
5094                 {
5095                     shift = XYZ2IS(tx, ty, tz);
5096
5097 #ifdef NBNXN_SHIFT_BACKWARD
5098                     if (gridi == gridj && shift > CENTRAL)
5099                     {
5100                         continue;
5101                     }
5102 #endif
5103
5104                     shx = tx*box[XX][XX] + ty*box[YY][XX] + tz*box[ZZ][XX];
5105
5106                     if (nbl->bSimple)
5107                     {
5108                         bx0 = bb_i[ci].lower[BB_X] + shx;
5109                         bx1 = bb_i[ci].upper[BB_X] + shx;
5110                     }
5111                     else
5112                     {
5113                         bx0 = gridi->c0[XX] + (ci_x  )*gridi->sx + shx;
5114                         bx1 = gridi->c0[XX] + (ci_x+1)*gridi->sx + shx;
5115                     }
5116
5117                     get_cell_range(bx0, bx1,
5118                                    gridj->ncx, gridj->c0[XX], gridj->sx, gridj->inv_sx,
5119                                    d2z_cy, rl2,
5120                                    &cxf, &cxl);
5121
5122                     if (cxf > cxl)
5123                     {
5124                         continue;
5125                     }
5126
5127                     if (nbl->bSimple)
5128                     {
5129                         new_ci_entry(nbl, cell0_i+ci, shift, flags_i[ci]);
5130                     }
5131                     else
5132                     {
5133                         new_sci_entry(nbl, cell0_i+ci, shift);
5134                     }
5135
5136 #ifndef NBNXN_SHIFT_BACKWARD
5137                     if (cxf < ci_x)
5138 #else
5139                     if (shift == CENTRAL && gridi == gridj &&
5140                         cxf < ci_x)
5141 #endif
5142                     {
5143                         /* Leave the pairs with i > j.
5144                          * x is the major index, so skip half of it.
5145                          */
5146                         cxf = ci_x;
5147                     }
5148
5149                     if (nbl->bSimple)
5150                     {
5151                         set_icell_bb_simple(bb_i, ci, shx, shy, shz,
5152                                             nbl->work->bb_ci);
5153                     }
5154                     else
5155                     {
5156 #ifdef NBNXN_BBXXXX
5157                         set_icell_bbxxxx_supersub(pbb_i, ci, shx, shy, shz,
5158                                                   nbl->work->pbb_ci);
5159 #else
5160                         set_icell_bb_supersub(bb_i, ci, shx, shy, shz,
5161                                               nbl->work->bb_ci);
5162 #endif
5163                     }
5164
5165                     nbs->icell_set_x(cell0_i+ci, shx, shy, shz,
5166                                      gridi->na_c, nbat->xstride, nbat->x,
5167                                      nbl->work);
5168
5169                     for (cx = cxf; cx <= cxl; cx++)
5170                     {
5171                         d2zx = d2z;
5172                         if (gridj->c0[XX] + cx*gridj->sx > bx1)
5173                         {
5174                             d2zx += sqr(gridj->c0[XX] + cx*gridj->sx - bx1);
5175                         }
5176                         else if (gridj->c0[XX] + (cx+1)*gridj->sx < bx0)
5177                         {
5178                             d2zx += sqr(gridj->c0[XX] + (cx+1)*gridj->sx - bx0);
5179                         }
5180
5181 #ifndef NBNXN_SHIFT_BACKWARD
5182                         if (gridi == gridj &&
5183                             cx == 0 && cyf < ci_y)
5184 #else
5185                         if (gridi == gridj &&
5186                             cx == 0 && shift == CENTRAL && cyf < ci_y)
5187 #endif
5188                         {
5189                             /* Leave the pairs with i > j.
5190                              * Skip half of y when i and j have the same x.
5191                              */
5192                             cyf_x = ci_y;
5193                         }
5194                         else
5195                         {
5196                             cyf_x = cyf;
5197                         }
5198
5199                         for (cy = cyf_x; cy <= cyl; cy++)
5200                         {
5201                             c0 = gridj->cxy_ind[cx*gridj->ncy+cy];
5202                             c1 = gridj->cxy_ind[cx*gridj->ncy+cy+1];
5203 #ifdef NBNXN_SHIFT_BACKWARD
5204                             if (gridi == gridj &&
5205                                 shift == CENTRAL && c0 < ci)
5206                             {
5207                                 c0 = ci;
5208                             }
5209 #endif
5210
5211                             d2zxy = d2zx;
5212                             if (gridj->c0[YY] + cy*gridj->sy > by1)
5213                             {
5214                                 d2zxy += sqr(gridj->c0[YY] + cy*gridj->sy - by1);
5215                             }
5216                             else if (gridj->c0[YY] + (cy+1)*gridj->sy < by0)
5217                             {
5218                                 d2zxy += sqr(gridj->c0[YY] + (cy+1)*gridj->sy - by0);
5219                             }
5220                             if (c1 > c0 && d2zxy < rl2)
5221                             {
5222                                 cs = c0 + (int)(bz1_frac*(c1 - c0));
5223                                 if (cs >= c1)
5224                                 {
5225                                     cs = c1 - 1;
5226                                 }
5227
5228                                 d2xy = d2zxy - d2z;
5229
5230                                 /* Find the lowest cell that can possibly
5231                                  * be within range.
5232                                  */
5233                                 cf = cs;
5234                                 while (cf > c0 &&
5235                                        (bbcz_j[cf*NNBSBB_D+1] >= bz0 ||
5236                                         d2xy + sqr(bbcz_j[cf*NNBSBB_D+1] - bz0) < rl2))
5237                                 {
5238                                     cf--;
5239                                 }
5240
5241                                 /* Find the highest cell that can possibly
5242                                  * be within range.
5243                                  */
5244                                 cl = cs;
5245                                 while (cl < c1-1 &&
5246                                        (bbcz_j[cl*NNBSBB_D] <= bz1 ||
5247                                         d2xy + sqr(bbcz_j[cl*NNBSBB_D] - bz1) < rl2))
5248                                 {
5249                                     cl++;
5250                                 }
5251
5252 #ifdef NBNXN_REFCODE
5253                                 {
5254                                     /* Simple reference code, for debugging,
5255                                      * overrides the more complex code above.
5256                                      */
5257                                     int k;
5258                                     cf = c1;
5259                                     cl = -1;
5260                                     for (k = c0; k < c1; k++)
5261                                     {
5262                                         if (box_dist2(bx0, bx1, by0, by1, bz0, bz1, bb+k) < rl2 &&
5263                                             k < cf)
5264                                         {
5265                                             cf = k;
5266                                         }
5267                                         if (box_dist2(bx0, bx1, by0, by1, bz0, bz1, bb+k) < rl2 &&
5268                                             k > cl)
5269                                         {
5270                                             cl = k;
5271                                         }
5272                                     }
5273                                 }
5274 #endif
5275
5276                                 if (gridi == gridj)
5277                                 {
5278                                     /* We want each atom/cell pair only once,
5279                                      * only use cj >= ci.
5280                                      */
5281 #ifndef NBNXN_SHIFT_BACKWARD
5282                                     cf = max(cf, ci);
5283 #else
5284                                     if (shift == CENTRAL)
5285                                     {
5286                                         cf = max(cf, ci);
5287                                     }
5288 #endif
5289                                 }
5290
5291                                 if (cf <= cl)
5292                                 {
5293                                     /* For f buffer flags with simple lists */
5294                                     ncj_old_j = nbl->ncj;
5295
5296                                     switch (nb_kernel_type)
5297                                     {
5298                                         case nbnxnk4x4_PlainC:
5299                                             check_subcell_list_space_simple(nbl, cl-cf+1);
5300
5301                                             make_cluster_list_simple(gridj,
5302                                                                      nbl, ci, cf, cl,
5303                                                                      (gridi == gridj && shift == CENTRAL),
5304                                                                      nbat->x,
5305                                                                      rl2, rbb2,
5306                                                                      &ndistc);
5307                                             break;
5308 #ifdef GMX_NBNXN_SIMD_4XN
5309                                         case nbnxnk4xN_SIMD_4xN:
5310                                             check_subcell_list_space_simple(nbl, ci_to_cj(na_cj_2log, cl-cf)+2);
5311                                             make_cluster_list_simd_4xn(gridj,
5312                                                                        nbl, ci, cf, cl,
5313                                                                        (gridi == gridj && shift == CENTRAL),
5314                                                                        nbat->x,
5315                                                                        rl2, rbb2,
5316                                                                        &ndistc);
5317                                             break;
5318 #endif
5319 #ifdef GMX_NBNXN_SIMD_2XNN
5320                                         case nbnxnk4xN_SIMD_2xNN:
5321                                             check_subcell_list_space_simple(nbl, ci_to_cj(na_cj_2log, cl-cf)+2);
5322                                             make_cluster_list_simd_2xnn(gridj,
5323                                                                         nbl, ci, cf, cl,
5324                                                                         (gridi == gridj && shift == CENTRAL),
5325                                                                         nbat->x,
5326                                                                         rl2, rbb2,
5327                                                                         &ndistc);
5328                                             break;
5329 #endif
5330                                         case nbnxnk8x8x8_PlainC:
5331                                         case nbnxnk8x8x8_CUDA:
5332                                             check_subcell_list_space_supersub(nbl, cl-cf+1);
5333                                             for (cj = cf; cj <= cl; cj++)
5334                                             {
5335                                                 make_cluster_list_supersub(gridi, gridj,
5336                                                                            nbl, ci, cj,
5337                                                                            (gridi == gridj && shift == CENTRAL && ci == cj),
5338                                                                            nbat->xstride, nbat->x,
5339                                                                            rl2, rbb2,
5340                                                                            &ndistc);
5341                                             }
5342                                             break;
5343                                     }
5344                                     ncpcheck += cl - cf + 1;
5345
5346                                     if (bFBufferFlag && nbl->ncj > ncj_old_j)
5347                                     {
5348                                         int cbf, cbl, cb;
5349
5350                                         cbf = nbl->cj[ncj_old_j].cj >> gridj_flag_shift;
5351                                         cbl = nbl->cj[nbl->ncj-1].cj >> gridj_flag_shift;
5352                                         for (cb = cbf; cb <= cbl; cb++)
5353                                         {
5354                                             bitmask_init_bit(&gridj_flag[cb], th);
5355                                         }
5356                                     }
5357                                 }
5358                             }
5359                         }
5360                     }
5361
5362                     /* Set the exclusions for this ci list */
5363                     if (nbl->bSimple)
5364                     {
5365                         set_ci_top_excls(nbs,
5366                                          nbl,
5367                                          shift == CENTRAL && gridi == gridj,
5368                                          gridj->na_c_2log,
5369                                          na_cj_2log,
5370                                          &(nbl->ci[nbl->nci]),
5371                                          excl);
5372
5373                         if (nbs->bFEP)
5374                         {
5375                             make_fep_list(nbs, nbat, nbl,
5376                                           shift == CENTRAL && gridi == gridj,
5377                                           &(nbl->ci[nbl->nci]),
5378                                           gridi, gridj, nbl_fep);
5379                         }
5380                     }
5381                     else
5382                     {
5383                         set_sci_top_excls(nbs,
5384                                           nbl,
5385                                           shift == CENTRAL && gridi == gridj,
5386                                           gridj->na_c_2log,
5387                                           &(nbl->sci[nbl->nsci]),
5388                                           excl);
5389
5390                         if (nbs->bFEP)
5391                         {
5392                             make_fep_list_supersub(nbs, nbat, nbl,
5393                                                    shift == CENTRAL && gridi == gridj,
5394                                                    &(nbl->sci[nbl->nsci]),
5395                                                    shx, shy, shz,
5396                                                    rl_fep2,
5397                                                    gridi, gridj, nbl_fep);
5398                         }
5399                     }
5400
5401                     /* Close this ci list */
5402                     if (nbl->bSimple)
5403                     {
5404                         close_ci_entry_simple(nbl);
5405                     }
5406                     else
5407                     {
5408                         close_ci_entry_supersub(nbl,
5409                                                 nsubpair_max,
5410                                                 progBal, min_ci_balanced,
5411                                                 th, nth);
5412                     }
5413                 }
5414             }
5415         }
5416
5417         if (bFBufferFlag && nbl->ncj > ncj_old_i)
5418         {
5419             bitmask_init_bit(&(work->buffer_flags.flag[(gridi->cell0+ci)>>gridi_flag_shift]), th);
5420         }
5421     }
5422
5423     work->ndistc = ndistc;
5424
5425     nbs_cycle_stop(&work->cc[enbsCCsearch]);
5426
5427     if (debug)
5428     {
5429         fprintf(debug, "number of distance checks %d\n", ndistc);
5430         fprintf(debug, "ncpcheck %s %d\n", gridi == gridj ? "local" : "non-local",
5431                 ncpcheck);
5432
5433         if (nbl->bSimple)
5434         {
5435             print_nblist_statistics_simple(debug, nbl, nbs, rlist);
5436         }
5437         else
5438         {
5439             print_nblist_statistics_supersub(debug, nbl, nbs, rlist);
5440         }
5441
5442         if (nbs->bFEP)
5443         {
5444             fprintf(debug, "nbl FEP list pairs: %d\n", nbl_fep->nrj);
5445         }
5446     }
5447 }
5448
5449 static void reduce_buffer_flags(const nbnxn_search_t        nbs,
5450                                 int                         nsrc,
5451                                 const nbnxn_buffer_flags_t *dest)
5452 {
5453     int            s, b;
5454     gmx_bitmask_t *flag;
5455
5456     for (s = 0; s < nsrc; s++)
5457     {
5458         flag = nbs->work[s].buffer_flags.flag;
5459
5460         for (b = 0; b < dest->nflag; b++)
5461         {
5462             bitmask_union(&(dest->flag[b]), flag[b]);
5463         }
5464     }
5465 }
5466
5467 static void print_reduction_cost(const nbnxn_buffer_flags_t *flags, int nout)
5468 {
5469     int           nelem, nkeep, ncopy, nred, b, c, out;
5470     gmx_bitmask_t mask_0;
5471
5472     nelem = 0;
5473     nkeep = 0;
5474     ncopy = 0;
5475     nred  = 0;
5476     bitmask_init_bit(&mask_0, 0);
5477     for (b = 0; b < flags->nflag; b++)
5478     {
5479         if (bitmask_is_equal(flags->flag[b], mask_0))
5480         {
5481             /* Only flag 0 is set, no copy of reduction required */
5482             nelem++;
5483             nkeep++;
5484         }
5485         else if (!bitmask_is_zero(flags->flag[b]))
5486         {
5487             c = 0;
5488             for (out = 0; out < nout; out++)
5489             {
5490                 if (bitmask_is_set(flags->flag[b], out))
5491                 {
5492                     c++;
5493                 }
5494             }
5495             nelem += c;
5496             if (c == 1)
5497             {
5498                 ncopy++;
5499             }
5500             else
5501             {
5502                 nred += c;
5503             }
5504         }
5505     }
5506
5507     fprintf(debug, "nbnxn reduction: #flag %d #list %d elem %4.2f, keep %4.2f copy %4.2f red %4.2f\n",
5508             flags->nflag, nout,
5509             nelem/(double)(flags->nflag),
5510             nkeep/(double)(flags->nflag),
5511             ncopy/(double)(flags->nflag),
5512             nred/(double)(flags->nflag));
5513 }
5514
5515 /* Perform a count (linear) sort to sort the smaller lists to the end.
5516  * This avoids load imbalance on the GPU, as large lists will be
5517  * scheduled and executed first and the smaller lists later.
5518  * Load balancing between multi-processors only happens at the end
5519  * and there smaller lists lead to more effective load balancing.
5520  * The sorting is done on the cj4 count, not on the actual pair counts.
5521  * Not only does this make the sort faster, but it also results in
5522  * better load balancing than using a list sorted on exact load.
5523  * This function swaps the pointer in the pair list to avoid a copy operation.
5524  */
5525 static void sort_sci(nbnxn_pairlist_t *nbl)
5526 {
5527     nbnxn_list_work_t *work;
5528     int                m, i, s, s0, s1;
5529     nbnxn_sci_t       *sci_sort;
5530
5531     if (nbl->ncj4 <= nbl->nsci)
5532     {
5533         /* nsci = 0 or all sci have size 1, sorting won't change the order */
5534         return;
5535     }
5536
5537     work = nbl->work;
5538
5539     /* We will distinguish differences up to double the average */
5540     m = (2*nbl->ncj4)/nbl->nsci;
5541
5542     if (m + 1 > work->sort_nalloc)
5543     {
5544         work->sort_nalloc = over_alloc_large(m + 1);
5545         srenew(work->sort, work->sort_nalloc);
5546     }
5547
5548     if (work->sci_sort_nalloc != nbl->sci_nalloc)
5549     {
5550         work->sci_sort_nalloc = nbl->sci_nalloc;
5551         nbnxn_realloc_void((void **)&work->sci_sort,
5552                            0,
5553                            work->sci_sort_nalloc*sizeof(*work->sci_sort),
5554                            nbl->alloc, nbl->free);
5555     }
5556
5557     /* Count the entries of each size */
5558     for (i = 0; i <= m; i++)
5559     {
5560         work->sort[i] = 0;
5561     }
5562     for (s = 0; s < nbl->nsci; s++)
5563     {
5564         i = min(m, nbl->sci[s].cj4_ind_end - nbl->sci[s].cj4_ind_start);
5565         work->sort[i]++;
5566     }
5567     /* Calculate the offset for each count */
5568     s0            = work->sort[m];
5569     work->sort[m] = 0;
5570     for (i = m - 1; i >= 0; i--)
5571     {
5572         s1            = work->sort[i];
5573         work->sort[i] = work->sort[i + 1] + s0;
5574         s0            = s1;
5575     }
5576
5577     /* Sort entries directly into place */
5578     sci_sort = work->sci_sort;
5579     for (s = 0; s < nbl->nsci; s++)
5580     {
5581         i = min(m, nbl->sci[s].cj4_ind_end - nbl->sci[s].cj4_ind_start);
5582         sci_sort[work->sort[i]++] = nbl->sci[s];
5583     }
5584
5585     /* Swap the sci pointers so we use the new, sorted list */
5586     work->sci_sort = nbl->sci;
5587     nbl->sci       = sci_sort;
5588 }
5589
5590 /* Make a local or non-local pair-list, depending on iloc */
5591 void nbnxn_make_pairlist(const nbnxn_search_t  nbs,
5592                          nbnxn_atomdata_t     *nbat,
5593                          const t_blocka       *excl,
5594                          real                  rlist,
5595                          int                   min_ci_balanced,
5596                          nbnxn_pairlist_set_t *nbl_list,
5597                          int                   iloc,
5598                          int                   nb_kernel_type,
5599                          t_nrnb               *nrnb)
5600 {
5601     nbnxn_grid_t      *gridi, *gridj;
5602     gmx_bool           bGPUCPU;
5603     int                nzi, zi, zj0, zj1, zj;
5604     int                nsubpair_max;
5605     int                th;
5606     int                nnbl;
5607     nbnxn_pairlist_t **nbl;
5608     int                ci_block;
5609     gmx_bool           CombineNBLists;
5610     gmx_bool           progBal;
5611     int                np_tot, np_noq, np_hlj, nap;
5612
5613     /* Check if we are running hybrid GPU + CPU nbnxn mode */
5614     bGPUCPU = (!nbs->grid[0].bSimple && nbl_list->bSimple);
5615
5616     nnbl            = nbl_list->nnbl;
5617     nbl             = nbl_list->nbl;
5618     CombineNBLists  = nbl_list->bCombined;
5619
5620     if (debug)
5621     {
5622         fprintf(debug, "ns making %d nblists\n", nnbl);
5623     }
5624
5625     nbat->bUseBufferFlags = (nbat->nout > 1);
5626     /* We should re-init the flags before making the first list */
5627     if (nbat->bUseBufferFlags && (LOCAL_I(iloc) || bGPUCPU))
5628     {
5629         init_buffer_flags(&nbat->buffer_flags, nbat->natoms);
5630     }
5631
5632     if (nbl_list->bSimple)
5633     {
5634         switch (nb_kernel_type)
5635         {
5636 #ifdef GMX_NBNXN_SIMD_4XN
5637             case nbnxnk4xN_SIMD_4xN:
5638                 nbs->icell_set_x = icell_set_x_simd_4xn;
5639                 break;
5640 #endif
5641 #ifdef GMX_NBNXN_SIMD_2XNN
5642             case nbnxnk4xN_SIMD_2xNN:
5643                 nbs->icell_set_x = icell_set_x_simd_2xnn;
5644                 break;
5645 #endif
5646             default:
5647                 nbs->icell_set_x = icell_set_x_simple;
5648                 break;
5649         }
5650     }
5651     else
5652     {
5653 #ifdef NBNXN_SEARCH_BB_SIMD4
5654         nbs->icell_set_x = icell_set_x_supersub_simd4;
5655 #else
5656         nbs->icell_set_x = icell_set_x_supersub;
5657 #endif
5658     }
5659
5660     if (LOCAL_I(iloc))
5661     {
5662         /* Only zone (grid) 0 vs 0 */
5663         nzi = 1;
5664         zj0 = 0;
5665         zj1 = 1;
5666     }
5667     else
5668     {
5669         nzi = nbs->zones->nizone;
5670     }
5671
5672     if (!nbl_list->bSimple && min_ci_balanced > 0)
5673     {
5674         nsubpair_max = get_nsubpair_max(nbs, iloc, rlist, min_ci_balanced);
5675     }
5676     else
5677     {
5678         nsubpair_max = 0;
5679     }
5680
5681     /* Clear all pair-lists */
5682     for (th = 0; th < nnbl; th++)
5683     {
5684         clear_pairlist(nbl[th]);
5685
5686         if (nbs->bFEP)
5687         {
5688             clear_pairlist_fep(nbl_list->nbl_fep[th]);
5689         }
5690     }
5691
5692     for (zi = 0; zi < nzi; zi++)
5693     {
5694         gridi = &nbs->grid[zi];
5695
5696         if (NONLOCAL_I(iloc))
5697         {
5698             zj0 = nbs->zones->izone[zi].j0;
5699             zj1 = nbs->zones->izone[zi].j1;
5700             if (zi == 0)
5701             {
5702                 zj0++;
5703             }
5704         }
5705         for (zj = zj0; zj < zj1; zj++)
5706         {
5707             gridj = &nbs->grid[zj];
5708
5709             if (debug)
5710             {
5711                 fprintf(debug, "ns search grid %d vs %d\n", zi, zj);
5712             }
5713
5714             nbs_cycle_start(&nbs->cc[enbsCCsearch]);
5715
5716             if (nbl[0]->bSimple && !gridi->bSimple)
5717             {
5718                 /* Hybrid list, determine blocking later */
5719                 ci_block = 0;
5720             }
5721             else
5722             {
5723                 ci_block = get_ci_block_size(gridi, nbs->DomDec, nnbl);
5724             }
5725
5726             /* With GPU: generate progressively smaller lists for
5727              * load balancing for local only or non-local with 2 zones.
5728              */
5729             progBal = (LOCAL_I(iloc) || nbs->zones->n <= 2);
5730
5731 #pragma omp parallel for num_threads(nnbl) schedule(static)
5732             for (th = 0; th < nnbl; th++)
5733             {
5734                 /* Re-init the thread-local work flag data before making
5735                  * the first list (not an elegant conditional).
5736                  */
5737                 if (nbat->bUseBufferFlags && ((zi == 0 && zj == 0) ||
5738                                               (bGPUCPU && zi == 0 && zj == 1)))
5739                 {
5740                     init_buffer_flags(&nbs->work[th].buffer_flags, nbat->natoms);
5741                 }
5742
5743                 if (CombineNBLists && th > 0)
5744                 {
5745                     clear_pairlist(nbl[th]);
5746                 }
5747
5748                 /* Divide the i super cell equally over the nblists */
5749                 nbnxn_make_pairlist_part(nbs, gridi, gridj,
5750                                          &nbs->work[th], nbat, excl,
5751                                          rlist,
5752                                          nb_kernel_type,
5753                                          ci_block,
5754                                          nbat->bUseBufferFlags,
5755                                          nsubpair_max,
5756                                          progBal, min_ci_balanced,
5757                                          th, nnbl,
5758                                          nbl[th],
5759                                          nbl_list->nbl_fep[th]);
5760             }
5761             nbs_cycle_stop(&nbs->cc[enbsCCsearch]);
5762
5763             np_tot = 0;
5764             np_noq = 0;
5765             np_hlj = 0;
5766             for (th = 0; th < nnbl; th++)
5767             {
5768                 inc_nrnb(nrnb, eNR_NBNXN_DIST2, nbs->work[th].ndistc);
5769
5770                 if (nbl_list->bSimple)
5771                 {
5772                     np_tot += nbl[th]->ncj;
5773                     np_noq += nbl[th]->work->ncj_noq;
5774                     np_hlj += nbl[th]->work->ncj_hlj;
5775                 }
5776                 else
5777                 {
5778                     /* This count ignores potential subsequent pair pruning */
5779                     np_tot += nbl[th]->nci_tot;
5780                 }
5781             }
5782             nap                   = nbl[0]->na_ci*nbl[0]->na_cj;
5783             nbl_list->natpair_ljq = (np_tot - np_noq)*nap - np_hlj*nap/2;
5784             nbl_list->natpair_lj  = np_noq*nap;
5785             nbl_list->natpair_q   = np_hlj*nap/2;
5786
5787             if (CombineNBLists && nnbl > 1)
5788             {
5789                 nbs_cycle_start(&nbs->cc[enbsCCcombine]);
5790
5791                 combine_nblists(nnbl-1, nbl+1, nbl[0]);
5792
5793                 nbs_cycle_stop(&nbs->cc[enbsCCcombine]);
5794             }
5795         }
5796     }
5797
5798     if (!nbl_list->bSimple)
5799     {
5800         /* Sort the entries on size, large ones first */
5801         if (CombineNBLists || nnbl == 1)
5802         {
5803             sort_sci(nbl[0]);
5804         }
5805         else
5806         {
5807 #pragma omp parallel for num_threads(nnbl) schedule(static)
5808             for (th = 0; th < nnbl; th++)
5809             {
5810                 sort_sci(nbl[th]);
5811             }
5812         }
5813     }
5814
5815     if (nbat->bUseBufferFlags)
5816     {
5817         reduce_buffer_flags(nbs, nnbl, &nbat->buffer_flags);
5818     }
5819
5820     if (nbs->bFEP)
5821     {
5822         /* Balance the free-energy lists over all the threads */
5823         balance_fep_lists(nbs, nbl_list);
5824     }
5825
5826     /* Special performance logging stuff (env.var. GMX_NBNXN_CYCLE) */
5827     if (LOCAL_I(iloc))
5828     {
5829         nbs->search_count++;
5830     }
5831     if (nbs->print_cycles &&
5832         (!nbs->DomDec || (nbs->DomDec && !LOCAL_I(iloc))) &&
5833         nbs->search_count % 100 == 0)
5834     {
5835         nbs_cycle_print(stderr, nbs);
5836     }
5837
5838     if (debug && (CombineNBLists && nnbl > 1))
5839     {
5840         if (nbl[0]->bSimple)
5841         {
5842             print_nblist_statistics_simple(debug, nbl[0], nbs, rlist);
5843         }
5844         else
5845         {
5846             print_nblist_statistics_supersub(debug, nbl[0], nbs, rlist);
5847         }
5848     }
5849
5850     if (debug)
5851     {
5852         if (gmx_debug_at)
5853         {
5854             if (nbl[0]->bSimple)
5855             {
5856                 print_nblist_ci_cj(debug, nbl[0]);
5857             }
5858             else
5859             {
5860                 print_nblist_sci_cj(debug, nbl[0]);
5861             }
5862         }
5863
5864         if (nbat->bUseBufferFlags)
5865         {
5866             print_reduction_cost(&nbat->buffer_flags, nnbl);
5867         }
5868     }
5869 }