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