drbd: New disk option al-updates
[firefly-linux-kernel-4.4.55.git] / drivers / block / drbd / drbd_nl.c
1 /*
2    drbd_nl.c
3
4    This file is part of DRBD by Philipp Reisner and Lars Ellenberg.
5
6    Copyright (C) 2001-2008, LINBIT Information Technologies GmbH.
7    Copyright (C) 1999-2008, Philipp Reisner <philipp.reisner@linbit.com>.
8    Copyright (C) 2002-2008, Lars Ellenberg <lars.ellenberg@linbit.com>.
9
10    drbd is free software; you can redistribute it and/or modify
11    it under the terms of the GNU General Public License as published by
12    the Free Software Foundation; either version 2, or (at your option)
13    any later version.
14
15    drbd is distributed in the hope that it will be useful,
16    but WITHOUT ANY WARRANTY; without even the implied warranty of
17    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18    GNU General Public License for more details.
19
20    You should have received a copy of the GNU General Public License
21    along with drbd; see the file COPYING.  If not, write to
22    the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
23
24  */
25
26 #include <linux/module.h>
27 #include <linux/drbd.h>
28 #include <linux/in.h>
29 #include <linux/fs.h>
30 #include <linux/file.h>
31 #include <linux/slab.h>
32 #include <linux/blkpg.h>
33 #include <linux/cpumask.h>
34 #include "drbd_int.h"
35 #include "drbd_req.h"
36 #include "drbd_wrappers.h"
37 #include <asm/unaligned.h>
38 #include <linux/drbd_limits.h>
39 #include <linux/kthread.h>
40
41 #include <net/genetlink.h>
42
43 /* .doit */
44 // int drbd_adm_create_resource(struct sk_buff *skb, struct genl_info *info);
45 // int drbd_adm_delete_resource(struct sk_buff *skb, struct genl_info *info);
46
47 int drbd_adm_add_minor(struct sk_buff *skb, struct genl_info *info);
48 int drbd_adm_delete_minor(struct sk_buff *skb, struct genl_info *info);
49
50 int drbd_adm_new_resource(struct sk_buff *skb, struct genl_info *info);
51 int drbd_adm_del_resource(struct sk_buff *skb, struct genl_info *info);
52 int drbd_adm_down(struct sk_buff *skb, struct genl_info *info);
53
54 int drbd_adm_set_role(struct sk_buff *skb, struct genl_info *info);
55 int drbd_adm_attach(struct sk_buff *skb, struct genl_info *info);
56 int drbd_adm_disk_opts(struct sk_buff *skb, struct genl_info *info);
57 int drbd_adm_detach(struct sk_buff *skb, struct genl_info *info);
58 int drbd_adm_connect(struct sk_buff *skb, struct genl_info *info);
59 int drbd_adm_net_opts(struct sk_buff *skb, struct genl_info *info);
60 int drbd_adm_resize(struct sk_buff *skb, struct genl_info *info);
61 int drbd_adm_start_ov(struct sk_buff *skb, struct genl_info *info);
62 int drbd_adm_new_c_uuid(struct sk_buff *skb, struct genl_info *info);
63 int drbd_adm_disconnect(struct sk_buff *skb, struct genl_info *info);
64 int drbd_adm_invalidate(struct sk_buff *skb, struct genl_info *info);
65 int drbd_adm_invalidate_peer(struct sk_buff *skb, struct genl_info *info);
66 int drbd_adm_pause_sync(struct sk_buff *skb, struct genl_info *info);
67 int drbd_adm_resume_sync(struct sk_buff *skb, struct genl_info *info);
68 int drbd_adm_suspend_io(struct sk_buff *skb, struct genl_info *info);
69 int drbd_adm_resume_io(struct sk_buff *skb, struct genl_info *info);
70 int drbd_adm_outdate(struct sk_buff *skb, struct genl_info *info);
71 int drbd_adm_resource_opts(struct sk_buff *skb, struct genl_info *info);
72 int drbd_adm_get_status(struct sk_buff *skb, struct genl_info *info);
73 int drbd_adm_get_timeout_type(struct sk_buff *skb, struct genl_info *info);
74 /* .dumpit */
75 int drbd_adm_get_status_all(struct sk_buff *skb, struct netlink_callback *cb);
76
77 #include <linux/drbd_genl_api.h>
78 #include "drbd_nla.h"
79 #include <linux/genl_magic_func.h>
80
81 /* used blkdev_get_by_path, to claim our meta data device(s) */
82 static char *drbd_m_holder = "Hands off! this is DRBD's meta data device.";
83
84 /* Configuration is strictly serialized, because generic netlink message
85  * processing is strictly serialized by the genl_lock().
86  * Which means we can use one static global drbd_config_context struct.
87  */
88 static struct drbd_config_context {
89         /* assigned from drbd_genlmsghdr */
90         unsigned int minor;
91         /* assigned from request attributes, if present */
92         unsigned int volume;
93 #define VOLUME_UNSPECIFIED              (-1U)
94         /* pointer into the request skb,
95          * limited lifetime! */
96         char *resource_name;
97         struct nlattr *my_addr;
98         struct nlattr *peer_addr;
99
100         /* reply buffer */
101         struct sk_buff *reply_skb;
102         /* pointer into reply buffer */
103         struct drbd_genlmsghdr *reply_dh;
104         /* resolved from attributes, if possible */
105         struct drbd_conf *mdev;
106         struct drbd_tconn *tconn;
107 } adm_ctx;
108
109 static void drbd_adm_send_reply(struct sk_buff *skb, struct genl_info *info)
110 {
111         genlmsg_end(skb, genlmsg_data(nlmsg_data(nlmsg_hdr(skb))));
112         if (genlmsg_reply(skb, info))
113                 printk(KERN_ERR "drbd: error sending genl reply\n");
114 }
115
116 /* Used on a fresh "drbd_adm_prepare"d reply_skb, this cannot fail: The only
117  * reason it could fail was no space in skb, and there are 4k available. */
118 int drbd_msg_put_info(const char *info)
119 {
120         struct sk_buff *skb = adm_ctx.reply_skb;
121         struct nlattr *nla;
122         int err = -EMSGSIZE;
123
124         if (!info || !info[0])
125                 return 0;
126
127         nla = nla_nest_start(skb, DRBD_NLA_CFG_REPLY);
128         if (!nla)
129                 return err;
130
131         err = nla_put_string(skb, T_info_text, info);
132         if (err) {
133                 nla_nest_cancel(skb, nla);
134                 return err;
135         } else
136                 nla_nest_end(skb, nla);
137         return 0;
138 }
139
140 /* This would be a good candidate for a "pre_doit" hook,
141  * and per-family private info->pointers.
142  * But we need to stay compatible with older kernels.
143  * If it returns successfully, adm_ctx members are valid.
144  */
145 #define DRBD_ADM_NEED_MINOR     1
146 #define DRBD_ADM_NEED_RESOURCE  2
147 #define DRBD_ADM_NEED_CONNECTION 4
148 static int drbd_adm_prepare(struct sk_buff *skb, struct genl_info *info,
149                 unsigned flags)
150 {
151         struct drbd_genlmsghdr *d_in = info->userhdr;
152         const u8 cmd = info->genlhdr->cmd;
153         int err;
154
155         memset(&adm_ctx, 0, sizeof(adm_ctx));
156
157         /* genl_rcv_msg only checks for CAP_NET_ADMIN on "GENL_ADMIN_PERM" :( */
158         if (cmd != DRBD_ADM_GET_STATUS
159         && security_netlink_recv(skb, CAP_SYS_ADMIN))
160                return -EPERM;
161
162         adm_ctx.reply_skb = genlmsg_new(NLMSG_GOODSIZE, GFP_KERNEL);
163         if (!adm_ctx.reply_skb) {
164                 err = -ENOMEM;
165                 goto fail;
166         }
167
168         adm_ctx.reply_dh = genlmsg_put_reply(adm_ctx.reply_skb,
169                                         info, &drbd_genl_family, 0, cmd);
170         /* put of a few bytes into a fresh skb of >= 4k will always succeed.
171          * but anyways */
172         if (!adm_ctx.reply_dh) {
173                 err = -ENOMEM;
174                 goto fail;
175         }
176
177         adm_ctx.reply_dh->minor = d_in->minor;
178         adm_ctx.reply_dh->ret_code = NO_ERROR;
179
180         adm_ctx.volume = VOLUME_UNSPECIFIED;
181         if (info->attrs[DRBD_NLA_CFG_CONTEXT]) {
182                 struct nlattr *nla;
183                 /* parse and validate only */
184                 err = drbd_cfg_context_from_attrs(NULL, info);
185                 if (err)
186                         goto fail;
187
188                 /* It was present, and valid,
189                  * copy it over to the reply skb. */
190                 err = nla_put_nohdr(adm_ctx.reply_skb,
191                                 info->attrs[DRBD_NLA_CFG_CONTEXT]->nla_len,
192                                 info->attrs[DRBD_NLA_CFG_CONTEXT]);
193                 if (err)
194                         goto fail;
195
196                 /* and assign stuff to the global adm_ctx */
197                 nla = nested_attr_tb[__nla_type(T_ctx_volume)];
198                 if (nla)
199                         adm_ctx.volume = nla_get_u32(nla);
200                 nla = nested_attr_tb[__nla_type(T_ctx_resource_name)];
201                 if (nla)
202                         adm_ctx.resource_name = nla_data(nla);
203                 adm_ctx.my_addr = nested_attr_tb[__nla_type(T_ctx_my_addr)];
204                 adm_ctx.peer_addr = nested_attr_tb[__nla_type(T_ctx_peer_addr)];
205                 if ((adm_ctx.my_addr &&
206                      nla_len(adm_ctx.my_addr) > sizeof(adm_ctx.tconn->my_addr)) ||
207                     (adm_ctx.peer_addr &&
208                      nla_len(adm_ctx.peer_addr) > sizeof(adm_ctx.tconn->peer_addr))) {
209                         err = -EINVAL;
210                         goto fail;
211                 }
212         }
213
214         adm_ctx.minor = d_in->minor;
215         adm_ctx.mdev = minor_to_mdev(d_in->minor);
216         adm_ctx.tconn = conn_get_by_name(adm_ctx.resource_name);
217
218         if (!adm_ctx.mdev && (flags & DRBD_ADM_NEED_MINOR)) {
219                 drbd_msg_put_info("unknown minor");
220                 return ERR_MINOR_INVALID;
221         }
222         if (!adm_ctx.tconn && (flags & DRBD_ADM_NEED_RESOURCE)) {
223                 drbd_msg_put_info("unknown resource");
224                 return ERR_INVALID_REQUEST;
225         }
226
227         if (flags & DRBD_ADM_NEED_CONNECTION) {
228                 if (adm_ctx.tconn && !(flags & DRBD_ADM_NEED_RESOURCE)) {
229                         drbd_msg_put_info("no resource name expected");
230                         return ERR_INVALID_REQUEST;
231                 }
232                 if (adm_ctx.mdev) {
233                         drbd_msg_put_info("no minor number expected");
234                         return ERR_INVALID_REQUEST;
235                 }
236                 if (adm_ctx.my_addr && adm_ctx.peer_addr)
237                         adm_ctx.tconn = conn_get_by_addrs(nla_data(adm_ctx.my_addr),
238                                                           nla_len(adm_ctx.my_addr),
239                                                           nla_data(adm_ctx.peer_addr),
240                                                           nla_len(adm_ctx.peer_addr));
241                 if (!adm_ctx.tconn) {
242                         drbd_msg_put_info("unknown connection");
243                         return ERR_INVALID_REQUEST;
244                 }
245         }
246
247         /* some more paranoia, if the request was over-determined */
248         if (adm_ctx.mdev && adm_ctx.tconn &&
249             adm_ctx.mdev->tconn != adm_ctx.tconn) {
250                 pr_warning("request: minor=%u, resource=%s; but that minor belongs to connection %s\n",
251                                 adm_ctx.minor, adm_ctx.resource_name,
252                                 adm_ctx.mdev->tconn->name);
253                 drbd_msg_put_info("minor exists in different resource");
254                 return ERR_INVALID_REQUEST;
255         }
256         if (adm_ctx.mdev &&
257             adm_ctx.volume != VOLUME_UNSPECIFIED &&
258             adm_ctx.volume != adm_ctx.mdev->vnr) {
259                 pr_warning("request: minor=%u, volume=%u; but that minor is volume %u in %s\n",
260                                 adm_ctx.minor, adm_ctx.volume,
261                                 adm_ctx.mdev->vnr, adm_ctx.mdev->tconn->name);
262                 drbd_msg_put_info("minor exists as different volume");
263                 return ERR_INVALID_REQUEST;
264         }
265
266         return NO_ERROR;
267
268 fail:
269         nlmsg_free(adm_ctx.reply_skb);
270         adm_ctx.reply_skb = NULL;
271         return err;
272 }
273
274 static int drbd_adm_finish(struct genl_info *info, int retcode)
275 {
276         if (adm_ctx.tconn) {
277                 kref_put(&adm_ctx.tconn->kref, &conn_destroy);
278                 adm_ctx.tconn = NULL;
279         }
280
281         if (!adm_ctx.reply_skb)
282                 return -ENOMEM;
283
284         adm_ctx.reply_dh->ret_code = retcode;
285         drbd_adm_send_reply(adm_ctx.reply_skb, info);
286         return 0;
287 }
288
289 static void setup_khelper_env(struct drbd_tconn *tconn, char **envp)
290 {
291         char *afs;
292
293         /* FIXME: A future version will not allow this case. */
294         if (tconn->my_addr_len == 0 || tconn->peer_addr_len == 0)
295                 return;
296
297         switch (((struct sockaddr *)&tconn->peer_addr)->sa_family) {
298         case AF_INET6:
299                 afs = "ipv6";
300                 snprintf(envp[4], 60, "DRBD_PEER_ADDRESS=%pI6",
301                          &((struct sockaddr_in6 *)&tconn->peer_addr)->sin6_addr);
302                 break;
303         case AF_INET:
304                 afs = "ipv4";
305                 snprintf(envp[4], 60, "DRBD_PEER_ADDRESS=%pI4",
306                          &((struct sockaddr_in *)&tconn->peer_addr)->sin_addr);
307                 break;
308         default:
309                 afs = "ssocks";
310                 snprintf(envp[4], 60, "DRBD_PEER_ADDRESS=%pI4",
311                          &((struct sockaddr_in *)&tconn->peer_addr)->sin_addr);
312         }
313         snprintf(envp[3], 20, "DRBD_PEER_AF=%s", afs);
314 }
315
316 int drbd_khelper(struct drbd_conf *mdev, char *cmd)
317 {
318         char *envp[] = { "HOME=/",
319                         "TERM=linux",
320                         "PATH=/sbin:/usr/sbin:/bin:/usr/bin",
321                          (char[20]) { }, /* address family */
322                          (char[60]) { }, /* address */
323                         NULL };
324         char mb[12];
325         char *argv[] = {usermode_helper, cmd, mb, NULL };
326         struct sib_info sib;
327         int ret;
328
329         snprintf(mb, 12, "minor-%d", mdev_to_minor(mdev));
330         setup_khelper_env(mdev->tconn, envp);
331
332         /* The helper may take some time.
333          * write out any unsynced meta data changes now */
334         drbd_md_sync(mdev);
335
336         dev_info(DEV, "helper command: %s %s %s\n", usermode_helper, cmd, mb);
337         sib.sib_reason = SIB_HELPER_PRE;
338         sib.helper_name = cmd;
339         drbd_bcast_event(mdev, &sib);
340         ret = call_usermodehelper(usermode_helper, argv, envp, 1);
341         if (ret)
342                 dev_warn(DEV, "helper command: %s %s %s exit code %u (0x%x)\n",
343                                 usermode_helper, cmd, mb,
344                                 (ret >> 8) & 0xff, ret);
345         else
346                 dev_info(DEV, "helper command: %s %s %s exit code %u (0x%x)\n",
347                                 usermode_helper, cmd, mb,
348                                 (ret >> 8) & 0xff, ret);
349         sib.sib_reason = SIB_HELPER_POST;
350         sib.helper_exit_code = ret;
351         drbd_bcast_event(mdev, &sib);
352
353         if (ret < 0) /* Ignore any ERRNOs we got. */
354                 ret = 0;
355
356         return ret;
357 }
358
359 static void conn_md_sync(struct drbd_tconn *tconn)
360 {
361         struct drbd_conf *mdev;
362         int vnr;
363
364         rcu_read_lock();
365         idr_for_each_entry(&tconn->volumes, mdev, vnr) {
366                 kref_get(&mdev->kref);
367                 rcu_read_unlock();
368                 drbd_md_sync(mdev);
369                 kref_put(&mdev->kref, &drbd_minor_destroy);
370                 rcu_read_lock();
371         }
372         rcu_read_unlock();
373 }
374
375 int conn_khelper(struct drbd_tconn *tconn, char *cmd)
376 {
377         char *envp[] = { "HOME=/",
378                         "TERM=linux",
379                         "PATH=/sbin:/usr/sbin:/bin:/usr/bin",
380                          (char[20]) { }, /* address family */
381                          (char[60]) { }, /* address */
382                         NULL };
383         char *argv[] = {usermode_helper, cmd, tconn->name, NULL };
384         int ret;
385
386         setup_khelper_env(tconn, envp);
387         conn_md_sync(tconn);
388
389         conn_info(tconn, "helper command: %s %s %s\n", usermode_helper, cmd, tconn->name);
390         /* TODO: conn_bcast_event() ?? */
391
392         ret = call_usermodehelper(usermode_helper, argv, envp, 1);
393         if (ret)
394                 conn_warn(tconn, "helper command: %s %s %s exit code %u (0x%x)\n",
395                           usermode_helper, cmd, tconn->name,
396                           (ret >> 8) & 0xff, ret);
397         else
398                 conn_info(tconn, "helper command: %s %s %s exit code %u (0x%x)\n",
399                           usermode_helper, cmd, tconn->name,
400                           (ret >> 8) & 0xff, ret);
401         /* TODO: conn_bcast_event() ?? */
402
403         if (ret < 0) /* Ignore any ERRNOs we got. */
404                 ret = 0;
405
406         return ret;
407 }
408
409 static enum drbd_fencing_p highest_fencing_policy(struct drbd_tconn *tconn)
410 {
411         enum drbd_fencing_p fp = FP_NOT_AVAIL;
412         struct drbd_conf *mdev;
413         int vnr;
414
415         rcu_read_lock();
416         idr_for_each_entry(&tconn->volumes, mdev, vnr) {
417                 if (get_ldev_if_state(mdev, D_CONSISTENT)) {
418                         fp = max_t(enum drbd_fencing_p, fp,
419                                    rcu_dereference(mdev->ldev->disk_conf)->fencing);
420                         put_ldev(mdev);
421                 }
422         }
423         rcu_read_unlock();
424
425         return fp;
426 }
427
428 bool conn_try_outdate_peer(struct drbd_tconn *tconn)
429 {
430         union drbd_state mask = { };
431         union drbd_state val = { };
432         enum drbd_fencing_p fp;
433         char *ex_to_string;
434         int r;
435
436         if (tconn->cstate >= C_WF_REPORT_PARAMS) {
437                 conn_err(tconn, "Expected cstate < C_WF_REPORT_PARAMS\n");
438                 return false;
439         }
440
441         fp = highest_fencing_policy(tconn);
442         switch (fp) {
443         case FP_NOT_AVAIL:
444                 conn_warn(tconn, "Not fencing peer, I'm not even Consistent myself.\n");
445                 goto out;
446         case FP_DONT_CARE:
447                 return true;
448         default: ;
449         }
450
451         r = conn_khelper(tconn, "fence-peer");
452
453         switch ((r>>8) & 0xff) {
454         case 3: /* peer is inconsistent */
455                 ex_to_string = "peer is inconsistent or worse";
456                 mask.pdsk = D_MASK;
457                 val.pdsk = D_INCONSISTENT;
458                 break;
459         case 4: /* peer got outdated, or was already outdated */
460                 ex_to_string = "peer was fenced";
461                 mask.pdsk = D_MASK;
462                 val.pdsk = D_OUTDATED;
463                 break;
464         case 5: /* peer was down */
465                 if (conn_highest_disk(tconn) == D_UP_TO_DATE) {
466                         /* we will(have) create(d) a new UUID anyways... */
467                         ex_to_string = "peer is unreachable, assumed to be dead";
468                         mask.pdsk = D_MASK;
469                         val.pdsk = D_OUTDATED;
470                 } else {
471                         ex_to_string = "peer unreachable, doing nothing since disk != UpToDate";
472                 }
473                 break;
474         case 6: /* Peer is primary, voluntarily outdate myself.
475                  * This is useful when an unconnected R_SECONDARY is asked to
476                  * become R_PRIMARY, but finds the other peer being active. */
477                 ex_to_string = "peer is active";
478                 conn_warn(tconn, "Peer is primary, outdating myself.\n");
479                 mask.disk = D_MASK;
480                 val.disk = D_OUTDATED;
481                 break;
482         case 7:
483                 if (fp != FP_STONITH)
484                         conn_err(tconn, "fence-peer() = 7 && fencing != Stonith !!!\n");
485                 ex_to_string = "peer was stonithed";
486                 mask.pdsk = D_MASK;
487                 val.pdsk = D_OUTDATED;
488                 break;
489         default:
490                 /* The script is broken ... */
491                 conn_err(tconn, "fence-peer helper broken, returned %d\n", (r>>8)&0xff);
492                 return false; /* Eventually leave IO frozen */
493         }
494
495         conn_info(tconn, "fence-peer helper returned %d (%s)\n",
496                   (r>>8) & 0xff, ex_to_string);
497
498  out:
499
500         /* Not using
501            conn_request_state(tconn, mask, val, CS_VERBOSE);
502            here, because we might were able to re-establish the connection in the
503            meantime. */
504         spin_lock_irq(&tconn->req_lock);
505         if (tconn->cstate < C_WF_REPORT_PARAMS && !test_bit(STATE_SENT, &tconn->flags))
506                 _conn_request_state(tconn, mask, val, CS_VERBOSE);
507         spin_unlock_irq(&tconn->req_lock);
508
509         return conn_highest_pdsk(tconn) <= D_OUTDATED;
510 }
511
512 static int _try_outdate_peer_async(void *data)
513 {
514         struct drbd_tconn *tconn = (struct drbd_tconn *)data;
515
516         conn_try_outdate_peer(tconn);
517
518         kref_put(&tconn->kref, &conn_destroy);
519         return 0;
520 }
521
522 void conn_try_outdate_peer_async(struct drbd_tconn *tconn)
523 {
524         struct task_struct *opa;
525
526         kref_get(&tconn->kref);
527         opa = kthread_run(_try_outdate_peer_async, tconn, "drbd_async_h");
528         if (IS_ERR(opa)) {
529                 conn_err(tconn, "out of mem, failed to invoke fence-peer helper\n");
530                 kref_put(&tconn->kref, &conn_destroy);
531         }
532 }
533
534 enum drbd_state_rv
535 drbd_set_role(struct drbd_conf *mdev, enum drbd_role new_role, int force)
536 {
537         const int max_tries = 4;
538         enum drbd_state_rv rv = SS_UNKNOWN_ERROR;
539         struct net_conf *nc;
540         int try = 0;
541         int forced = 0;
542         union drbd_state mask, val;
543
544         if (new_role == R_PRIMARY)
545                 request_ping(mdev->tconn); /* Detect a dead peer ASAP */
546
547         mutex_lock(mdev->state_mutex);
548
549         mask.i = 0; mask.role = R_MASK;
550         val.i  = 0; val.role  = new_role;
551
552         while (try++ < max_tries) {
553                 rv = _drbd_request_state(mdev, mask, val, CS_WAIT_COMPLETE);
554
555                 /* in case we first succeeded to outdate,
556                  * but now suddenly could establish a connection */
557                 if (rv == SS_CW_FAILED_BY_PEER && mask.pdsk != 0) {
558                         val.pdsk = 0;
559                         mask.pdsk = 0;
560                         continue;
561                 }
562
563                 if (rv == SS_NO_UP_TO_DATE_DISK && force &&
564                     (mdev->state.disk < D_UP_TO_DATE &&
565                      mdev->state.disk >= D_INCONSISTENT)) {
566                         mask.disk = D_MASK;
567                         val.disk  = D_UP_TO_DATE;
568                         forced = 1;
569                         continue;
570                 }
571
572                 if (rv == SS_NO_UP_TO_DATE_DISK &&
573                     mdev->state.disk == D_CONSISTENT && mask.pdsk == 0) {
574                         D_ASSERT(mdev->state.pdsk == D_UNKNOWN);
575
576                         if (conn_try_outdate_peer(mdev->tconn)) {
577                                 val.disk = D_UP_TO_DATE;
578                                 mask.disk = D_MASK;
579                         }
580                         continue;
581                 }
582
583                 if (rv == SS_NOTHING_TO_DO)
584                         goto out;
585                 if (rv == SS_PRIMARY_NOP && mask.pdsk == 0) {
586                         if (!conn_try_outdate_peer(mdev->tconn) && force) {
587                                 dev_warn(DEV, "Forced into split brain situation!\n");
588                                 mask.pdsk = D_MASK;
589                                 val.pdsk  = D_OUTDATED;
590
591                         }
592                         continue;
593                 }
594                 if (rv == SS_TWO_PRIMARIES) {
595                         /* Maybe the peer is detected as dead very soon...
596                            retry at most once more in this case. */
597                         int timeo;
598                         rcu_read_lock();
599                         nc = rcu_dereference(mdev->tconn->net_conf);
600                         timeo = nc ? (nc->ping_timeo + 1) * HZ / 10 : 1;
601                         rcu_read_unlock();
602                         schedule_timeout_interruptible(timeo);
603                         if (try < max_tries)
604                                 try = max_tries - 1;
605                         continue;
606                 }
607                 if (rv < SS_SUCCESS) {
608                         rv = _drbd_request_state(mdev, mask, val,
609                                                 CS_VERBOSE + CS_WAIT_COMPLETE);
610                         if (rv < SS_SUCCESS)
611                                 goto out;
612                 }
613                 break;
614         }
615
616         if (rv < SS_SUCCESS)
617                 goto out;
618
619         if (forced)
620                 dev_warn(DEV, "Forced to consider local data as UpToDate!\n");
621
622         /* Wait until nothing is on the fly :) */
623         wait_event(mdev->misc_wait, atomic_read(&mdev->ap_pending_cnt) == 0);
624
625         if (new_role == R_SECONDARY) {
626                 set_disk_ro(mdev->vdisk, true);
627                 if (get_ldev(mdev)) {
628                         mdev->ldev->md.uuid[UI_CURRENT] &= ~(u64)1;
629                         put_ldev(mdev);
630                 }
631         } else {
632                 mutex_lock(&mdev->tconn->conf_update);
633                 nc = mdev->tconn->net_conf;
634                 if (nc)
635                         nc->discard_my_data = 0; /* without copy; single bit op is atomic */
636                 mutex_unlock(&mdev->tconn->conf_update);
637
638                 set_disk_ro(mdev->vdisk, false);
639                 if (get_ldev(mdev)) {
640                         if (((mdev->state.conn < C_CONNECTED ||
641                                mdev->state.pdsk <= D_FAILED)
642                               && mdev->ldev->md.uuid[UI_BITMAP] == 0) || forced)
643                                 drbd_uuid_new_current(mdev);
644
645                         mdev->ldev->md.uuid[UI_CURRENT] |=  (u64)1;
646                         put_ldev(mdev);
647                 }
648         }
649
650         /* writeout of activity log covered areas of the bitmap
651          * to stable storage done in after state change already */
652
653         if (mdev->state.conn >= C_WF_REPORT_PARAMS) {
654                 /* if this was forced, we should consider sync */
655                 if (forced)
656                         drbd_send_uuids(mdev);
657                 drbd_send_current_state(mdev);
658         }
659
660         drbd_md_sync(mdev);
661
662         kobject_uevent(&disk_to_dev(mdev->vdisk)->kobj, KOBJ_CHANGE);
663 out:
664         mutex_unlock(mdev->state_mutex);
665         return rv;
666 }
667
668 static const char *from_attrs_err_to_txt(int err)
669 {
670         return  err == -ENOMSG ? "required attribute missing" :
671                 err == -EOPNOTSUPP ? "unknown mandatory attribute" :
672                 err == -EEXIST ? "can not change invariant setting" :
673                 "invalid attribute value";
674 }
675
676 int drbd_adm_set_role(struct sk_buff *skb, struct genl_info *info)
677 {
678         struct set_role_parms parms;
679         int err;
680         enum drbd_ret_code retcode;
681
682         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_MINOR);
683         if (!adm_ctx.reply_skb)
684                 return retcode;
685         if (retcode != NO_ERROR)
686                 goto out;
687
688         memset(&parms, 0, sizeof(parms));
689         if (info->attrs[DRBD_NLA_SET_ROLE_PARMS]) {
690                 err = set_role_parms_from_attrs(&parms, info);
691                 if (err) {
692                         retcode = ERR_MANDATORY_TAG;
693                         drbd_msg_put_info(from_attrs_err_to_txt(err));
694                         goto out;
695                 }
696         }
697
698         if (info->genlhdr->cmd == DRBD_ADM_PRIMARY)
699                 retcode = drbd_set_role(adm_ctx.mdev, R_PRIMARY, parms.assume_uptodate);
700         else
701                 retcode = drbd_set_role(adm_ctx.mdev, R_SECONDARY, 0);
702 out:
703         drbd_adm_finish(info, retcode);
704         return 0;
705 }
706
707 /* initializes the md.*_offset members, so we are able to find
708  * the on disk meta data */
709 static void drbd_md_set_sector_offsets(struct drbd_conf *mdev,
710                                        struct drbd_backing_dev *bdev)
711 {
712         sector_t md_size_sect = 0;
713         int meta_dev_idx;
714
715         rcu_read_lock();
716         meta_dev_idx = rcu_dereference(bdev->disk_conf)->meta_dev_idx;
717
718         switch (meta_dev_idx) {
719         default:
720                 /* v07 style fixed size indexed meta data */
721                 bdev->md.md_size_sect = MD_RESERVED_SECT;
722                 bdev->md.md_offset = drbd_md_ss__(mdev, bdev);
723                 bdev->md.al_offset = MD_AL_OFFSET;
724                 bdev->md.bm_offset = MD_BM_OFFSET;
725                 break;
726         case DRBD_MD_INDEX_FLEX_EXT:
727                 /* just occupy the full device; unit: sectors */
728                 bdev->md.md_size_sect = drbd_get_capacity(bdev->md_bdev);
729                 bdev->md.md_offset = 0;
730                 bdev->md.al_offset = MD_AL_OFFSET;
731                 bdev->md.bm_offset = MD_BM_OFFSET;
732                 break;
733         case DRBD_MD_INDEX_INTERNAL:
734         case DRBD_MD_INDEX_FLEX_INT:
735                 bdev->md.md_offset = drbd_md_ss__(mdev, bdev);
736                 /* al size is still fixed */
737                 bdev->md.al_offset = -MD_AL_SECTORS;
738                 /* we need (slightly less than) ~ this much bitmap sectors: */
739                 md_size_sect = drbd_get_capacity(bdev->backing_bdev);
740                 md_size_sect = ALIGN(md_size_sect, BM_SECT_PER_EXT);
741                 md_size_sect = BM_SECT_TO_EXT(md_size_sect);
742                 md_size_sect = ALIGN(md_size_sect, 8);
743
744                 /* plus the "drbd meta data super block",
745                  * and the activity log; */
746                 md_size_sect += MD_BM_OFFSET;
747
748                 bdev->md.md_size_sect = md_size_sect;
749                 /* bitmap offset is adjusted by 'super' block size */
750                 bdev->md.bm_offset   = -md_size_sect + MD_AL_OFFSET;
751                 break;
752         }
753         rcu_read_unlock();
754 }
755
756 /* input size is expected to be in KB */
757 char *ppsize(char *buf, unsigned long long size)
758 {
759         /* Needs 9 bytes at max including trailing NUL:
760          * -1ULL ==> "16384 EB" */
761         static char units[] = { 'K', 'M', 'G', 'T', 'P', 'E' };
762         int base = 0;
763         while (size >= 10000 && base < sizeof(units)-1) {
764                 /* shift + round */
765                 size = (size >> 10) + !!(size & (1<<9));
766                 base++;
767         }
768         sprintf(buf, "%u %cB", (unsigned)size, units[base]);
769
770         return buf;
771 }
772
773 /* there is still a theoretical deadlock when called from receiver
774  * on an D_INCONSISTENT R_PRIMARY:
775  *  remote READ does inc_ap_bio, receiver would need to receive answer
776  *  packet from remote to dec_ap_bio again.
777  *  receiver receive_sizes(), comes here,
778  *  waits for ap_bio_cnt == 0. -> deadlock.
779  * but this cannot happen, actually, because:
780  *  R_PRIMARY D_INCONSISTENT, and peer's disk is unreachable
781  *  (not connected, or bad/no disk on peer):
782  *  see drbd_fail_request_early, ap_bio_cnt is zero.
783  *  R_PRIMARY D_INCONSISTENT, and C_SYNC_TARGET:
784  *  peer may not initiate a resize.
785  */
786 /* Note these are not to be confused with
787  * drbd_adm_suspend_io/drbd_adm_resume_io,
788  * which are (sub) state changes triggered by admin (drbdsetup),
789  * and can be long lived.
790  * This changes an mdev->flag, is triggered by drbd internals,
791  * and should be short-lived. */
792 void drbd_suspend_io(struct drbd_conf *mdev)
793 {
794         set_bit(SUSPEND_IO, &mdev->flags);
795         if (drbd_suspended(mdev))
796                 return;
797         wait_event(mdev->misc_wait, !atomic_read(&mdev->ap_bio_cnt));
798 }
799
800 void drbd_resume_io(struct drbd_conf *mdev)
801 {
802         clear_bit(SUSPEND_IO, &mdev->flags);
803         wake_up(&mdev->misc_wait);
804 }
805
806 /**
807  * drbd_determine_dev_size() -  Sets the right device size obeying all constraints
808  * @mdev:       DRBD device.
809  *
810  * Returns 0 on success, negative return values indicate errors.
811  * You should call drbd_md_sync() after calling this function.
812  */
813 enum determine_dev_size drbd_determine_dev_size(struct drbd_conf *mdev, enum dds_flags flags) __must_hold(local)
814 {
815         sector_t prev_first_sect, prev_size; /* previous meta location */
816         sector_t la_size, u_size;
817         sector_t size;
818         char ppb[10];
819
820         int md_moved, la_size_changed;
821         enum determine_dev_size rv = unchanged;
822
823         /* race:
824          * application request passes inc_ap_bio,
825          * but then cannot get an AL-reference.
826          * this function later may wait on ap_bio_cnt == 0. -> deadlock.
827          *
828          * to avoid that:
829          * Suspend IO right here.
830          * still lock the act_log to not trigger ASSERTs there.
831          */
832         drbd_suspend_io(mdev);
833
834         /* no wait necessary anymore, actually we could assert that */
835         wait_event(mdev->al_wait, lc_try_lock(mdev->act_log));
836
837         prev_first_sect = drbd_md_first_sector(mdev->ldev);
838         prev_size = mdev->ldev->md.md_size_sect;
839         la_size = mdev->ldev->md.la_size_sect;
840
841         /* TODO: should only be some assert here, not (re)init... */
842         drbd_md_set_sector_offsets(mdev, mdev->ldev);
843
844         rcu_read_lock();
845         u_size = rcu_dereference(mdev->ldev->disk_conf)->disk_size;
846         rcu_read_unlock();
847         size = drbd_new_dev_size(mdev, mdev->ldev, u_size, flags & DDSF_FORCED);
848
849         if (drbd_get_capacity(mdev->this_bdev) != size ||
850             drbd_bm_capacity(mdev) != size) {
851                 int err;
852                 err = drbd_bm_resize(mdev, size, !(flags & DDSF_NO_RESYNC));
853                 if (unlikely(err)) {
854                         /* currently there is only one error: ENOMEM! */
855                         size = drbd_bm_capacity(mdev)>>1;
856                         if (size == 0) {
857                                 dev_err(DEV, "OUT OF MEMORY! "
858                                     "Could not allocate bitmap!\n");
859                         } else {
860                                 dev_err(DEV, "BM resizing failed. "
861                                     "Leaving size unchanged at size = %lu KB\n",
862                                     (unsigned long)size);
863                         }
864                         rv = dev_size_error;
865                 }
866                 /* racy, see comments above. */
867                 drbd_set_my_capacity(mdev, size);
868                 mdev->ldev->md.la_size_sect = size;
869                 dev_info(DEV, "size = %s (%llu KB)\n", ppsize(ppb, size>>1),
870                      (unsigned long long)size>>1);
871         }
872         if (rv == dev_size_error)
873                 goto out;
874
875         la_size_changed = (la_size != mdev->ldev->md.la_size_sect);
876
877         md_moved = prev_first_sect != drbd_md_first_sector(mdev->ldev)
878                 || prev_size       != mdev->ldev->md.md_size_sect;
879
880         if (la_size_changed || md_moved) {
881                 int err;
882
883                 drbd_al_shrink(mdev); /* All extents inactive. */
884                 dev_info(DEV, "Writing the whole bitmap, %s\n",
885                          la_size_changed && md_moved ? "size changed and md moved" :
886                          la_size_changed ? "size changed" : "md moved");
887                 /* next line implicitly does drbd_suspend_io()+drbd_resume_io() */
888                 err = drbd_bitmap_io(mdev, &drbd_bm_write,
889                                 "size changed", BM_LOCKED_MASK);
890                 if (err) {
891                         rv = dev_size_error;
892                         goto out;
893                 }
894                 drbd_md_mark_dirty(mdev);
895         }
896
897         if (size > la_size)
898                 rv = grew;
899         if (size < la_size)
900                 rv = shrunk;
901 out:
902         lc_unlock(mdev->act_log);
903         wake_up(&mdev->al_wait);
904         drbd_resume_io(mdev);
905
906         return rv;
907 }
908
909 sector_t
910 drbd_new_dev_size(struct drbd_conf *mdev, struct drbd_backing_dev *bdev,
911                   sector_t u_size, int assume_peer_has_space)
912 {
913         sector_t p_size = mdev->p_size;   /* partner's disk size. */
914         sector_t la_size = bdev->md.la_size_sect; /* last agreed size. */
915         sector_t m_size; /* my size */
916         sector_t size = 0;
917
918         m_size = drbd_get_max_capacity(bdev);
919
920         if (mdev->state.conn < C_CONNECTED && assume_peer_has_space) {
921                 dev_warn(DEV, "Resize while not connected was forced by the user!\n");
922                 p_size = m_size;
923         }
924
925         if (p_size && m_size) {
926                 size = min_t(sector_t, p_size, m_size);
927         } else {
928                 if (la_size) {
929                         size = la_size;
930                         if (m_size && m_size < size)
931                                 size = m_size;
932                         if (p_size && p_size < size)
933                                 size = p_size;
934                 } else {
935                         if (m_size)
936                                 size = m_size;
937                         if (p_size)
938                                 size = p_size;
939                 }
940         }
941
942         if (size == 0)
943                 dev_err(DEV, "Both nodes diskless!\n");
944
945         if (u_size) {
946                 if (u_size > size)
947                         dev_err(DEV, "Requested disk size is too big (%lu > %lu)\n",
948                             (unsigned long)u_size>>1, (unsigned long)size>>1);
949                 else
950                         size = u_size;
951         }
952
953         return size;
954 }
955
956 /**
957  * drbd_check_al_size() - Ensures that the AL is of the right size
958  * @mdev:       DRBD device.
959  *
960  * Returns -EBUSY if current al lru is still used, -ENOMEM when allocation
961  * failed, and 0 on success. You should call drbd_md_sync() after you called
962  * this function.
963  */
964 static int drbd_check_al_size(struct drbd_conf *mdev, struct disk_conf *dc)
965 {
966         struct lru_cache *n, *t;
967         struct lc_element *e;
968         unsigned int in_use;
969         int i;
970
971         if (mdev->act_log &&
972             mdev->act_log->nr_elements == dc->al_extents)
973                 return 0;
974
975         in_use = 0;
976         t = mdev->act_log;
977         n = lc_create("act_log", drbd_al_ext_cache, AL_UPDATES_PER_TRANSACTION,
978                 dc->al_extents, sizeof(struct lc_element), 0);
979
980         if (n == NULL) {
981                 dev_err(DEV, "Cannot allocate act_log lru!\n");
982                 return -ENOMEM;
983         }
984         spin_lock_irq(&mdev->al_lock);
985         if (t) {
986                 for (i = 0; i < t->nr_elements; i++) {
987                         e = lc_element_by_index(t, i);
988                         if (e->refcnt)
989                                 dev_err(DEV, "refcnt(%d)==%d\n",
990                                     e->lc_number, e->refcnt);
991                         in_use += e->refcnt;
992                 }
993         }
994         if (!in_use)
995                 mdev->act_log = n;
996         spin_unlock_irq(&mdev->al_lock);
997         if (in_use) {
998                 dev_err(DEV, "Activity log still in use!\n");
999                 lc_destroy(n);
1000                 return -EBUSY;
1001         } else {
1002                 if (t)
1003                         lc_destroy(t);
1004         }
1005         drbd_md_mark_dirty(mdev); /* we changed mdev->act_log->nr_elemens */
1006         return 0;
1007 }
1008
1009 static void drbd_setup_queue_param(struct drbd_conf *mdev, unsigned int max_bio_size)
1010 {
1011         struct request_queue * const q = mdev->rq_queue;
1012         int max_hw_sectors = max_bio_size >> 9;
1013         int max_segments = 0;
1014
1015         if (get_ldev_if_state(mdev, D_ATTACHING)) {
1016                 struct request_queue * const b = mdev->ldev->backing_bdev->bd_disk->queue;
1017
1018                 max_hw_sectors = min(queue_max_hw_sectors(b), max_bio_size >> 9);
1019                 rcu_read_lock();
1020                 max_segments = rcu_dereference(mdev->ldev->disk_conf)->max_bio_bvecs;
1021                 rcu_read_unlock();
1022                 put_ldev(mdev);
1023         }
1024
1025         blk_queue_logical_block_size(q, 512);
1026         blk_queue_max_hw_sectors(q, max_hw_sectors);
1027         /* This is the workaround for "bio would need to, but cannot, be split" */
1028         blk_queue_max_segments(q, max_segments ? max_segments : BLK_MAX_SEGMENTS);
1029         blk_queue_segment_boundary(q, PAGE_CACHE_SIZE-1);
1030
1031         if (get_ldev_if_state(mdev, D_ATTACHING)) {
1032                 struct request_queue * const b = mdev->ldev->backing_bdev->bd_disk->queue;
1033
1034                 blk_queue_stack_limits(q, b);
1035
1036                 if (q->backing_dev_info.ra_pages != b->backing_dev_info.ra_pages) {
1037                         dev_info(DEV, "Adjusting my ra_pages to backing device's (%lu -> %lu)\n",
1038                                  q->backing_dev_info.ra_pages,
1039                                  b->backing_dev_info.ra_pages);
1040                         q->backing_dev_info.ra_pages = b->backing_dev_info.ra_pages;
1041                 }
1042                 put_ldev(mdev);
1043         }
1044 }
1045
1046 void drbd_reconsider_max_bio_size(struct drbd_conf *mdev)
1047 {
1048         int now, new, local, peer;
1049
1050         now = queue_max_hw_sectors(mdev->rq_queue) << 9;
1051         local = mdev->local_max_bio_size; /* Eventually last known value, from volatile memory */
1052         peer = mdev->peer_max_bio_size; /* Eventually last known value, from meta data */
1053
1054         if (get_ldev_if_state(mdev, D_ATTACHING)) {
1055                 local = queue_max_hw_sectors(mdev->ldev->backing_bdev->bd_disk->queue) << 9;
1056                 mdev->local_max_bio_size = local;
1057                 put_ldev(mdev);
1058         }
1059
1060         /* We may ignore peer limits if the peer is modern enough.
1061            Because new from 8.3.8 onwards the peer can use multiple
1062            BIOs for a single peer_request */
1063         if (mdev->state.conn >= C_CONNECTED) {
1064                 if (mdev->tconn->agreed_pro_version < 94)
1065                         peer = min_t(int, mdev->peer_max_bio_size, DRBD_MAX_SIZE_H80_PACKET);
1066                         /* Correct old drbd (up to 8.3.7) if it believes it can do more than 32KiB */
1067                 else if (mdev->tconn->agreed_pro_version == 94)
1068                         peer = DRBD_MAX_SIZE_H80_PACKET;
1069                 else if (mdev->tconn->agreed_pro_version < 100)
1070                         peer = DRBD_MAX_BIO_SIZE_P95;  /* drbd 8.3.8 onwards, before 8.4.0 */
1071                 else
1072                         peer = DRBD_MAX_BIO_SIZE;
1073         }
1074
1075         new = min_t(int, local, peer);
1076
1077         if (mdev->state.role == R_PRIMARY && new < now)
1078                 dev_err(DEV, "ASSERT FAILED new < now; (%d < %d)\n", new, now);
1079
1080         if (new != now)
1081                 dev_info(DEV, "max BIO size = %u\n", new);
1082
1083         drbd_setup_queue_param(mdev, new);
1084 }
1085
1086 /* Starts the worker thread */
1087 static void conn_reconfig_start(struct drbd_tconn *tconn)
1088 {
1089         drbd_thread_start(&tconn->worker);
1090         conn_flush_workqueue(tconn);
1091 }
1092
1093 /* if still unconfigured, stops worker again. */
1094 static void conn_reconfig_done(struct drbd_tconn *tconn)
1095 {
1096         bool stop_threads;
1097         spin_lock_irq(&tconn->req_lock);
1098         stop_threads = conn_all_vols_unconf(tconn) &&
1099                 tconn->cstate == C_STANDALONE;
1100         spin_unlock_irq(&tconn->req_lock);
1101         if (stop_threads) {
1102                 /* asender is implicitly stopped by receiver
1103                  * in conn_disconnect() */
1104                 drbd_thread_stop(&tconn->receiver);
1105                 drbd_thread_stop(&tconn->worker);
1106         }
1107 }
1108
1109 /* Make sure IO is suspended before calling this function(). */
1110 static void drbd_suspend_al(struct drbd_conf *mdev)
1111 {
1112         int s = 0;
1113
1114         if (!lc_try_lock(mdev->act_log)) {
1115                 dev_warn(DEV, "Failed to lock al in drbd_suspend_al()\n");
1116                 return;
1117         }
1118
1119         drbd_al_shrink(mdev);
1120         spin_lock_irq(&mdev->tconn->req_lock);
1121         if (mdev->state.conn < C_CONNECTED)
1122                 s = !test_and_set_bit(AL_SUSPENDED, &mdev->flags);
1123         spin_unlock_irq(&mdev->tconn->req_lock);
1124         lc_unlock(mdev->act_log);
1125
1126         if (s)
1127                 dev_info(DEV, "Suspended AL updates\n");
1128 }
1129
1130
1131 static bool should_set_defaults(struct genl_info *info)
1132 {
1133         unsigned flags = ((struct drbd_genlmsghdr*)info->userhdr)->flags;
1134         return 0 != (flags & DRBD_GENL_F_SET_DEFAULTS);
1135 }
1136
1137 static void enforce_disk_conf_limits(struct disk_conf *dc)
1138 {
1139         if (dc->al_extents < DRBD_AL_EXTENTS_MIN)
1140                 dc->al_extents = DRBD_AL_EXTENTS_MIN;
1141         if (dc->al_extents > DRBD_AL_EXTENTS_MAX)
1142                 dc->al_extents = DRBD_AL_EXTENTS_MAX;
1143
1144         if (dc->c_plan_ahead > DRBD_C_PLAN_AHEAD_MAX)
1145                 dc->c_plan_ahead = DRBD_C_PLAN_AHEAD_MAX;
1146 }
1147
1148 int drbd_adm_disk_opts(struct sk_buff *skb, struct genl_info *info)
1149 {
1150         enum drbd_ret_code retcode;
1151         struct drbd_conf *mdev;
1152         struct disk_conf *new_disk_conf, *old_disk_conf;
1153         struct fifo_buffer *old_plan = NULL, *new_plan = NULL;
1154         int err, fifo_size;
1155
1156         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_MINOR);
1157         if (!adm_ctx.reply_skb)
1158                 return retcode;
1159         if (retcode != NO_ERROR)
1160                 goto out;
1161
1162         mdev = adm_ctx.mdev;
1163
1164         /* we also need a disk
1165          * to change the options on */
1166         if (!get_ldev(mdev)) {
1167                 retcode = ERR_NO_DISK;
1168                 goto out;
1169         }
1170
1171         new_disk_conf = kmalloc(sizeof(struct disk_conf), GFP_KERNEL);
1172         if (!new_disk_conf) {
1173                 retcode = ERR_NOMEM;
1174                 goto fail;
1175         }
1176
1177         mutex_lock(&mdev->tconn->conf_update);
1178         old_disk_conf = mdev->ldev->disk_conf;
1179         *new_disk_conf = *old_disk_conf;
1180         if (should_set_defaults(info))
1181                 set_disk_conf_defaults(new_disk_conf);
1182
1183         err = disk_conf_from_attrs_for_change(new_disk_conf, info);
1184         if (err && err != -ENOMSG) {
1185                 retcode = ERR_MANDATORY_TAG;
1186                 drbd_msg_put_info(from_attrs_err_to_txt(err));
1187         }
1188
1189         if (!expect(new_disk_conf->resync_rate >= 1))
1190                 new_disk_conf->resync_rate = 1;
1191
1192         enforce_disk_conf_limits(new_disk_conf);
1193
1194         fifo_size = (new_disk_conf->c_plan_ahead * 10 * SLEEP_TIME) / HZ;
1195         if (fifo_size != mdev->rs_plan_s->size) {
1196                 new_plan = fifo_alloc(fifo_size);
1197                 if (!new_plan) {
1198                         dev_err(DEV, "kmalloc of fifo_buffer failed");
1199                         retcode = ERR_NOMEM;
1200                         goto fail_unlock;
1201                 }
1202         }
1203
1204         wait_event(mdev->al_wait, lc_try_lock(mdev->act_log));
1205         drbd_al_shrink(mdev);
1206         err = drbd_check_al_size(mdev, new_disk_conf);
1207         lc_unlock(mdev->act_log);
1208         wake_up(&mdev->al_wait);
1209
1210         if (err) {
1211                 retcode = ERR_NOMEM;
1212                 goto fail_unlock;
1213         }
1214
1215         write_lock_irq(&global_state_lock);
1216         retcode = drbd_resync_after_valid(mdev, new_disk_conf->resync_after);
1217         if (retcode == NO_ERROR) {
1218                 rcu_assign_pointer(mdev->ldev->disk_conf, new_disk_conf);
1219                 drbd_resync_after_changed(mdev);
1220         }
1221         write_unlock_irq(&global_state_lock);
1222
1223         if (retcode != NO_ERROR)
1224                 goto fail_unlock;
1225
1226         if (new_plan) {
1227                 old_plan = mdev->rs_plan_s;
1228                 rcu_assign_pointer(mdev->rs_plan_s, new_plan);
1229         }
1230
1231         mutex_unlock(&mdev->tconn->conf_update);
1232
1233         if (new_disk_conf->al_updates)
1234                 mdev->ldev->md.flags &= MDF_AL_DISABLED;
1235         else
1236                 mdev->ldev->md.flags |= MDF_AL_DISABLED;
1237
1238         drbd_bump_write_ordering(mdev->tconn, WO_bdev_flush);
1239
1240         drbd_md_sync(mdev);
1241
1242         if (mdev->state.conn >= C_CONNECTED)
1243                 drbd_send_sync_param(mdev);
1244
1245         synchronize_rcu();
1246         kfree(old_disk_conf);
1247         kfree(old_plan);
1248         mod_timer(&mdev->request_timer, jiffies + HZ);
1249         goto success;
1250
1251 fail_unlock:
1252         mutex_unlock(&mdev->tconn->conf_update);
1253  fail:
1254         kfree(new_disk_conf);
1255         kfree(new_plan);
1256 success:
1257         put_ldev(mdev);
1258  out:
1259         drbd_adm_finish(info, retcode);
1260         return 0;
1261 }
1262
1263 int drbd_adm_attach(struct sk_buff *skb, struct genl_info *info)
1264 {
1265         struct drbd_conf *mdev;
1266         int err;
1267         enum drbd_ret_code retcode;
1268         enum determine_dev_size dd;
1269         sector_t max_possible_sectors;
1270         sector_t min_md_device_sectors;
1271         struct drbd_backing_dev *nbc = NULL; /* new_backing_conf */
1272         struct disk_conf *new_disk_conf = NULL;
1273         struct block_device *bdev;
1274         struct lru_cache *resync_lru = NULL;
1275         struct fifo_buffer *new_plan = NULL;
1276         union drbd_state ns, os;
1277         enum drbd_state_rv rv;
1278         struct net_conf *nc;
1279
1280         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_MINOR);
1281         if (!adm_ctx.reply_skb)
1282                 return retcode;
1283         if (retcode != NO_ERROR)
1284                 goto finish;
1285
1286         mdev = adm_ctx.mdev;
1287         conn_reconfig_start(mdev->tconn);
1288
1289         /* if you want to reconfigure, please tear down first */
1290         if (mdev->state.disk > D_DISKLESS) {
1291                 retcode = ERR_DISK_CONFIGURED;
1292                 goto fail;
1293         }
1294         /* It may just now have detached because of IO error.  Make sure
1295          * drbd_ldev_destroy is done already, we may end up here very fast,
1296          * e.g. if someone calls attach from the on-io-error handler,
1297          * to realize a "hot spare" feature (not that I'd recommend that) */
1298         wait_event(mdev->misc_wait, !atomic_read(&mdev->local_cnt));
1299
1300         /* allocation not in the IO path, drbdsetup context */
1301         nbc = kzalloc(sizeof(struct drbd_backing_dev), GFP_KERNEL);
1302         if (!nbc) {
1303                 retcode = ERR_NOMEM;
1304                 goto fail;
1305         }
1306         new_disk_conf = kzalloc(sizeof(struct disk_conf), GFP_KERNEL);
1307         if (!new_disk_conf) {
1308                 retcode = ERR_NOMEM;
1309                 goto fail;
1310         }
1311         nbc->disk_conf = new_disk_conf;
1312
1313         set_disk_conf_defaults(new_disk_conf);
1314         err = disk_conf_from_attrs(new_disk_conf, info);
1315         if (err) {
1316                 retcode = ERR_MANDATORY_TAG;
1317                 drbd_msg_put_info(from_attrs_err_to_txt(err));
1318                 goto fail;
1319         }
1320
1321         enforce_disk_conf_limits(new_disk_conf);
1322
1323         new_plan = fifo_alloc((new_disk_conf->c_plan_ahead * 10 * SLEEP_TIME) / HZ);
1324         if (!new_plan) {
1325                 retcode = ERR_NOMEM;
1326                 goto fail;
1327         }
1328
1329         if (new_disk_conf->meta_dev_idx < DRBD_MD_INDEX_FLEX_INT) {
1330                 retcode = ERR_MD_IDX_INVALID;
1331                 goto fail;
1332         }
1333
1334         rcu_read_lock();
1335         nc = rcu_dereference(mdev->tconn->net_conf);
1336         if (nc) {
1337                 if (new_disk_conf->fencing == FP_STONITH && nc->wire_protocol == DRBD_PROT_A) {
1338                         rcu_read_unlock();
1339                         retcode = ERR_STONITH_AND_PROT_A;
1340                         goto fail;
1341                 }
1342         }
1343         rcu_read_unlock();
1344
1345         bdev = blkdev_get_by_path(new_disk_conf->backing_dev,
1346                                   FMODE_READ | FMODE_WRITE | FMODE_EXCL, mdev);
1347         if (IS_ERR(bdev)) {
1348                 dev_err(DEV, "open(\"%s\") failed with %ld\n", new_disk_conf->backing_dev,
1349                         PTR_ERR(bdev));
1350                 retcode = ERR_OPEN_DISK;
1351                 goto fail;
1352         }
1353         nbc->backing_bdev = bdev;
1354
1355         /*
1356          * meta_dev_idx >= 0: external fixed size, possibly multiple
1357          * drbd sharing one meta device.  TODO in that case, paranoia
1358          * check that [md_bdev, meta_dev_idx] is not yet used by some
1359          * other drbd minor!  (if you use drbd.conf + drbdadm, that
1360          * should check it for you already; but if you don't, or
1361          * someone fooled it, we need to double check here)
1362          */
1363         bdev = blkdev_get_by_path(new_disk_conf->meta_dev,
1364                                   FMODE_READ | FMODE_WRITE | FMODE_EXCL,
1365                                   (new_disk_conf->meta_dev_idx < 0) ?
1366                                   (void *)mdev : (void *)drbd_m_holder);
1367         if (IS_ERR(bdev)) {
1368                 dev_err(DEV, "open(\"%s\") failed with %ld\n", new_disk_conf->meta_dev,
1369                         PTR_ERR(bdev));
1370                 retcode = ERR_OPEN_MD_DISK;
1371                 goto fail;
1372         }
1373         nbc->md_bdev = bdev;
1374
1375         if ((nbc->backing_bdev == nbc->md_bdev) !=
1376             (new_disk_conf->meta_dev_idx == DRBD_MD_INDEX_INTERNAL ||
1377              new_disk_conf->meta_dev_idx == DRBD_MD_INDEX_FLEX_INT)) {
1378                 retcode = ERR_MD_IDX_INVALID;
1379                 goto fail;
1380         }
1381
1382         resync_lru = lc_create("resync", drbd_bm_ext_cache,
1383                         1, 61, sizeof(struct bm_extent),
1384                         offsetof(struct bm_extent, lce));
1385         if (!resync_lru) {
1386                 retcode = ERR_NOMEM;
1387                 goto fail;
1388         }
1389
1390         /* RT - for drbd_get_max_capacity() DRBD_MD_INDEX_FLEX_INT */
1391         drbd_md_set_sector_offsets(mdev, nbc);
1392
1393         if (drbd_get_max_capacity(nbc) < new_disk_conf->disk_size) {
1394                 dev_err(DEV, "max capacity %llu smaller than disk size %llu\n",
1395                         (unsigned long long) drbd_get_max_capacity(nbc),
1396                         (unsigned long long) new_disk_conf->disk_size);
1397                 retcode = ERR_DISK_TOO_SMALL;
1398                 goto fail;
1399         }
1400
1401         if (new_disk_conf->meta_dev_idx < 0) {
1402                 max_possible_sectors = DRBD_MAX_SECTORS_FLEX;
1403                 /* at least one MB, otherwise it does not make sense */
1404                 min_md_device_sectors = (2<<10);
1405         } else {
1406                 max_possible_sectors = DRBD_MAX_SECTORS;
1407                 min_md_device_sectors = MD_RESERVED_SECT * (new_disk_conf->meta_dev_idx + 1);
1408         }
1409
1410         if (drbd_get_capacity(nbc->md_bdev) < min_md_device_sectors) {
1411                 retcode = ERR_MD_DISK_TOO_SMALL;
1412                 dev_warn(DEV, "refusing attach: md-device too small, "
1413                      "at least %llu sectors needed for this meta-disk type\n",
1414                      (unsigned long long) min_md_device_sectors);
1415                 goto fail;
1416         }
1417
1418         /* Make sure the new disk is big enough
1419          * (we may currently be R_PRIMARY with no local disk...) */
1420         if (drbd_get_max_capacity(nbc) <
1421             drbd_get_capacity(mdev->this_bdev)) {
1422                 retcode = ERR_DISK_TOO_SMALL;
1423                 goto fail;
1424         }
1425
1426         nbc->known_size = drbd_get_capacity(nbc->backing_bdev);
1427
1428         if (nbc->known_size > max_possible_sectors) {
1429                 dev_warn(DEV, "==> truncating very big lower level device "
1430                         "to currently maximum possible %llu sectors <==\n",
1431                         (unsigned long long) max_possible_sectors);
1432                 if (new_disk_conf->meta_dev_idx >= 0)
1433                         dev_warn(DEV, "==>> using internal or flexible "
1434                                       "meta data may help <<==\n");
1435         }
1436
1437         drbd_suspend_io(mdev);
1438         /* also wait for the last barrier ack. */
1439         wait_event(mdev->misc_wait, !atomic_read(&mdev->ap_pending_cnt) || drbd_suspended(mdev));
1440         /* and for any other previously queued work */
1441         drbd_flush_workqueue(mdev);
1442
1443         rv = _drbd_request_state(mdev, NS(disk, D_ATTACHING), CS_VERBOSE);
1444         retcode = rv;  /* FIXME: Type mismatch. */
1445         drbd_resume_io(mdev);
1446         if (rv < SS_SUCCESS)
1447                 goto fail;
1448
1449         if (!get_ldev_if_state(mdev, D_ATTACHING))
1450                 goto force_diskless;
1451
1452         drbd_md_set_sector_offsets(mdev, nbc);
1453
1454         if (!mdev->bitmap) {
1455                 if (drbd_bm_init(mdev)) {
1456                         retcode = ERR_NOMEM;
1457                         goto force_diskless_dec;
1458                 }
1459         }
1460
1461         retcode = drbd_md_read(mdev, nbc);
1462         if (retcode != NO_ERROR)
1463                 goto force_diskless_dec;
1464
1465         if (mdev->state.conn < C_CONNECTED &&
1466             mdev->state.role == R_PRIMARY &&
1467             (mdev->ed_uuid & ~((u64)1)) != (nbc->md.uuid[UI_CURRENT] & ~((u64)1))) {
1468                 dev_err(DEV, "Can only attach to data with current UUID=%016llX\n",
1469                     (unsigned long long)mdev->ed_uuid);
1470                 retcode = ERR_DATA_NOT_CURRENT;
1471                 goto force_diskless_dec;
1472         }
1473
1474         /* Since we are diskless, fix the activity log first... */
1475         if (drbd_check_al_size(mdev, new_disk_conf)) {
1476                 retcode = ERR_NOMEM;
1477                 goto force_diskless_dec;
1478         }
1479
1480         /* Prevent shrinking of consistent devices ! */
1481         if (drbd_md_test_flag(nbc, MDF_CONSISTENT) &&
1482             drbd_new_dev_size(mdev, nbc, nbc->disk_conf->disk_size, 0) < nbc->md.la_size_sect) {
1483                 dev_warn(DEV, "refusing to truncate a consistent device\n");
1484                 retcode = ERR_DISK_TOO_SMALL;
1485                 goto force_diskless_dec;
1486         }
1487
1488         /* Reset the "barriers don't work" bits here, then force meta data to
1489          * be written, to ensure we determine if barriers are supported. */
1490         if (new_disk_conf->md_flushes)
1491                 clear_bit(MD_NO_FUA, &mdev->flags);
1492         else
1493                 set_bit(MD_NO_FUA, &mdev->flags);
1494
1495         /* Point of no return reached.
1496          * Devices and memory are no longer released by error cleanup below.
1497          * now mdev takes over responsibility, and the state engine should
1498          * clean it up somewhere.  */
1499         D_ASSERT(mdev->ldev == NULL);
1500         mdev->ldev = nbc;
1501         mdev->resync = resync_lru;
1502         mdev->rs_plan_s = new_plan;
1503         nbc = NULL;
1504         resync_lru = NULL;
1505         new_disk_conf = NULL;
1506         new_plan = NULL;
1507
1508         drbd_bump_write_ordering(mdev->tconn, WO_bdev_flush);
1509
1510         if (drbd_md_test_flag(mdev->ldev, MDF_CRASHED_PRIMARY))
1511                 set_bit(CRASHED_PRIMARY, &mdev->flags);
1512         else
1513                 clear_bit(CRASHED_PRIMARY, &mdev->flags);
1514
1515         if (drbd_md_test_flag(mdev->ldev, MDF_PRIMARY_IND) &&
1516             !(mdev->state.role == R_PRIMARY && mdev->tconn->susp_nod))
1517                 set_bit(CRASHED_PRIMARY, &mdev->flags);
1518
1519         mdev->send_cnt = 0;
1520         mdev->recv_cnt = 0;
1521         mdev->read_cnt = 0;
1522         mdev->writ_cnt = 0;
1523
1524         drbd_reconsider_max_bio_size(mdev);
1525
1526         /* If I am currently not R_PRIMARY,
1527          * but meta data primary indicator is set,
1528          * I just now recover from a hard crash,
1529          * and have been R_PRIMARY before that crash.
1530          *
1531          * Now, if I had no connection before that crash
1532          * (have been degraded R_PRIMARY), chances are that
1533          * I won't find my peer now either.
1534          *
1535          * In that case, and _only_ in that case,
1536          * we use the degr-wfc-timeout instead of the default,
1537          * so we can automatically recover from a crash of a
1538          * degraded but active "cluster" after a certain timeout.
1539          */
1540         clear_bit(USE_DEGR_WFC_T, &mdev->flags);
1541         if (mdev->state.role != R_PRIMARY &&
1542              drbd_md_test_flag(mdev->ldev, MDF_PRIMARY_IND) &&
1543             !drbd_md_test_flag(mdev->ldev, MDF_CONNECTED_IND))
1544                 set_bit(USE_DEGR_WFC_T, &mdev->flags);
1545
1546         dd = drbd_determine_dev_size(mdev, 0);
1547         if (dd == dev_size_error) {
1548                 retcode = ERR_NOMEM_BITMAP;
1549                 goto force_diskless_dec;
1550         } else if (dd == grew)
1551                 set_bit(RESYNC_AFTER_NEG, &mdev->flags);
1552
1553         if (drbd_md_test_flag(mdev->ldev, MDF_FULL_SYNC) ||
1554             (test_bit(CRASHED_PRIMARY, &mdev->flags) &&
1555              drbd_md_test_flag(mdev->ldev, MDF_AL_DISABLED))) {
1556                 dev_info(DEV, "Assuming that all blocks are out of sync "
1557                      "(aka FullSync)\n");
1558                 if (drbd_bitmap_io(mdev, &drbd_bmio_set_n_write,
1559                         "set_n_write from attaching", BM_LOCKED_MASK)) {
1560                         retcode = ERR_IO_MD_DISK;
1561                         goto force_diskless_dec;
1562                 }
1563         } else {
1564                 if (drbd_bitmap_io(mdev, &drbd_bm_read,
1565                         "read from attaching", BM_LOCKED_MASK)) {
1566                         retcode = ERR_IO_MD_DISK;
1567                         goto force_diskless_dec;
1568                 }
1569         }
1570
1571         if (_drbd_bm_total_weight(mdev) == drbd_bm_bits(mdev))
1572                 drbd_suspend_al(mdev); /* IO is still suspended here... */
1573
1574         spin_lock_irq(&mdev->tconn->req_lock);
1575         os = drbd_read_state(mdev);
1576         ns = os;
1577         /* If MDF_CONSISTENT is not set go into inconsistent state,
1578            otherwise investigate MDF_WasUpToDate...
1579            If MDF_WAS_UP_TO_DATE is not set go into D_OUTDATED disk state,
1580            otherwise into D_CONSISTENT state.
1581         */
1582         if (drbd_md_test_flag(mdev->ldev, MDF_CONSISTENT)) {
1583                 if (drbd_md_test_flag(mdev->ldev, MDF_WAS_UP_TO_DATE))
1584                         ns.disk = D_CONSISTENT;
1585                 else
1586                         ns.disk = D_OUTDATED;
1587         } else {
1588                 ns.disk = D_INCONSISTENT;
1589         }
1590
1591         if (drbd_md_test_flag(mdev->ldev, MDF_PEER_OUT_DATED))
1592                 ns.pdsk = D_OUTDATED;
1593
1594         rcu_read_lock();
1595         if (ns.disk == D_CONSISTENT &&
1596             (ns.pdsk == D_OUTDATED || rcu_dereference(mdev->ldev->disk_conf)->fencing == FP_DONT_CARE))
1597                 ns.disk = D_UP_TO_DATE;
1598
1599         /* All tests on MDF_PRIMARY_IND, MDF_CONNECTED_IND,
1600            MDF_CONSISTENT and MDF_WAS_UP_TO_DATE must happen before
1601            this point, because drbd_request_state() modifies these
1602            flags. */
1603
1604         if (rcu_dereference(mdev->ldev->disk_conf)->al_updates)
1605                 mdev->ldev->md.flags &= MDF_AL_DISABLED;
1606         else
1607                 mdev->ldev->md.flags |= MDF_AL_DISABLED;
1608
1609         rcu_read_unlock();
1610
1611         /* In case we are C_CONNECTED postpone any decision on the new disk
1612            state after the negotiation phase. */
1613         if (mdev->state.conn == C_CONNECTED) {
1614                 mdev->new_state_tmp.i = ns.i;
1615                 ns.i = os.i;
1616                 ns.disk = D_NEGOTIATING;
1617
1618                 /* We expect to receive up-to-date UUIDs soon.
1619                    To avoid a race in receive_state, free p_uuid while
1620                    holding req_lock. I.e. atomic with the state change */
1621                 kfree(mdev->p_uuid);
1622                 mdev->p_uuid = NULL;
1623         }
1624
1625         rv = _drbd_set_state(mdev, ns, CS_VERBOSE, NULL);
1626         spin_unlock_irq(&mdev->tconn->req_lock);
1627
1628         if (rv < SS_SUCCESS)
1629                 goto force_diskless_dec;
1630
1631         mod_timer(&mdev->request_timer, jiffies + HZ);
1632
1633         if (mdev->state.role == R_PRIMARY)
1634                 mdev->ldev->md.uuid[UI_CURRENT] |=  (u64)1;
1635         else
1636                 mdev->ldev->md.uuid[UI_CURRENT] &= ~(u64)1;
1637
1638         drbd_md_mark_dirty(mdev);
1639         drbd_md_sync(mdev);
1640
1641         kobject_uevent(&disk_to_dev(mdev->vdisk)->kobj, KOBJ_CHANGE);
1642         put_ldev(mdev);
1643         conn_reconfig_done(mdev->tconn);
1644         drbd_adm_finish(info, retcode);
1645         return 0;
1646
1647  force_diskless_dec:
1648         put_ldev(mdev);
1649  force_diskless:
1650         drbd_force_state(mdev, NS(disk, D_DISKLESS));
1651         drbd_md_sync(mdev);
1652  fail:
1653         conn_reconfig_done(mdev->tconn);
1654         if (nbc) {
1655                 if (nbc->backing_bdev)
1656                         blkdev_put(nbc->backing_bdev,
1657                                    FMODE_READ | FMODE_WRITE | FMODE_EXCL);
1658                 if (nbc->md_bdev)
1659                         blkdev_put(nbc->md_bdev,
1660                                    FMODE_READ | FMODE_WRITE | FMODE_EXCL);
1661                 kfree(nbc);
1662         }
1663         kfree(new_disk_conf);
1664         lc_destroy(resync_lru);
1665         kfree(new_plan);
1666
1667  finish:
1668         drbd_adm_finish(info, retcode);
1669         return 0;
1670 }
1671
1672 static int adm_detach(struct drbd_conf *mdev, int force)
1673 {
1674         enum drbd_state_rv retcode;
1675         int ret;
1676
1677         if (force) {
1678                 drbd_force_state(mdev, NS(disk, D_FAILED));
1679                 retcode = SS_SUCCESS;
1680                 goto out;
1681         }
1682
1683         drbd_suspend_io(mdev); /* so no-one is stuck in drbd_al_begin_io */
1684         drbd_md_get_buffer(mdev); /* make sure there is no in-flight meta-data IO */
1685         retcode = drbd_request_state(mdev, NS(disk, D_FAILED));
1686         drbd_md_put_buffer(mdev);
1687         /* D_FAILED will transition to DISKLESS. */
1688         ret = wait_event_interruptible(mdev->misc_wait,
1689                         mdev->state.disk != D_FAILED);
1690         drbd_resume_io(mdev);
1691         if ((int)retcode == (int)SS_IS_DISKLESS)
1692                 retcode = SS_NOTHING_TO_DO;
1693         if (ret)
1694                 retcode = ERR_INTR;
1695 out:
1696         return retcode;
1697 }
1698
1699 /* Detaching the disk is a process in multiple stages.  First we need to lock
1700  * out application IO, in-flight IO, IO stuck in drbd_al_begin_io.
1701  * Then we transition to D_DISKLESS, and wait for put_ldev() to return all
1702  * internal references as well.
1703  * Only then we have finally detached. */
1704 int drbd_adm_detach(struct sk_buff *skb, struct genl_info *info)
1705 {
1706         enum drbd_ret_code retcode;
1707         struct detach_parms parms = { };
1708         int err;
1709
1710         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_MINOR);
1711         if (!adm_ctx.reply_skb)
1712                 return retcode;
1713         if (retcode != NO_ERROR)
1714                 goto out;
1715
1716         if (info->attrs[DRBD_NLA_DETACH_PARMS]) {
1717                 err = detach_parms_from_attrs(&parms, info);
1718                 if (err) {
1719                         retcode = ERR_MANDATORY_TAG;
1720                         drbd_msg_put_info(from_attrs_err_to_txt(err));
1721                         goto out;
1722                 }
1723         }
1724
1725         retcode = adm_detach(adm_ctx.mdev, parms.force_detach);
1726 out:
1727         drbd_adm_finish(info, retcode);
1728         return 0;
1729 }
1730
1731 static bool conn_resync_running(struct drbd_tconn *tconn)
1732 {
1733         struct drbd_conf *mdev;
1734         bool rv = false;
1735         int vnr;
1736
1737         rcu_read_lock();
1738         idr_for_each_entry(&tconn->volumes, mdev, vnr) {
1739                 if (mdev->state.conn == C_SYNC_SOURCE ||
1740                     mdev->state.conn == C_SYNC_TARGET ||
1741                     mdev->state.conn == C_PAUSED_SYNC_S ||
1742                     mdev->state.conn == C_PAUSED_SYNC_T) {
1743                         rv = true;
1744                         break;
1745                 }
1746         }
1747         rcu_read_unlock();
1748
1749         return rv;
1750 }
1751
1752 static bool conn_ov_running(struct drbd_tconn *tconn)
1753 {
1754         struct drbd_conf *mdev;
1755         bool rv = false;
1756         int vnr;
1757
1758         rcu_read_lock();
1759         idr_for_each_entry(&tconn->volumes, mdev, vnr) {
1760                 if (mdev->state.conn == C_VERIFY_S ||
1761                     mdev->state.conn == C_VERIFY_T) {
1762                         rv = true;
1763                         break;
1764                 }
1765         }
1766         rcu_read_unlock();
1767
1768         return rv;
1769 }
1770
1771 static enum drbd_ret_code
1772 _check_net_options(struct drbd_tconn *tconn, struct net_conf *old_conf, struct net_conf *new_conf)
1773 {
1774         struct drbd_conf *mdev;
1775         int i;
1776
1777         if (old_conf && tconn->cstate == C_WF_REPORT_PARAMS && tconn->agreed_pro_version < 100) {
1778                 if (new_conf->wire_protocol != old_conf->wire_protocol)
1779                         return ERR_NEED_APV_100;
1780
1781                 if (new_conf->two_primaries != old_conf->two_primaries)
1782                         return ERR_NEED_APV_100;
1783
1784                 if (!new_conf->integrity_alg != !old_conf->integrity_alg)
1785                         return ERR_NEED_APV_100;
1786
1787                 if (strcmp(new_conf->integrity_alg, old_conf->integrity_alg))
1788                         return ERR_NEED_APV_100;
1789         }
1790
1791         if (!new_conf->two_primaries &&
1792             conn_highest_role(tconn) == R_PRIMARY &&
1793             conn_highest_peer(tconn) == R_PRIMARY)
1794                 return ERR_NEED_ALLOW_TWO_PRI;
1795
1796         if (new_conf->two_primaries &&
1797             (new_conf->wire_protocol != DRBD_PROT_C))
1798                 return ERR_NOT_PROTO_C;
1799
1800         idr_for_each_entry(&tconn->volumes, mdev, i) {
1801                 if (get_ldev(mdev)) {
1802                         enum drbd_fencing_p fp = rcu_dereference(mdev->ldev->disk_conf)->fencing;
1803                         put_ldev(mdev);
1804                         if (new_conf->wire_protocol == DRBD_PROT_A && fp == FP_STONITH)
1805                                 return ERR_STONITH_AND_PROT_A;
1806                 }
1807                 if (mdev->state.role == R_PRIMARY && new_conf->discard_my_data)
1808                         return ERR_DISCARD;
1809         }
1810
1811         if (new_conf->on_congestion != OC_BLOCK && new_conf->wire_protocol != DRBD_PROT_A)
1812                 return ERR_CONG_NOT_PROTO_A;
1813
1814         return NO_ERROR;
1815 }
1816
1817 static enum drbd_ret_code
1818 check_net_options(struct drbd_tconn *tconn, struct net_conf *new_conf)
1819 {
1820         static enum drbd_ret_code rv;
1821         struct drbd_conf *mdev;
1822         int i;
1823
1824         rcu_read_lock();
1825         rv = _check_net_options(tconn, rcu_dereference(tconn->net_conf), new_conf);
1826         rcu_read_unlock();
1827
1828         /* tconn->volumes protected by genl_lock() here */
1829         idr_for_each_entry(&tconn->volumes, mdev, i) {
1830                 if (!mdev->bitmap) {
1831                         if(drbd_bm_init(mdev))
1832                                 return ERR_NOMEM;
1833                 }
1834         }
1835
1836         return rv;
1837 }
1838
1839 struct crypto {
1840         struct crypto_hash *verify_tfm;
1841         struct crypto_hash *csums_tfm;
1842         struct crypto_hash *cram_hmac_tfm;
1843         struct crypto_hash *integrity_tfm;
1844 };
1845
1846 static int
1847 alloc_hash(struct crypto_hash **tfm, char *tfm_name, int err_alg)
1848 {
1849         if (!tfm_name[0])
1850                 return NO_ERROR;
1851
1852         *tfm = crypto_alloc_hash(tfm_name, 0, CRYPTO_ALG_ASYNC);
1853         if (IS_ERR(*tfm)) {
1854                 *tfm = NULL;
1855                 return err_alg;
1856         }
1857
1858         return NO_ERROR;
1859 }
1860
1861 static enum drbd_ret_code
1862 alloc_crypto(struct crypto *crypto, struct net_conf *new_conf)
1863 {
1864         char hmac_name[CRYPTO_MAX_ALG_NAME];
1865         enum drbd_ret_code rv;
1866
1867         rv = alloc_hash(&crypto->csums_tfm, new_conf->csums_alg,
1868                        ERR_CSUMS_ALG);
1869         if (rv != NO_ERROR)
1870                 return rv;
1871         rv = alloc_hash(&crypto->verify_tfm, new_conf->verify_alg,
1872                        ERR_VERIFY_ALG);
1873         if (rv != NO_ERROR)
1874                 return rv;
1875         rv = alloc_hash(&crypto->integrity_tfm, new_conf->integrity_alg,
1876                        ERR_INTEGRITY_ALG);
1877         if (rv != NO_ERROR)
1878                 return rv;
1879         if (new_conf->cram_hmac_alg[0] != 0) {
1880                 snprintf(hmac_name, CRYPTO_MAX_ALG_NAME, "hmac(%s)",
1881                          new_conf->cram_hmac_alg);
1882
1883                 rv = alloc_hash(&crypto->cram_hmac_tfm, hmac_name,
1884                                ERR_AUTH_ALG);
1885         }
1886
1887         return rv;
1888 }
1889
1890 static void free_crypto(struct crypto *crypto)
1891 {
1892         crypto_free_hash(crypto->cram_hmac_tfm);
1893         crypto_free_hash(crypto->integrity_tfm);
1894         crypto_free_hash(crypto->csums_tfm);
1895         crypto_free_hash(crypto->verify_tfm);
1896 }
1897
1898 int drbd_adm_net_opts(struct sk_buff *skb, struct genl_info *info)
1899 {
1900         enum drbd_ret_code retcode;
1901         struct drbd_tconn *tconn;
1902         struct net_conf *old_conf, *new_conf = NULL;
1903         int err;
1904         int ovr; /* online verify running */
1905         int rsr; /* re-sync running */
1906         struct crypto crypto = { };
1907
1908         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_CONNECTION);
1909         if (!adm_ctx.reply_skb)
1910                 return retcode;
1911         if (retcode != NO_ERROR)
1912                 goto out;
1913
1914         tconn = adm_ctx.tconn;
1915
1916         new_conf = kzalloc(sizeof(struct net_conf), GFP_KERNEL);
1917         if (!new_conf) {
1918                 retcode = ERR_NOMEM;
1919                 goto out;
1920         }
1921
1922         conn_reconfig_start(tconn);
1923
1924         mutex_lock(&tconn->data.mutex);
1925         mutex_lock(&tconn->conf_update);
1926         old_conf = tconn->net_conf;
1927
1928         if (!old_conf) {
1929                 drbd_msg_put_info("net conf missing, try connect");
1930                 retcode = ERR_INVALID_REQUEST;
1931                 goto fail;
1932         }
1933
1934         *new_conf = *old_conf;
1935         if (should_set_defaults(info))
1936                 set_net_conf_defaults(new_conf);
1937
1938         err = net_conf_from_attrs_for_change(new_conf, info);
1939         if (err && err != -ENOMSG) {
1940                 retcode = ERR_MANDATORY_TAG;
1941                 drbd_msg_put_info(from_attrs_err_to_txt(err));
1942                 goto fail;
1943         }
1944
1945         retcode = check_net_options(tconn, new_conf);
1946         if (retcode != NO_ERROR)
1947                 goto fail;
1948
1949         /* re-sync running */
1950         rsr = conn_resync_running(tconn);
1951         if (rsr && strcmp(new_conf->csums_alg, old_conf->csums_alg)) {
1952                 retcode = ERR_CSUMS_RESYNC_RUNNING;
1953                 goto fail;
1954         }
1955
1956         /* online verify running */
1957         ovr = conn_ov_running(tconn);
1958         if (ovr && strcmp(new_conf->verify_alg, old_conf->verify_alg)) {
1959                 retcode = ERR_VERIFY_RUNNING;
1960                 goto fail;
1961         }
1962
1963         retcode = alloc_crypto(&crypto, new_conf);
1964         if (retcode != NO_ERROR)
1965                 goto fail;
1966
1967         rcu_assign_pointer(tconn->net_conf, new_conf);
1968
1969         if (!rsr) {
1970                 crypto_free_hash(tconn->csums_tfm);
1971                 tconn->csums_tfm = crypto.csums_tfm;
1972                 crypto.csums_tfm = NULL;
1973         }
1974         if (!ovr) {
1975                 crypto_free_hash(tconn->verify_tfm);
1976                 tconn->verify_tfm = crypto.verify_tfm;
1977                 crypto.verify_tfm = NULL;
1978         }
1979
1980         crypto_free_hash(tconn->integrity_tfm);
1981         tconn->integrity_tfm = crypto.integrity_tfm;
1982         if (tconn->cstate >= C_WF_REPORT_PARAMS && tconn->agreed_pro_version >= 100)
1983                 /* Do this without trying to take tconn->data.mutex again.  */
1984                 __drbd_send_protocol(tconn, P_PROTOCOL_UPDATE);
1985
1986         crypto_free_hash(tconn->cram_hmac_tfm);
1987         tconn->cram_hmac_tfm = crypto.cram_hmac_tfm;
1988
1989         mutex_unlock(&tconn->conf_update);
1990         mutex_unlock(&tconn->data.mutex);
1991         synchronize_rcu();
1992         kfree(old_conf);
1993
1994         if (tconn->cstate >= C_WF_REPORT_PARAMS)
1995                 drbd_send_sync_param(minor_to_mdev(conn_lowest_minor(tconn)));
1996
1997         goto done;
1998
1999  fail:
2000         mutex_unlock(&tconn->conf_update);
2001         mutex_unlock(&tconn->data.mutex);
2002         free_crypto(&crypto);
2003         kfree(new_conf);
2004  done:
2005         conn_reconfig_done(tconn);
2006  out:
2007         drbd_adm_finish(info, retcode);
2008         return 0;
2009 }
2010
2011 int drbd_adm_connect(struct sk_buff *skb, struct genl_info *info)
2012 {
2013         struct drbd_conf *mdev;
2014         struct net_conf *old_conf, *new_conf = NULL;
2015         struct crypto crypto = { };
2016         struct drbd_tconn *tconn;
2017         enum drbd_ret_code retcode;
2018         int i;
2019         int err;
2020
2021         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_RESOURCE);
2022
2023         if (!adm_ctx.reply_skb)
2024                 return retcode;
2025         if (retcode != NO_ERROR)
2026                 goto out;
2027         if (!(adm_ctx.my_addr && adm_ctx.peer_addr)) {
2028                 drbd_msg_put_info("connection endpoint(s) missing");
2029                 retcode = ERR_INVALID_REQUEST;
2030                 goto out;
2031         }
2032
2033         /* No need for _rcu here. All reconfiguration is
2034          * strictly serialized on genl_lock(). We are protected against
2035          * concurrent reconfiguration/addition/deletion */
2036         list_for_each_entry(tconn, &drbd_tconns, all_tconn) {
2037                 if (nla_len(adm_ctx.my_addr) == tconn->my_addr_len &&
2038                     !memcmp(nla_data(adm_ctx.my_addr), &tconn->my_addr, tconn->my_addr_len)) {
2039                         retcode = ERR_LOCAL_ADDR;
2040                         goto out;
2041                 }
2042
2043                 if (nla_len(adm_ctx.peer_addr) == tconn->peer_addr_len &&
2044                     !memcmp(nla_data(adm_ctx.peer_addr), &tconn->peer_addr, tconn->peer_addr_len)) {
2045                         retcode = ERR_PEER_ADDR;
2046                         goto out;
2047                 }
2048         }
2049
2050         tconn = adm_ctx.tconn;
2051         conn_reconfig_start(tconn);
2052
2053         if (tconn->cstate > C_STANDALONE) {
2054                 retcode = ERR_NET_CONFIGURED;
2055                 goto fail;
2056         }
2057
2058         /* allocation not in the IO path, drbdsetup / netlink process context */
2059         new_conf = kzalloc(sizeof(*new_conf), GFP_KERNEL);
2060         if (!new_conf) {
2061                 retcode = ERR_NOMEM;
2062                 goto fail;
2063         }
2064
2065         set_net_conf_defaults(new_conf);
2066
2067         err = net_conf_from_attrs(new_conf, info);
2068         if (err && err != -ENOMSG) {
2069                 retcode = ERR_MANDATORY_TAG;
2070                 drbd_msg_put_info(from_attrs_err_to_txt(err));
2071                 goto fail;
2072         }
2073
2074         retcode = check_net_options(tconn, new_conf);
2075         if (retcode != NO_ERROR)
2076                 goto fail;
2077
2078         retcode = alloc_crypto(&crypto, new_conf);
2079         if (retcode != NO_ERROR)
2080                 goto fail;
2081
2082         ((char *)new_conf->shared_secret)[SHARED_SECRET_MAX-1] = 0;
2083
2084         conn_flush_workqueue(tconn);
2085
2086         mutex_lock(&tconn->conf_update);
2087         old_conf = tconn->net_conf;
2088         if (old_conf) {
2089                 retcode = ERR_NET_CONFIGURED;
2090                 mutex_unlock(&tconn->conf_update);
2091                 goto fail;
2092         }
2093         rcu_assign_pointer(tconn->net_conf, new_conf);
2094
2095         conn_free_crypto(tconn);
2096         tconn->cram_hmac_tfm = crypto.cram_hmac_tfm;
2097         tconn->integrity_tfm = crypto.integrity_tfm;
2098         tconn->csums_tfm = crypto.csums_tfm;
2099         tconn->verify_tfm = crypto.verify_tfm;
2100
2101         tconn->my_addr_len = nla_len(adm_ctx.my_addr);
2102         memcpy(&tconn->my_addr, nla_data(adm_ctx.my_addr), tconn->my_addr_len);
2103         tconn->peer_addr_len = nla_len(adm_ctx.peer_addr);
2104         memcpy(&tconn->peer_addr, nla_data(adm_ctx.peer_addr), tconn->peer_addr_len);
2105
2106         mutex_unlock(&tconn->conf_update);
2107
2108         rcu_read_lock();
2109         idr_for_each_entry(&tconn->volumes, mdev, i) {
2110                 mdev->send_cnt = 0;
2111                 mdev->recv_cnt = 0;
2112         }
2113         rcu_read_unlock();
2114
2115         retcode = conn_request_state(tconn, NS(conn, C_UNCONNECTED), CS_VERBOSE);
2116
2117         conn_reconfig_done(tconn);
2118         drbd_adm_finish(info, retcode);
2119         return 0;
2120
2121 fail:
2122         free_crypto(&crypto);
2123         kfree(new_conf);
2124
2125         conn_reconfig_done(tconn);
2126 out:
2127         drbd_adm_finish(info, retcode);
2128         return 0;
2129 }
2130
2131 static enum drbd_state_rv conn_try_disconnect(struct drbd_tconn *tconn, bool force)
2132 {
2133         enum drbd_state_rv rv;
2134
2135         rv = conn_request_state(tconn, NS(conn, C_DISCONNECTING),
2136                         force ? CS_HARD : 0);
2137
2138         switch (rv) {
2139         case SS_NOTHING_TO_DO:
2140                 break;
2141         case SS_ALREADY_STANDALONE:
2142                 return SS_SUCCESS;
2143         case SS_PRIMARY_NOP:
2144                 /* Our state checking code wants to see the peer outdated. */
2145                 rv = conn_request_state(tconn, NS2(conn, C_DISCONNECTING,
2146                                                 pdsk, D_OUTDATED), CS_VERBOSE);
2147                 break;
2148         case SS_CW_FAILED_BY_PEER:
2149                 /* The peer probably wants to see us outdated. */
2150                 rv = conn_request_state(tconn, NS2(conn, C_DISCONNECTING,
2151                                                         disk, D_OUTDATED), 0);
2152                 if (rv == SS_IS_DISKLESS || rv == SS_LOWER_THAN_OUTDATED) {
2153                         rv = conn_request_state(tconn, NS(conn, C_DISCONNECTING),
2154                                         CS_HARD);
2155                 }
2156                 break;
2157         default:;
2158                 /* no special handling necessary */
2159         }
2160
2161         if (rv >= SS_SUCCESS) {
2162                 enum drbd_state_rv rv2;
2163                 /* No one else can reconfigure the network while I am here.
2164                  * The state handling only uses drbd_thread_stop_nowait(),
2165                  * we want to really wait here until the receiver is no more.
2166                  */
2167                 drbd_thread_stop(&adm_ctx.tconn->receiver);
2168
2169                 /* Race breaker.  This additional state change request may be
2170                  * necessary, if this was a forced disconnect during a receiver
2171                  * restart.  We may have "killed" the receiver thread just
2172                  * after drbdd_init() returned.  Typically, we should be
2173                  * C_STANDALONE already, now, and this becomes a no-op.
2174                  */
2175                 rv2 = conn_request_state(tconn, NS(conn, C_STANDALONE),
2176                                 CS_VERBOSE | CS_HARD);
2177                 if (rv2 < SS_SUCCESS)
2178                         conn_err(tconn,
2179                                 "unexpected rv2=%d in conn_try_disconnect()\n",
2180                                 rv2);
2181         }
2182         return rv;
2183 }
2184
2185 int drbd_adm_disconnect(struct sk_buff *skb, struct genl_info *info)
2186 {
2187         struct disconnect_parms parms;
2188         struct drbd_tconn *tconn;
2189         enum drbd_state_rv rv;
2190         enum drbd_ret_code retcode;
2191         int err;
2192
2193         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_CONNECTION);
2194         if (!adm_ctx.reply_skb)
2195                 return retcode;
2196         if (retcode != NO_ERROR)
2197                 goto fail;
2198
2199         tconn = adm_ctx.tconn;
2200         memset(&parms, 0, sizeof(parms));
2201         if (info->attrs[DRBD_NLA_DISCONNECT_PARMS]) {
2202                 err = disconnect_parms_from_attrs(&parms, info);
2203                 if (err) {
2204                         retcode = ERR_MANDATORY_TAG;
2205                         drbd_msg_put_info(from_attrs_err_to_txt(err));
2206                         goto fail;
2207                 }
2208         }
2209
2210         rv = conn_try_disconnect(tconn, parms.force_disconnect);
2211         if (rv < SS_SUCCESS)
2212                 retcode = rv;  /* FIXME: Type mismatch. */
2213         else
2214                 retcode = NO_ERROR;
2215  fail:
2216         drbd_adm_finish(info, retcode);
2217         return 0;
2218 }
2219
2220 void resync_after_online_grow(struct drbd_conf *mdev)
2221 {
2222         int iass; /* I am sync source */
2223
2224         dev_info(DEV, "Resync of new storage after online grow\n");
2225         if (mdev->state.role != mdev->state.peer)
2226                 iass = (mdev->state.role == R_PRIMARY);
2227         else
2228                 iass = test_bit(DISCARD_CONCURRENT, &mdev->tconn->flags);
2229
2230         if (iass)
2231                 drbd_start_resync(mdev, C_SYNC_SOURCE);
2232         else
2233                 _drbd_request_state(mdev, NS(conn, C_WF_SYNC_UUID), CS_VERBOSE + CS_SERIALIZE);
2234 }
2235
2236 int drbd_adm_resize(struct sk_buff *skb, struct genl_info *info)
2237 {
2238         struct disk_conf *old_disk_conf, *new_disk_conf = NULL;
2239         struct resize_parms rs;
2240         struct drbd_conf *mdev;
2241         enum drbd_ret_code retcode;
2242         enum determine_dev_size dd;
2243         enum dds_flags ddsf;
2244         sector_t u_size;
2245         int err;
2246
2247         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_MINOR);
2248         if (!adm_ctx.reply_skb)
2249                 return retcode;
2250         if (retcode != NO_ERROR)
2251                 goto fail;
2252
2253         memset(&rs, 0, sizeof(struct resize_parms));
2254         if (info->attrs[DRBD_NLA_RESIZE_PARMS]) {
2255                 err = resize_parms_from_attrs(&rs, info);
2256                 if (err) {
2257                         retcode = ERR_MANDATORY_TAG;
2258                         drbd_msg_put_info(from_attrs_err_to_txt(err));
2259                         goto fail;
2260                 }
2261         }
2262
2263         mdev = adm_ctx.mdev;
2264         if (mdev->state.conn > C_CONNECTED) {
2265                 retcode = ERR_RESIZE_RESYNC;
2266                 goto fail;
2267         }
2268
2269         if (mdev->state.role == R_SECONDARY &&
2270             mdev->state.peer == R_SECONDARY) {
2271                 retcode = ERR_NO_PRIMARY;
2272                 goto fail;
2273         }
2274
2275         if (!get_ldev(mdev)) {
2276                 retcode = ERR_NO_DISK;
2277                 goto fail;
2278         }
2279
2280         if (rs.no_resync && mdev->tconn->agreed_pro_version < 93) {
2281                 retcode = ERR_NEED_APV_93;
2282                 goto fail_ldev;
2283         }
2284
2285         rcu_read_lock();
2286         u_size = rcu_dereference(mdev->ldev->disk_conf)->disk_size;
2287         rcu_read_unlock();
2288         if (u_size != (sector_t)rs.resize_size) {
2289                 new_disk_conf = kmalloc(sizeof(struct disk_conf), GFP_KERNEL);
2290                 if (!new_disk_conf) {
2291                         retcode = ERR_NOMEM;
2292                         goto fail_ldev;
2293                 }
2294         }
2295
2296         if (mdev->ldev->known_size != drbd_get_capacity(mdev->ldev->backing_bdev))
2297                 mdev->ldev->known_size = drbd_get_capacity(mdev->ldev->backing_bdev);
2298
2299         if (new_disk_conf) {
2300                 mutex_lock(&mdev->tconn->conf_update);
2301                 old_disk_conf = mdev->ldev->disk_conf;
2302                 *new_disk_conf = *old_disk_conf;
2303                 new_disk_conf->disk_size = (sector_t)rs.resize_size;
2304                 rcu_assign_pointer(mdev->ldev->disk_conf, new_disk_conf);
2305                 mutex_unlock(&mdev->tconn->conf_update);
2306                 synchronize_rcu();
2307                 kfree(old_disk_conf);
2308         }
2309
2310         ddsf = (rs.resize_force ? DDSF_FORCED : 0) | (rs.no_resync ? DDSF_NO_RESYNC : 0);
2311         dd = drbd_determine_dev_size(mdev, ddsf);
2312         drbd_md_sync(mdev);
2313         put_ldev(mdev);
2314         if (dd == dev_size_error) {
2315                 retcode = ERR_NOMEM_BITMAP;
2316                 goto fail;
2317         }
2318
2319         if (mdev->state.conn == C_CONNECTED) {
2320                 if (dd == grew)
2321                         set_bit(RESIZE_PENDING, &mdev->flags);
2322
2323                 drbd_send_uuids(mdev);
2324                 drbd_send_sizes(mdev, 1, ddsf);
2325         }
2326
2327  fail:
2328         drbd_adm_finish(info, retcode);
2329         return 0;
2330
2331  fail_ldev:
2332         put_ldev(mdev);
2333         goto fail;
2334 }
2335
2336 int drbd_adm_resource_opts(struct sk_buff *skb, struct genl_info *info)
2337 {
2338         enum drbd_ret_code retcode;
2339         struct drbd_tconn *tconn;
2340         struct res_opts res_opts;
2341         int err;
2342
2343         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_RESOURCE);
2344         if (!adm_ctx.reply_skb)
2345                 return retcode;
2346         if (retcode != NO_ERROR)
2347                 goto fail;
2348         tconn = adm_ctx.tconn;
2349
2350         res_opts = tconn->res_opts;
2351         if (should_set_defaults(info))
2352                 set_res_opts_defaults(&res_opts);
2353
2354         err = res_opts_from_attrs(&res_opts, info);
2355         if (err && err != -ENOMSG) {
2356                 retcode = ERR_MANDATORY_TAG;
2357                 drbd_msg_put_info(from_attrs_err_to_txt(err));
2358                 goto fail;
2359         }
2360
2361         err = set_resource_options(tconn, &res_opts);
2362         if (err) {
2363                 retcode = ERR_INVALID_REQUEST;
2364                 if (err == -ENOMEM)
2365                         retcode = ERR_NOMEM;
2366         }
2367
2368 fail:
2369         drbd_adm_finish(info, retcode);
2370         return 0;
2371 }
2372
2373 int drbd_adm_invalidate(struct sk_buff *skb, struct genl_info *info)
2374 {
2375         struct drbd_conf *mdev;
2376         int retcode; /* enum drbd_ret_code rsp. enum drbd_state_rv */
2377
2378         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_MINOR);
2379         if (!adm_ctx.reply_skb)
2380                 return retcode;
2381         if (retcode != NO_ERROR)
2382                 goto out;
2383
2384         mdev = adm_ctx.mdev;
2385
2386         /* If there is still bitmap IO pending, probably because of a previous
2387          * resync just being finished, wait for it before requesting a new resync. */
2388         drbd_suspend_io(mdev);
2389         wait_event(mdev->misc_wait, !test_bit(BITMAP_IO, &mdev->flags));
2390
2391         retcode = _drbd_request_state(mdev, NS(conn, C_STARTING_SYNC_T), CS_ORDERED);
2392
2393         if (retcode < SS_SUCCESS && retcode != SS_NEED_CONNECTION)
2394                 retcode = drbd_request_state(mdev, NS(conn, C_STARTING_SYNC_T));
2395
2396         while (retcode == SS_NEED_CONNECTION) {
2397                 spin_lock_irq(&mdev->tconn->req_lock);
2398                 if (mdev->state.conn < C_CONNECTED)
2399                         retcode = _drbd_set_state(_NS(mdev, disk, D_INCONSISTENT), CS_VERBOSE, NULL);
2400                 spin_unlock_irq(&mdev->tconn->req_lock);
2401
2402                 if (retcode != SS_NEED_CONNECTION)
2403                         break;
2404
2405                 retcode = drbd_request_state(mdev, NS(conn, C_STARTING_SYNC_T));
2406         }
2407         drbd_resume_io(mdev);
2408
2409 out:
2410         drbd_adm_finish(info, retcode);
2411         return 0;
2412 }
2413
2414 static int drbd_adm_simple_request_state(struct sk_buff *skb, struct genl_info *info,
2415                 union drbd_state mask, union drbd_state val)
2416 {
2417         enum drbd_ret_code retcode;
2418
2419         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_MINOR);
2420         if (!adm_ctx.reply_skb)
2421                 return retcode;
2422         if (retcode != NO_ERROR)
2423                 goto out;
2424
2425         retcode = drbd_request_state(adm_ctx.mdev, mask, val);
2426 out:
2427         drbd_adm_finish(info, retcode);
2428         return 0;
2429 }
2430
2431 static int drbd_bmio_set_susp_al(struct drbd_conf *mdev)
2432 {
2433         int rv;
2434
2435         rv = drbd_bmio_set_n_write(mdev);
2436         drbd_suspend_al(mdev);
2437         return rv;
2438 }
2439
2440 int drbd_adm_invalidate_peer(struct sk_buff *skb, struct genl_info *info)
2441 {
2442         int retcode; /* drbd_ret_code, drbd_state_rv */
2443         struct drbd_conf *mdev;
2444
2445         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_MINOR);
2446         if (!adm_ctx.reply_skb)
2447                 return retcode;
2448         if (retcode != NO_ERROR)
2449                 goto out;
2450
2451         mdev = adm_ctx.mdev;
2452
2453         /* If there is still bitmap IO pending, probably because of a previous
2454          * resync just being finished, wait for it before requesting a new resync. */
2455         drbd_suspend_io(mdev);
2456         wait_event(mdev->misc_wait, !test_bit(BITMAP_IO, &mdev->flags));
2457
2458         retcode = _drbd_request_state(mdev, NS(conn, C_STARTING_SYNC_S), CS_ORDERED);
2459         if (retcode < SS_SUCCESS) {
2460                 if (retcode == SS_NEED_CONNECTION && mdev->state.role == R_PRIMARY) {
2461                         /* The peer will get a resync upon connect anyways.
2462                          * Just make that into a full resync. */
2463                         retcode = drbd_request_state(mdev, NS(pdsk, D_INCONSISTENT));
2464                         if (retcode >= SS_SUCCESS) {
2465                                 if (drbd_bitmap_io(mdev, &drbd_bmio_set_susp_al,
2466                                                    "set_n_write from invalidate_peer",
2467                                                    BM_LOCKED_SET_ALLOWED))
2468                                         retcode = ERR_IO_MD_DISK;
2469                         }
2470                 } else
2471                         retcode = drbd_request_state(mdev, NS(conn, C_STARTING_SYNC_S));
2472         }
2473         drbd_resume_io(mdev);
2474
2475 out:
2476         drbd_adm_finish(info, retcode);
2477         return 0;
2478 }
2479
2480 int drbd_adm_pause_sync(struct sk_buff *skb, struct genl_info *info)
2481 {
2482         enum drbd_ret_code retcode;
2483
2484         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_MINOR);
2485         if (!adm_ctx.reply_skb)
2486                 return retcode;
2487         if (retcode != NO_ERROR)
2488                 goto out;
2489
2490         if (drbd_request_state(adm_ctx.mdev, NS(user_isp, 1)) == SS_NOTHING_TO_DO)
2491                 retcode = ERR_PAUSE_IS_SET;
2492 out:
2493         drbd_adm_finish(info, retcode);
2494         return 0;
2495 }
2496
2497 int drbd_adm_resume_sync(struct sk_buff *skb, struct genl_info *info)
2498 {
2499         union drbd_dev_state s;
2500         enum drbd_ret_code retcode;
2501
2502         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_MINOR);
2503         if (!adm_ctx.reply_skb)
2504                 return retcode;
2505         if (retcode != NO_ERROR)
2506                 goto out;
2507
2508         if (drbd_request_state(adm_ctx.mdev, NS(user_isp, 0)) == SS_NOTHING_TO_DO) {
2509                 s = adm_ctx.mdev->state;
2510                 if (s.conn == C_PAUSED_SYNC_S || s.conn == C_PAUSED_SYNC_T) {
2511                         retcode = s.aftr_isp ? ERR_PIC_AFTER_DEP :
2512                                   s.peer_isp ? ERR_PIC_PEER_DEP : ERR_PAUSE_IS_CLEAR;
2513                 } else {
2514                         retcode = ERR_PAUSE_IS_CLEAR;
2515                 }
2516         }
2517
2518 out:
2519         drbd_adm_finish(info, retcode);
2520         return 0;
2521 }
2522
2523 int drbd_adm_suspend_io(struct sk_buff *skb, struct genl_info *info)
2524 {
2525         return drbd_adm_simple_request_state(skb, info, NS(susp, 1));
2526 }
2527
2528 int drbd_adm_resume_io(struct sk_buff *skb, struct genl_info *info)
2529 {
2530         struct drbd_conf *mdev;
2531         int retcode; /* enum drbd_ret_code rsp. enum drbd_state_rv */
2532
2533         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_MINOR);
2534         if (!adm_ctx.reply_skb)
2535                 return retcode;
2536         if (retcode != NO_ERROR)
2537                 goto out;
2538
2539         mdev = adm_ctx.mdev;
2540         if (test_bit(NEW_CUR_UUID, &mdev->flags)) {
2541                 drbd_uuid_new_current(mdev);
2542                 clear_bit(NEW_CUR_UUID, &mdev->flags);
2543         }
2544         drbd_suspend_io(mdev);
2545         retcode = drbd_request_state(mdev, NS3(susp, 0, susp_nod, 0, susp_fen, 0));
2546         if (retcode == SS_SUCCESS) {
2547                 if (mdev->state.conn < C_CONNECTED)
2548                         tl_clear(mdev->tconn);
2549                 if (mdev->state.disk == D_DISKLESS || mdev->state.disk == D_FAILED)
2550                         tl_restart(mdev->tconn, FAIL_FROZEN_DISK_IO);
2551         }
2552         drbd_resume_io(mdev);
2553
2554 out:
2555         drbd_adm_finish(info, retcode);
2556         return 0;
2557 }
2558
2559 int drbd_adm_outdate(struct sk_buff *skb, struct genl_info *info)
2560 {
2561         return drbd_adm_simple_request_state(skb, info, NS(disk, D_OUTDATED));
2562 }
2563
2564 int nla_put_drbd_cfg_context(struct sk_buff *skb, struct drbd_tconn *tconn, unsigned vnr)
2565 {
2566         struct nlattr *nla;
2567         nla = nla_nest_start(skb, DRBD_NLA_CFG_CONTEXT);
2568         if (!nla)
2569                 goto nla_put_failure;
2570         if (vnr != VOLUME_UNSPECIFIED &&
2571             nla_put_u32(skb, T_ctx_volume, vnr))
2572                 goto nla_put_failure;
2573         if (nla_put_string(skb, T_ctx_resource_name, tconn->name))
2574                 goto nla_put_failure;
2575         if (tconn->my_addr_len &&
2576             nla_put(skb, T_ctx_my_addr, tconn->my_addr_len, &tconn->my_addr))
2577                 goto nla_put_failure;
2578         if (tconn->peer_addr_len &&
2579             nla_put(skb, T_ctx_peer_addr, tconn->peer_addr_len, &tconn->peer_addr))
2580                 goto nla_put_failure;
2581         nla_nest_end(skb, nla);
2582         return 0;
2583
2584 nla_put_failure:
2585         if (nla)
2586                 nla_nest_cancel(skb, nla);
2587         return -EMSGSIZE;
2588 }
2589
2590 int nla_put_status_info(struct sk_buff *skb, struct drbd_conf *mdev,
2591                 const struct sib_info *sib)
2592 {
2593         struct state_info *si = NULL; /* for sizeof(si->member); */
2594         struct net_conf *nc;
2595         struct nlattr *nla;
2596         int got_ldev;
2597         int err = 0;
2598         int exclude_sensitive;
2599
2600         /* If sib != NULL, this is drbd_bcast_event, which anyone can listen
2601          * to.  So we better exclude_sensitive information.
2602          *
2603          * If sib == NULL, this is drbd_adm_get_status, executed synchronously
2604          * in the context of the requesting user process. Exclude sensitive
2605          * information, unless current has superuser.
2606          *
2607          * NOTE: for drbd_adm_get_status_all(), this is a netlink dump, and
2608          * relies on the current implementation of netlink_dump(), which
2609          * executes the dump callback successively from netlink_recvmsg(),
2610          * always in the context of the receiving process */
2611         exclude_sensitive = sib || !capable(CAP_SYS_ADMIN);
2612
2613         got_ldev = get_ldev(mdev);
2614
2615         /* We need to add connection name and volume number information still.
2616          * Minor number is in drbd_genlmsghdr. */
2617         if (nla_put_drbd_cfg_context(skb, mdev->tconn, mdev->vnr))
2618                 goto nla_put_failure;
2619
2620         if (res_opts_to_skb(skb, &mdev->tconn->res_opts, exclude_sensitive))
2621                 goto nla_put_failure;
2622
2623         rcu_read_lock();
2624         if (got_ldev)
2625                 if (disk_conf_to_skb(skb, rcu_dereference(mdev->ldev->disk_conf), exclude_sensitive))
2626                         goto nla_put_failure;
2627
2628         nc = rcu_dereference(mdev->tconn->net_conf);
2629         if (nc)
2630                 err = net_conf_to_skb(skb, nc, exclude_sensitive);
2631         rcu_read_unlock();
2632         if (err)
2633                 goto nla_put_failure;
2634
2635         nla = nla_nest_start(skb, DRBD_NLA_STATE_INFO);
2636         if (!nla)
2637                 goto nla_put_failure;
2638         if (nla_put_u32(skb, T_sib_reason, sib ? sib->sib_reason : SIB_GET_STATUS_REPLY) ||
2639             nla_put_u32(skb, T_current_state, mdev->state.i) ||
2640             nla_put_u64(skb, T_ed_uuid, mdev->ed_uuid) ||
2641             nla_put_u64(skb, T_capacity, drbd_get_capacity(mdev->this_bdev)))
2642                 goto nla_put_failure;
2643
2644         if (got_ldev) {
2645                 if (nla_put_u32(skb, T_disk_flags, mdev->ldev->md.flags) ||
2646                     nla_put(skb, T_uuids, sizeof(si->uuids), mdev->ldev->md.uuid) ||
2647                     nla_put_u64(skb, T_bits_total, drbd_bm_bits(mdev)) ||
2648                     nla_put_u64(skb, T_bits_oos, drbd_bm_total_weight(mdev)))
2649                         goto nla_put_failure;
2650                 if (C_SYNC_SOURCE <= mdev->state.conn &&
2651                     C_PAUSED_SYNC_T >= mdev->state.conn) {
2652                         if (nla_put_u64(skb, T_bits_rs_total, mdev->rs_total) ||
2653                             nla_put_u64(skb, T_bits_rs_failed, mdev->rs_failed))
2654                                 goto nla_put_failure;
2655                 }
2656         }
2657
2658         if (sib) {
2659                 switch(sib->sib_reason) {
2660                 case SIB_SYNC_PROGRESS:
2661                 case SIB_GET_STATUS_REPLY:
2662                         break;
2663                 case SIB_STATE_CHANGE:
2664                         if (nla_put_u32(skb, T_prev_state, sib->os.i) ||
2665                             nla_put_u32(skb, T_new_state, sib->ns.i))
2666                                 goto nla_put_failure;
2667                         break;
2668                 case SIB_HELPER_POST:
2669                         if (nla_put_u32(skb, T_helper_exit_code,
2670                                         sib->helper_exit_code))
2671                                 goto nla_put_failure;
2672                         /* fall through */
2673                 case SIB_HELPER_PRE:
2674                         if (nla_put_string(skb, T_helper, sib->helper_name))
2675                                 goto nla_put_failure;
2676                         break;
2677                 }
2678         }
2679         nla_nest_end(skb, nla);
2680
2681         if (0)
2682 nla_put_failure:
2683                 err = -EMSGSIZE;
2684         if (got_ldev)
2685                 put_ldev(mdev);
2686         return err;
2687 }
2688
2689 int drbd_adm_get_status(struct sk_buff *skb, struct genl_info *info)
2690 {
2691         enum drbd_ret_code retcode;
2692         int err;
2693
2694         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_MINOR);
2695         if (!adm_ctx.reply_skb)
2696                 return retcode;
2697         if (retcode != NO_ERROR)
2698                 goto out;
2699
2700         err = nla_put_status_info(adm_ctx.reply_skb, adm_ctx.mdev, NULL);
2701         if (err) {
2702                 nlmsg_free(adm_ctx.reply_skb);
2703                 return err;
2704         }
2705 out:
2706         drbd_adm_finish(info, retcode);
2707         return 0;
2708 }
2709
2710 int get_one_status(struct sk_buff *skb, struct netlink_callback *cb)
2711 {
2712         struct drbd_conf *mdev;
2713         struct drbd_genlmsghdr *dh;
2714         struct drbd_tconn *pos = (struct drbd_tconn*)cb->args[0];
2715         struct drbd_tconn *tconn = NULL;
2716         struct drbd_tconn *tmp;
2717         unsigned volume = cb->args[1];
2718
2719         /* Open coded, deferred, iteration:
2720          * list_for_each_entry_safe(tconn, tmp, &drbd_tconns, all_tconn) {
2721          *      idr_for_each_entry(&tconn->volumes, mdev, i) {
2722          *        ...
2723          *      }
2724          * }
2725          * where tconn is cb->args[0];
2726          * and i is cb->args[1];
2727          *
2728          * cb->args[2] indicates if we shall loop over all resources,
2729          * or just dump all volumes of a single resource.
2730          *
2731          * This may miss entries inserted after this dump started,
2732          * or entries deleted before they are reached.
2733          *
2734          * We need to make sure the mdev won't disappear while
2735          * we are looking at it, and revalidate our iterators
2736          * on each iteration.
2737          */
2738
2739         /* synchronize with conn_create()/conn_destroy() */
2740         rcu_read_lock();
2741         /* revalidate iterator position */
2742         list_for_each_entry_rcu(tmp, &drbd_tconns, all_tconn) {
2743                 if (pos == NULL) {
2744                         /* first iteration */
2745                         pos = tmp;
2746                         tconn = pos;
2747                         break;
2748                 }
2749                 if (tmp == pos) {
2750                         tconn = pos;
2751                         break;
2752                 }
2753         }
2754         if (tconn) {
2755 next_tconn:
2756                 mdev = idr_get_next(&tconn->volumes, &volume);
2757                 if (!mdev) {
2758                         /* No more volumes to dump on this tconn.
2759                          * Advance tconn iterator. */
2760                         pos = list_entry_rcu(tconn->all_tconn.next,
2761                                              struct drbd_tconn, all_tconn);
2762                         /* Did we dump any volume on this tconn yet? */
2763                         if (volume != 0) {
2764                                 /* If we reached the end of the list,
2765                                  * or only a single resource dump was requested,
2766                                  * we are done. */
2767                                 if (&pos->all_tconn == &drbd_tconns || cb->args[2])
2768                                         goto out;
2769                                 volume = 0;
2770                                 tconn = pos;
2771                                 goto next_tconn;
2772                         }
2773                 }
2774
2775                 dh = genlmsg_put(skb, NETLINK_CB(cb->skb).pid,
2776                                 cb->nlh->nlmsg_seq, &drbd_genl_family,
2777                                 NLM_F_MULTI, DRBD_ADM_GET_STATUS);
2778                 if (!dh)
2779                         goto out;
2780
2781                 if (!mdev) {
2782                         /* This is a tconn without a single volume.
2783                          * Suprisingly enough, it may have a network
2784                          * configuration. */
2785                         struct net_conf *nc;
2786                         dh->minor = -1U;
2787                         dh->ret_code = NO_ERROR;
2788                         if (nla_put_drbd_cfg_context(skb, tconn, VOLUME_UNSPECIFIED))
2789                                 goto cancel;
2790                         nc = rcu_dereference(tconn->net_conf);
2791                         if (nc && net_conf_to_skb(skb, nc, 1) != 0)
2792                                 goto cancel;
2793                         goto done;
2794                 }
2795
2796                 D_ASSERT(mdev->vnr == volume);
2797                 D_ASSERT(mdev->tconn == tconn);
2798
2799                 dh->minor = mdev_to_minor(mdev);
2800                 dh->ret_code = NO_ERROR;
2801
2802                 if (nla_put_status_info(skb, mdev, NULL)) {
2803 cancel:
2804                         genlmsg_cancel(skb, dh);
2805                         goto out;
2806                 }
2807 done:
2808                 genlmsg_end(skb, dh);
2809         }
2810
2811 out:
2812         rcu_read_unlock();
2813         /* where to start the next iteration */
2814         cb->args[0] = (long)pos;
2815         cb->args[1] = (pos == tconn) ? volume + 1 : 0;
2816
2817         /* No more tconns/volumes/minors found results in an empty skb.
2818          * Which will terminate the dump. */
2819         return skb->len;
2820 }
2821
2822 /*
2823  * Request status of all resources, or of all volumes within a single resource.
2824  *
2825  * This is a dump, as the answer may not fit in a single reply skb otherwise.
2826  * Which means we cannot use the family->attrbuf or other such members, because
2827  * dump is NOT protected by the genl_lock().  During dump, we only have access
2828  * to the incoming skb, and need to opencode "parsing" of the nlattr payload.
2829  *
2830  * Once things are setup properly, we call into get_one_status().
2831  */
2832 int drbd_adm_get_status_all(struct sk_buff *skb, struct netlink_callback *cb)
2833 {
2834         const unsigned hdrlen = GENL_HDRLEN + GENL_MAGIC_FAMILY_HDRSZ;
2835         struct nlattr *nla;
2836         const char *resource_name;
2837         struct drbd_tconn *tconn;
2838         int maxtype;
2839
2840         /* Is this a followup call? */
2841         if (cb->args[0]) {
2842                 /* ... of a single resource dump,
2843                  * and the resource iterator has been advanced already? */
2844                 if (cb->args[2] && cb->args[2] != cb->args[0])
2845                         return 0; /* DONE. */
2846                 goto dump;
2847         }
2848
2849         /* First call (from netlink_dump_start).  We need to figure out
2850          * which resource(s) the user wants us to dump. */
2851         nla = nla_find(nlmsg_attrdata(cb->nlh, hdrlen),
2852                         nlmsg_attrlen(cb->nlh, hdrlen),
2853                         DRBD_NLA_CFG_CONTEXT);
2854
2855         /* No explicit context given.  Dump all. */
2856         if (!nla)
2857                 goto dump;
2858         maxtype = ARRAY_SIZE(drbd_cfg_context_nl_policy) - 1;
2859         nla = drbd_nla_find_nested(maxtype, nla, __nla_type(T_ctx_resource_name));
2860         if (IS_ERR(nla))
2861                 return PTR_ERR(nla);
2862         /* context given, but no name present? */
2863         if (!nla)
2864                 return -EINVAL;
2865         resource_name = nla_data(nla);
2866         tconn = conn_get_by_name(resource_name);
2867
2868         if (!tconn)
2869                 return -ENODEV;
2870
2871         kref_put(&tconn->kref, &conn_destroy); /* get_one_status() (re)validates tconn by itself */
2872
2873         /* prime iterators, and set "filter" mode mark:
2874          * only dump this tconn. */
2875         cb->args[0] = (long)tconn;
2876         /* cb->args[1] = 0; passed in this way. */
2877         cb->args[2] = (long)tconn;
2878
2879 dump:
2880         return get_one_status(skb, cb);
2881 }
2882
2883 int drbd_adm_get_timeout_type(struct sk_buff *skb, struct genl_info *info)
2884 {
2885         enum drbd_ret_code retcode;
2886         struct timeout_parms tp;
2887         int err;
2888
2889         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_MINOR);
2890         if (!adm_ctx.reply_skb)
2891                 return retcode;
2892         if (retcode != NO_ERROR)
2893                 goto out;
2894
2895         tp.timeout_type =
2896                 adm_ctx.mdev->state.pdsk == D_OUTDATED ? UT_PEER_OUTDATED :
2897                 test_bit(USE_DEGR_WFC_T, &adm_ctx.mdev->flags) ? UT_DEGRADED :
2898                 UT_DEFAULT;
2899
2900         err = timeout_parms_to_priv_skb(adm_ctx.reply_skb, &tp);
2901         if (err) {
2902                 nlmsg_free(adm_ctx.reply_skb);
2903                 return err;
2904         }
2905 out:
2906         drbd_adm_finish(info, retcode);
2907         return 0;
2908 }
2909
2910 int drbd_adm_start_ov(struct sk_buff *skb, struct genl_info *info)
2911 {
2912         struct drbd_conf *mdev;
2913         enum drbd_ret_code retcode;
2914
2915         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_MINOR);
2916         if (!adm_ctx.reply_skb)
2917                 return retcode;
2918         if (retcode != NO_ERROR)
2919                 goto out;
2920
2921         mdev = adm_ctx.mdev;
2922         if (info->attrs[DRBD_NLA_START_OV_PARMS]) {
2923                 /* resume from last known position, if possible */
2924                 struct start_ov_parms parms =
2925                         { .ov_start_sector = mdev->ov_start_sector };
2926                 int err = start_ov_parms_from_attrs(&parms, info);
2927                 if (err) {
2928                         retcode = ERR_MANDATORY_TAG;
2929                         drbd_msg_put_info(from_attrs_err_to_txt(err));
2930                         goto out;
2931                 }
2932                 /* w_make_ov_request expects position to be aligned */
2933                 mdev->ov_start_sector = parms.ov_start_sector & ~BM_SECT_PER_BIT;
2934         }
2935         /* If there is still bitmap IO pending, e.g. previous resync or verify
2936          * just being finished, wait for it before requesting a new resync. */
2937         drbd_suspend_io(mdev);
2938         wait_event(mdev->misc_wait, !test_bit(BITMAP_IO, &mdev->flags));
2939         retcode = drbd_request_state(mdev,NS(conn,C_VERIFY_S));
2940         drbd_resume_io(mdev);
2941 out:
2942         drbd_adm_finish(info, retcode);
2943         return 0;
2944 }
2945
2946
2947 int drbd_adm_new_c_uuid(struct sk_buff *skb, struct genl_info *info)
2948 {
2949         struct drbd_conf *mdev;
2950         enum drbd_ret_code retcode;
2951         int skip_initial_sync = 0;
2952         int err;
2953         struct new_c_uuid_parms args;
2954
2955         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_MINOR);
2956         if (!adm_ctx.reply_skb)
2957                 return retcode;
2958         if (retcode != NO_ERROR)
2959                 goto out_nolock;
2960
2961         mdev = adm_ctx.mdev;
2962         memset(&args, 0, sizeof(args));
2963         if (info->attrs[DRBD_NLA_NEW_C_UUID_PARMS]) {
2964                 err = new_c_uuid_parms_from_attrs(&args, info);
2965                 if (err) {
2966                         retcode = ERR_MANDATORY_TAG;
2967                         drbd_msg_put_info(from_attrs_err_to_txt(err));
2968                         goto out_nolock;
2969                 }
2970         }
2971
2972         mutex_lock(mdev->state_mutex); /* Protects us against serialized state changes. */
2973
2974         if (!get_ldev(mdev)) {
2975                 retcode = ERR_NO_DISK;
2976                 goto out;
2977         }
2978
2979         /* this is "skip initial sync", assume to be clean */
2980         if (mdev->state.conn == C_CONNECTED && mdev->tconn->agreed_pro_version >= 90 &&
2981             mdev->ldev->md.uuid[UI_CURRENT] == UUID_JUST_CREATED && args.clear_bm) {
2982                 dev_info(DEV, "Preparing to skip initial sync\n");
2983                 skip_initial_sync = 1;
2984         } else if (mdev->state.conn != C_STANDALONE) {
2985                 retcode = ERR_CONNECTED;
2986                 goto out_dec;
2987         }
2988
2989         drbd_uuid_set(mdev, UI_BITMAP, 0); /* Rotate UI_BITMAP to History 1, etc... */
2990         drbd_uuid_new_current(mdev); /* New current, previous to UI_BITMAP */
2991
2992         if (args.clear_bm) {
2993                 err = drbd_bitmap_io(mdev, &drbd_bmio_clear_n_write,
2994                         "clear_n_write from new_c_uuid", BM_LOCKED_MASK);
2995                 if (err) {
2996                         dev_err(DEV, "Writing bitmap failed with %d\n",err);
2997                         retcode = ERR_IO_MD_DISK;
2998                 }
2999                 if (skip_initial_sync) {
3000                         drbd_send_uuids_skip_initial_sync(mdev);
3001                         _drbd_uuid_set(mdev, UI_BITMAP, 0);
3002                         drbd_print_uuids(mdev, "cleared bitmap UUID");
3003                         spin_lock_irq(&mdev->tconn->req_lock);
3004                         _drbd_set_state(_NS2(mdev, disk, D_UP_TO_DATE, pdsk, D_UP_TO_DATE),
3005                                         CS_VERBOSE, NULL);
3006                         spin_unlock_irq(&mdev->tconn->req_lock);
3007                 }
3008         }
3009
3010         drbd_md_sync(mdev);
3011 out_dec:
3012         put_ldev(mdev);
3013 out:
3014         mutex_unlock(mdev->state_mutex);
3015 out_nolock:
3016         drbd_adm_finish(info, retcode);
3017         return 0;
3018 }
3019
3020 static enum drbd_ret_code
3021 drbd_check_resource_name(const char *name)
3022 {
3023         if (!name || !name[0]) {
3024                 drbd_msg_put_info("resource name missing");
3025                 return ERR_MANDATORY_TAG;
3026         }
3027         /* if we want to use these in sysfs/configfs/debugfs some day,
3028          * we must not allow slashes */
3029         if (strchr(name, '/')) {
3030                 drbd_msg_put_info("invalid resource name");
3031                 return ERR_INVALID_REQUEST;
3032         }
3033         return NO_ERROR;
3034 }
3035
3036 int drbd_adm_new_resource(struct sk_buff *skb, struct genl_info *info)
3037 {
3038         enum drbd_ret_code retcode;
3039         struct res_opts res_opts;
3040         int err;
3041
3042         retcode = drbd_adm_prepare(skb, info, 0);
3043         if (!adm_ctx.reply_skb)
3044                 return retcode;
3045         if (retcode != NO_ERROR)
3046                 goto out;
3047
3048         set_res_opts_defaults(&res_opts);
3049         err = res_opts_from_attrs(&res_opts, info);
3050         if (err && err != -ENOMSG) {
3051                 retcode = ERR_MANDATORY_TAG;
3052                 drbd_msg_put_info(from_attrs_err_to_txt(err));
3053                 goto out;
3054         }
3055
3056         retcode = drbd_check_resource_name(adm_ctx.resource_name);
3057         if (retcode != NO_ERROR)
3058                 goto out;
3059
3060         if (adm_ctx.tconn) {
3061                 if (info->nlhdr->nlmsg_flags & NLM_F_EXCL) {
3062                         retcode = ERR_INVALID_REQUEST;
3063                         drbd_msg_put_info("resource exists");
3064                 }
3065                 /* else: still NO_ERROR */
3066                 goto out;
3067         }
3068
3069         if (!conn_create(adm_ctx.resource_name, &res_opts))
3070                 retcode = ERR_NOMEM;
3071 out:
3072         drbd_adm_finish(info, retcode);
3073         return 0;
3074 }
3075
3076 int drbd_adm_add_minor(struct sk_buff *skb, struct genl_info *info)
3077 {
3078         struct drbd_genlmsghdr *dh = info->userhdr;
3079         enum drbd_ret_code retcode;
3080
3081         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_RESOURCE);
3082         if (!adm_ctx.reply_skb)
3083                 return retcode;
3084         if (retcode != NO_ERROR)
3085                 goto out;
3086
3087         if (dh->minor > MINORMASK) {
3088                 drbd_msg_put_info("requested minor out of range");
3089                 retcode = ERR_INVALID_REQUEST;
3090                 goto out;
3091         }
3092         if (adm_ctx.volume > DRBD_VOLUME_MAX) {
3093                 drbd_msg_put_info("requested volume id out of range");
3094                 retcode = ERR_INVALID_REQUEST;
3095                 goto out;
3096         }
3097
3098         /* drbd_adm_prepare made sure already
3099          * that mdev->tconn and mdev->vnr match the request. */
3100         if (adm_ctx.mdev) {
3101                 if (info->nlhdr->nlmsg_flags & NLM_F_EXCL)
3102                         retcode = ERR_MINOR_EXISTS;
3103                 /* else: still NO_ERROR */
3104                 goto out;
3105         }
3106
3107         retcode = conn_new_minor(adm_ctx.tconn, dh->minor, adm_ctx.volume);
3108 out:
3109         drbd_adm_finish(info, retcode);
3110         return 0;
3111 }
3112
3113 static enum drbd_ret_code adm_delete_minor(struct drbd_conf *mdev)
3114 {
3115         if (mdev->state.disk == D_DISKLESS &&
3116             /* no need to be mdev->state.conn == C_STANDALONE &&
3117              * we may want to delete a minor from a live replication group.
3118              */
3119             mdev->state.role == R_SECONDARY) {
3120                 _drbd_request_state(mdev, NS(conn, C_WF_REPORT_PARAMS),
3121                                     CS_VERBOSE + CS_WAIT_COMPLETE);
3122                 idr_remove(&mdev->tconn->volumes, mdev->vnr);
3123                 idr_remove(&minors, mdev_to_minor(mdev));
3124                 del_gendisk(mdev->vdisk);
3125                 synchronize_rcu();
3126                 kref_put(&mdev->kref, &drbd_minor_destroy);
3127                 return NO_ERROR;
3128         } else
3129                 return ERR_MINOR_CONFIGURED;
3130 }
3131
3132 int drbd_adm_delete_minor(struct sk_buff *skb, struct genl_info *info)
3133 {
3134         enum drbd_ret_code retcode;
3135
3136         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_MINOR);
3137         if (!adm_ctx.reply_skb)
3138                 return retcode;
3139         if (retcode != NO_ERROR)
3140                 goto out;
3141
3142         retcode = adm_delete_minor(adm_ctx.mdev);
3143 out:
3144         drbd_adm_finish(info, retcode);
3145         return 0;
3146 }
3147
3148 int drbd_adm_down(struct sk_buff *skb, struct genl_info *info)
3149 {
3150         int retcode; /* enum drbd_ret_code rsp. enum drbd_state_rv */
3151         struct drbd_conf *mdev;
3152         unsigned i;
3153
3154         retcode = drbd_adm_prepare(skb, info, 0);
3155         if (!adm_ctx.reply_skb)
3156                 return retcode;
3157         if (retcode != NO_ERROR)
3158                 goto out;
3159
3160         if (!adm_ctx.tconn) {
3161                 retcode = ERR_RES_NOT_KNOWN;
3162                 goto out;
3163         }
3164
3165         /* demote */
3166         idr_for_each_entry(&adm_ctx.tconn->volumes, mdev, i) {
3167                 retcode = drbd_set_role(mdev, R_SECONDARY, 0);
3168                 if (retcode < SS_SUCCESS) {
3169                         drbd_msg_put_info("failed to demote");
3170                         goto out;
3171                 }
3172         }
3173
3174         retcode = conn_try_disconnect(adm_ctx.tconn, 0);
3175         if (retcode < SS_SUCCESS) {
3176                 drbd_msg_put_info("failed to disconnect");
3177                 goto out;
3178         }
3179
3180         /* detach */
3181         idr_for_each_entry(&adm_ctx.tconn->volumes, mdev, i) {
3182                 retcode = adm_detach(mdev, 0);
3183                 if (retcode < SS_SUCCESS) {
3184                         drbd_msg_put_info("failed to detach");
3185                         goto out;
3186                 }
3187         }
3188
3189         /* If we reach this, all volumes (of this tconn) are Secondary,
3190          * Disconnected, Diskless, aka Unconfigured. Make sure all threads have
3191          * actually stopped, state handling only does drbd_thread_stop_nowait(). */
3192         drbd_thread_stop(&adm_ctx.tconn->worker);
3193
3194         /* Now, nothing can fail anymore */
3195
3196         /* delete volumes */
3197         idr_for_each_entry(&adm_ctx.tconn->volumes, mdev, i) {
3198                 retcode = adm_delete_minor(mdev);
3199                 if (retcode != NO_ERROR) {
3200                         /* "can not happen" */
3201                         drbd_msg_put_info("failed to delete volume");
3202                         goto out;
3203                 }
3204         }
3205
3206         /* delete connection */
3207         if (conn_lowest_minor(adm_ctx.tconn) < 0) {
3208                 list_del_rcu(&adm_ctx.tconn->all_tconn);
3209                 synchronize_rcu();
3210                 kref_put(&adm_ctx.tconn->kref, &conn_destroy);
3211
3212                 retcode = NO_ERROR;
3213         } else {
3214                 /* "can not happen" */
3215                 retcode = ERR_RES_IN_USE;
3216                 drbd_msg_put_info("failed to delete connection");
3217         }
3218         goto out;
3219 out:
3220         drbd_adm_finish(info, retcode);
3221         return 0;
3222 }
3223
3224 int drbd_adm_del_resource(struct sk_buff *skb, struct genl_info *info)
3225 {
3226         enum drbd_ret_code retcode;
3227
3228         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_RESOURCE);
3229         if (!adm_ctx.reply_skb)
3230                 return retcode;
3231         if (retcode != NO_ERROR)
3232                 goto out;
3233
3234         if (conn_lowest_minor(adm_ctx.tconn) < 0) {
3235                 list_del_rcu(&adm_ctx.tconn->all_tconn);
3236                 synchronize_rcu();
3237                 kref_put(&adm_ctx.tconn->kref, &conn_destroy);
3238
3239                 retcode = NO_ERROR;
3240         } else {
3241                 retcode = ERR_RES_IN_USE;
3242         }
3243
3244         if (retcode == NO_ERROR)
3245                 drbd_thread_stop(&adm_ctx.tconn->worker);
3246 out:
3247         drbd_adm_finish(info, retcode);
3248         return 0;
3249 }
3250
3251 void drbd_bcast_event(struct drbd_conf *mdev, const struct sib_info *sib)
3252 {
3253         static atomic_t drbd_genl_seq = ATOMIC_INIT(2); /* two. */
3254         struct sk_buff *msg;
3255         struct drbd_genlmsghdr *d_out;
3256         unsigned seq;
3257         int err = -ENOMEM;
3258
3259         seq = atomic_inc_return(&drbd_genl_seq);
3260         msg = genlmsg_new(NLMSG_GOODSIZE, GFP_NOIO);
3261         if (!msg)
3262                 goto failed;
3263
3264         err = -EMSGSIZE;
3265         d_out = genlmsg_put(msg, 0, seq, &drbd_genl_family, 0, DRBD_EVENT);
3266         if (!d_out) /* cannot happen, but anyways. */
3267                 goto nla_put_failure;
3268         d_out->minor = mdev_to_minor(mdev);
3269         d_out->ret_code = NO_ERROR;
3270
3271         if (nla_put_status_info(msg, mdev, sib))
3272                 goto nla_put_failure;
3273         genlmsg_end(msg, d_out);
3274         err = drbd_genl_multicast_events(msg, 0);
3275         /* msg has been consumed or freed in netlink_broadcast() */
3276         if (err && err != -ESRCH)
3277                 goto failed;
3278
3279         return;
3280
3281 nla_put_failure:
3282         nlmsg_free(msg);
3283 failed:
3284         dev_err(DEV, "Error %d while broadcasting event. "
3285                         "Event seq:%u sib_reason:%u\n",
3286                         err, seq, sib->sib_reason);
3287 }