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