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