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