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