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